My knowledge of low-level TCP/IP networking is a bit of a fog, with a few clear patches and plenty of dark ones. I get the big picture, but there are a ton of details I don’t know. For instance, I’m hazy on how routing works on the internet beyond a local network, BGP and all that, or even what an Ethernet frame looks like (I just looked it up because I thought they were called datagrams).

As far as I’m usually concerned, a TCP connection is a stream of data between two endpoints, each identified by an IP address and a port. The two million layers underneath that get my data to the other side often go over my head.

The main reason is simply that there aren’t enough hours in the day. But another reason is that you rarely have to worry about those layers. The implementations seem pretty much bulletproof. And because they usually ‘just work’, there’s not much reason to go chasing rabbits down holes. Besides, on Linux the code that normally handles these protocols lives in kernel space, so the rabbit hole goes fairly deep. In my entire life, I might have touched one line of code down there, or none (hint: none, it’s none).

Anyway, whenever I run into something about networking that I don’t get, I try to fill in a few gaps. I reckon that by the time I retire and no longer need to know any of this, I’ll finally have understood all those layers.

Grampa Simpson talking
Me explaining the difference between BGP and IGPs

1. Background

Recently I ran into a problem that required me to get into the weeds of TCP/IP. This didn’t come out of nowhere: I’m not the kind of person who wakes up on a Saturday morning and decides to write a user-space TCP/IP stack in Rust.

There was a real problem behind it: we wanted our agent to stop needing elevated privileges to bring up WireGuard tunnels. But what did we use WireGuard tunnels for? Why did we need privileges? And why did we want to stop needing them? I hope to answer all three questions in this first part.

Before getting into the details, I’ll explain why we needed this, how WireGuard works at a high level, and how we used it at Kittengrid. Then I’ll lay out the problem in more detail. In Part II, I’ll focus on the implementation with smoltcp and walk through different pieces of the library step by step.

2. Kittengrid Agent

Kittengrid lets users spin up preview environments for their pull requests. Each environment can expose several services, and we generate a URL for each one.

There are two distinct sides here. On one side is the user’s environment, which might be on a CI runner or somewhere else. Their applications keep running there: we don’t move them onto our own infrastructure. On the other side are our systems, which manage access and route traffic to the right service.

To connect the two sides, we run an agent inside each user environment. The agent starts and manages the services, registers them with our infrastructure, and establishes a WireGuard tunnel to our systems. That tells us which services are available and gives us a way to get traffic to them.

Traffic flows from the browser to the runner's services, with kernel-space WireGuard on Kittengrid's side and a user-space agent using TUN on the runner

The diagram simplifies the path a request takes when a user opens one of those URLs in their browser, once the service is up and configured. Our load balancer identifies the internal destination IP and routes the traffic to the right runner through the WireGuard tunnel.

In our original architecture, our end of the tunnel used the Linux kernel’s WireGuard implementation for performance. On the runner, WireGuard ran inside the agent in user space, and we used a TUN interface. You don’t need to understand every detail in the diagram yet; that’s what the next few sections are about.

3. The problem

This approach had one big drawback: our agent needed CAP_NET_ADMIN to bring up the TUN interface.

At first, this was a minor issue because users typically already have the necessary privileges in CI. It became a problem when we wanted to let people spin up those same environments locally to expose services or development environments.

In that setting, requiring administrator privileges seemed unnecessary and likely to get in people’s way. I wouldn’t use a solution that asked me to run sudo just to start a TCP proxy. That’s what led us to look for an alternative that got rid of TUN and moved all this logic into user space. The diagram below shows what we were aiming for.

Target architecture: the agent acts as a user-space proxy without a TUN interface

What I hadn’t seen coming was that TUN didn’t just give us an interface: it was how we handed IP packets to the kernel so it could take care of TCP. If we got rid of TUN, someone else had to do that work. To see who does it in each case, let’s start with the thing we didn’t want to get rid of: WireGuard.

4. WireGuard

WireGuard lets you connect two or more peers across an untrusted network, using UDP to carry IP packets securely.

What sets WireGuard apart is that you don’t need a PhD in networking to set it up. Alternatives like IPsec/IKE and OpenVPN are much more complicated.

WireGuard tries to strip the problem down to its essentials. Its cryptographic design uses a fixed set of algorithms, and distributing the peers’ public keys is left outside the protocol. To me, that separation is what it gets most right. We already have plenty of ways to manage configuration, so we can distribute those keys ourselves instead of asking the VPN to do it for us. We’ve already got a hammer for that: Kubernetes, Ansible, or that little Bash script nobody dares touch.

Back to how it works: WireGuard encrypts and encapsulates IP packets to send them over UDP, then decrypts and delivers them at the other end. That’s what we call a tunnel: one protocol carries another. The IP packets you send through one peer’s interface show up at the other peer’s interface as though they came over an ordinary network, but it’s UDP doing the carrying underneath.

Magic

Think of a tunnel as a virtual network cable connecting an interface on server A to an interface on server B, using another protocol.

4.1 How the protocol works

First, let’s put names to the two machines in the diagrams. A is the Kittengrid server and B is the machine running the agent, say a CI runner. The service we want to reach is on B.

Picture a regular network interface like eth0, with a physical network card and an Ethernet cable plugged into a switch or whatever. Now imagine each machine also has a virtual interface called wg0. To an application, it’s just another interface: it has its own IP address and can show up in the routing table. Underneath, the tunnel traffic still travels over the physical network.

In WireGuard terms, A and B are the two peers in our example. Each has a key pair, keeps its own private key and knows the other’s public key. During a thing called a handshake, they authenticate each other and derive the symmetric keys they’ll use to encrypt traffic (a bit like TLS; see the note). A single WireGuard interface can have several peers configured, but we only need one at each end.

Let’s look at a WireGuard configuration to see how this would work in practice. Suppose A is reachable over the internet on UDP port 51820 and we want to use 10.0.1.0/24 inside the tunnel. A gets 10.0.1.1 and B gets 10.0.1.2. With wg-quick (a WireGuard configuration tool), A’s wg0.conf would look like this:

# I'm A, and this is how my wg0 is set up.
[Interface]
Address = 10.0.1.1/24
PrivateKey = A_PRIVATE_KEY
ListenPort = 51820
# To talk to B, I need its public key.
[Peer]
PublicKey = B_PUBLIC_KEY
AllowedIPs = 10.0.1.2/32

And on B we’d have this:

# I'm B, and I let WireGuard pick my port. That's just how I am.
[Interface]
Address = 10.0.1.2/24
PrivateKey = B_PRIVATE_KEY
[Peer]
PublicKey = A_PUBLIC_KEY
AllowedIPs = 10.0.1.1/32
Endpoint = A_PUBLIC_IP:51820

Only A’s UDP port 51820 needs to be reachable over the internet. B doesn’t expose a port to the outside.

There are two addresses here that are easy to mix up. From B we use 10.0.1.1 to talk to A inside the tunnel. Endpoint, on the other hand, tells WireGuard which public IP and UDP port to send datagrams to over the internet. AllowedIPs maps internal IPs to peers. On the way out, WireGuard checks the destination IP to choose a peer. On the way in, it checks that the peer is allowed to send from the source IP in the decrypted packet.

So how does A know where B is if it has no Endpoint for B? In this example, B makes the first move. If we run ping 10.0.1.1 on B, WireGuard has traffic to send and starts the handshake with A. When A receives B’s authenticated message, it learns B’s IP and UDP port. Traffic can now flow both ways, which is exactly what we wanted. Even though B started the tunnel, A can use it to reach the service listening on 10.0.1.2:8080.

Animation showing how WireGuard encrypts and encapsulates IP packets in UDP datagrams

Notice that what travels between A and B is encrypted. If someone intercepts the UDP datagram halfway there, they can’t see the IP packet inside. In other words, they can’t tell that k3 4s3 really means ke ase.

Fair question: if the data ultimately travels over UDP, can packets get lost? Yes, but our shiny TCP/IP stack already has an answer for that: TCP. Packets can get lost in the tunnel, but if they’re part of a TCP connection, TCP handles retransmission and congestion control. Packets can get lost on a physical Ethernet link too, mind you. Once the tunnel has done its job, the recovered IP packet goes through the same channels as any other packet.

Now let’s follow one of those packets from A to B. Say A wants to talk to a service on B listening on TCP port 8080. WireGuard decrypts the traffic and recovers the original IP packet. But the service expects data from a TCP socket. Who turns that IP packet into the data the service reads?

That’s what changes across the next three cases. A always runs WireGuard in the Linux kernel; we’re changing what happens on B.

  • WireGuard in the kernel at both ends. B’s kernel decrypts the packet and passes it to its TCP/IP stack. The service reads the data from its socket.
  • WireGuard in user space with a TUN interface. The agent receives the datagram on a UDP socket, decrypts it and writes the resulting IP packet to TUN. The kernel’s TCP/IP stack takes it from there.
  • WireGuard and the TCP/IP stack in user space. The agent still gets the datagram on a UDP socket and decrypts it, but this time it processes the IP packet itself. It opens a separate local TCP connection to pass the data to the service. That’s where the user-space TCP/IP stack comes in, and why I’m writing this article.

4.2 WireGuard in kernel space

This is the simplest case: everything happens in kernel space, and processes see only sockets.

Diagram of WireGuard running in kernel space at both ends

The diagram shows how the two machines communicate. From our application’s point of view, we still have my favorite abstraction: a stream of data between two endpoints identified by their IP addresses and ports, accessed through a TCP socket. In short, a process on A can exchange data with a service listening on port 8080 on B.

Things get a little more complicated underneath. The data the process on A sends to B enters the kernel through the socket, which is just an abstraction that lets applications interact with the network stack. The data then goes through the TCP/IP stack, which builds the packets and routes them through the wg0 virtual interface according to the configured routes.

From wg0, WireGuard takes care of getting the IP packet to B. There, the kernel’s WireGuard module recovers the original packet and passes it straight to the network stack, as though it arrived through wg0. That’s where the tunnel’s job ends: the kernel’s TCP stack reassembles the stream and delivers the data to the service listening on port 8080.

Finally, the data reaches the user-space process. From the application’s point of view, it has only sent and received data. Neither process has had to construct or deconstruct an IP packet by hand. Why that matters will become clearer in the next examples.

A chef deconstructing an IP packet
Person deconstructing an IP packet

4.3 WireGuard in user space with a TUN interface

A common way to deploy WireGuard, especially with user-space implementations, is to use a TUN interface. A TUN interface is simply a virtual network interface provided by the Linux kernel that lets a user-space program receive and send raw IP packets. Before we use one with WireGuard, let’s see what that actually means.

4.3.1 TUN/TAP interfaces

We generally talk to the kernel’s network stack through sockets. With TCP or UDP sockets, we’re moving data: I can send a payload, but I can’t use that API to inject a whole packet into the kernel’s TCP/IP stack. For that I need something like a raw socket or a TUN/TAP interface. Whether I want TUN or TAP depends on what I’m moving:

  • TUN: when I want to send and receive IP packets.
  • TAP: when I’m “speaking” Ethernet.

Here’s a little preview of what we’ll do with a user-space TCP/IP stack in Part II. This Rust program sends a ping (an ICMP echo request) through a TUN interface and reads the reply the kernel generates from the same interface.

/**
* This is a simple program that uses a TUN interface to send
* an ICMP Echo Request directly to the local kernel and
* receive its Echo Reply.
*
* First, create a TUN interface and assign it an IP address:
*
* sudo ip tuntap add dev tun0 mode tun
* sudo ip addr add 10.166.0.2/24 dev tun0
* sudo ip link set dev tun0 up
*
**/
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Obtain a file descriptor to read/write to the interface
let mut tun = create_tun("tun0")?;
// IPv4 ICMP Echo Request: 10.166.0.1 -> 10.166.0.2
let echo_request = ping_echo_request([10, 166, 0, 1], [10, 166, 0, 2]);
// Now we send the ping
tun.write(&echo_request)?;
// Now we wait for the echo reply
// (discarding what we receive until we get the echo reply)
let mut buffer = [0u8; 65535];
loop {
let n = tun.read(&mut buffer)?;
let packet = SlicedPacket::from_ip(&buffer[..n])?;
if let Some(TransportSlice::Icmpv4(icmp)) = packet.transport {
if let Icmpv4Type::EchoReply(header) = icmp.icmp_type() {
if let Some(NetSlice::Ipv4(ip)) = packet.net {
println!(
"PONG: {} -> {}",
ip.header().source_addr(),
ip.header().destination_addr()
);
}
println!("id={}, seq={}", header.id, header.seq);
let payload = String::from_utf8_lossy(icmp.payload());
println!("Payload: {}", payload);
break;
}
}
}
Ok(())
}

Let’s go through it. As the comment says, the program expects the TUN interface to exist already. That’s just so I don’t have to configure its IP address from Rust:

Terminal window
sudo ip tuntap add dev tun0 mode tun
sudo ip addr add 10.166.0.2/24 dev tun0
sudo ip link set dev tun0 up

That creates the interface, gives it the IP we’ll use as the packet’s destination and brings it up.

First (line 16), we call a helper that opens the file descriptor. I haven’t included it here, but it’s basically the Rust version of what the Linux documentation describes. The descriptor is tied to the interface and lets us read and write IP packets.

If you want to dig into the details, you can always check out the full ping example on GitHub, including the create_tun helper I left out here.

Next we build the echo request and send it (lines 19 and 22). Here’s the magic of TUN: we’re telling the kernel an echo request just came in through that interface. The kernel is clever enough to know it should answer with an echo reply. This is what I mean when I talk about the kernel’s TCP/IP stack. It knows how to reassemble a TCP stream, answer a ping, populate an ARP table, route an IP packet and do a thousand other things I don’t know about.

If the kernel is that clever, it should have left an echo reply on the interface for us to read. That’s what the loop does (lines 28 and 29). I use a loop because other traffic can show up on a network interface (and it did), but I’m only interested in the ICMP reply.

If we run the program once the interface is up, we should see:

Terminal window
PONG: 10.166.0.2 -> 10.166.0.1
id=1, seq=1
Payload: ola

The IPs in the PONG are the other way around: the reply goes back to the source of the echo request. The payload is unchanged.

Here’s what that round trip looks like:

The Rust program sends a ping to the kernel through tun0 and reads the reply through the same interface

We’ve sent and received IP packets through TUN. That lets us work with the TCP/IP stack at the level of a network interface. And what better way to build an IP tunnel than with an interface like that?

4.3.2 WireGuard and TUN

This is the case we’re particularly interested in, because it’s exactly what our agent was doing when we decided to move to a fully user-space approach.

Diagram of user-space WireGuard passing IP packets to the kernel through a TUN interface

Nothing changes on A: WireGuard still runs in the kernel. On B, though, the kernel uses its UDP/IP stack (yes, that’s a joke; that’s where we’re at) to deliver the datagram to the agent’s socket. The agent decrypts it and recovers the original IP packet.

Okay, so who handles TCP now? The kernel, same as before. The agent does the same thing as the ping program: it calls write() to hand the packet to TUN, the interface with the local tunnel IP. To the kernel, that packet just came in through TUN. In the other direction, the agent uses read() to pick up the packets the kernel sends out through TUN and forward them to the other peer.

That’s roughly what the kernel-space WireGuard implementation did before: it passed the decrypted packet straight to the network stack. The difference is that now we do it with a write() system call, whereas before the kernel code used its own internal functions, which I’m going to call kwrite() because I’m worth it.

A little AI bird tells me that, actually:

As before, the stack ultimately delivers the data to the socket for the connection accepted by the service listening on port 8080.

4.3.3 Implementation

Here’s a real user-space WireGuard implementation: the code our agent used before we went fully user-space. We wanted to use WireGuard without going too crazy. How? By using libraries written by people who did in fact go a little crazy.

In our case, we put everything in a struct that, in a burst of originality, we called WireGuard.

let device = match wireguard::WireGuard::new("wg0").await {
Ok(device) => device,
Err(e) => {
return Err(KittengridAgentError::WireguardError(e));
}
};
match device.set_config(peer, &endpoint).await {
Ok(_) => {
info!(
"Successfully configured WireGuard device {}.",
device.name()
);
}
Err(e) => {
return Err(KittengridAgentError::WireguardError(e));
}
}
std::thread::spawn(move || {
info!("Starting Kittengrid tunnel for device {}.", device.name());
device.wait();
});

It’s fairly straightforward. We create the interface, configure WireGuard, and leave a thread waiting for the TUN readers to finish.

For this first implementation, we used wireguard-rs. The project was shipped as an executable that ran WireGuard in user space with a TUN interface. I copied what it did in main.rs into my library.

This is a simplified version. I’m leaving out the part where we configure the interface IP address and routes on Linux.

impl WireGuard {
pub async fn new(device_name: &str) -> Result<WireGuard, Box<dyn std::error::Error>> {
// Create the TUN interface
let (readers, writer, mut status) =
wireguard_rs::platform::plt::Tun::create(device_name)?;
// Create the user-space WireGuard device
let device = WireGuardRs::new(writer);
for reader in readers {
device.add_tun_reader(reader);
}
let cfg = wireguard_rs::configuration::WireGuardConfig::new(device.clone());
Ok(WireGuard {
device,
config: cfg,
})
}
pub async fn set_config(
&self,
peer: PeerConfig,
endpoint: &SocketAddr,
) -> Result<(), ConfigError> {
let cfg = &self.config;
// Configure our private key
cfg.set_private_key(Some(peer.local_private_key));
// Let the OS choose the local UDP port
cfg.set_listen_port(0)?;
// Configure the remote peer
cfg.add_peer(&peer.public_key);
cfg.set_endpoint(&peer.public_key, *endpoint);
cfg.add_allowed_ip(&peer.public_key, peer.allowed_ip, 32);
Ok(())
}
}

The first thing we do in new is create the TUN interface. Tun::create() is the cross-platform counterpart of create_tun from the ping example. It gives us three things: readers is a collection of readers (just one in this implementation), writer lets us write to TUN, and status tells us when the interface comes up or goes down. The reader and writer share the TUN file descriptor. The status notifications come through a Netlink socket.

Next I create the user-space WireGuard instance and give it the writer. That way, when WireGuard receives UDP traffic from another peer and decrypts it, it has somewhere to write the IP packet it just recovered. Writing it to TUN hands it to the kernel’s TCP/IP stack, which can deliver the data to the receiving process’s socket.

Next I pass it the reader. add_tun_reader() starts a thread that keeps reading packets from the interface. This is where I tend to get a little confused. When you read() from TUN, you get an IP packet the kernel put there because its routing table said to send it out through that interface. That’s what we saw when the kernel left us the ping reply. WireGuard looks at the destination IP and uses AllowedIPs to find the right peer. If it finds one, it sends the encrypted packet over UDP, doing a handshake first if needed.

So new sets up the TUN side, and set_config tells WireGuard how to talk to other peers. We give it the other peer’s address and UDP port so it knows where to find it, and the keys it needs to encrypt outgoing traffic and decrypt incoming traffic.

That covers the TUN part, but, as we saw earlier, this setup needs the CAP_NET_ADMIN capability.

4.4 A fully user-space implementation

So far, WireGuard is running in user space, but we’re still using the kernel’s TCP/IP stack through a TUN interface. The goal, as I mentioned earlier, was to do all the tunnel processing in user space. By “all,” I mean on only one of the peers: the one running our agent. Our server, machine A, always uses the kernel implementation.

WireGuard runs in user space on machine B, where the agent proxies traffic to a local service without TUN

This is where it gets a little more complicated. Server B used to have a TUN interface where we could read packets bound for A and inject packets coming from A. Now there’s nothing there.

This is where the magic of a user-space TCP/IP stack comes in. I don’t want to get into the details yet. The idea is that we can take an IP packet and make sense of it. If it’s “speaking” TCP, we can reconstruct the data stream and pass it to a local service. Doing all of that ourselves, though, would be a monumental task.

What the hell is a user-space TCP/IP stack, and why do I need one?

That’s what went through my head as I looked into moving everything into user space.

Once I got the WireGuard library to hand me incoming packets without a TUN interface, reality hit. What came out the other end was, of course, IP packets. (Cue the ominous music.)

I had one simple question: “What the heck am I supposed to do with these now?” My first thought was, well, I guess I could take each SYN that comes in, send back a SYN/ACK, and handle the ACK. Then I’d open a local TCP socket to the service I wanted to expose and forward the payloads from that connection. I’d need a layer up front to inspect each packet and figure out whether it belonged to a connection I already had or was a fresh SYN that needed a new stream. It sounded complicated. Basically, I’d have to implement TCP myself in user space and open a local socket for every incoming TCP connection. In other words, I’d have to build a TCP proxy all in user space.

I thought, if I ask a coding agent, it’ll tell me this is three months of work and then build it in five minutes and a few hundred thousand tokens. The problem was that I didn’t want a big ball of inscrutable code in my project.

The solution was simple: use a different big ball of inscrutable code called smoltcp.

smoltcp is a standalone, event-driven TCP/IP stack that is designed for bare-metal, real-time systems. Its design goals are simplicity and robustness. Its design anti-goals include complicated compile-time computations, such as macro or type tricks, even at cost of performance degradation.

The problem was that when I started reading the library’s examples and documentation, instead of answers I found more doubts, more questions, and more headaches. That’s what Part II is about.

Kittengrid gives every pull request a live URL and a terminal on the runner, using the CI you already have.

Sign up / Log in