net.tun
Full device VPN mode: a tun device on Linux, macOS and Windows, split routes, DNS capture and a NAT that hands every TCP connection to a net.tunnel dialer.
import net.tun
net.tun gives a VPN app full device mode: every application on the machine goes through the tunnel, not only the ones that honour the system proxy. It creates a layer 3 tunnel device (/dev/net/tun on Linux, utun on macOS, a Wintun adapter on Windows), points the default routes at it and turns the IP packets that arrive into ordinary TCP connections, which it hands to any net.tunnel dialer: a router with direct, proxy and block rules, a VLESS, VMess, Trojan or Shadowsocks dialer, or a chain.
It has no TCP stack of its own. Like the system stack of sing-tun, it rewrites the addresses of each TCP packet so the connection lands on a local listener, and the kernel does all of TCP. Only IP and TCP headers are touched, with incremental checksum updates, so throughput stays close to the kernel.
app -> 1.1.1.1:443 kernel TCP
| routes 0.0.0.0/1, 128.0.0.0/1 ^
v |
tun device -> Nat.Rewrite: 172.19.0.2:10000 -> 172.19.0.1:listener
|
listener accepts, Nat.Lookup(10000) = 1.1.1.1:443, sniff SNI, dialer.Dial(host:443)
Things to know:
- It needs privileges. Root or CAP_NET_ADMIN on Linux, root on macOS, administrator rights and
wintun.dllnext to the executable on Windows (download it from wintun.net). CallAvailablefirst and show its reason. - Exclude your servers. Put the VPN server names or addresses in
exclude. They are resolved before the routes change and keep a route through the old gateway. Fordirectrules useBypass, which binds to the physical interface. - TCP and DNS only. UDP queries to port 53 are answered through the dialer over TCP. Other UDP (QUIC, games, calls) and ICMP are dropped, so browsers fall back to TCP. IPv6 is blocked rather than leaked.
- Routes never replace the default route. Two /1 routes win over it and
Stopremoves everything it added. If the process is killed, the Linux and Windows device disappears with it; host routes for excluded servers stay until reboot. - Linux is tested end to end by
tools/interop/tun_e2e.shin a container. The macOS and Windows device code is type checked for every target.
Full device mode in a VPN app
Build the same router dialer you would give a local SOCKS inbound, but use Bypass() for the direct tag so direct traffic leaves through the physical interface instead of looping back into the tunnel. Pass the VPN server in exclude, start the session when the user flips the switch and stop it when they flip it back or the app quits.
import net.tun
import net.tunnel
func start_full_device(proxy: dyn tunnel.Dialer, server: str): tun.Session:
av := tun.Available()
if not av.ok:
println "full device mode is off:", av.reason
ret tun.Session {}
end
rules := tunnel.ParseRules("domain:ir direct\nprivate direct", "proxy")
mut router := tunnel.NewRouterDialer(rules.router)
tunnel.RouterDialerAdd(router, "direct", tun.Bypass())
tunnel.RouterDialerAdd(router, "block", tunnel.Block())
tunnel.RouterDialerAdd(router, "proxy", proxy)
mut servers := Vector {} as Vector<str>
servers.Push(server)
s := tun.Start(tun.Options { dialer = router, exclude = servers })
if not s.ok:
println "could not start:", s.error
end
ret s
end
func main():
s := start_full_device(tunnel.Direct(), "vpn.example.com")
if s.ok:
st := tun.SessionStats(s)
println st.connections, st.dns_queries
tun.Stop(s)
end
end
Show Available().reason next to a disabled switch when the process lacks the rights; a desktop app usually starts a small privileged helper for this mode. Read SessionStats on a timer for the traffic counters.
Handling packets yourself
OpenDevice gives a bare device with no address, routes or stack: each Read returns one IP packet and each Write injects one. Combine it with Parse, Nat and the packet builders to write your own stack, a packet logger or a test harness. Configure the address and routes yourself, or look at what BuildPlan would run.
import mem
import sync
import net.tun
func main():
dev := tun.OpenDevice("salam0", 1500)
if not dev.ok:
println dev.error
ret
end
nat := tun.NewNat("172.19.0.1", "172.19.0.2", 7000, 0)
buf := mem.Allocate(65536 as u64)
repeat 1000:
n := dev.Read(buf, 65536, 200)
if n > 0:
info := tun.Parse(buf, n)
println info.src, info.sport, "->", info.dst, info.dport
if nat.Rewrite(buf, n, sync.NowMs()) == tun.action_reply:
_w := dev.Write(buf, n)
end
end
end
mem.Free(buf)
tun.FreeNat(nat)
dev.Close()
end
Types
Options
struct OptionsStart.| Name | Type | Description |
|---|---|---|
name | str = "" | Interface name. Empty picks salamtun, or the next free utunN on macOS. |
address | str = "172.19.0.1" | IPv4 address of the device. The next address must be in the same subnet. |
prefix | int = 30 | Prefix length of the device subnet, 30 by default. |
mtu | int = 1500 | MTU of the device. |
dialer | dyn tunnel.Dialer | Where captured connections go, usually a net.tunnel router dialer. Without one every connection is refused. |
exclude | Vector | Host names or IPv4 addresses that must keep using the real network, such as the VPN servers. They get host routes through the old gateway, so the dialer does not loop into the tunnel. |
auto_route | bool = true | Adds the routes. When false only the device and its address are set up. |
hijack_dns | bool = true | Answers every UDP query to port 53 that enters the tunnel, and routes private DNS servers of the machine into the tunnel too. |
upstream | str = "1.1.1.1:53" | The DNS server, as host:port, that queries are sent to over TCP through the dialer. |
set_system_dns | bool = true | Points the system resolver at the DNS address inside the tunnel (systemd-resolved on Linux, the interface DNS on Windows). |
block_ipv6 | bool = true | Stops IPv6 from leaking around the tunnel: unreachable routes on Linux, IPv6 routes into the device on macOS and Windows. |
sniff | bool = true | Reads the first bytes of each connection to find a TLS or HTTP host name, so domain rules of the router work. |
sniff_ms | int = 300 | How long to wait for those bytes. Protocols where the server speaks first wait this long once. |
idle_ms | int = 600000 | Idle timeout of a connection in milliseconds. |
dial_ms | int = 10000 | Connect timeout in milliseconds. |
import net.tun
func main():
gw := tun.ParseLinuxRoutes(
"Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask\neth0\t00000000\t0101A8C0\t0003\t0\t0\t100\t00000000\n"
)
println "linux", gw.ok, gw.ip, gw.iface, gw.index
mac := tun.ParseMacRoute(" gateway: 10.0.0.1\n interface: en0\n")
println "macos", mac.ip, mac.iface
dns := tun.ParseResolvers("nameserver 192.168.1.1\n")
println "resolvers", dns.Len(), dns[0]
println "name ok", tun.ValidName("salamtun"), "next", tun.NextAddress(tun.default_address)
println "defaults", tun.default_address6, tun.default_upstream
mut hosts := Vector {} as Vector<str>
hosts.Push("203.0.113.7")
opts := tun.Options { name = "salamtun", set_system_dns = false }
pl := tun.BuildPlan("linux", "salamtun", opts, gw, hosts, dns, "")
each line in pl.up:
println "up ", line
end
each line in pl.down:
println "down", line
end
parts := tun.SplitCommand(pl.up[0])
println "argv", parts.Len(), parts[0]
endGateway
struct Gateway| Name | Type | Description |
|---|---|---|
ok | bool = false | False when no default route was found. |
ip | str = "" | The gateway address, empty for a point to point link. |
iface | str = "" | The interface name, empty on Windows. |
index | int = 0 | The interface index on Windows, 0 elsewhere. |
The example for this item is shown with the ones above: net-tun-Plan.salam
Plan
struct Plan- may fail.| Name | Type | Description |
|---|---|---|
up | Vector | Commands run by Start, in order. |
down | Vector | Commands run by Stop. |
The example for this item is shown with the ones above: net-tun-Plan.salam
Availability
struct Availability| Name | Type | Description |
|---|---|---|
ok | bool = false | True when Start can work. |
reason | str = "" | Why not, in words an app can show: missing privileges, missing /dev/net/tun, missing wintun.dll. |
import mem
import net.tun
import net.tunnel
func main():
av := tun.Available()
if not av.ok:
println "full device mode is off:", av.reason
ret
end
println "platform", tun.Platform()
gw := tun.DefaultGateway()
println "gateway", gw.ip, gw.iface
println "resolvers", tun.SystemResolvers().Len()
mut servers := Vector {} as Vector<str>
servers.Push("vpn.example.com")
s := tun.Start(tun.Options { dialer = tunnel.Direct(), exclude = servers })
if not s.ok:
println "start failed:", s.error, tun.LastError()
ret
end
println "up", s.name, s.address, "dns", s.dns, tun.Running()
direct := tun.NewBypassDialer()
c := direct.Dial(tunnel.NewAddr("example.com", 80))
println direct.Name(), c.Ok()
c.Close()
_d := tun.Bypass()
st := tun.SessionStats(s)
println st.packets_in,
st.packets_out,
st.connections,
st.active,
st.dns_queries,
st.sniffed,
st.failed,
st.dropped,
st.bytes_up,
st.bytes_down
tun.Stop(s)
dev := tun.OpenDevice("salamtest", 1500)
if dev.ok:
buf := mem.Allocate(65536 as u64)
n := dev.Read(buf, 65536, 100)
if n > 0:
_w := dev.Write(buf, n)
end
mem.Free(buf)
dev.Close()
end
endStats
struct Stats| Name | Type | Description |
|---|---|---|
packets_in | i64 = 0 | Packets read from the device. |
packets_out | i64 = 0 | Packets written to the device. |
dropped | i64 = 0 | Packets dropped: UDP other than DNS, ICMP, fragments, unknown connections. |
connections | i64 = 0 | TCP connections accepted. |
active | i64 = 0 | TCP connections being relayed now. |
dns_queries | i64 = 0 | DNS queries forwarded. |
sniffed | i64 = 0 | Connections whose host name was found by sniffing. |
failed | i64 = 0 | Dials that failed. |
bytes_up | i64 = 0 | Bytes sent by applications. |
bytes_down | i64 = 0 | Bytes received by applications. |
The example for this item is shown with the ones above: net-tun-Session.salam
Device
struct Device/dev/net/tun on Linux, utun on macOS, a Wintun adapter on Windows. Each read or write is one IP packet.| Name | Type | Description |
|---|---|---|
ok | bool = false | True when the device is open. |
error | str = "" | Why opening failed. |
name | str = "" | The interface name the system gave the device. |
mtu | int = 1500 | MTU asked for. |
fd | i64 = -1 | File descriptor on Linux and macOS. |
session | void* | Wintun session on Windows. |
adapter | void* | Wintun adapter on Windows. |
event | void* | Wintun read event on Windows. |
scratch | void* | Buffer for the packet header of utun on macOS. |
The example for this item is shown with the ones above: net-tun-Session.salam
Read
func Read(buf: void*, max: int, timeout_ms: int): inttimeout_ms. Returns its length, 0 on timeout and a negative number when the device is gone.Write
func Write(ptr: void*, n: int): intClose
func Close()BypassDialer
struct BypassDialernet.tunnel dialer whose sockets are bound to the physical interface (SO_BINDTODEVICE, IP_BOUND_IF or IP_UNICAST_IF), for the direct route while the tunnel owns the default routes. Domain names are resolved by the system, which means through the tunnel DNS.| Name | Type | Description |
|---|---|---|
gateway | Gateway | The physical gateway and interface, saved before the routes changed. |
timeout_ms | int = 10000 | Connect timeout in milliseconds. |
The example for this item is shown with the ones above: net-tun-Session.salam
Dial
func Dial(target: tunnel.Addr): dyn tunnel.StreamName
func Name(): strbypass.Session
struct SessionStart.| Name | Type | Description |
|---|---|---|
ok | bool = false | True when the session started. |
error | str = "" | Why it did not start. |
name | str = "" | Interface name. |
address | str = "" | Device address. |
dns | str = "" | The DNS address inside the tunnel. |
id | int = 0 | Session number. |
The example for this item is shown with the ones above: net-tun-Session.salam
NatEntry
struct NatEntry| Name | Type | Description |
|---|---|---|
ok | bool = false | False when no connection uses that port. |
src | str = "" | The application side address. |
sport | int = 0 | The application side port. |
dst | str = "" | The address the application wanted to reach. |
dport | int = 0 | The port the application wanted to reach. |
import net.tun
func main():
nat := tun.NewNat("172.19.0.1", "172.19.0.2", 7000, 0)
out := tun.BuildTcp4(
"172.19.0.1", 51000, "1.1.1.1", 443, 1 as i64, 0 as i64, tun.tcp_syn, null, 0
)
println "forward", nat.Rewrite(out.data, out.len, 0 as i64) == tun.action_reply
seen := tun.Parse(out.data, out.len)
println "kernel sees", seen.src, seen.sport, seen.dst, seen.dport
e := nat.Lookup(seen.sport)
println "original", e.ok, e.src, e.sport, e.dst, e.dport
back := tun.BuildTcp4(
"172.19.0.1",
nat.Port(),
"172.19.0.2",
seen.sport,
9 as i64,
2 as i64,
tun.tcp_syn | tun.tcp_ack,
null,
0
)
_r := nat.Rewrite(back.data, back.len, 1 as i64)
app := tun.Parse(back.data, back.len)
println "app sees", app.src, app.sport, app.dst, app.dport
dns := tun.BuildUdp4("172.19.0.1", 5353, "172.19.0.2", 53, null, 0)
println "dns", nat.Rewrite(dns.data, dns.len, 2 as i64) == tun.action_dns
println "drop", tun.action_drop, "ipv6", tun.action_ipv6
println "active", nat.Active(), "expired", nat.Sweep(3600000 as i64), "active", nat.Active()
tun.FreePacket(out)
tun.FreePacket(back)
tun.FreePacket(dns)
tun.FreeNat(nat)
endNat
struct Natdst:dport is rewritten to come from next:nat_port and go to the local listener, so the kernel itself runs TCP; replies get the original addresses back. The same addressing as the system stack of sing-tun.| Name | Type | Description |
|---|---|---|
core | void* | Native state. Create it with NewNat. |
The example for this item is shown with the ones above: net-tun-Nat.salam
Rewrite
func Rewrite(ptr: void*, n: int, now_ms: i64): intaction_ values. now_ms is a clock in milliseconds used for timeouts.Lookup
func Lookup(nat_port: int): NatEntrySweep
func Sweep(now_ms: i64): intActive
func Active(): intPort
func Port(): intPacketInfo
struct PacketInfoParse read from one IP packet: version, protocol, addresses, ports, TCP flags and where the payload starts.| Name | Type | Description |
|---|---|---|
valid | bool = false | False when the bytes are not a complete IPv4 or IPv6 packet. |
version | int = 0 | 4 or 6. |
proto | int = 0 | The transport protocol number, for example proto_tcp. |
src | str = "" | Source address as text. |
dst | str = "" | Destination address as text. |
sport | int = 0 | Source port for TCP and UDP, 0 otherwise. |
dport | int = 0 | Destination port for TCP and UDP, 0 otherwise. |
flags | int = 0 | The TCP flag bits, see tcp_syn and the others. |
header_len | int = 0 | Length of the IP header in bytes. |
payload_offset | int = 0 | Offset of the transport payload from the start of the packet. |
payload_len | int = 0 | Length of the transport payload. |
total | int = 0 | Total length of the packet from its header. |
fragment | bool = false | True for an IPv4 fragment. The stack drops fragments. |
import net.tun
func main():
body := "hi"
pk := tun.BuildTcp4(
"172.19.0.1", 40000, "93.184.216.34", 443, 1 as i64, 0 as i64, tun.tcp_syn, body as void*,
2
)
info := tun.Parse(pk.data, pk.len)
println info.valid,
info.version,
info.proto == tun.proto_tcp,
info.src,
info.sport,
info.dst,
info.dport
println "syn",
(info.flags & tun.tcp_syn) != 0,
"ack",
(info.flags & tun.tcp_ack) != 0,
"payload",
info.payload_len,
"of",
info.total
println "checksums ok", tun.ChecksumsOk(pk.data, pk.len)
p := pk.data as u8*
p[8] = 32 as u8
println "after edit", tun.ChecksumsOk(pk.data, pk.len)
tun.FinishChecksums(pk.data, pk.len)
println "after finish", tun.ChecksumsOk(pk.data, pk.len)
println "header sum", tun.Checksum(pk.data, 20)
println "rfc 1624", tun.ChecksumAdjust(56623, 21845, 12933)
udp := tun.BuildUdp4("10.0.0.2", 5000, "10.0.0.1", 53, null, 0)
u := tun.Parse(udp.data, udp.len)
println "udp", u.proto == tun.proto_udp, u.header_len, u.payload_offset, u.fragment
println "other flags", tun.tcp_fin, tun.tcp_rst, tun.tcp_psh, tun.proto_icmp, tun.proto_icmp6
tun.FreePacket(pk)
tun.FreePacket(udp)
endPacket
struct PacketFreePacket.| Name | Type | Description |
|---|---|---|
data | void* | Pointer to the bytes, or null when building failed. |
len | int = 0 | Number of bytes. |
The example for this item is shown with the ones above: net-tun-Packet.salam
DnsQuestion
struct DnsQuestion| Name | Type | Description |
|---|---|---|
ok | bool = false | False when the bytes are not a DNS query. |
id | int = 0 | The query id. |
name | str = "" | The name asked for, without the final dot. |
qtype | int = 0 | The record type, 1 for A and 28 for AAAA. |
import net.tun
func main():
req := "GET / HTTP/1.1\r\nHost: Example.com:8080\r\n\r\n"
println "host", tun.SniffHost(req as void*, req.Len())
q := tun.BuildDnsQuery(42, "salamlang.ir", 1)
d := tun.ParseDnsQuery(q.data, q.len)
println "question", d.ok, d.id, d.name, d.qtype
tun.FreePacket(q)
endConstants and variables
default_address
const default_address: str = "172.19.0.1"The example for this item is shown with the ones above: net-tun-Plan.salam
default_address6
const default_address6: str = "fdfe:dcba:9876::1"The example for this item is shown with the ones above: net-tun-Plan.salam
default_upstream
const default_upstream: str = "1.1.1.1:53"The example for this item is shown with the ones above: net-tun-Plan.salam
action_drop
const action_drop: i32 = 0Rewrite result: drop the packet.The example for this item is shown with the ones above: net-tun-Nat.salam
action_reply
const action_reply: i32 = 1Rewrite result: the packet was rewritten in place, write it back to the device.The example for this item is shown with the ones above: net-tun-Nat.salam
action_dns
const action_dns: i32 = 2Rewrite result: a UDP query to port 53, answer it yourself.The example for this item is shown with the ones above: net-tun-Nat.salam
action_ipv6
const action_ipv6: i32 = 3Rewrite result: an IPv6 packet. The stack answers a TCP SYN with a reset so the app falls back to IPv4 at once.The example for this item is shown with the ones above: net-tun-Nat.salam
proto_icmp
const proto_icmp: i32 = 1The example for this item is shown with the ones above: net-tun-Packet.salam
proto_tcp
const proto_tcp: i32 = 6The example for this item is shown with the ones above: net-tun-Packet.salam
proto_udp
const proto_udp: i32 = 17The example for this item is shown with the ones above: net-tun-Packet.salam
proto_icmp6
const proto_icmp6: i32 = 58The example for this item is shown with the ones above: net-tun-Packet.salam
tcp_fin
const tcp_fin: i32 = 1The example for this item is shown with the ones above: net-tun-Packet.salam
tcp_syn
const tcp_syn: i32 = 2The example for this item is shown with the ones above: net-tun-Packet.salam
tcp_rst
const tcp_rst: i32 = 4The example for this item is shown with the ones above: net-tun-Packet.salam
tcp_psh
const tcp_psh: i32 = 8The example for this item is shown with the ones above: net-tun-Packet.salam
tcp_ack
const tcp_ack: i32 = 16The example for this item is shown with the ones above: net-tun-Packet.salam
Functions
Available
func Available(): AvailabilityThe example for this item is shown with the ones above: net-tun-Session.salam
Platform
func Platform(): strlinux, macos, windows or other.The example for this item is shown with the ones above: net-tun-Session.salam
DefaultGateway
func DefaultGateway(): GatewayThe example for this item is shown with the ones above: net-tun-Session.salam
SystemResolvers
func SystemResolvers(): Vector<str>The example for this item is shown with the ones above: net-tun-Session.salam
NewBypassDialer
func NewBypassDialer(): BypassDialerBypassDialer for the current physical interface.The example for this item is shown with the ones above: net-tun-Session.salam
Bypass
func Bypass(): dyn tunnel.DialerNewBypassDialer, as a dyn tunnel.Dialer ready for a router.The example for this item is shown with the ones above: net-tun-Session.salam
OpenDevice
func OpenDevice(name: str, mtu: int): DeviceThe example for this item is shown with the ones above: net-tun-Session.salam
Running
func Running(): boolThe example for this item is shown with the ones above: net-tun-Session.salam
LastError
func LastError(): strStart.The example for this item is shown with the ones above: net-tun-Session.salam
Start
func Start(opts: Options): SessionThe example for this item is shown with the ones above: net-tun-Session.salam
SessionStats
func SessionStats(s: Session): StatsThe example for this item is shown with the ones above: net-tun-Session.salam
Stop
func Stop(s: Session)The example for this item is shown with the ones above: net-tun-Session.salam
NewNat
func NewNat(address: str, next: str, listen_port: int, idle_ms: int): NatThe example for this item is shown with the ones above: net-tun-Nat.salam
FreeNat
func FreeNat(nat: Nat)The example for this item is shown with the ones above: net-tun-Nat.salam
Checksum
func Checksum(p: void*, n: int): intThe example for this item is shown with the ones above: net-tun-Packet.salam
ChecksumAdjust
func ChecksumAdjust(sum: int, old_word: int, new_word: int): intThe example for this item is shown with the ones above: net-tun-Packet.salam
FinishChecksums
func FinishChecksums(ptr: void*, n: int)The example for this item is shown with the ones above: net-tun-Packet.salam
ChecksumsOk
func ChecksumsOk(ptr: void*, n: int): boolThe example for this item is shown with the ones above: net-tun-Packet.salam
Parse
func Parse(ptr: void*, n: int): PacketInfoPacketInfo.The example for this item is shown with the ones above: net-tun-Packet.salam
FreePacket
func FreePacket(pk: Packet)Packet.The example for this item is shown with the ones above: net-tun-Packet.salam
BuildTcp4
func BuildTcp4(src: str, sport: int, dst: str, dport: int, seq: i64, ack: i64, flags: int, data: void*, n: int): PacketThe example for this item is shown with the ones above: net-tun-Packet.salam
BuildUdp4
func BuildUdp4(src: str, sport: int, dst: str, dport: int, data: void*, n: int): PacketThe example for this item is shown with the ones above: net-tun-Packet.salam
ValidName
func ValidName(name: str): bool- or _.The example for this item is shown with the ones above: net-tun-Plan.salam
NextAddress
func NextAddress(address: str): strThe example for this item is shown with the ones above: net-tun-Plan.salam
ParseLinuxRoutes
func ParseLinuxRoutes(text: str): Gateway/proc/net/route, preferring the lowest metric.The example for this item is shown with the ones above: net-tun-Plan.salam
ParseMacRoute
func ParseMacRoute(text: str): Gatewayroute -n get default on macOS.The example for this item is shown with the ones above: net-tun-Plan.salam
ParseResolvers
func ParseResolvers(text: str): Vector<str>resolv.conf text or scutil --dns output.The example for this item is shown with the ones above: net-tun-Plan.salam
BuildPlan
func BuildPlan(platform: str, dev: str, opts: Options, gw: Gateway, hosts: Vector<str>, resolvers: Vector<str>, exe: str): Planlinux, macos or windows. Pure: it runs nothing, so a plan can be shown or tested.The example for this item is shown with the ones above: net-tun-Plan.salam
SplitCommand
func SplitCommand(line: str): Vector<str>The example for this item is shown with the ones above: net-tun-Plan.salam
SniffHost
func SniffHost(ptr: void*, n: int): strThe example for this item is shown with the ones above: net-tun-Sniff.salam
ParseDnsQuery
func ParseDnsQuery(ptr: void*, n: int): DnsQuestionThe example for this item is shown with the ones above: net-tun-Sniff.salam
BuildDnsQuery
func BuildDnsQuery(id: int, name: str, qtype: int): PacketThe example for this item is shown with the ones above: net-tun-Sniff.salam