{"slug": "linux-c2-from-scratch-0x01-virtualising-your-malware", "title": "Linux C2 from Scratch 0x01: Virtualising Your Malware", "summary": "Security researcher jm33 published lesson one of a \"Linux C2 from Scratch\" course, based on a Ruxmon talk given on 27 November 2026 titled \"Virtualising Your Malware,\" showing how to run malware payloads inside a custom RV32IMA virtual machine on x86-64 Linux so the payload is never mapped executable. Guest code is copied into a 64 MiB arena mapped PROT_READ | PROT_WRITE and interpreted by rvvm_linux.so, moving the detection surface from memory behavior such as mmap(PROT_EXEC) and /proc/<pid>/maps to syscall behavior, at the cost of running orders of magnitude slower than native. The emp3r0r agent maps the interpreter on 386, amd64, arm, arm64 and riscv64 Linux hosts.", "body_md": "# Before we start\n\nI 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.\n\nBut 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.\n\nLearning how a VM works is, in my opinion, the best way to consolidate your OS internals knowledge.\n\nA VM makes you implement what a normal program never sees: the loader, the initial stack, the instruction decoder, the syscall boundary.\n\nThis is lesson one of the course I started in [lesson zero](https://jm33.me/linux-c2-from-scratch-0x00-processes-syscalls-libc-and-tls.html). Most of it is the talk I gave at Ruxmon on 27 November 2026, *Virtualising Your Malware*.\n\nLesson 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.\n\n## Why I built this\n\nA 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.\n\nIt 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.\n\nWhat if there is no code to run? Then nothing has to be mapped executable.\n\nA 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.\n\nYour malware code looks like data to the host. It runs in an emulated machine with its own CPU and its own memory.\n\nGuest 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.\n\nThe 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.\n\nThe 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.\n\n## Who this course is for\n\nYou 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.\n\n# What is a ~~virtual~~ machine?\n\nVMware, VirtualBox, KVM, Hyper-V, the JVM and the RV32 CPU this post builds are all called virtual machines.\n\nA 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.\n\nScope 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.\n\n## What are we computing when we say computer?\n\nA 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.\n\nThe 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.\n\nMemory 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.\n\nThat 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`.\n\nA 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.\n\nThe **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.\n\n## Computer, but virtualised?\n\n**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.\n\n## Emulation?\n\nWe 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.\n\nThat 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](https://github.com/cnlohr/mini-rv32ima).\n\nBoth 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.\n\nThe 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.\n\n# RISC-V VM\n\nA 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.\n\nRISC-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.\n\nThat 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.\n\nThe 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.\n\nRV32I, 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](https://github.com/cnlohr/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.\n\nThe guest state, from the vendored header:\n\n```\nstruct MiniRV32IMAState {\n    uint32_t regs[32];      /* x0 .. x31 */\n\n    uint32_t pc;            /* program counter */\n    uint32_t mstatus;       /* machine status: privilege, interrupt enable */\n    uint32_t cyclel, cycleh;\n\n    uint32_t timerl, timerh, timermatchl, timermatchh;\n\n    uint32_t mscratch;\n    uint32_t mtvec;         /* where traps go */\n    uint32_t mie, mip;\n\n    uint32_t mepc;          /* PC of the trap */\n    uint32_t mtval;\n    uint32_t mcause;        /* why we trapped */\n\n    uint32_t extraflags;    /* privilege bits, WFI, reservations */\n};\n```\n\n32 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.\n\n`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.\n\nMemory is a byte array:\n\n```\nstatic int rv_ram_map(void) {\n    void *p = mmap(NULL, RV_RAM_SIZE, PROT_READ | PROT_WRITE,\n                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n    ...\n}\n```\n\n`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:\n\n```\nstatic uint8_t *rv_gptr(uint32_t addr, uint32_t len) {\n    if (addr < RV_RAM_BASE || !rv_in_ram(addr - RV_RAM_BASE, len))\n        return NULL;\n    return rv_ram + (addr - RV_RAM_BASE);\n}\n```\n\nEvery pointer the host side needs goes through it. A guest address is never dereferenced directly and never passed to the kernel raw.\n\nThat 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.\n\nThe layout inside those 64 MiB has to look like a normal process to musl:\n\n```\n0x80000000  program header scratch\n0x80080000  guest image, linked by the C2 (max 4 MiB)\n   ...      brk heap, page-aligned, up to the mmap arena\n0x80700000  mmap arena (51 MiB)\n0x83c00000  stack, growing down through a 2 MiB window\n0x83e00000  argument block\n0x84000000  end of guest RAM (the trap sentinel lives here)\n```\n\nmusl 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.\n\nThe 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.\n\n## Running RISC-V 32 assembly in our virtual computer\n\nThe guest's entry point:\n\n``` bash\n$ r2 -q -c 'e asm.arch=riscv; e asm.bits=32; pd 6 @ 0x8008000c' whoami.rv\n0x8008000c      auipc gp, 0x7ff80\n0x80080010      addi gp, gp, 2036\n0x80080014      mv a0, sp\n0x80080018      auipc a1, 0x7ff80\n0x8008001c      addi a1, a1, -24\n0x80080020      andi sp, sp, -16\n```\n\n`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`.\n\nExecuting a program is that cycle repeated: decode the word at `pc`, update the state. 17,664 iterations run `whoami`.\n\nThe core of mini-rv32ima:\n\n```\nir = MINIRV32_LOAD4(ofs_pc);\nuint32_t rdid = (ir >> 7) & 0x1f;\n\nswitch (ir & 0x7f) {\ncase 0x37: /* LUI  */ rval = (ir & 0xfffff000); break;\ncase 0x17: /* AUIPC */ rval = pc + (ir & 0xfffff000); break;\ncase 0x6f: /* JAL  */ ...\ncase 0x13: /* OP-IMM */ ...\n...\n```\n\nThe 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`.\n\nEvery 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.\n\nA 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.\n\nFetch 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:\n\n``` php\nif (state->pc == RV_TRAP_PC) {\n    rv_set_err_hex(rv_trap_name(state->mcause), state->mepc);\n    return -1;\n}\n```\n\nThe guest gets an error string with cause and PC; the agent keeps running. A guest whose `go()` executes `.word 0`:\n\n```\n$ ./core/modules/rvvm/tools/rvvmrun /tmp/trap.rv\nrvvmrun: illegal instruction at 0x80080068\nrvvmrun: 0x80080068 is go+0x10\n```\n\nThe runner keeps symbols, so the address becomes `go+0x10`. In the agent the same string is the job error.\n\nThe 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).\n\n# What good is a VM if all it does is compute numbers?\n\nMost 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`.\n\n## Ask the host to do the job\n\nA 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.\n\nOn 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`.\n\nmusl registering the thread ID:\n\n`96` is `set_tid_address`; `ecall` is the trap.\n\nInside 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.\n\nThe guest runs in machine mode (`extraflags` is 3), so the cause is 12 and the post-exec hook handles it before the trap vector:\n\n```\n/* Guest ECALL: a7 is the Linux syscall number. */\nstatic void rv_host_postexec(struct MiniRV32IMAState *state, uint32_t *pc,\n                             uint32_t ir, uint32_t *trap) {\n    if (*trap != 12)\n        return;\n    int64_t result = rv_guest_syscall(\n        state->regs[17], state->regs[10], state->regs[11], state->regs[12],\n        state->regs[13], state->regs[14], state->regs[15]);\n    state->regs[10] = (uint32_t)result;\n    state->regs[11] = (uint32_t)(result >> 32);\n    *trap = 0;\n    *pc += 4;\n}\n```\n\n`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.\n\n`rv_guest_syscall` is a switch over the number:\n\n```\ncase RV_SYS_SET_TID_ADDRESS:\n    return getpid();\ncase RV_SYS_BRK:\n    ...\n    if (want <= RV_MAP_BASE)\n        rv_heap_cur = want;\n    return rv_heap_cur;\ncase RV_SYS_MMAP:\ncase RV_SYS_MMAP2: {\n    uint32_t p = rv_guest_mmap(a1);\n    return p == 0 ? -ENOMEM : (int64_t)p;\n}\ncase RV_SYS_EXIT:\ncase RV_SYS_EXIT_GROUP:\n    rv_guest_status = (int)a0;\n    rv_stopped = 1;\n    return 0;\n```\n\nThe 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\").\n\nThe same switch in gdb, right before the host's `getpid()`:\n\n`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`.\n\nPointers 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.\n\nEvery syscall a guest makes can be printed:\n\n```\n$ ./core/modules/rvvm/tools/rvvmrun -t /tmp/pwd.rv\n[rv] set_tid_address a0=0x8008c2c4 a1=0x00000000 a2=0x00000002 a3=0x8008c350 a4=0xfffffff8 a5=0x00000000 = 1492268\n[rv] getcwd a0=0x83bffec0 a1=0x000000ff a2=0x000000ff a3=0x00000010 a4=0x00000000 a5=0x00000002 = 255\n[rv] writev a0=0x00000001 a1=0x83bffd14 a2=0x00000002 a3=0x00000005 a4=0x83bffd50 a5=0x8008c210 = 5\n[rv] writev a0=0x00000001 a1=0x83bffe54 a2=0x00000002 a3=0x00000000 a4=0x8008c3e4 a5=0x8008c210 = 1\n[rv] exit_group a0=0x00000000 a1=0x00000000 a2=0x00000002 a3=0x00000000 a4=0x8008c3e4 a5=0x8008c210 = 0\n[rv] 3485 guest instructions, exit status 0\n```\n\n`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.\n\n## The gate is also an API\n\nLinux 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:\n\n| Number | Name | What it does | \n|---|---|---|\n| `0x40000001` | `ReadFile` | read a file into guest memory | \n| `0x40000002` | `WriteFile` | write guest memory to a file | \n| `0x40000004` | `UploadFile` | push a file to the C2 | \n| `0x40000005` | `Sha256Hex` | hash a guest buffer | \n| `0x40000006` | `RelaySocket` | hand a connected socket to the agent's relay | \n| `0x40000007` | `ExecCmd` | run a command on the agent, output in guest memory | \n\nThe BOF calls ordinary C wrappers from the guest shim, the entry code every guest is linked with:\n\n``` js\nint ReadFile(const char *path, unsigned char **out, unsigned long *len,\n             char *err, int err_cap) {\n  long need = syscall(RV_SYS_XFER_READ, path, NULL, 0);\n  unsigned char *buf = malloc(need > 0 ? (size_t)need : 1);\n  long got = syscall(RV_SYS_XFER_READ, path, buf, (unsigned long)need);\n  ...\n}\n```\n\nWithout 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.\n\n# Is it a BOF?\n\nThe 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.\n\nOn 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.\n\nRV32 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.\n\nThe files the C2 sends are complete programs: static RV32 images with their own libc. A BOF object is not one.\n\n## Why not? What's wrong with a BOF?\n\nA 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.\n\nIn 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:\n\n``` bash\n$ file whoami.rv\nwhoami.rv: ELF 32-bit LSB executable, UCB RISC-V, soft-float ABI, version 1 (SYSV),\n  statically linked, not stripped\n\n$ readelf -h whoami.rv\n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Type:                              EXEC (Executable file)\n  Machine:                           RISC-V\n  Entry point address:               0x8008000c\n  Number of program headers:         7\n\n$ readelf -l whoami.rv\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  LOAD           0x001000 0x80080000 0x80080000 0x0000c 0x0000c RW  0x1000\n  LOAD           0x00100c 0x8008000c 0x8008000c 0x0aa60 0x0aa60 R E 0x1000\n  LOAD           0x00ba6c 0x8008aa6c 0x8008aa6c 0x01844 0x01844 R   0x1000\n  LOAD           0x00d2b0 0x8008c2b0 0x8008c2b0 0x00098 0x04654 RW  0x1000\n```\n\nFour `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.\n\nThe first segment is 12 bytes at `0x80080000`: the `.rvhdr` argument handoff.\n\n```\nstruct rv_hdr {\n  char *args;\n  int len;\n  char **env;\n};\nstruct rv_hdr rv_bof_hdr __attribute__((section(\".rvhdr\"), used));\n```\n\nThe 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)`.\n\nThe 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.\n\nA 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.\n\n## Loading the image\n\n`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.\n\n```\nfor (uint16_t i = 0; i < phnum; i++) {\n    if (rv_le32(ph) != RV_PT_LOAD)\n        continue;\n    uint32_t vaddr  = rv_le32(ph + 8);\n    uint32_t filesz = rv_le32(ph + 16);\n    uint32_t memsz  = rv_le32(ph + 20);\n    ...\n    uint8_t *dst = rv_ram + (vaddr - RV_RAM_BASE);\n    rv_memzero(dst, memsz);\n    rv_memcpy(dst, image + off, filesz);\n}\n```\n\nThe heap starts at the page-aligned end of the image; the argument block goes in at the top of the arena.\n\nThe stack is the part that breaks. `_start` takes no arguments; it reads them from the stack the kernel normally builds:\n\n``` php\nsp -> argc\n      argv[0] ... argv[n-1]\n      NULL\n      envp[0] ... envp[n-1]\n      NULL\n      AT_PHDR, value\n      ...\n      AT_NULL\n```\n\nmusl 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.\n\n```\nRV_AUX(3, phdr_addr);  /* AT_PHDR */\nRV_AUX(4, phent);      /* AT_PHENT */\nRV_AUX(5, phnum);      /* AT_PHNUM */\nRV_AUX(6, 4096);       /* AT_PAGESZ */\nRV_AUX(7, 0);          /* AT_BASE */\nRV_AUX(9, entry);      /* AT_ENTRY */\nRV_AUX(11, getuid());  /* AT_UID */\nRV_AUX(25, rnd);       /* AT_RANDOM */\nRV_AUX(0, 0);          /* AT_NULL */\n```\n\n`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.\n\nThe runner prints the layout:\n\n```\n$ ./core/modules/rvvm/tools/rvvmrun -v /tmp/pwd.rv\nimage: pwd.rv (118348 bytes)\n  entry: 0x8008000c (_start+0x0)\n  .rvhdr: 0x80080000 (12 bytes)\n  program headers: 7\n    PT_LOAD vaddr=0x80080000 filesz=12 memsz=12\n    PT_LOAD vaddr=0x8008000c filesz=43564 memsz=43564\n    PT_LOAD vaddr=0x8008aa38 filesz=6104 memsz=6104\n    PT_LOAD vaddr=0x8008c210 filesz=152 memsz=17972\n  arguments: 0, block 4 bytes (00000000)\n  environment: 99 entries, 4828 bytes\nrvvmrun: 6 output bytes, guest exit status 0\n/tmp\n```\n\nEntry `0x8008000c`, `.rvhdr` at `0x80080000`, `bss` 152 bytes on disk and 17,972 in memory, 99 environment entries from the agent, six bytes of output.\n\n# The life cycle of a whoami BOF\n\n**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:\n\n``` bash\n$ zig cc -target riscv32-linux-musl -mcpu=generic_rv32 -O2 -g0 -fno-pic \\\n    -mno-relax -msmall-data-limit=0 -fno-asynchronous-unwind-tables \\\n    -fno-unwind-tables -fno-builtin -fno-stack-protector -fno-sanitize=all \\\n    -I includes -c -o whoami.rv.o whoami.c\n```\n\nThe same recipe builds the rest of `SA_linux`, which comes from TrustedSec's Linux BOFs: process listing, file reads, `ifconfig`, `find`, `cat`.\n\nThe 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.\n\n``` bash\n$ zig build-exe -target riscv32-linux-musl -mcpu=generic_rv32+a -static \\\n    -O ReleaseSmall -fno-entry -fstrip -lc -T guest.ld \\\n    main.c whoami.rv.o -femit-bin=whoami.rv\n```\n\nTwo artifacts go to the agent: `rvvm_linux.<arch>.gz` and `whoami.rv`. The module stays a normal `coff` module.\n\n**Run, on the agent.** `memmod` (Go) or `elfload` (C) maps the interpreter from memory and calls it once:\n\n``` js\nchar *Run(const uint8_t *image, size_t len, const struct rv_bof_args *args);\n```\n\n`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.\n\nThis 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`:\n\n**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)`.\n\nTLS 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.\n\nThe 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.\n\nEvery 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.\n\n**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.\n\nLocal run, no agent involved:\n\n``` bash\n$ make -C core/modules/rvvm/tools\n$ ./core/modules/rvvm/tools/rvvmrun build -o /tmp/whoami.rv \\\n    core/modules/SA_linux/SA/src/whoami.rv.o\n$ ./core/modules/rvvm/tools/rvvmrun /tmp/whoami.rv\nUID: 1000 EUID: 1000\n\nCurrent Working Directory: /tmp\n\nRunning as a standard user.\n```\n\nAnd with a debugger:\n\n``` bash\n$ gdb --args core/modules/rvvm/tools/rvvmrun /tmp/whoami.rv\n(gdb) break rv_guest_syscall\n(gdb) break rv_run_state\n```\n\nThe 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.\n\nSizes and counts from this build:\n\n| Artifact | Size | Guest instructions | Syscalls | \n|---|---|---|---|\n| `rvvm_linux.so` | 33,992 B | n/a | n/a | \n| `whoami.rv` | 118,524 B | 17,664 | 15 | \n| `pwd.rv` | 118,348 B | 3,485 | 5 | \n\n`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`.\n\nThe guest is RV32 and only the interpreter is host code, so the same image runs on every agent architecture.\n\n# Limitations\n\n**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.\n\n**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.\n\n**Single thread, no fork.** The interpreter keeps one `MiniRV32IMAState` in file scope: one register file, one `pc`, one stack pointer. Supporting threads would need:\n\n- a state struct, a stack and a `tp` (thread pointer) per thread, because each thread needs its own TLS block for`errno` and the allocator;\n- a scheduler and a timer tick, so the interpreter can switch threads; today it runs until the guest exits;\n- `clone` (create a task from the caller, with flags deciding what is shared; a thread shares the address space) and`futex` (fast userspace mutex: a lock that spins in user space and only enters the kernel to sleep or wake) semantics, and`ppoll` (poll with a signal mask) must wake one thread instead of blocking the run;\n- guest atomics (load-modify-store operations that cannot interleave) mapped to host atomics, since `RV32A` is the extension that provides them;\n- locking in the gate, because host descriptors and the output buffer would be shared.\n\nThat 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`.\n\n**RV32IMA only.** Nothing beyond it is implemented. `mprotect` succeeds and does nothing, and a JIT inside the guest is impossible.\n\n**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.\n\n**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.\n\n**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.\n\n# What the host sees\n\nThe 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.\n\nSo 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.\n\nThe 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.\n\nWhat 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.\n\nThose 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.", "url": "https://wpnews.pro/news/linux-c2-from-scratch-0x01-virtualising-your-malware", "canonical_source": "https://jm33.me/linux-c2-from-scratch-0x01-virtualising-your-malware.html", "published_at": "2026-11-28 12:51:30+00:00", "updated_at": "2026-11-28 13:12:29.038573+00:00", "lang": "en", "topics": ["ai-safety"], "entities": ["jm33", "Ruxmon", "emp3r0r", "RV32IMA", "Linux", "Beacon Object File"], "also_reported_by": [], "takeaway": "Running guest payloads in a 64 MiB PROT_READ | PROT_WRITE arena interpreted by rvvm_linux.so avoids any executable mapping, since mprotect returns success without effect and mmap only hands out more RW arena memory.", "recommendation": {"advice": "If you need to execute untrusted or generated code without an executable mapping, interpret it in a read-write arena and accept orders-of-magnitude slowdown; the source shows mprotect silently no-ops and mmap only extends the RW arena.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/linux-c2-from-scratch-0x01-virtualising-your-malware", "markdown": "https://wpnews.pro/news/linux-c2-from-scratch-0x01-virtualising-your-malware.md", "text": "https://wpnews.pro/news/linux-c2-from-scratch-0x01-virtualising-your-malware.txt", "jsonld": "https://wpnews.pro/news/linux-c2-from-scratch-0x01-virtualising-your-malware.jsonld"}}