An OpenVPN client library for Go
v1.0.5
A VPN connection that is a net.Conn.
gopenvpn-conn speaks the OpenVPN protocol as a client, inside your program. It is pure Go, needs no root and no TUN device, and changes nothing on the machine: only the connections of your program use the VPN.
dir := os.DirFS("/etc/openvpn/client")
profile, err := ovpn.ParseFS(dir, "work.ovpn")
if err != nil {
log.Fatal(err)
}
conn, err := profile.Dial(ctx) // tries the remotes in order
if err != nil {
log.Fatal(err)
}
n, err := vpnnet.New(conn, &vpnnet.Options{CloseConn: true})
if err != nil {
log.Fatal(err)
}
defer n.Close()
// The name is looked up through the VPN, with the DNS servers
// that the server pushed, and the connection goes through it too.
client := &http.Client{
Transport: &http.Transport{DialContext: n.DialContext},
}
resp, err := client.Get("http://intranet.example.com/")
A web page through the VPN, from an .ovpn profile. examples/http of the repository is this program.
3 layers
The tunnel, the parser of profiles and the userspace network. Each one works without the ones above it.
0 allocations
for a packet that Read or Write carries, in the benchmarks of the data channel.
21 fuzz targets
in the tests, for the parsers of bytes that come from the network or from a file.
2.7.9
is the OpenVPN server that it was run against, on Linux, under Wine for Windows, and on macOS.
The patterns of the standard library
openvpn.Dialworks astls.Dialdoes, andopenvpn.Clientastls.Client. The tunnel is anet.Conn: its deadlines, itsCloseand the errors ofReadandWritefollownet.Conn.No root, and nothing changes
There is no TUN device to make, and no route or DNS setting of the machine to change. A TCP/IP stack inside the program carries its connections, and every other program keeps the machine’s own network.
Pure Go
No cgo, and no
unsafeof its own. TLS iscrypto/tls. The same code works on Linux, Windows and macOS.
Run against the real server
The reference server is OpenVPN 2.7.9. The library was run against it on Linux, under Wine for Windows, and on macOS on Apple silicon, over UDP and TCP. The two examples of the repository are programs that you can point at your own server.
examples/httpreads a profile and gets a web page through the tunnel.examples/pingsends ICMP echo requests through it- The unit tests run the client against a server written for the tests, in the same process, on a fake clock
- The tests against the real server run in a private user and network namespace, with no root
# Get a page through the tunnel, from a profile
$ go run ./examples/http -profile client.ovpn \
-url http://10.8.0.1:36327/
connected: address [10.8.0.2/24], DNS servers []
http://10.8.0.1:36327/: 200 OK, 1000000 bytes
# The unit tests need no openvpn binary and no privileges
$ go test -race ./...
# The same against a real server, in a private namespace
$ scripts/vpn-ns.sh -- go test -race \
-tags gopenvpn_server ./...
Three layers
Take the profile parser and the userspace network, as the example at the top does, or only the tunnel. The packages are ovpn, vpnnet and openvpn.
ovpn
Read a profile, and dial it
ovpn.ParseFS turns an .ovpn profile into a Config and a list of remotes. It reads the files that the profile names (ca, cert, key, tls-crypt, auth-user-pass) from the directory of the profile and from nowhere else. It never runs a command and never reads the environment.
Profile.Dialtries the remotes in order, or at random withremote-random, each forconnect-timeout- A profile with
auth-user-passand no file leaves the password to the program. The library never reads a terminal ovpn.Parsetakes a profile whose files are all inline
profile, err := ovpn.ParseFS(dir, "work.ovpn")
if err != nil {
log.Fatal(err)
}
if profile.NeedsCredentials {
// auth-user-pass with no file: the program asks for
// the password its own way.
profile.Config.Credentials = func(
ctx context.Context,
) (openvpn.Credentials, error) {
return openvpn.Credentials{
Username: "alice",
Password: os.Getenv("VPN_PASSWORD"),
}, nil
}
}
conn, err := profile.Dial(ctx)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
fmt.Println("addresses:", conn.ConnectionState().Addrs)
Errors
A profile it cannot honor is refused
An option that the library cannot honor, and that would be unsafe or wrong to skip, is an error that names the option, its line and the reason. The options that are accepted and do nothing are in profile.Ignored. Every error of the library has a tag, so a program can branch on it.
- The tags are the
Tag...constants of the packages, such asopenvpn.TagAuthFailed - The errors are made with my errors package, and
errors.FromErrorreads them ReadandWritereturnio.EOFwhen the server leaves,net.ErrClosedafterCloseandos.ErrDeadlineExceededfor a deadline
// The profile has "compress lz4" at line 11.
_, err := ovpn.Parse(strings.NewReader(text))
if e, ok := errors.FromError(err); ok {
fmt.Println(e.Tag == ovpn.TagUnsupportedOption)
fmt.Println(e.Message)
fmt.Println(e.Metadata["option"], e.Metadata["line"])
fmt.Println(e.Metadata["reason"])
}
// Output:
// true
// the profile has an option that is not supported
// compress 11
// compression is not supported
vpnnet
Dial and listen through the VPN
A Net runs a TCP/IP stack inside the program, and the one interface of the stack is the tunnel. DialContext, Listen and ListenPacket return a net.Conn, a net.Listener and a net.PacketConn, so the code that uses them does not know about the VPN.
- A listener is reached by the other machines of the VPN at the client’s tunnel address
- The stack is gVisor’s, and no type of gVisor is in the API
- The methods of a
Netare safe to call from several goroutines
n, err := vpnnet.New(conn, &vpnnet.Options{CloseConn: true})
if err != nil {
log.Fatal(err)
}
defer n.Close()
l, err := n.Listen("tcp", ":8080") // every address of the tunnel
if err != nil {
log.Fatal(err)
}
fmt.Println("listening at", l.Addr())
mux := http.NewServeMux()
mux.HandleFunc("/", hello)
server := &http.Server{
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
log.Fatal(server.Serve(l))
vpnnet
Names are looked up through the VPN too
By default the names are asked of the DNS servers that the VPN server pushed. Give your own in Options.DNSServers, and the pushed ones are not used. The DNS client of the package reads nothing of the machine: not /etc/resolv.conf, not /etc/hosts.
- The queries go through the tunnel, so the VPN must route to the DNS server
- A name is asked as it is given, with no search list
n.Resolver()is Go’s*net.Resolverover the same servers, for code that needs that type
n, err := vpnnet.New(conn, &vpnnet.Options{
CloseConn: true,
// In order; a port of 0 is 53.
DNSServers: []netip.AddrPort{
netip.MustParseAddrPort("1.1.1.1:53"),
netip.MustParseAddrPort("1.0.0.1:53"),
},
})
if err != nil {
log.Fatal(err)
}
defer n.Close()
// Asked of 1.1.1.1, through the VPN.
addrs, err := n.LookupNetIP(ctx, "ip", "example.com")
openvpn
A ping, built by hand
examples/ping uses only the tunnel. It connects, takes its address from what the server pushed, and sends ICMP echo requests: it builds and reads the IP packets itself, with the public API only. Beside is a run against an OpenVPN 2.7.9 server on the same machine, with no root.
- The address, the cipher and the MTU of the first line are from
conn.ConnectionState() - Ctrl-C stops it at any moment, and the tunnel is closed before it exits
$ go run ./examples/ping -server vpn.example.com:1194 -count 3 \
-ca ca.crt -cert client.crt -key client.key -tls-crypt ta.key
connected: address 10.8.0.2/24, cipher AES-256-GCM, MTU 1500; pinging 10.8.0.1
28 bytes from 10.8.0.1: seq=1 time=60µs payload="ping 0001 from gopenvpn-conn"
28 bytes from 10.8.0.1: seq=2 time=650µs payload="ping 0002 from gopenvpn-conn"
28 bytes from 10.8.0.1: seq=3 time=420µs payload="ping 0003 from gopenvpn-conn"
Written to be checked
A VPN client holds keys and passwords, and reads bytes from the network. These are the rules that the code keeps.
Secrets stay out of the logs
The password is never logged and never in an error. The logger never gets a key, a password or the bytes of a packet.
The server is verified as OpenVPN does
NewTLSConfigchecks that the certificate of the server leads to the CA, and takesremote-cert-tls,verify-x509-nameandpeer-fingerprintof a profile.The parser reads what it is given
A file name of a profile that is absolute, or climbs out of the directory with
.., is an error.Tests on a fake clock
The unit tests of the tunnel run on a fake clock, with
testing/synctest. They need noopenvpnbinary and no privileges.
What it supports
The target of 1.0 is a modern client. Servers from OpenVPN 2.6 on are expected to work.
| Supported | Not in 1.0 |
|---|---|
| UDP and TCP, IPv4 and IPv6 | HTTP and SOCKS proxies (a dial function of your own can do it) |
TLS 1.2 and 1.3 through crypto/tls | TLS below 1.2 |
tls-auth, tls-crypt, tls-crypt-v2, or no protection of the control channel; dynamic tls-crypt at renegotiations | |
| AES-128/192/256-GCM and CHACHA20-POLY1305, with both AEAD packet formats | CBC, CFB and OFB ciphers |
| Cipher negotiation, data keys from the TLS exporter | The old key derivation (servers before 2.6) |
Certificates, auth-user-pass, auth-token, verify-x509-name, peer-fingerprint | Challenge/response, web authentication, PKCS#11 |
| Pushed options, keepalive, renegotiation without a lost packet, exit notification | PUSH_UPDATE, compression, fragment, static-key mode, --dev tap |
Profiles: remote, remote-random, connect-timeout, <connection> blocks, inline files, pull-filter, route-nopull | A system TUN device |
From the README of version 1.0.5.
The tunnel on its own
openvpn.Dial returns a *openvpn.Conn. One Read returns one IP packet from the VPN, and one Write sends one. What you do with the packets is yours: Tube feeds a TUN device from them, and examples/ping builds them itself.
ConnectionState()has the addresses, routes, DNS servers and MTU that the server pushedopenvpn.Clientandopenvpn.PacketClientdo the same over a connection that you made- A
Dialerwith aDialContextof your own makes the link, which is a way to go through a proxy - A
Connis one session. When it ends,ReadandWritereturn the error and the program dials again
config := &openvpn.Config{
// The server's certificate must lead to the CA,
// as in an OpenVPN profile.
TLS: openvpn.NewTLSConfig(openvpn.TLSOptions{
RootCAs: roots,
Certificates: []tls.Certificate{cert},
RemoteCertTLSServer: true,
}),
ControlWrap: wrap, // openvpn.NewTLSCrypt(key)
}
conn, err := openvpn.Dial(ctx, "udp",
"vpn.example.com:1194", config)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// What the server pushed is in the state.
state := conn.ConnectionState()
packet := make([]byte, state.MTU)
n, err := conn.Read(packet) // one IP packet
Used by Tube, made with errors
Tube connects to OpenVPN servers with this library, and the library tags its errors with the errors package.
What gopenvpn-conn does not do
Better to read it here than to find it out.
- It is a client. Its API has no server.
- It does not reconnect. When a session ends, the program dials again. A reconnecting client is after 1.0.
- It makes no TUN device of the system, so other programs do not use the VPN. Tube puts another program in a VPN with it.
- No proxies, compression,
fragment, static-key mode,--dev tap, CBC ciphers, or servers before OpenVPN 2.6. The table above has the whole list. - Under a tunnel that loses about a fifth of its packets, a TCP connection of
vpnnetwith both directions saturated can stall for minutes. Put a deadline on connections on such a link. - The license is GPL-2.0-only. A program that uses the library and is distributed must be distributed under the GPL-2.0 as a whole.
Under the hood#
The library has three layers, and each one works without the ones above it.
| Package | What it gives |
|---|---|
openvpn | The tunnel. openvpn.Dial returns a net.Conn whose Read returns one IP packet from the VPN and whose Write sends one. |
ovpn | The parser of .ovpn profiles. A profile becomes a Config and a list of remotes, and Profile.Dial connects. |
vpnnet | A userspace network over a connection: DialContext, Listen, ListenPacket and a *net.Resolver that go through the VPN, with no TUN device and no root. |
vpnnet runs gVisor’s TCP/IP stack inside the program, and it is the only package of the module that imports it. The packets that the stack sends are written to the connection, and the packets that the connection reads are given to the stack.
The library is derived from the client side of OpenVPN 2, which has the same license. TLS comes from crypto/tls of Go. In the repository, docs/SPEC.md is the specification, and docs/IMPLEMENTED.md is the log of what is done and how it was shown to work.
Tube is built on it.
This is a library that speaks the OpenVPN protocol as a client. It is not OpenVPN’s own program, it is not affiliated with OpenVPN Inc, and OpenVPN is a trademark of OpenVPN Inc.
- Kind
- Library
- Language
- Go
- Runs on
- Linux, macOS, Windows
- License
- GPL-2.0
- Version
- v1.0.5
Start with a profile
You need Go 1.27.3 or newer, the version of the module’s go.mod. The examples are in the repository, and they run with your own server and profile.
# Add the library to your module
$ go get github.com/rm4n0s/gopenvpn-conn
# Or get the repository, and a page through your VPN
$ git clone https://github.com/rm4n0s/gopenvpn-conn
$ cd gopenvpn-conn
$ go run ./examples/http -profile client.ovpn \
-url http://intranet.example.com/