Building a VPN in Go: the plan
I spent the summer working close to tunneling products, mostly from the product side. I learned a lot about how people use them and very little about what happens to a packet on the way through. So I’m going to build one myself: a small point-to-point VPN in Go.
The goal is understanding, not a product. WireGuard and friends already exist and are far better than anything I’ll write. If I end up with something that moves packets between two Linux machines, encrypts them properly, and that I can explain line by line, that’s a win.
What it should do
Two hosts, each running the same binary. An application on host A sends a packet to a tunnel address, the VPN picks it up, sends it to host B over UDP, and host B hands it to the right application as if the two were on the same network:
app -> tun0 -> govpn -> UDP -> govpn -> tun0 -> app
That one line hides most of the work:
- A TUN device. A virtual network interface. The kernel routes packets into it like any other interface, but instead of reaching a cable they reach my program, which reads them as raw IP packets.
- A UDP transport. A socket that sends each packet to the other peer and receives the packets coming back.
- A forwarding loop. Read from the TUN device, send over UDP. Receive from UDP, write to the TUN device. In both directions at once.
- Encryption. Until this exists it isn’t a VPN, just a tunnel. I plan to borrow heavily from WireGuard’s design here instead of inventing my own scheme.
What it won’t do (for now)
- Only Linux, since TUN devices are configured differently on every OS.
- Only two peers. No mesh, no server with many clients.
- IPv4 inside the tunnel.
- No key exchange at first. I’ll start with a pre-shared key and add a handshake later.
How I’m going to build it
Small steps, each one working on its own before the next starts. Once the basics are in place, every feature goes through a pull request, even though I’m the only one reviewing them. It forces me to describe what changed and why, which is most of what I want to write about here anyway.
I’ll also need a way to test networking code without two physical machines. I don’t have a good answer for that yet.
What’s next
Creating a TUN device, reading the first packets out of it, and getting two UDP sockets to talk to each other.