
NAT Tunnel: to effortlessly serve from behind NAT
NOTE: The old Python version is final and unmaintained. Instructions for it are at the end of this file. It is incompatible with the current C version. Use C only.
If you have access to a server with public IP and unfiltered ports you can run NAT Tunnel (NT) server on the server, and NT client on your box behind NAT. The server requires 2 open ports: one for communication with the NT client (--admin), the other for regular clients to connect to (--public: this is the port you want your users to use).
The NT client opens a connection to the server's admin ip/port. As soon as the server receives a new connection, it signals the NT client, which then creates a new tunnel connection to the server, which is then connected to the desired service on the NT client's side (--local)
The connection between NT Client and NT Server on the admin interface is protected by a shared secret against unauthorized use. An adversary who can intercept packets could crack the secret if it's of insufficient complexity. At least 10 random characters and numbers are recommended.
Example: You have a HTTP server listening on your local machine on port 80. You want to make it available on your cloud server/VPS/etc's public IP on port 8000. We use port 7000 on the cloud server for the control channel.
Server:
./natsrv --mode server --secret-file secret.txt --server-key server.key --public 0.0.0.0:8000 --admin 0.0.0.0:7000
Client:
./natsrv --mode client --secret-file secret.txt --server-pubkey PUBKEY_HEX --local localhost:80 --admin example.com:7000
Both IPv4 and IPv6 work everywhere. Address syntax is host:port. For IPv6 literals use brackets: [::1]:8080, [2001:db8::1]:7000. A bare IPv6 address without brackets is rejected, since the colons make the port ambiguous. For host names IPv4 is preferred and IPv6 is the fallback; an explicit numeric literal always wins for its own family. Listen address 0.0.0.0 means IPv4 all interfaces, :: means IPv6 all interfaces. On the wire the server reports a peer as ip:port for IPv4 and [ip]:port for IPv6, and both sides parse both forms.
Generate the server signing key once:
./natsrv --genkey server.key
This writes the private key with 0600 permissions and prints the public key hex. Give that hex string to the client as --server-pubkey. The server requires --server-key, the client requires --server-pubkey. Prefer --secret-file PATH over --secret on shared boxes, since --secret leaks via ps aux.
Build with plain GNU Make (3.82 or newer):
make
This produces ./natsrv. The Makefile starts with -include config.mak before the first target, so a local config.mak can permanently set CFLAGS, CPPDFGS, LDFLAGS, and friends. The Makefile appends its own defaults with CFLAGS += -Wall -std=c99. Options on the Make command line also pass through:
make CPPFLAGS=-DHAVE_GETRANDOM
make CFLAGS="-Wall -Wextra -std=c99 -pedantic"
make USE_SODIUM=1
make clean
HAVE_GETRANDOM: by default randomness comes from /dev/urandom. Define HAVE_GETRANDOM to use the getrandom() syscall instead (Linux 3.17+ / glibc 2.25+). Both paths fail closed. Linkage is -lpthread by default, plus -lsodium with USE_SODIUM=1. The code itself is C99 and portable with no GNU99 extensions. Tabs are used for indentation, following the microsocks code style.
Tunnel encryption uses XSalsa20. By default it is provided by the bundled TweetNaCl code (tweetnacl.c, tweetnacl.h). With USE_SODIUM=1 it links libsodium instead. The sha256 code in sha256.c is written from scratch; no crypto library is needed for the default build.
On x86 with Intel SHA extensions, sha256.c uses the SHA-NI intrinsics automatically when the compiler defines SHA and SSSE3. The scalar implementation remains the fallback. Enable it without -march=native:
make CPPFLAGS="-msha -msse4.1"
That builds a binary that needs any x86 CPU with SHA-NI and SSE4.1 support, without other -march=native features. Plain make without those flags still works everywhere.
Measured on an i7-1160G7, raw SHA256 of 16 KiB blocks: scalar -O2 is about 257 MB/s, SHA-NI -O2 is about 1574 MB/s (about 6 times faster).
Tunnel sockets have send and receive timeouts, set with --timeout SECS (default 1800, 0 disables them). The default is deliberately conservative: a slow server such as llama.cpp below 10 tokens per second, or a huge system prompt upload, can legitimately block for many minutes. Shorter values kill such tunnels; longer values delay dead socket detection. Control sockets never get the timeout, so an idle control connection is not killed.
All sockets use TCP keepalive with probes every 30 seconds of idle time (5 second interval, 3 probes), so a silently dead peer is detected in about 45 seconds instead of the 2 hour default.
The client and the server both run one poll loop. Neither end blocks in accept. The client polls the control socket and the spare socket together, and it re-arms the spare when the spare shows data, an error, or fails the death check every 5 seconds. The server polls the admin listener, the public listener, the control socket, and the spare socket together. As a result, the server services the public port while it has no spare, and it never stops watching the control socket.
A public connection that arrives while no live spare exists is reset at once. The peer sees a failure, not a hang. A spare that already shows FIN or RST is dropped and re-armed before it is paired, so a dead spare never reaches a tunnel. Readable data alone is not treated as death on a spare that is about to be paired, since tunnel bytes can legitimately be in flight.
Run the whole suite with:
make test
This needs python3 and builds natsrv first. The suite starts real server and client processes on loopback ports. Each test gets its own ports, work dir and logs, so a failure never leaks into the next test.
Tests can be selected by name, and listed:
python3 tests/natt.py --list
python3 tests/natt.py spare_rst control_rst
Fault injection uses a TCP proxy in front of the admin port (tests/natt.py, class FaultProxy). Each accepted connection gets an id in accept order and a role read from its client hello, so the control socket and the spare socket are told apart. A test can drop one with RST, drop it with FIN, or freeze it, i.e. stop forwarding bytes while both sockets stay open. A freeze on the control socket models a silently dead path. The peer kernel keeps answering keepalive probes on loopback, so the control_blackhole test drops the packets with iptables instead. That test needs root and is skipped otherwise.
Slow tests detect a blackhole through TCP keepalive, which takes about 45 seconds. They only run on request:
make test-slow
All console output goes to stderr, through one dprintf() call per line (macro dolog, ported from microsocks sockssrv.c). stderr is not line buffered, and dprintf writes straight to the fd. Neither needs a stdio lock, so dolog is safe from any thread and no fflush is needed after a line. Direct the log with 2> file.
The timestamp is part of the same dprintf call as the message. Concurrent handshakes therefore never interleave inside a line. Only the main thread prints in practice, so the order stays readable.
Help text (--help) is the answer to a CLI call and goes to stdout. Everything else, including --genkey output, goes to stderr.