
Before we start
I know this sounds crazy. Who would teach you to "build your own VM" right after a "getting started" course? Whenever people bring up "VM" in malware, it means frontier, master-level stuff, the kind of thing you are supposed to pick up after years of the basics.
But no, nothing is too difficult to learn. Especially in cyber security, you don't need to understand every detail unless it matters to your work. I wrote my first LKM in 2019 with little experience in kernel development, and no AI to help me. I didn't need to know everything about the Linux kernel, because there were already plenty of resources online.
Learning how a VM works is, in my opinion, the best way to consolidate your OS internals knowledge.
A VM makes you implement what a normal program never sees: the loader, the initial stack, the instruction decoder, the syscall boundary.
This is lesson one of the course I started in lesson zero. Most of it is the talk I gave at Ruxmon on 27 November 2026, Virtualising Your Malware.
Lesson zero ended with W^X: a page is writable or executable, never both, so generated code lives in an anonymous executable mapping. That assumed the code was for the host CPU. This lesson removes the assumption, and the payload stops being executable memory.
Why I built this
A BOF (Beacon Object File) has to be mapped executable to run. The native loader packs its sections by protection, code as RX (read and execute) and data as RW (read and write), and jumps into the code. That mapping is anonymous: no file with a path name to "back" it. Because in most cases, code has to come from somewhere legitimate. If you see code not existing as a file but executing, it's probably trying to hide something.
It is also easy to find. mmap(PROT_EXEC) and mprotect(PROT_EXEC) are syscalls (calls into the kernel) that ask for executable memory, and /proc/<pid>/maps shows a private executable region in a process that should not have one. An eBPF probe is the kernel's own instrumentation. The name is extended Berkeley Packet Filter: it started as a smarter packet filter and grew into a small virtual machine that runs inside the kernel. You attach one to a syscall or tracepoint, and it runs where the watched process cannot unhook it. W^X does not help: splitting data from code does not remove the executable mapping, because the code still has to run.
What if there is no code to run? Then nothing has to be mapped executable.
A VM is code too, sure. Its core logic is benign: decode instructions, call the kernel. The part you cannot hide is the syscalls, so the detection surface moves from memory behavior to syscall behavior, which is much less specific.
Your malware code looks like data to the host. It runs in an emulated machine with its own CPU and its own memory.
Guest code is copied into a 64 MiB arena mapped PROT_READ | PROT_WRITE and is never flipped executable. The interpreter fetches guest instructions through its memory bus and executes them as its own code in rvvm_linux.so. The agent (the process running on the target) still maps that shared object executable; the payload itself is never mapped executable.
The guest cannot create one either. There is no MMU, so mprotect returns success and does nothing, and mmap hands out more of the same RW arena.
The cost is speed. Every guest instruction is decoded on the host, so a BOF runs orders of magnitude slower than native. For a scanner that runs once and prints a listing, that is fine.
Who this course is for
You need C and a shell. Nothing about VMs, RISC-V, ELF or syscalls is assumed. The host is x86-64 Linux, the guest is RV32IMA. The interpreter is portable C, and emp3r0r maps it on 386, amd64, arm, arm64 and riscv64 Linux agents.
What is a virtual machine?
VMware, VirtualBox, KVM, Hyper-V, the JVM and the RV32 CPU this post builds are all called virtual machines.
A VM is a CPU and some memory that a host process owns but lends to code which thinks it is running on its own machine. The code inside is the guest; the machine running the process is the host. Implementations differ in who executes the guest's instructions: the CPU with VT-x or AMD-V at native speed, or software that decodes every instruction itself.
Scope is separate. VMware runs a whole OS inside the VM; the JVM (Java's virtual machine) runs one program. A VMware VM on a CPU without VT-x still runs a whole OS, but it is implemented instruction by instruction in software, the same way the JVM is. This post builds that kind.
What are we computing when we say computer?
A computer is a CPU (central processing unit: the chip that runs code) and a memory. The CPU executes code, memory stores code, code modifies data, and data represents information: text, media, a packet. Disks, network cards and timers belong to the kernel.
The CPU only works on what is inside it. That storage is a small set of registers, each holding one machine word; on x86-64, 16 general-purpose registers, an instruction pointer (RIP) and flags (RFLAGS). Add an ALU (arithmetic logic unit: arithmetic, plus the logic operations that compare values) and a bus to move bytes, and that is the machine. Registers are fast because they sit next to the ALU; memory is larger but slower.
Memory is a flat array of bytes, each with an address. The kernel hands it out in pages, usually 4 KiB each, with permissions: read, write, execute. The CPU reads it in two ways: it fetches the instruction at RIP, and instructions load or store data at computed addresses. x = y + 1 becomes load y into a register, add 1, store the register into x. The CPU never adds two memory locations directly.
That is why code and data can share one array. Nothing marks a byte as an instruction; the CPU treats whatever the program counter points at as code, and everything else as data. x86-64 calls the pointer RIP, RISC-V calls it pc.
A running program gives that array a structure: code, a stack for call frames, a heap for allocations. The kernel decides where each part lives; the program just uses the addresses.
The CPU state is the registers, the program counter and the flags, which is everything the CPU needs to continue where it stopped. The stack is memory, not CPU state, but a thread needs both: the registers say where execution is, the stack says what it will return to. Save and restore the pair, and the thread cannot tell it was interrupted.
Computer, but virtualised?
Virtualisation is what VMware, KVM and Hyper-V do when the CPU supports it. These are hypervisors: the layer that creates and runs virtual machines. The CPU has at least two modes, user mode for normal programs and kernel mode for the kernel, and privileged instructions only work in the second. A guest OS (the operating system inside the VM) needs that access, and user mode cannot provide it, so the CPU does: Intel VT-x and AMD-V (the two vendors' names for the same feature) run the guest's privileged code natively, and trap the operations the hypervisor must see. A trap is a VM exit: the hypervisor emulates that one operation and resumes the guest. Only the exits are software.
Emulation?
We don't always have hardware virtualisation like VT-x. In the early days, before VT-x existed, I ran VMware on a Pentium 4: it was slow, because VMware was an emulator, faking a privileged CPU so kernel code could run.
That is emulation: software decodes every instruction, because the hardware cannot run the guest. Fetch the word, look at the opcode, compute the result, update the registers. VT-x switched off is one case. A foreign architecture is the other: there is no CPU mode to borrow, and an Intel CPU has no way to execute RISC-V. Either way the guest kernel still runs, and you can run another OS beside the host. QEMU's TCG (it compiles small blocks of guest instructions into host instructions) does this, and so does mini-rv32ima.
Both cases produce the same result as virtualisation: an environment inside a user process where code that does not belong there can execute anyway. The kernel sees a normal process.
The trade-off is speed and privilege. Virtualisation runs near native speed but needs VT-x/AMD-V and root (the administrator account) to set up. Emulation runs in user mode and is orders of magnitude slower per guest instruction.
RISC-V VM
A CPU can only do a fixed list of things: add, compare, load, store, jump. The instruction set is that list written as bit patterns, one pattern per operation and operand combination. The architecture part of the name is the context those patterns assume: which registers exist, how an instruction forms a memory address. Any chip that decodes the patterns and produces the specified results is a valid implementation.
RISC-V 32, x86-64, aarch64, PowerPC and MIPS define different instruction sets, so the same bytes mean different things on each, and one CPU cannot run code built for another. A decoder exists per ISA.
That is also why C is compiled per target: the same source becomes x86-64 for the host and RV32 for the guest, and the two binaries share no instructions. "Write once, build everywhere" applies to C source code, not to machine code.
The VM interpreter reads the guest's code one instruction at a time, and each one changes the guest's CPU state. The whole machine lives in a normal user process, and the kernel sees nothing unusual.
RV32I, the base integer set, is 37 instructions, regularly encoded. The name decodes: RV32 is 32-bit RISC-V, I is the integer base, M adds multiply/divide and A adds atomics, so RV32IMA is the subset we implement. That is what the vendored interpreter, mini-rv32ima, implements and what musl's RISC-V build needs. musl is the small C library (libc) that ends up inside every guest. Compressed instructions, floating point and an MMU (the hardware that turns the addresses a program uses into the addresses RAM actually has, by walking page tables) are not implemented. I use that header unmodified; everything else here turns it into a Linux process.
The guest state, from the vendored header:
struct MiniRV32IMAState {
uint32_t regs[32]; /* x0 .. x31 */
uint32_t pc; /* program counter */
uint32_t mstatus; /* machine status: privilege, interrupt enable */
uint32_t cyclel, cycleh;
uint32_t timerl, timerh, timermatchl, timermatchh;
uint32_t mscratch;
uint32_t mtvec; /* where traps go */
uint32_t mie, mip;
uint32_t mepc; /* PC of the trap */
uint32_t mtval;
uint32_t mcause; /* why we trapped */
uint32_t extraflags; /* privilege bits, WFI, reservations */
};
32 registers, a program counter and a few CSRs. CSRs are the control and status registers: control bits you write, status bits you read. They are settings, not data: mtvec says where the CPU jumps on a trap, mepc holds the PC at the trap so the handler can return, and mcause says what the trap was. That is the architectural state: what the ISA promises survives between instructions. A real chip also has caches and a TLB. TLB is the translation lookaside buffer: translation is turning a virtual address into a physical one, lookaside means a small side cache you check before walking the page table, and buffer means it is just an array of recent translations. Code cannot see it. Here the whole state is one 192-byte struct you can copy, step and inspect.
x0 reads as zero. x2 is the stack pointer. x1 is the return address, x10 to x17 are a0 to a7 for arguments and return values, and a7 is the syscall number. li a7, 96 is a program choosing a syscall.
Memory is a byte array:
static int rv_ram_map(void) {
void *p = mmap(NULL, RV_RAM_SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
...
}
mmap (memory map) asks the kernel for memory; MAP_ANONYMOUS means it is not backed by a file, and PROT_READ | PROT_WRITE makes it readable and writable but not executable. RV_RAM_SIZE is 64 MiB, and guest address 0x80000000 is offset zero. Translating a guest pointer is a subtraction and a bounds check:
static uint8_t *rv_gptr(uint32_t addr, uint32_t len) {
if (addr < RV_RAM_BASE || !rv_in_ram(addr - RV_RAM_BASE, len))
return NULL;
return rv_ram + (addr - RV_RAM_BASE);
}
Every pointer the host side needs goes through it. A guest address is never dereferenced directly and never passed to the kernel raw.
That is the whole mapping: arithmetic, not page tables. Guest 0x83bffec0 is byte 0x3bffec0 of the host mapping, so the host pointer is rv_ram + (0x83bffec0 - 0x80000000). The host base comes from mmap and can be anywhere; guest addresses are offsets, never host pointers. Change rv_ram and the whole guest moves.
The layout inside those 64 MiB has to look like a normal process to musl:
0x80000000 program header scratch
0x80080000 guest image, linked by the C2 (max 4 MiB)
... brk heap, page-aligned, up to the mmap arena
0x80700000 mmap arena (51 MiB)
0x83c00000 stack, growing down through a 2 MiB window
0x83e00000 argument block
0x84000000 end of guest RAM (the trap sentinel lives here)
musl uses the brk heap (brk moves the program break, the address where the heap ends, so it is the syscall that grows the heap) for small allocations and the mmap arena for large ones; the stack holds locals and return addresses; the argument block holds the arguments the agent sent, packed in the BOF argument format. The program header copy exists because musl wants AT_PHDR to point at something real. The address at the end of the layout is a sentinel, a value picked so it cannot be real data: a fake address just past the arena, so a trap jumps there and the interpreter notices.
The guest has no page table and no permissions. mprotect returns success and does nothing, and every load or store is a bounds check in the interpreter. A guest cannot make its own memory executable.
Running RISC-V 32 assembly in our virtual computer
The guest's entry point:
$ r2 -q -c 'e asm.arch=riscv; e asm.bits=32; pd 6 @ 0x8008000c' whoami.rv
0x8008000c auipc gp, 0x7ff80
0x80080010 addi gp, gp, 2036
0x80080014 mv a0, sp
0x80080018 auipc a1, 0x7ff80
0x8008001c addi a1, a1, -24
0x80080020 andi sp, sp, -16
auipc and addi form a global pointer as an offset from the current pc, so the code works wherever it is loaded. That is what PC-relative means. mv a0, sp passes the stack pointer as the first C argument. andi sp, sp, -16 aligns the stack to 16 bytes. Each instruction changes registers, memory, or pc.
Executing a program is that cycle repeated: decode the word at pc, update the state. 17,664 iterations run whoami.
The core of mini-rv32ima:
ir = MINIRV32_LOAD4(ofs_pc);
uint32_t rdid = (ir >> 7) & 0x1f;
switch (ir & 0x7f) {
case 0x37: /* LUI */ rval = (ir & 0xfffff000); break;
case 0x17: /* AUIPC */ rval = pc + (ir & 0xfffff000); break;
case 0x6f: /* JAL */ ...
case 0x13: /* OP-IMM */ ...
...
The low seven bits are the opcode, bits 7 to 11 are the destination register, so every class shares the writeback at the bottom of the loop. Each case computes a rval; if nothing trapped, the loop writes it and adds four to pc.
Every instruction is 32 bits, which is why the decoder is a single switch. x86 instructions are variable length: a decoder has to read prefixes and work out where the next instruction starts. Here pc += 4 is the whole rule.
A fetch reads the four bytes at pc as one little-endian word. mv a3, a0 is addi a3, a0, 0, which assembles to 0x00050693, so the bytes in guest memory are 93 06 05 00. The low seven bits, 0x13, say OP-IMM; bits 7 to 11 give a3; bits 15 to 19 give a0; the immediate is zero.
Fetch faults, a misaligned pc and illegal opcodes set a trap: the CPU abandons the instruction and jumps to a handler address instead of running the next one. mtvec points at RV_TRAP_PC, just past the end of guest RAM, so any unhandled trap lands where the run loop can see it:
if (state->pc == RV_TRAP_PC) {
rv_set_err_hex(rv_trap_name(state->mcause), state->mepc);
return -1;
}
The guest gets an error string with cause and PC; the agent keeps running. A guest whose go() executes .word 0:
$ ./core/modules/rvvm/tools/rvvmrun /tmp/trap.rv
rvvmrun: illegal instruction at 0x80080068
rvvmrun: 0x80080068 is go+0x10
The runner keeps symbols, so the address becomes go+0x10. In the agent the same string is the job error.
The loop is bounded twice: MiniRV32IMAStep returns after a chunk so the host can check for exit and trap, and the whole run has an instruction budget (0xffffffff by default, a runaway guard).
What good is a VM if all it does is compute numbers?
Most instructions only move numbers between registers and memory. A useful program opens files, prints and talks to the network, and none of that is arithmetic: it has to reach the host. On RISC-V that happens at one instruction, ecall.
Ask the host to do the job
A program cannot open a file or send a packet by itself. Those operations touch hardware and kernel structures, and the CPU only allows them in kernel mode. So the program executes a trap instruction, the CPU switches to the kernel, and the kernel does the work. That is a syscall.
On RISC-V the trap instruction is ecall: number in a7, arguments in a0 to a5, result in a0. x86-64's syscall is the same shape with rax and rdi, rsi, rdx, r10, r8, r9.
musl registering the thread ID:

96 is set_tid_address; ecall is the trap.
Inside the guest that trap does not switch the host CPU. The guest CPU is a struct, so the trap is a value MiniRV32IMAStep hands to the hook; the hook makes the real host syscall and writes the result back.
The guest runs in machine mode (extraflags is 3), so the cause is 12 and the post-exec hook handles it before the trap vector:
/* Guest ECALL: a7 is the Linux syscall number. */
static void rv_host_postexec(struct MiniRV32IMAState *state, uint32_t *pc,
uint32_t ir, uint32_t *trap) {
if (*trap != 12)
return;
int64_t result = rv_guest_syscall(
state->regs[17], state->regs[10], state->regs[11], state->regs[12],
state->regs[13], state->regs[14], state->regs[15]);
state->regs[10] = (uint32_t)result;
state->regs[11] = (uint32_t)(result >> 32);
*trap = 0;
*pc += 4;
}
regs[17] is a7, regs[10..15] are the arguments, the result goes back in a0 and a1, and pc advances past the ecall. The guest says ecall; the host does the syscall.
rv_guest_syscall is a switch over the number:
case RV_SYS_SET_TID_ADDRESS:
return getpid();
case RV_SYS_BRK:
...
if (want <= RV_MAP_BASE)
rv_heap_cur = want;
return rv_heap_cur;
case RV_SYS_MMAP:
case RV_SYS_MMAP2: {
uint32_t p = rv_guest_mmap(a1);
return p == 0 ? -ENOMEM : (int64_t)p;
}
case RV_SYS_EXIT:
case RV_SYS_EXIT_GROUP:
rv_guest_status = (int)a0;
rv_stopped = 1;
return 0;
The gate implements around forty calls: files, sockets, brk, mmap, ppoll, IDs, uname, statx, clock_gettime64. Anything else returns -ENOSYS (errno for "no such system call").
The same switch in gdb, right before the host's getpid():

brk is a bump pointer inside the arena and mmap hands out slices of the same 51 MiB. mprotect is a no-op because there is no MMU. Errors come back negative in a0: -ENOSYS, -EFAULT, -EBADF.
Pointers are translated before they cross. sched_getaffinity accepts only the guest's own pid, recvmsg rejects an untranslatable iovec or socket name, and descriptors opened through the gate are close-on-exec so a spawned process cannot inherit them. core/modules/rvvm/tests/guests/ covers those cases.
Every syscall a guest makes can be printed:
$ ./core/modules/rvvm/tools/rvvmrun -t /tmp/pwd.rv
[rv] set_tid_address a0=0x8008c2c4 a1=0x00000000 a2=0x00000002 a3=0x8008c350 a4=0xfffffff8 a5=0x00000000 = 1492268
[rv] getcwd a0=0x83bffec0 a1=0x000000ff a2=0x000000ff a3=0x00000010 a4=0x00000000 a5=0x00000002 = 255
[rv] writev a0=0x00000001 a1=0x83bffd14 a2=0x00000002 a3=0x00000005 a4=0x83bffd50 a5=0x8008c210 = 5
[rv] writev a0=0x00000001 a1=0x83bffe54 a2=0x00000002 a3=0x00000000 a4=0x8008c3e4 a5=0x8008c210 = 1
[rv] exit_group a0=0x00000000 a1=0x00000000 a2=0x00000002 a3=0x00000000 a4=0x8008c3e4 a5=0x8008c210 = 0
[rv] 3485 guest instructions, exit status 0
pwd is 3,485 instructions and five syscalls. This is the layer under strace, except you own the switch and can log, filter or refuse anything in it.
The gate is also an API
Linux syscalls cover most of what a BOF needs. Reading a file through the agent, uploading it to the C2 (the command and control server), or running a command belongs to the session, not the kernel. The C agent adds six private numbers above the Linux range:
| Number | Name | What it does |
|---|---|---|
0x40000001 |
ReadFile |
read a file into guest memory |
0x40000002 |
WriteFile |
write guest memory to a file |
0x40000004 |
UploadFile |
push a file to the C2 |
0x40000005 |
Sha256Hex |
hash a guest buffer |
0x40000006 |
RelaySocket |
hand a connected socket to the agent's relay |
0x40000007 |
ExecCmd |
run a command on the agent, output in guest memory |
The BOF calls ordinary C wrappers from the guest shim, the entry code every guest is linked with:
int ReadFile(const char *path, unsigned char **out, unsigned long *len,
char *err, int err_cap) {
long need = syscall(RV_SYS_XFER_READ, path, NULL, 0);
unsigned char *buf = malloc(need > 0 ? (size_t)need : 1);
long got = syscall(RV_SYS_XFER_READ, path, buf, (unsigned long)need);
...
}
Without a host bridge (the callbacks the agent installs for these calls) they return -ENOSYS. Each agent capability costs one gate case and one wrapper; that is the FFI boundary.
Is it a BOF?
The kernel keeps one record per running program: the addresses it may touch, the threads running in it, and its bookkeeping (file descriptors, which are handles to open files; credentials; a pid). That record is the process. The address space is what makes the program believe it owns memory; a thread is one CPU state running in it. The kernel switches between processes, and each one starts from an executable: it maps the file's segments, builds a stack, and jumps to the entry point.
On x86 a BOF skips all of that. It is host machine code, so the loader maps it into the agent's address space, applies its relocations, and calls its entry point as a function. The agent's process already has libc, a stack and a thread; the BOF borrows them. That works because the BOF and the host speak the same instruction set.
RV32 does not. The host CPU cannot execute one instruction of it, so there is nothing to call. The code has to be interpreted, and an interpreted program needs what the kernel would normally provide: an entry point, a stack, initialized libc. A BOF object is a fragment that expects all of that to exist already, and for RV32 it exists nowhere on the host.
The files the C2 sends are complete programs: static RV32 images with their own libc. A BOF object is not one.
Why not? What's wrong with a BOF?
A BOF is a COFF object: compiled code whose addresses are not assigned yet, plus relocations that say where each missing address goes and external names (printf and friends) that a loader fills in at runtime. COFF is the object format Windows compilers emit; the BOF loader was written for it. ELF is Linux's equivalent, and its name is the two jobs the format serves: a file can be linkable (an object, ET_REL, addresses still to be assigned) or executable (ET_EXEC, addresses fixed). The guest has to be the second kind.
In the VM there is nothing to link against: host libraries are x86-64, and a RISC-V call cannot reach them. So link the BOF statically against musl for riscv32-linux-musl at build time. The result is ET_EXEC with every symbol resolved and libc inside the image:
$ file whoami.rv
whoami.rv: ELF 32-bit LSB executable, UCB RISC-V, soft-float ABI, version 1 (SYSV),
statically linked, not stripped
$ readelf -h whoami.rv
Class: ELF32
Data: 2's complement, little endian
Type: EXEC (Executable file)
Machine: RISC-V
Entry point address: 0x8008000c
Number of program headers: 7
$ readelf -l whoami.rv
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
LOAD 0x001000 0x80080000 0x80080000 0x0000c 0x0000c RW 0x1000
LOAD 0x00100c 0x8008000c 0x8008000c 0x0aa60 0x0aa60 R E 0x1000
LOAD 0x00ba6c 0x8008aa6c 0x8008aa6c 0x01844 0x01844 R 0x1000
LOAD 0x00d2b0 0x8008c2b0 0x8008c2b0 0x00098 0x04654 RW 0x1000
Four PT_LOAD segments (the program header table lists the file's chunks; entries marked load are the ones mapped into memory, while sections are for tools), a fixed base, no interpreter (no dynamic linker path), no dynamic section (the table of shared libraries and runtime relocations). The price is about 118 KB per BOF, almost all of it musl.
The first segment is 12 bytes at 0x80080000: the .rvhdr argument handoff.
struct rv_hdr {
char *args;
int len;
char **env;
};
struct rv_hdr rv_bof_hdr __attribute__((section(".rvhdr"), used));
The interpreter finds that section by name and writes the argument pointer, length and environment pointer before starting the guest. main then calls go(rv_bof_hdr.args, rv_bof_hdr.len).
The image is non-PIC: not position-independent, meaning it assumes the address it was linked at instead of working wherever it is loaded. It is fixed (-fno-pic -mno-relax), so the loader needs no relocation engine and no relaxation pass (a linker trick that rewrites instructions into shorter forms). A dynamic binary would need ld.so (the dynamic linker that maps shared libraries) inside the guest as well; ET_EXEC with absolute addresses needs neither.
A module can declare riscv_libraries, static RISC-V libraries linked into the guest at build time. zlib, OpenSSL, libbpf and anything else with a riscv32-linux-musl build become available without a new gate case. A crash in the library takes down the guest, not the agent.
Loading the image

rv_run_exec does what the kernel does: map each PT_LOAD, zero the part past the file, build argc/argv/envp and the auxiliary vector (auxv: a vector, meaning a list, of key/value pairs the kernel passes to a new program), then jump to the entry point. It is under 200 lines.
for (uint16_t i = 0; i < phnum; i++) {
if (rv_le32(ph) != RV_PT_LOAD)
continue;
uint32_t vaddr = rv_le32(ph + 8);
uint32_t filesz = rv_le32(ph + 16);
uint32_t memsz = rv_le32(ph + 20);
...
uint8_t *dst = rv_ram + (vaddr - RV_RAM_BASE);
rv_memzero(dst, memsz);
rv_memcpy(dst, image + off, filesz);
}
The heap starts at the page-aligned end of the image; the argument block goes in at the top of the arena.
The stack is the part that breaks. _start takes no arguments; it reads them from the stack the kernel normally builds:
sp -> argc
argv[0] ... argv[n-1]
NULL
envp[0] ... envp[n-1]
NULL
AT_PHDR, value
...
AT_NULL
musl reads the program headers, page size, IDs and random bytes from the auxiliary vector. Get the layout off by one word and it dereferences garbage as a pointer.
RV_AUX(3, phdr_addr); /* AT_PHDR */
RV_AUX(4, phent); /* AT_PHENT */
RV_AUX(5, phnum); /* AT_PHNUM */
RV_AUX(6, 4096); /* AT_PAGESZ */
RV_AUX(7, 0); /* AT_BASE */
RV_AUX(9, entry); /* AT_ENTRY */
RV_AUX(11, getuid()); /* AT_UID */
RV_AUX(25, rnd); /* AT_RANDOM */
RV_AUX(0, 0); /* AT_NULL */
AT_RANDOM comes from getrandom, with /dev/urandom as a fallback, and a run fails rather than returning predictable bytes. A wrong auxv kills musl early with no message.
The runner prints the layout:
$ ./core/modules/rvvm/tools/rvvmrun -v /tmp/pwd.rv
image: pwd.rv (118348 bytes)
entry: 0x8008000c (_start+0x0)
.rvhdr: 0x80080000 (12 bytes)
program headers: 7
PT_LOAD vaddr=0x80080000 filesz=12 memsz=12
PT_LOAD vaddr=0x8008000c filesz=43564 memsz=43564
PT_LOAD vaddr=0x8008aa38 filesz=6104 memsz=6104
PT_LOAD vaddr=0x8008c210 filesz=152 memsz=17972
arguments: 0, block 4 bytes (00000000)
environment: 99 entries, 4828 bytes
rvvmrun: 6 output bytes, guest exit status 0
/tmp
Entry 0x8008000c, .rvhdr at 0x80080000, bss 152 bytes on disk and 17,972 in memory, 99 environment entries from the agent, six bytes of output.
The life cycle of a whoami BOF
Build, on the C2. sa_linux_whoami --riscv makes the C2 point CC and CXX at riscv32-linux-musl shims, export RV_TARGET=riscv32-linux-musl and EMP3R0R_BOF_ARCH=riscv32, and run the module's normal build (or rv_build.sh). The Makefile emits the RV32 object:
$ zig cc -target riscv32-linux-musl -mcpu=generic_rv32 -O2 -g0 -fno-pic \
-mno-relax -msmall-data-limit=0 -fno-asynchronous-unwind-tables \
-fno-unwind-tables -fno-builtin -fno-stack-protector -fno-sanitize=all \
-I includes -c -o whoami.rv.o whoami.c
The same recipe builds the rest of SA_linux, which comes from TrustedSec's Linux BOFs: process listing, file reads, ifconfig, find, cat.
The C2 links it with the guest entry shim, the linker script and musl. The link strips symbols (function and variable names) to keep the payload small; the local runner keeps them.
$ zig build-exe -target riscv32-linux-musl -mcpu=generic_rv32+a -static \
-O ReleaseSmall -fno-entry -fstrip -lc -T guest.ld \
main.c whoami.rv.o -femit-bin=whoami.rv
Two artifacts go to the agent: rvvm_linux.<arch>.gz and whoami.rv. The module stays a normal coff module.
Run, on the agent. memmod (Go) or elfload (C) maps the interpreter from memory and calls it once:
char *Run(const uint8_t *image, size_t len, const struct rv_bof_args *args);
args carries the packed COFF argument block and the agent's environment. Mapping the arena, loading the image, building the stack, running the guest and capturing its output all happen inside that call. Afterwards the interpreter and the 64 MiB arena are unmapped.
This is the call from the C agent, in gdb. The backtrace goes from rv_run_exec through Run to the agent's command loop; the loader has just read the entry point from image+24, and the image starts at \177ELF:

Inside the guest. musl's _start sets up TLS, errno, stdio and the heap, then calls main, which calls go(rv_bof_hdr.args, rv_bof_hdr.len).
TLS holds the variables that belong to one thread. A thread is one flow of execution inside a process: a CPU state plus a stack of its own, sharing the process's memory. Local means each thread gets its own copy instead of sharing one. Storage means ordinary variables that would otherwise be a single global; errno is the case that matters: thread A must not read thread B's error code. The compiler marks variables like that as thread-local and puts them in .tdata (initialised) or .tbss (zeroed); the runtime gives every thread a private block with its own copies, and tp points at the current block. Access is tp plus a fixed offset, so errno costs one load even though it is written like a global.
The guest has one thread, so it has one block, but musl still needs it: errno and the allocator's state live there, and musl's own code reaches them through tp. musl builds the block from the TLS segment in the program headers, which is one reason AT_PHDR has to be correct.
Every libc call that needs the kernel is an ecall; output is writev on fd 1, which the gate appends to the run's output buffer.
Back on the agent. exit_group stops the run. Run returns the captured stdout as a NUL-terminated string, the agent copies it and frees the interpreter's buffer, and the module is unmapped.
Local run, no agent involved:
$ make -C core/modules/rvvm/tools
$ ./core/modules/rvvm/tools/rvvmrun build -o /tmp/whoami.rv \
core/modules/SA_linux/SA/src/whoami.rv.o
$ ./core/modules/rvvm/tools/rvvmrun /tmp/whoami.rv
UID: 1000 EUID: 1000
Current Working Directory: /tmp
Running as a standard user.
And with a debugger:
$ gdb --args core/modules/rvvm/tools/rvvmrun /tmp/whoami.rv
(gdb) break rv_guest_syscall
(gdb) break rv_run_state

The guest is stopped in the gate (rv_guest_syscall+65, called from rv_host_postexec, MiniRV32IMAStep, rv_run_state, rv_run_exec, Run), then continued to completion. A native BOF cannot be stepped like this: its state is the host CPU's registers, which the agent has already overwritten.
Sizes and counts from this build:
| Artifact | Size | Guest instructions | Syscalls |
|---|---|---|---|
rvvm_linux.so |
33,992 B | n/a | n/a |
whoami.rv |
118,524 B | 17,664 | 15 |
pwd.rv |
118,348 B | 3,485 | 5 |
whoami makes fifteen syscalls: set_tid_address, sched_getaffinity, an mmap/munmap pair for the allocator, getuid, geteuid, getcwd, six writev calls for three lines (text and newline separately), a second getuid for the root check, and exit_group.
The guest is RV32 and only the interpreter is host code, so the same image runs on every agent architecture.
Limitations
FFI for everything the kernel cannot express. FFI is a foreign function interface: foreign because the code lives on the other side of a binary boundary, interface because you call it like any other function. libc works because the guest carries it. Agent capabilities do not: each is a gate case and a wrapper. That is why the C agent exposes six host calls.
Static libraries only. The guest has no dynamic linker, so dlopen (the call that loads a shared library at runtime) has nothing to call. A library has to be in riscv_libraries at build time.
Single thread, no fork. The interpreter keeps one MiniRV32IMAState in file scope: one register file, one pc, one stack pointer. Supporting threads would need:
- a state struct, a stack and a
tp(thread pointer) per thread, because each thread needs its own TLS block forerrnoand the allocator; - a scheduler and a timer tick, so the interpreter can switch threads; today it runs until the guest exits;
clone(create a task from the caller, with flags deciding what is shared; a thread shares the address space) andfutex(fast userspace mutex: a lock that spins in user space and only enters the kernel to sleep or wake) semantics, andppoll(poll with a signal mask) must wake one thread instead of blocking the run;- guest atomics (load-modify-store operations that cannot interleave) mapped to host atomics, since
RV32Ais the extension that provides them; - locking in the gate, because host descriptors and the output buffer would be shared.
That is a different interpreter, with a scheduler instead of a for loop. A guest that needs threads, or calls fork (clone the process), gets -ENOSYS.
RV32IMA only. Nothing beyond it is implemented. mprotect succeeds and does nothing, and a JIT inside the guest is impossible.
Slow. Each guest instruction becomes a switch case and a few host operations, so a run costs orders of magnitude more than native code. 17,664 instructions is instant; a scanning BOF at hundreds of millions is seconds. The budget is a runaway guard, not a performance target.
One run at a time. The interpreter keeps per-image state in file-scope variables, so runs are serialized with a mutex (a lock); a second run would overwrite the first.
Bounded. 64 MiB of address space (one arena, sized so a scanner that allocates and frees per entry has room), 8 MiB of output (the agent's tunnel frame, the message that carries one job result, is 10 MiB, so one run fits in one response), a 2 MiB argument block, an instruction budget.
What the host sees
The only executable thing the payload adds is the interpreter. rvvm_linux.so is mapped from memory, so it appears as an anonymous executable region with no path, and the arena it runs in is mapped only for the run.
So the signals are different, not gone: an anonymous .so, a 64 MiB rw region, and a process that maps it, runs a CPU in it, and unmaps it. None of that is the payload's code.
The return address of a syscall tells the kernel, and an eBPF probe, whether the call came from libc or from anonymous memory (lesson zero). Here the host syscalls are issued from rvvm_linux.so, which is anonymous, so the file-backed heuristic fails differently. The calls still land in the kernel with the agent's credentials; they just do not match the profile of a native process.
What the gate enforces: the guest cannot read or write host memory. Every pointer is translated and bounds-checked, every descriptor is a guest handle, unknown calls return -ENOSYS, and a trap becomes an error string. A malicious guest can burn CPU and output until the budget stops it, and that is all.
Those three things are all fingerprintable: the interpreter's bytes, the arena's size and lifetime, the gate's syscall mix. The advantage is that when one is burned, you rebuild one component, not the whole implant.
Comments
comments powered by Disqus