User-mode network gateway (SLIRP / vpnkit) in pure OCaml
README.md

slirp #

A user-mode network gateway for virtual machines and unikernels, in OCaml, with an I/O-free core.

A virtual machine started by an unprivileged user still needs a network. The usual answers are a bridge or a tap device wired into the host's routing table, both of which need root, or a user-mode gateway in the style of SLIRP, moby/vpnkit (Docker Desktop) and passt, which terminates the guest's connections and re-opens them as ordinary host sockets. slirp is such a gateway. It hands the guest an address (DHCP on IPv4, SLAAC on IPv6), answers its ARP and Neighbor Discovery, resolves its names, and forwards its TCP, UDP and ICMP echo traffic through host sockets, with no change to the host routing table and no root. SLAAC (stateless address autoconfiguration, RFC 4862) lets an IPv6 host build its own address from a prefix that a router advertises plus an interface identifier, and Neighbor Discovery (RFC 4861) is IPv6's counterpart of ARP, done with ICMPv6 Neighbor Solicitation and Advertisement messages; the gateway plays the router and the neighbour in both.

Installation #

Install with opam:

$ opam install slirp

If opam cannot find the package, it may not yet be released in the public opam-repository. Add the overlay repository, then install it:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install slirp

Design #

The core does no I/O. It is a state machine: handle takes the current state and one input, such as a guest Ethernet frame or data from a host socket, and returns the next state with the effects to perform: frames to send to the guest and host sockets to open or write. The Eio adapter, slirp-eio, supplies the guest frame transport (an Apple Virtualization.framework device, a Solo5 net device or a tap flow) and the host sockets, so the core can be tested in memory with no device present. Two sublibraries sit on top of it: slirp-eio.gateway holds the startup shared by in-process VM launchers, and slirp-eio.sqlite renders a snapshot of the gateway's NAT tables into a SQLite database, so the running gateway can be queried in SQL.

The protocol codecs come from existing packages: nox-ethernet, nox-arp, nox-ip, nox-udp and nox-tcp.

Usage #

# let gw, _ = Slirp.v ~now:(Mtime.of_uint64_ns 0L) (Slirp.Config.v ()) in
  Ipaddr.V4.to_string (Slirp.gateway_ip gw)
- : string = "192.168.65.1"

v returns the gateway together with the frames to emit at once: a gratuitous ARP and the initial IPv6 Router Advertisement. Supply the same monotonic clock domain at construction and each handle call. Wait for next_deadline or a new input; ordinary inputs also service due timers before handling the input. The core owns neighbour epochs and advertisement placement across executor shards.

Features #

The gateway answers the guest's ARP requests for itself and leases it an IPv4 address over DHCP. It terminates the guest's TCP connections and splices each one to a host socket, NATs UDP to host sockets, forwards DNS to an upstream resolver, and NATs ICMP echo through an unprivileged datagram socket, so the guest can ping out. The echo's 16-bit sequence number is the NAT's correlator: each request takes the next value in turn, so an unanswered flood displaces only the oldest outstanding requests and never refuses a later echo. Host services can be published into the guest on the gateway address (tcp_forwards), and host ports forwarded to guest ports. A guest UDP datagram whose checksum fails is discarded (RFC 1122 section 4.1.3.4), as is one with a zero checksum over IPv6 (RFC 8200 section 8.1).

The gateway answers DNS on port 53 over UDP and over TCP (RFC 7766 section 5), so a guest that retries a truncated UDP answer over TCP gets it whole. It queries its upstream over UDP only.

On IPv6 there is no DHCPv6 and no ARP. The gateway answers the guest's Neighbor Solicitations (RFC 4861), and its Router Advertisements give the guest an on-link prefix for SLAAC (RFC 4862) and a DNS server (RFC 8106 RDNSS); it also re-advertises unprompted, for a guest that missed the reply. Outbound TCP, UDP and ICMPv6 echo are NATed as on IPv4, over one flow table keyed on the address family, and inbound forwarding finds the guest by Neighbor Solicitation.

An accepted host TCP connection is admitted against the same flow limit before ARP or Neighbor Discovery starts, and one past it is closed at once; a connection reset while its guest address resolves opens nothing when the resolution arrives. The gateway owns how far each host socket is read: a socket starts with no read window, so the edge reads nothing until the flow can carry host bytes to the guest (its host socket is up and its guest connection established), when Tcp_window opens host_window bytes (4 MiB by default), and every guest acknowledgement returns its bytes. Host bytes in the gateway and the edge together are therefore bounded by host_window times the flow limit, whatever a host peer sends. The other direction holds nothing before its host socket is up: the gateway answers a guest's SYN only once the host socket has connected, with its SYN-ACK, or with a reset when the connect fails, so the guest has no window to send into until the host can take its bytes.

Inbound UDP endpoints are admitted against the pure flow limit before ARP or Neighbor Discovery starts. Each admitted endpoint retains at most one ordinary IP datagram while its guest address resolves; additional pending datagrams are tail-dropped. Resolution delivers that first datagram, and 60 seconds of inactivity releases the endpoint, pending body and reserved gateway port. Within the pure state, a flow limit F bounds unresolved UDP bodies to F * 65,527 bytes (the IPv4 ceiling is 65,507); endpoint records are also bounded by F. Snapshots expose pending_bytes separately from delivery. Replies carry the listener port and original peer address in Udp_forward_to; the IO adapter retains bound sockets without per-peer tables. The limit bounds UDP flow retention; it does not promise delivery when address resolution fails.

The guest transport can be a device file descriptor carrying one frame per datagram (Slirp_eio.transport_of_fd, the host side of an Apple Virtualization.framework file-handle device), a tap or other two-way flow (transport_of_flow), or a Solo5 net device (transport_of_netif).

Egress is default-deny for every destination that is not public, since the guest is an untrusted tenant or build step: loopback and "this network", link-local with its metadata endpoints, RFC 1918, RFC 6598 shared address space, RFC 4193 unique local addresses, multicast, the reserved IPv4 block and IPv4-mapped IPv6 (Slirp.default_egress_deny). So are the host's own interface addresses and the networks on their links, whatever their class: a server or a cloud VM with a public address is otherwise reached at it, with every service it binds to the wildcard address. Slirp_eio.run reads them with Eio_net_unix.Interface as it starts and again on each change the kernel reports; where the host refuses that watch, as a macOS sandbox refuses PF_ROUTE, it reads them again before it opens each flow they judge. The rule covers TCP, UDP and ICMP echo; a denied destination is reached only through an egress_allow prefix naming it, and the gateway's own addresses stay reachable for DNS and published services.

The gateway does not intercept HTTP the way vpnkit's proxy does, and the --pcap capture of the standalone slirp-gateway executable records every frame, with no filter. ICMP echo is forwarded outbound only, so a host cannot ping the guest.

Booting a VM through the gateway #

The vz launcher (macOS) backs a VM's virtio-net with one end of a datagram socketpair and runs the gateway over the other with transport_of_fd. The guest boots with ip=dhcp, leases its address from the gateway and reaches the network through ordinary host sockets, with no host routing change and no root:

vz -p 5201:5201 <kernel> [initrd]

-p HOST:GUEST publishes a TCP port into the VM, in Docker's notation; repeat it for several services. vz gives its single guest a fixed 192.168.65.2 lease, so every published port has a stable target.

vz defaults to an IP MTU of 65521, advertised to the guest by DHCP. With the 14-byte Ethernet header this fills, and does not exceed, the transport's 65535-byte frame envelope, and it matches the jumbo synthetic link Docker Desktop uses for host networking. Pass --mtu=1500 to measure conventional Ethernet instead.

macOS lets a process create a Virtualization.framework VM only when its binary is code-signed with the com.apple.security.virtualization entitlement, so the dune rule of the @integration test signs the test binary ad hoc (codesign --sign - with slirp-vz.entitlements) before running it. The test (test/integration/, macOS on Apple Silicon) boots a real linuxkit arm64 kernel with ip=dhcp, networked only through the gateway, and checks that the kernel's in-boot DHCP completes against it: a DISCOVER, then a REQUEST, which the kernel sends only once it has accepted the gateway's OFFER. Run it with:

dune build @test/integration/integration

Performance #

Three benchmarks isolate the tiers.

The gateway core alone (bench/bench.ml, with no sockets and no scheduler) segments a bulk TCP download and reports allocation per delivered byte; dune exec bench/bench.exe runs it. At the 1500-byte Ethernet MTU it sustains about 560 MiB/s. When the guest raises its MTU, which the gateway advertises with DHCP option 26, the same core does about 1960 MiB/s (16.4 Gbit/s) at 0.2 bytes allocated per byte delivered. Both figures come from an Apple Silicon laptop; the run did not record which chip.

The two figures fit a cost of c_f per segment plus c_b per byte, so the time per delivered byte is c_b + c_f / P for a TCP payload of P bytes. With P = 1460 at the 1500-byte MTU and P = 65,481 at the 65,521-byte one, the two points give c_f ≈ 1.8 µs per segment (building the headers, setting up the checksum, updating the flow table) and c_b ≈ 0.46 ns per byte (copying and checksumming the payload). At 1500 bytes the fixed cost is 73% of the total; at 65,521 bytes it is 6%, and the per-byte copy sets the ceiling of the core, about 1 / c_b ≈ 2.2 GB/s.

The device-fd edge (bench/edge_bench.ml, a real datagram socketpair through Slirp_eio.transport_of_fd, the path vz uses) gives the end-to-end ceiling:

frame size throughput round-trip
1514 B ~1 Gbit/s ~38 us
8974 B ~7 Gbit/s n/a
61454 B ~26-37 Gbit/s ~51 us

At the 1500-byte MTU the edge is bound by system calls at about 1 Gbit/s. Big frames cut the system calls per byte and take the edge to 26-37 Gbit/s, above the core, so with big frames the end-to-end ceiling is the gateway core.

The third, bench/vz_bench.sh, runs iperf3 in a VM on macOS through a VZCustomVirtioDevice edge. PROFILING.md says how to run it, how to read its counters and how to profile that path.

For comparison, at a similar 65520-byte MTU passt measures 19.6 Gbit/s guest-to-host and 19.2 host-to-guest over sockets, and 26.6 and 43.6 with vhost-user (passt's continuous benchmarks); slirp4netns reaches 9.21. The same stacks measure 1.07 (slirp4netns) and 4.7 (passt) at MTU 1500, so a figure means little without its MTU. vpnkit publishes no throughput figure; the one third-party measurement, slirp4netns's table, gives 514 Mbit/s at MTU 1500 (jumbo MTU unsupported) from a 2018 CI run.

Same-machine figures above about 50 Gbit/s deserve suspicion: several published numbers for macOS VM stacks are loopback transfers with segmentation offload, which exceed any wire rate and do not measure a gateway.

On features, the gateway matches the state of the art. IPv6 uses the same Neighbor Discovery and Router Advertisement (SLAAC) autoconfiguration as libslirp and vpnkit, with TCP, UDP and ICMPv6 echo NATed outbound and host-to-guest forwarding resolved by Neighbor Discovery inbound: the dual-stack feature set those implementations carry, in both directions. On throughput, the big-frame path already clears the range of libslirp and vpnkit and reaches passt's.

Untrusted input is fuzzed (fuzz/fuzz_slirp.ml): arbitrary and crafted frames, and sequences of them, must neither crash the handler nor make it emit a malformed frame to the guest.

Credits #

The design is adapted from the hostnet user-mode network stack of moby/vpnkit, reshaped around an I/O-free core.

Licence #

ISC. See LICENSE.md.