美文网首页
DLL注入---任务管理器之进程保护--Python

DLL注入---任务管理器之进程保护--Python

作者: Bug2Coder | 来源:发表于2019-12-02 10:59 被阅读0次

    Python 实现DLL注入
    dll文件 dll.c

    #include <stdio.h>
    #include <windows.h>
     
    unsigned char code[12];
    unsigned char oldcode[12];
    FARPROC addr;
    DWORD pid;
     //获取注册表需要保护的程序pid
    int getpid()
    {
        char buffer[255];
        DWORD get = 255;
        //判断环境是否为WOW64
        BOOL isWOW64;
        REGSAM p = KEY_READ;
        IsWow64Process(GetCurrentProcess(), &isWOW64);
        if (isWOW64)p |= KEY_WOW64_64KEY;
     
        HKEY hKey;
        if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\测试"), 0, NULL, 0, p, NULL, &hKey, NULL) != ERROR_SUCCESS){
            return 0;
        }
        if (RegQueryValueExA(hKey, "Main_PID", 0, NULL, (BYTE*)buffer, &get) != ERROR_SUCCESS){
            return 0;
        }
        return atoi(buffer);
    }
     
    HANDLE WINAPI MyOpenProcess(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId){
        HANDLE handle;
        if (getpid() == dwProcessId){
            SetLastError(5);
            return NULL;
        }
     
        DWORD old;
        if (VirtualProtectEx(GetCurrentProcess(), addr, 12, PAGE_EXECUTE_READWRITE, &old)){
            WriteProcessMemory(GetCurrentProcess(), addr, oldcode, 12, NULL);
            VirtualProtectEx(GetCurrentProcess(), addr, 12, old, &old);
        }
        handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
        if (VirtualProtectEx(GetCurrentProcess(), addr, 12, PAGE_EXECUTE_READWRITE, &old)){
            WriteProcessMemory(GetCurrentProcess(), addr, code, 12, NULL);
            VirtualProtectEx(GetCurrentProcess(), addr, 12, old, &old);
        }
     
        return handle;
    }
     
    BOOL APIENTRY DllMain(HMODULE hModule,
        DWORD  ul_reason_for_call,
        LPVOID lpReserved
        )
    {
        switch (ul_reason_for_call)
        {
        case DLL_PROCESS_ATTACH:
            addr = 0;
            HMODULE hdll; hdll = LoadLibrary(TEXT("Kernel32.dll"));
            addr = GetProcAddress(hdll, "OpenProcess");
            if (addr){
                code[0] = 0x48;
                code[1] = 0xB8;
                code[10] = 0x50;
                code[11] = 0xC3;
                long long a = (long long)MyOpenProcess;
                RtlMoveMemory(code + 2, &a, 8);
     
                DWORD old;
                if (VirtualProtectEx(GetCurrentProcess(), addr, 12, PAGE_EXECUTE_READWRITE, &old)){
                    RtlMoveMemory(oldcode, addr, 12);
                    WriteProcessMemory(GetCurrentProcess(), addr, code, 12, NULL);
                    VirtualProtectEx(GetCurrentProcess(), addr, 12, old, &old);
                }
            }
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
            break;
        }
        return TRUE;
    }
    

    python注入程序

    import win32api, ctypes, psutil, os, win32con, time
    
    
    class Regedit(object):
        """
        创建、修改和读取注册表类
        """
    
        def __init__(self):
            self.reg_app_root = win32con.HKEY_LOCAL_MACHINE
            self.reg_config_path = r"SOFTWARE\测试"
            self.reg_flags = win32con.WRITE_OWNER | win32con.KEY_WOW64_64KEY | win32con.KEY_ALL_ACCESS
    
        def create(self):
            """
            创建和修改注册表项
            项不存在时创建、存在时修改键值
            :param kw: 需要创建的键值对、字典类型
            :return:
            """
            pid = os.getpid()
            kw = {"Main_PID": "{}".format(pid)}
    
            for keys, values in kw.items():
                key, _ = win32api.RegCreateKeyEx(self.reg_app_root, self.reg_config_path, self.reg_flags)
    
                win32api.RegSetValueEx(key, keys, 0, win32con.REG_SZ, values)
    
                win32api.RegCloseKey(key)
            return True
    
    
    def injectDll(dllpath, pid):
        """
        dll注入方法
        :param dllpath: dll路径
        :param pid: 注入的任务管理器pid
        :return:
        """
        PROCESS_ALL_ACCESS = (0x000F0000 | 0x00100000 | 0xFFF)
    
        MEM_COMMIT = (0x1000 | 0x2000)
        PAGE_READWRITE = 0x04
        dllname = "{}".format(dllpath).encode('ascii', 'ignore')
    
        dlllen = len(dllname)
    
        kernel32 = ctypes.windll.kernel32
    
        hProcess = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid)
        if hProcess:
            h_kernel32 = win32api.GetModuleHandle("Kernel32")
    
            h_loadlib = win32api.GetProcAddress(h_kernel32, "LoadLibraryA")
    
            arg_adress = kernel32.VirtualAllocEx(hProcess, None, dlllen, MEM_COMMIT, PAGE_READWRITE)
            written = ctypes.c_int(0)
            kernel32.WriteProcessMemory(hProcess, arg_adress, dllname, dlllen, ctypes.byref(written))
            hTread = kernel32.CreateRemoteThread(hProcess, None, 0, h_loadlib, arg_adress, 0,
                                                 ctypes.byref(ctypes.c_ulong(0)))
            return hTread
        else:
            return False
    
    
    r = Regedit()
    r.create()
    # 可在子线程中检查是否任务管理器运行,运行则注入dll,保护本进程
    dllpath = "c:\\DLL12.dll"
    pid = None
    while 1:   
        for i in psutil.pids():
            p = psutil.Process(i)
            if p.name() == "taskmgr.exe" and pid != p.pid:
                pid = p.pid
                if injectDll(dllpath, pid):
                    break
                else:
                    print('error')
        time.sleep(1)
    

    相关文章

      网友评论

          本文标题:DLL注入---任务管理器之进程保护--Python

          本文链接:https://www.haomeiwen.com/subject/vqyxgctx.html