malbox: building a self-hosted malware sandbox
contents
malbox is an interactive malware sandbox i built over about two weeks in october 2026. you upload a file, it gets detonated in a fresh windows vm, and you get a report: process tree with command lines, registry and file activity, dns and http traffic, a pcap, memory dumps, yara and suricata hits, extracted malware configs, and a verdict. while it runs you can watch the vm's screen in the browser, and take control if the job allows it. it's live at malbox.neels.dev.
it ended up being around 362 commits, and most of what's interesting came from things breaking, so a lot of this post is about those.
why build one#
any.run, triage, and joe sandbox already exist and are good. but they're hosted, and the parts i wanted to understand (vm isolation, where telemetry comes from, how cleanup is guaranteed) are hidden. building one end to end was the most direct way to learn it, and it runs on my own hardware.
the pieces#
| component | language | job |
|---|---|---|
malboxd / malboxctl | go | node controller: vm lifecycle, network isolation, capture, api |
| backend + workers | go | public api, postgres queue, kafka consumers (yara, suricata, configs, verdicts) |
malbox-agent | rust | in-guest agent, cross-compiled to a windows .exe |
| config extractor | rust | static config parsers for malware families |
malboxmon.sys | c | windows kernel driver for process/registry/image telemetry |
| frontend | react + ts | submit page, report, live vnc |
| hosts | nix | all of it as nixos configs in one flake |
one job, end to end#
- the browser hashes the file, gets a presigned s3 url from the backend, and uploads directly to minio, so the backend never touches sample bytes. files over 80 MiB use multipart upload because cloudflare caps request bodies at 100 MB (a 147 MB sample found this).
- a finalize call checks the object exists and inserts a
queuedrow in postgres. - the execution node, when it has a free slot, claims the oldest matching job.
- the controller allocates a subnet, creates a bridge, installs nftables rules, starts dnsmasq and capture, creates a qcow2 overlay on a read-only golden image, and starts a libvirt domain named
malbox-<job-id>. - the guest agent connects over virtio-serial, receives the sample, and runs it.
- at the timeout, the controller stops the agent, collects dropped files, a screenshot, and a memory dump, then tears everything down.
- artifacts go to s3 and
artifact_readyevents go onto kafka for the workers.
the claim in step 3 is one query:
SELECT ... FROM jobs
WHERE state = 'queued'
AND profile = ANY($1)
AND network = ANY($2)
AND requirements <@ $3
ORDER BY submitted_at
FOR UPDATE SKIP LOCKED
LIMIT 1originally the backend pushed jobs to nodes using a free_slots value cached from heartbeats every ~5s, while the scheduler ticked every 500ms. bulk submits would see a stale free_slots=1 twice and put two jobs on a one-vm node. switching to a pull model fixed this properly: a node only asks for work when it actually has a slot.
vm and network isolation#
each job gets its own vm, its own linux bridge, and its own /24. the controller owns one nftables table, inet malbox, recreated from scratch on startup. guest traffic dispatches to a per-job chain through a verdict map keyed on the bridge name:
fmt.Fprintf(&b, "add chain inet %s fwd_%d\n", tableName, idx)
// Anti-spoofing: the guest may only use its assigned address.
fmt.Fprintf(&b, "add rule inet %s fwd_%d ip saddr != %s drop\n", tableName, idx, guest)
switch mode {
case api.NetInternet:
fmt.Fprintf(&b, "add rule inet %s fwd_%d ip daddr @host_blocked drop\n", tableName, idx)
fmt.Fprintf(&b, "add rule inet %s fwd_%d oifname \"%s\" accept\n", tableName, idx, m.cfg.WANInterface)
fmt.Fprintf(&b, "add rule inet %s fwd_%d drop\n", tableName, idx)
default:
// isolated and simulated: no forwarding off the bridge at all.
fmt.Fprintf(&b, "add rule inet %s fwd_%d drop\n", tableName, idx)
}
fmt.Fprintf(&b, "add element inet %s fwd_jobs { \"%s\" : jump fwd_%d }\n", tableName, br, idx)rulesets are applied atomically with nft -f -. on the input hook a guest can only reach dhcp, dns, and the fakenet ports, never ssh, the api, or libvirt. ipv6 from guests is dropped.
there are three network modes:
- isolated: dns is refused and nothing is forwarded.
- simulated: every name resolves to the gateway, and all other tcp/udp is dnat'd to small go listeners that log what the guest sends.
- internet: real egress through the wan nic, except anything in
host_blocked(private, loopback, link-local, cgnat, documentation, and multicast ranges, plus the host's own addresses). 80 and 443 also go through a per-job tls mitm proxy whose ca is baked into the image, so the report can show decrypted http bodies.
capture is af_packet on the bridge via gopacket, written to a pcap and decoded live into dns, flow, and http events. windows domains also hide the hypervisor cpuid bit and use a generic oem smbios identity with a randomized serial, since some samples exit as soon as they detect a vm.
cleanup guarantees#
the requirement i cared most about: a SIGKILL of malboxd mid-job leaves no vm, bridge, or firewall rule behind, and the job comes back as failed. there are three layers.
in the runner, teardown is deferred first so it runs last, and a second defer guarantees a terminal state even on panic:
// Teardown is unconditional. Deferred FIRST so it is the LAST thing
// to run.
defer r.teardown(domainName)
// (locking trimmed)
defer func() {
rec := recover()
if rec == nil {
if !r.job.State.Terminal() {
r.setState(api.StateFailed, "runner exited without terminal state")
}
return
}
if !r.job.State.Terminal() {
r.setState(api.StateFailed, fmt.Sprintf("runner panic: %v", rec))
}
panic(rec)
}()that does nothing against SIGKILL, so the second layer is systemd. helpers like dnsmasq live in the service cgroup and also get Pdeathsig:
serviceConfig = {
User = "malbox";
SupplementaryGroups = [ "libvirtd" "kvm" "qemu-libvirtd" ];
AmbientCapabilities = [ "CAP_NET_ADMIN" "CAP_NET_RAW" "CAP_NET_BIND_SERVICE" "CAP_DAC_READ_SEARCH" ];
# Helpers (dnsmasq) die with the controller; on restart it
# reconciles anything left in libvirt or the kernel.
KillMode = "control-group";
Restart = "always";
NoNewPrivileges = true;
ProtectSystem = "strict";
};the third layer is Recover() at startup: reinstall the nftables table, delete every mbx-* bridge, destroy every libvirt domain named malbox-*, and fail every non-terminal job with controller restarted. it doesn't need to know what was running before.
teardown had its own bugs. once it hung for over a minute in the volatility3 memory scan: vol3's python workers inherited the stdout pipe, so cmd.Wait kept waiting after the parent was killed. running it in its own process group, killing the group, and setting WaitDelay fixed it. separately, an 82-job archive burst had 14 jobs fail with qemu's Cannot allocate memory, because the slot was released when the job went terminal while teardown was still freeing the previous vm. now the slot is held until teardown finishes, and the node runs vm.overcommit_memory=1 with zram.
hot start#
a cold windows boot took about 90 seconds. so the controller boots each profile once to a ready state and saves it with virsh save. jobs restore from that with their own overlay and virtio socket swapped into the xml, and they're ready in about 5 to 7 seconds.
restores kept failing with Target domain uuid ... does not match source, because i never set a uuid and libvirt baked a random one into the save file. a deterministic uuid per profile fixed that, until two concurrent cold boots of the same profile collided on it. now restores use the profile uuid and cold boots use a per-job one. each snapshot also has a fingerprint (image size and mtime, controller version, uuid), and on any mismatch the job cold-boots instead.
the guest agent#
the agent is a rust binary cross-compiled with mingw. it talks to the host over virtio-serial, not the guest network, using a big-endian u32 length followed by a json object. the controller treats everything from the guest as hostile: sizes and rates are bounded, guest strings are never used as host paths, and stored files are re-hashed on the host. pcap, screenshots, and memory dumps are collected host-side, so they still work if the agent is killed.
keeping the channel alive on windows took a few tries. a synchronous windows file handle serializes reads and writes on the same file object, even across duplicated handles, so a blocked read starved the agent's heartbeat writes. the fix was a host-driven heartbeat: the host pings every 5 seconds, and the agent is one thread that only writes right after a read returns. startup had a similar saga with a separate loader that spawned the agent, which i ended up deleting. now the agent is baked into the image and runs at boot as SYSTEM, because the virtio-serial device's acl only grants SYSTEM.
telemetry sources implement a trait, and the agent composes them at startup:
let (driver, etw) = if crate::driver::available() {
(Some(crate::driver::DriverSource::new()), crate::etw::EtwSource::new_image_only())
} else {
(None, crate::etw::EtwSource::new())
};alongside these are etw sources for file, network, mutex, and dns events, all scoped to the sample's process subtree. one bug: a non-zero etw MatchAnyKeyword mask is a filter, and the kernel-network provider emits many events with no keyword bits, so my network source was dropping most of its own events. passing 0 and filtering by event id fixed it.
why a kernel driver#
the etw process provider i was using didn't give command lines, and for malware cmd /c whoami & ping ... says a lot more than cmd.exe. a kernel process-notify callback gets the command line directly, so i wrote malboxmon, a small observation-only driver:
static VOID MbxProcessNotify(PEPROCESS Process, HANDLE ProcessId,
PPS_CREATE_NOTIFY_INFO CreateInfo)
{
MBX_EVENT ev;
UNREFERENCED_PARAMETER(Process);
RtlZeroMemory(&ev, sizeof(ev));
ev.Pid = (unsigned int)(ULONG_PTR)ProcessId;
if (CreateInfo != NULL) {
ev.Type = MBX_EV_PROC_START;
ev.Ppid = (unsigned int)(ULONG_PTR)CreateInfo->ParentProcessId;
ev.ImageLen = MbxCopyUnicode(ev.Image, MBX_IMAGE_WCHARS, CreateInfo->ImageFileName);
ev.CmdLen = MbxCopyUnicode(ev.Cmd, MBX_CMD_WCHARS, CreateInfo->CommandLine);
/* Extend the tracked subtree: a child of a tracked process is tracked. */
if (MbxTrackContains(ev.Ppid)) {
MbxTrackAdd(ev.Pid);
}
} else {
ev.Type = MBX_EV_PROC_EXIT;
}
MbxPush(&ev);
}events are fixed-size records in a spinlock-protected ring buffer. when it's full the oldest record is overwritten and a drop counter increments. the agent drains it with IOCTL_MBX_DRAIN every 100ms and reads fields at fixed offsets. it also seeds the sample's pid with IOCTL_MBX_SET_ROOT. process start/exit is reported system-wide, while registry writes, image loads, cross-process thread creation (an injection signal), and process handle opens are only reported for the tracked subtree.
i wanted the driver to cross-compile on linux inside nix. clang-cl plus lld-link with wdk headers from nuget built a .sys the kernel refused with STATUS_CONFLICTING_ADDRESSES, since lld doesn't really support /DRIVER. the mingw gnu toolchain that already built the agent worked:
x86_64-w64-mingw32-gcc -std=gnu11 -O2 -municode -ffreestanding \
-nostartfiles -nostdlib -nodefaultlibs -I${ddk} -I. \
-c malboxmon.c -o malboxmon.o
x86_64-w64-mingw32-ld \
--exclude-all-symbols --gc-sections --dynamicbase --nxcompat --forceinteg \
--subsystem=native --file-alignment=0x200 --section-alignment=0x1000 \
--image-base=0x140000000 --stack=0x100000 --entry=DriverEntry \
-o malboxmon.sys malboxmon.o -L${libdir} -lntoskrnl -lhal--forceinteg is required because PsSetCreateProcessNotifyRoutineEx won't register without the force-integrity flag. the derivation signs the driver with a throwaway test cert, and the image runs with test-signing on and secure boot off. the first test drained 75 process events with full command lines.
the analysis pipeline#
everything after the vm goes through kafka: one topic, events, 32 partitions keyed by job_id so each job's events stay ordered. each worker is a separate go binary in its own consumer group:
- persistence writes states, artifacts, hits, and configs to postgres.
- yara-workers scan every artifact with yara-x using a ruleset precompiled at nix build time.
- suricata-workers run et open rules over each job's pcap.
- config-extractors run the cape community parsers through maco, plus my rust crate with 42 family extractors.
- verdict-scorer combines yara hits and configs into a score and label.
- events-unpacker loads telemetry into postgres.
the bus went from redis streams to redpanda to kafka over two days. telemetry doesn't go through kafka directly. the controller writes it to s3 in gzipped 5-second chunks and publishes a small artifact_ready for each one, and the unpacker batch-inserts them idempotently.
each rust extractor implements one trait:
pub trait Extractor: Send + Sync {
fn name(&self) -> &'static str;
/// `Ok(None)` is a miss, not an error.
fn extract(&self, bytes: &[u8]) -> Result<Option<Finding>, ExtractorError>;
}some extractors, like ones that decrypt at a fixed offset, produce plausible garbage on almost any pe, so they're excluded from the default registry and only run when yara already points at that family. the verdict scorer is simple: +50 for a yara rule matching a family keyword, +10 for other hits, capped at 100. early on, the controller's terminal "benign" verdict overwrote the scorer's family label, so the store now merges verdicts by max score instead of last write.
frontend and the live view#
the frontend is react and typescript, built with vite and bun. the report shows the process tree, network flows with suricata badges and a hex view, http bodies, extracted configs, third-party intel lookups, and a replay video stitched from screenshots.
the live view is novnc. qemu's vnc server only listens on a unix socket. the browser gets a 60-second hs256 ticket, connects to the backend through the cloudflare tunnel, and the backend forwards to the node, which checks the ticket again. in view mode the node drops client messages that change guest state:
// First byte of each client-to-server RFB message. See RFB 6.4:
// 3 FramebufferUpdateRequest ← NOT input, must forward in view mode
// 4 KeyEvent ← drop in view mode
// 5 PointerEvent ← drop in view mode
// 6 ClientCutText ← drop in view mode (paste from client)
func isClientInputMessage(b byte) bool {
switch b {
case rfbKeyEvent, rfbPointerEvent, rfbClientCutText:
return true
}
return false
}the first version had these off by one (3/4/5), which dropped FramebufferUpdateRequest, so the viewer was a black canvas over a healthy websocket. control mode is a raw passthrough, only for the signed-in submitter on jobs that enabled input.
deployment#
it's one nix flake with three nixos configs, running as incus instances on my homelab:
- execution node: an incus vm with nested kvm running
malboxdand libvirt. 6 vcpus, 15 GiB of ram, 2 analysis vms at a time. - control plane: an lxc container with the backend, postgres, kafka, the workers, and
cloudflared. - object storage: an lxc container running minio behind its own tunnel.
secrets come from sops-nix and are read at service start. the windows 11 and windows 10 golden images are also nix derivations, built in layered stages on top of an upstream unattended-install project. the image build took more commits than anything else (bcd entries that wouldn't boot, the "press any key to boot from cd" prompt, installing .net 3.5 offline), and it's covered in the homelab post.
what's left#
- file events still come from etw. a minifilter would be better, but mingw doesn't ship the
fltMgrimport library. - five more agent sources (threat-intelligence etw, amsi, clipboard, rwx memory scanning, windows) are written but disabled until i validate them in a guest.
- vm hiding only covers the easy tells. virtio pci ids, acpi tables, and timing would need a patched qemu.
- the verdict scorer should be weighted rules, not a keyword list.
- there's one execution node. the claim query already matches by profile, network, and capabilities, so a second node should mostly be deployment work.
questions or corrections? email me.