openvpn

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: GPL-2.0 Imports: 25 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gopenvpn-conn

An OpenVPN client library for Go, with the patterns of the standard library. It is pure Go (no cgo, no unsafe of its own), needs no root and changes nothing on the machine, and works on Linux, Windows and macOS.

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.

Status: 1.0 (v1.0.1). The tunnel (package openvpn), the profile parser (ovpn) and the userspace network (vpnnet) are complete and were run against a real OpenVPN 2.7.9 server on Linux, under Wine on Windows, and on macOS (Apple silicon, against a server in a Linux VM, over UDP and TCP, with the server's kernel data channel (DCO) and without it). docs/SPEC.md is the specification, docs/IMPLEMENTATION.md the plan, and docs/IMPLEMENTED.md the log of what is done and how it was shown to work.

Three layers

Each layer works without the ones above it.

Package What it gives
openvpn The tunnel: openvpn.Dial returns a *openvpn.Conn, 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 Conn: DialContext, Listen, ListenPacket and a *net.Resolver that go through the VPN, with no TUN device and no root; only the connections of the program use the VPN
A web page through the VPN, from a profile
profile, err := ovpn.ParseFS(os.DirFS("/etc/openvpn/client"), "work.ovpn")
if err != nil {
	log.Fatal(err)
}
conn, err := profile.Dial(ctx) // tries the remotes of the profile 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 (or those of vpnnet.Options.DNSServers), and the connection goes through it too.
client := &http.Client{Transport: &http.Transport{DialContext: n.DialContext}}
resp, err := client.Get("http://intranet.example.com/")

ovpn.ParseFS 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. A profile with auth-user-pass and no file leaves the password to the program: set profile.Config.Credentials. Options that the library cannot honor are refused with an error that names the option and its line (profile.Ignored lists the ones that were accepted and do nothing). vpnnet listens too: n.Listen("tcp", ":8080") is reached by the other machines of the VPN at the client's tunnel address. See ovpn/example_test.go, vpnnet/example_test.go and examples/http:

go run ./examples/http -profile client.ovpn -url http://intranet.example.com/
Your own DNS servers

By default the names are looked up at the DNS servers that the VPN server pushed. To use your own, here 1.1.1.1, give them in Options.DNSServers; the pushed ones are then not used.

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()

addrs, err := n.LookupNetIP(ctx, "ip", "example.com") // asked of 1.1.1.1, through the VPN

// The names of the dials are looked up at 1.1.1.1 too.
client := &http.Client{Transport: &http.Transport{DialContext: n.DialContext}}
resp, err := client.Get("http://example.com/")

The queries go through the tunnel, so the VPN must route to the DNS server (1.1.1.1 needs a VPN that reaches the internet). LookupNetIP, LookupHost and DialContext use a DNS client of this package that reads nothing of the machine: not /etc/resolv.conf, not /etc/hosts. A name is asked as it is given, with no search list. n.Resolver() is Go's *net.Resolver over the same servers, for code that needs that type; Go's resolver still reads those two files. See ExampleNet_LookupNetIP in vpnnet/example_test.go.

The tunnel on its own

openvpn.Dial works as tls.Dial does.

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), NewTLSAuth, NewTLSCryptV2; nil for none
}
conn, err := openvpn.Dial(ctx, "udp", "vpn.example.com:1194", config)
if err != nil {
	log.Fatal(err)
}
defer conn.Close()

state := conn.ConnectionState() // the address, routes, DNS servers and MTU the server pushed
packet := make([]byte, state.MTU)
n, err := conn.Read(packet) // one IP packet

openvpn.Client(conn, config) and openvpn.PacketClient(conn, config) do the same over a connection that you made (a stream, or a connected datagram socket), as tls.Client does. Deadlines, Close and the errors of Read and Write follow net.Conn: io.EOF when the server leaves, net.ErrClosed after Close, os.ErrDeadlineExceeded for a deadline. Every other error is tagged, so a program can branch on it with errors.FromError (the tags are the Tag... constants of the packages). See example_test.go and examples/ping, which sends ICMP echo requests through the tunnel:

go run ./examples/ping -server vpn.example.com:1194 -ca ca.crt -cert client.crt -key client.key -tls-crypt ta.key

A Conn is one session: when it ends (the server says so, the keepalive times out, a renegotiation fails, a TCP link fails) Read and Write return the error and the program dials again. A UDP link that loses packets, or refuses some for a moment, does not end it: the keepalive decides.

What it supports

The target of 1.0 is a modern client; the reference server is OpenVPN 2.7.9, and servers from 2.6 on are expected to work.

Supported Not in 1.0
UDP and TCP, IPv4 and IPv6 HTTP and SOCKS proxies (a custom dial function 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 (32-bit packet ids and epochs) 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 (tun, after 1.0)

A reconnecting client is after 1.0. The userspace network has one known limit under a very lossy tunnel (SPEC §13, "Known limit"): a TCP connection with both directions saturated can stall for minutes when about a fifth of the tunnel's packets are lost; put a deadline on connections on such a link.

Testing

go test -race ./...                       # unit tests: no openvpn binary, no privileges
CGO_ENABLED=0 go test ./...               # the same without cgo
scripts/vpn-ns.sh -- go test -race -tags gopenvpn_server ./...   # against a real OpenVPN server
scripts/test-windows.sh                   # the unit tests for Windows, under Wine
scripts/check.sh                          # every check of the definition of done

The unit tests run the client against a server written for the tests, in the same process, on a fake clock (testing/synctest). The tests against the real server need openvpn installed; scripts/vpn-ns.sh runs them in a private user and network namespace, with no root, where the server and the client talk over the loopback. The soak tests (loss, reordering, an hour of renegotiations) are listed in CLAUDE.md.

The go line of go.mod is 1.27.3, the version that gVisor's go branch needs (SPEC §18).

License

GPL-2.0-only, with the linking exception for Apache-2.0 code in NOTICE. The library is derived from the client side of OpenVPN 2, which has the same license. A program that uses the library and is distributed must be distributed under the GPL-2.0 as a whole. See LICENSE and NOTICE.

Documentation

Overview

Package openvpn is an OpenVPN client library with the patterns of the Go standard library.

A program gives a Config (or an .ovpn profile, parsed by package ovpn) and gets a *Conn: a net.Conn whose Read returns one IP packet from the VPN and whose Write sends one. It needs no root and changes nothing on the machine. Package vpnnet builds on a *Conn to give DialContext, Listen and ListenPacket over the tunnel, with a TCP/IP stack inside the program.

The library speaks the modern OpenVPN protocol (servers from OpenVPN 2.6 on) over UDP and TCP, with TLS from crypto/tls, the control channel protections tls-auth, tls-crypt and tls-crypt-v2, and AEAD data channel ciphers.

This is not OpenVPN's own program and is not affiliated with OpenVPN Inc. The library is licensed GPL-2.0-only; see the files LICENSE and NOTICE.

Index

Examples

Constants

View Source
const (
	// TagHandshakeTimeout: the handshake did not finish within
	// Config.HandshakeTimeout. Metadata: "timeout".
	TagHandshakeTimeout = session.TagHandshakeTimeout
	// TagServerPollTimeout: no packet of the server came within
	// Config.ServerPollTimeout: the server is not there, or a firewall drops the
	// packets. Metadata: "timeout".
	TagServerPollTimeout = session.TagServerPollTimeout
	// TagLinkFailed: reading or writing the link to the server failed. The
	// cause (an io.EOF, a closed connection) can be found with errors.Is.
	// Metadata: "op" ("read" or "write").
	TagLinkFailed = session.TagLinkFailed
	// TagAuthFailed: the server refused the credentials (AUTH_FAILED). Metadata:
	// "reason" (the server's text), "session" (the form "SESSION:", a token
	// that has expired), "temporary" (the form "TEMP": try again later),
	// "backoff" (seconds the server asks to wait), "advance" ("no", "remote",
	// "addr" or "": what it says about the next server).
	TagAuthFailed = session.TagAuthFailed
	// TagServerHalt: the server told the client to stop (HALT). Metadata: "reason".
	TagServerHalt = session.TagServerHalt
	// TagServerRestart: the server asked the client to connect again (RESTART).
	// Metadata: "reason", "flags" (P keeps the credentials, N goes to the next server).
	TagServerRestart = session.TagServerRestart
	// TagKeyExchangeFailed: the connection ended while the key exchange
	// message was written or read. Metadata: "op" ("read" or "write").
	TagKeyExchangeFailed = session.TagKeyExchangeFailed
	// TagCredentialsFailed: Config.Credentials returned an error; the cause can
	// be found with errors.Is.
	TagCredentialsFailed = session.TagCredentialsFailed
	// TagKeyExchangeTooLong: the user name and the password that Config.Credentials
	// returned do not fit, with the peer info, in the one message of 2048 bytes
	// that a server reads. Nothing of them was sent. Metadata: "length", "max".
	TagKeyExchangeTooLong = ctrlmsg.TagKeyExchangeTooLong
	// TagTLSHandshakeFailed: the TLS handshake with the server failed: a
	// certificate that does not verify, a client certificate that the server
	// refuses, no TLS version in common. The cause, a crypto/tls or x509
	// error, can be found with errors.Is and errors.As.
	TagTLSHandshakeFailed = session.TagTLSHandshakeFailed
	// TagKeyDerivationUnsupported: the server did not ask for the keys of the TLS
	// exporter (key-derivation tls-ekm), the only derivation this library has.
	// Metadata: "key_derivation".
	TagKeyDerivationUnsupported = session.TagKeyDerivationUnsupported
	// TagKeyExportFailed: the TLS session could not export the key material of the
	// data channel (a TLS 1.2 session without the extended master secret); the
	// cause is the crypto/tls error.
	TagKeyExportFailed = session.TagKeyExportFailed
	// TagPacketTooLarge: Write got a packet larger than the MTU of the tunnel.
	// Metadata: "len" and "mtu".
	TagPacketTooLarge = session.TagPacketTooLarge
	// TagPingTimeout: nothing authentic arrived from the server for PingTimeout (the
	// pushed ping-restart, else Config.PingTimeout): the server or the path to it is
	// gone. Metadata: "timeout".
	TagPingTimeout = session.TagPingTimeout
	// TagServerExit: the server said EXIT before the handshake was complete. After
	// it, the same message ends the session with io.EOF from Read (SPEC §5.3).
	TagServerExit = session.TagServerExit
	// TagPacketIDExhausted: every packet id of the data key was used (4 billion
	// packets), and the session ended rather than repeat a nonce: the last resort
	// of the rule of SPEC §10.
	TagPacketIDExhausted = datachan.TagPacketIDExhausted
)

Tags of the errors that a caller may branch on, with errors.FromError and the Tag field of the error.

View Source
const (
	// TagDialFailed: the connection to the server could not be made. The
	// cause (a refused connection, a timeout, the context) can be found with
	// errors.Is. Metadata: "network", "address".
	TagDialFailed = "DialFailed"
	// TagUnsupportedNetwork: the network is not one of "udp", "udp4", "udp6",
	// "tcp", "tcp4" or "tcp6". Metadata: "network".
	TagUnsupportedNetwork = "UnsupportedNetwork"
)

Tags of the errors of Dial.

View Source
const (
	// TagUnsupportedPushedOption: the server pushed an option that changes what
	// is on the wire in a way this library does not implement (compression,
	// fragmentation, a data cipher that is not AEAD). Metadata: "option".
	TagUnsupportedPushedOption = ctrlmsg.TagUnsupportedPushedOption
	// TagCipherNegotiationFailed: the server pushed a data cipher that the
	// client did not offer. Metadata: "cipher".
	TagCipherNegotiationFailed = ctrlmsg.TagCipherNegotiationFailed
	// TagPushedOptionRejected: a pull filter with the action PullReject matched a
	// pushed option. Metadata: "option" (its name, never its arguments).
	TagPushedOptionRejected = ctrlmsg.TagPushedOptionRejected
	// TagControlChannelFailed: reading or writing the control channel failed
	// after the key exchange: the server ended the TLS session, or the
	// connection broke. Metadata: "op" ("read" or "write").
	TagControlChannelFailed = session.TagControlChannelFailed
)

Tags of the errors about what the server pushed.

View Source
const (
	// TagServerFingerprintMismatch: the server's certificate is not one of the
	// fingerprints of TLSOptions.PeerFingerprints. Metadata: "fingerprint" (the
	// server's, in hexadecimal).
	TagServerFingerprintMismatch = "ServerFingerprintMismatch"
	// TagServerCertificateUsage: TLSOptions.RemoteCertTLSServer is set and the
	// server's certificate has no key usage extension, or its extended key usage
	// does not name a TLS server. Metadata: "missing".
	TagServerCertificateUsage = "ServerCertificateUsage"
	// TagServerNameMismatch: the server's certificate does not have the name that
	// TLSOptions.VerifyName asks for. Metadata: "subject", "want".
	TagServerNameMismatch = "ServerNameMismatch"
	// TagServerNameUnreadable: the subject of the server's certificate cannot be
	// compared with a name (it does not parse, or it has a NUL byte).
	TagServerNameUnreadable = "ServerNameUnreadable"
)
View Source
const DefaultHandshakeTimeout = 60 * time.Second

DefaultHandshakeTimeout is how long the handshake may take when Config.HandshakeTimeout is zero: OpenVPN's --hand-window.

View Source
const (
	// DefaultMTU is the tunnel MTU when Config.MTU is zero: OpenVPN's tun-mtu.
	DefaultMTU = 1500
)

The defaults of Config.

View Source
const DefaultRenegotiateAfter = time.Hour

DefaultRenegotiateAfter is how long a key is used when Config.RenegotiateAfter is zero: OpenVPN's --reneg-sec.

Variables

This section is empty.

Functions

func NewTLSConfig

func NewTLSConfig(o TLSOptions) *tls.Config

NewTLSConfig builds a tls.Config for Config.TLS that verifies the server the way OpenVPN does: the certificate chain must lead to RootCAs, and the name in the certificate is not compared with the address that was dialed (a profile asks for a check of the name with verify-x509-name: VerifyName). Nothing is left unverified: crypto/tls would check the name, so it is told to skip only its own check, and the chain is verified in VerifyConnection.

OpenVPN: ssl_verify.c verify_callback, verify_cert; doc: tls-options.rst --remote-cert-tls, --verify-x509-name, --peer-fingerprint, --tls-groups.

Types

type Config

type Config struct {
	// TLS is the configuration of the TLS client of the control channel: the
	// server's certificate is verified with it, and its Certificates are the
	// client's. It is required. NewTLSConfig builds one that verifies the
	// server the way OpenVPN does. The library uses a copy, and raises a
	// MinVersion below TLS 1.2 to it.
	TLS *tls.Config

	// ControlWrap protects the control channel with a key shared in advance:
	// the value of NewTLSAuth, NewTLSCrypt or NewTLSCryptV2. Nil means no
	// protection, which the servers that are set up for it refuse.
	ControlWrap ControlWrap

	// Credentials gives the user name and password that the server asks for
	// (the profile's auth-user-pass). It is called once for each connection,
	// when the key exchange starts, with a context that ends with the
	// connection. Nil means no credentials. The password is never logged and
	// never in an error.
	Credentials func(ctx context.Context) (Credentials, error)

	// AuthNoCache makes the client forget the user name and password once the first key
	// exchange is done (the profile's auth-nocache). A renegotiation then uses the auth
	// token that the server pushed, or, when it pushed none, calls Credentials again.
	AuthNoCache bool

	// DataCiphers are the ciphers of the data channel that the client offers to
	// the server, best first (the profile's data-ciphers). The server picks one.
	// The default is AES-256-GCM, AES-128-GCM and CHACHA20-POLY1305; AES-192-GCM
	// is also supported.
	DataCiphers []string

	// MTU is the MTU of the tunnel (the profile's tun-mtu). Zero means 1500.
	MTU int

	// MSSFix makes the client lower the MSS that the TCP SYNs in the tunnel
	// announce, in the packets that it reads and in the ones that it writes, so
	// that a full TCP segment in its OpenVPN packet fits in one packet of the
	// network under the tunnel and is not cut into IP fragments (the profile's
	// mssfix; SPEC §10). Zero means OpenVPN's default: 1492 counted with the
	// headers of the link (MSSFixMTU) when MTU is 1500, and MTU (MSSFixFixed)
	// when it is not. A negative value turns the clamp off; otherwise it is 154
	// to 65535. ConnectionState.MSS is the MSS that results.
	MSSFix int
	// MSSFixMode is what MSSFix counts. When MSSFix is zero only MSSFixFixed
	// changes the default.
	MSSFixMode MSSFixMode

	// PeerInfo are variables that the server's scripts get with the other
	// information about the client (the profile's setenv UV_name value). Each
	// name starts with "UV_". At most 32 variables, 64 bytes a name, 256 a value
	// and 1024 bytes of all the lines "name=value" together: they travel in a
	// message that a server reads 2048 bytes of.
	PeerInfo map[string]string

	// HandshakeTimeout is how long the handshake may take; zero means
	// DefaultHandshakeTimeout. It is OpenVPN's --hand-window.
	HandshakeTimeout time.Duration

	// ServerPollTimeout is how long the client waits for the server to answer: in
	// Dial, for the link to be made and for the first packet of the server; with
	// Client and PacketClient, for the first packet, from the start of the handshake.
	// When it passes the connection fails with TagDialFailed (the link) or
	// TagServerPollTimeout (no packet). Once the server has answered it bounds
	// nothing more: HandshakeTimeout bounds the handshake. It is OpenVPN's
	// --connect-timeout (--server-poll-timeout). Zero means no limit of its own;
	// negative is invalid.
	ServerPollTimeout time.Duration

	// PingInterval is how long the connection may be idle before the client sends
	// a keepalive ping (OpenVPN's --ping). A value that the server pushes (ping)
	// wins. Zero means no ping unless the server pushes one; negative is invalid.
	PingInterval time.Duration

	// PingTimeout is how long the client waits for anything from the server before
	// it ends the session with TagPingTimeout (--ping-restart). A value that the
	// server pushes (ping-restart) wins. Zero means no timeout unless the server
	// pushes one; negative is invalid.
	PingTimeout time.Duration

	// RenegotiateAfter is how long a key is used before the client makes a new one,
	// without a break in the traffic (the profile's reneg-sec); zero means
	// DefaultRenegotiateAfter and a negative value means never. A value that the
	// server pushes does not change it: the server renegotiates by its own time too,
	// and whoever is first starts it. Early renegotiations when a key is nearly used up
	// happen whatever this is.
	RenegotiateAfter time.Duration

	// RetransmitTimeout is how long the client waits for the acknowledgement of a
	// control packet before it sends it again; each repetition waits twice as long
	// (the profile's tls-timeout). Zero means 2 seconds.
	RetransmitTimeout time.Duration

	// PullFilters decide, in order, about each option that the server pushes: the
	// first filter whose Prefix the option starts with decides, and an option that no
	// filter matches is accepted (the profile's pull-filter). An ignored option is
	// not seen by the library and is not in ConnectionState.
	PullFilters []PullFilter

	// RouteNoPull ignores the pushed options about routes and DNS (route, route-ipv6,
	// route-gateway, redirect-gateway, redirect-private, dhcp-option, dns and
	// block-outside-dns) and accepts the others (the profile's route-nopull).
	RouteNoPull bool

	// Logger gets the events of the connection, with the error of a failure
	// as the attribute "err". It never gets a key, a password or a packet's
	// bytes. Nil means no logs.
	Logger *slog.Logger
	// contains filtered or unexported fields
}

Config is the configuration of a client, as tls.Config is for TLS. The zero value of a field means its default. A Config is not changed by the library and may be shared by connections.

func (*Config) Validate added in v0.3.0

func (c *Config) Validate() error

Validate reports whether the Config can be used: it returns the error that a Conn made with it would fail with, or nil. The error names the field and never carries a value that could be a secret.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn is one session with a server and a net.Conn of IP packets: Read returns one IP packet that the server sent, and Write sends one (SPEC §5.1).

The error that ends a Conn is one value: every later call returns that same error, to every goroutine, and its route begins at the call that started the session (Dial, HandshakeContext, or a first Read or Write). It is shared, so a program must not change it (SetMetadata) (SPEC §14.2).

func Client

func Client(conn net.Conn, config *Config) *Conn

Client makes a Conn over conn, which is a stream (TCP framing). It returns at once and starts nothing: the handshake runs at HandshakeContext. The Conn takes conn over: Close closes it, and so does the end of the session. A nil config is the zero Config.

func Dial

func Dial(ctx context.Context, network, address string, config *Config) (*Conn, error)

Dial connects to the server at address and returns when the handshake is complete, or when it fails or ctx is done. network is "udp", "udp4", "udp6", "tcp", "tcp4" or "tcp6". A nil config is the zero Config.

ctx bounds the connecting and the handshake; it does not bound the life of the Conn that is returned. Config.ServerPollTimeout bounds the connecting and the wait for the server's first packet, and Config.HandshakeTimeout the handshake.

A name with more than one address: over TCP the addresses are tried until a connection is made, as net.Dialer does. Over UDP, where no connection says that the server is there, the next address is tried when the server at one sends nothing at all, each with Config.ServerPollTimeout of its own (without it, an address that is silent takes the time of the handshake); the error is the one of the last address, with the metadata "addresses" and "addresses_tried". A server that has answered is the server: what fails after that is returned.

Example

ExampleDial connects to a server and reads the first IP packet that it sends. It is compiled but not run: it needs a server and the files of a profile.

package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"log"
	"os"
	"time"

	openvpn "github.com/rm4n0s/gopenvpn-conn"
)

func main() {
	ca, err := os.ReadFile("ca.crt")
	if err != nil {
		log.Fatal(err)
	}
	roots := x509.NewCertPool()
	if !roots.AppendCertsFromPEM(ca) {
		log.Fatal("ca.crt has no certificate")
	}
	cert, err := tls.LoadX509KeyPair("client.crt", "client.key")
	if err != nil {
		log.Fatal(err)
	}
	key, err := os.ReadFile("tls-crypt.key") // the profile's tls-crypt file
	if err != nil {
		log.Fatal(err)
	}
	wrap, err := openvpn.NewTLSCrypt(key)
	if err != nil {
		log.Fatal(err)
	}

	config := &openvpn.Config{
		// The server's certificate must lead to the CA, as in an OpenVPN profile; the
		// name in it is not compared with the address.
		TLS: openvpn.NewTLSConfig(openvpn.TLSOptions{
			RootCAs:             roots,
			Certificates:        []tls.Certificate{cert},
			RemoteCertTLSServer: true,
		}),
		ControlWrap: wrap,
	}

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	conn, err := openvpn.Dial(ctx, "udp", "vpn.example.com:1194", config)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := conn.Close(); err != nil {
			log.Print(err)
		}
	}()

	// The tunnel is up. What the server pushed is in the state of the connection.
	state := conn.ConnectionState()
	fmt.Println("addresses:", state.Addrs, "cipher:", state.Cipher, "MTU:", state.MTU)

	// A Conn is a net.Conn of IP packets: one Read returns one packet.
	packet := make([]byte, state.MTU)
	n, err := conn.Read(packet)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("an IP packet of %d bytes\n", n)
}

func PacketClient

func PacketClient(conn net.Conn, config *Config) *Conn

PacketClient is Client for a connected datagram socket: each Read and Write of conn is one packet.

func (*Conn) Close

func (c *Conn) Close() error

Close ends the session, closes the connection to the server and waits for the goroutines of the Conn. After Close, every method returns net.ErrClosed.

func (*Conn) ConnectionState added in v0.2.0

func (c *Conn) ConnectionState() ConnectionState

ConnectionState returns what was negotiated. It is safe to call at any time and from any goroutine; it returns a copy.

func (*Conn) HandshakeContext

func (c *Conn) HandshakeContext(ctx context.Context) error

HandshakeContext runs the handshake if it has not run, and returns when it is complete, when it fails, or when ctx is done. A done ctx ends the session: the Conn is then unusable and the caller closes it. Calls after the handshake returns the same result.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr is the local address of the link to the server.

func (*Conn) NetConn

func (c *Conn) NetConn() net.Conn

NetConn returns the connection to the server that was given to Client or PacketClient. Reading or writing it breaks the session.

func (*Conn) Read added in v0.2.0

func (c *Conn) Read(b []byte) (int, error)

Read returns the next IP packet that the server sent, waiting for it, as one Read of a connected UDP socket does: a buffer that is too small gets the start of the packet and the rest is dropped (ConnectionState().MTU is always enough). It runs the handshake first when that has not run. When the session ends, Read returns the error that ended it.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr is the address of the server on the link.

func (*Conn) SetDeadline added in v0.2.0

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines of the connection, as net.Conn says: a Read or Write that is waiting or comes later returns os.ErrDeadlineExceeded (that value, a net.Error whose Timeout is true) when the time has passed, a time in the past unblocks the calls that are waiting, and the zero time is no deadline. The deadlines bound the wait for a packet and for the link, not the handshake that a first Read or Write may start (HandshakeTimeout does). After Close it returns net.ErrClosed.

func (*Conn) SetReadDeadline added in v0.2.0

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline of Read; see SetDeadline.

func (*Conn) SetWriteDeadline added in v0.2.0

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline of Write; see SetDeadline.

func (*Conn) Write added in v0.2.0

func (c *Conn) Write(b []byte) (int, error)

Write sends one IP packet to the server. It runs the handshake first when that has not run. A packet larger than ConnectionState().MTU is an error (TagPacketTooLarge). A nil error does not mean that the packet arrived: the data channel does not guarantee it.

type ConnectionState added in v0.2.0

type ConnectionState struct {
	// HandshakeComplete is true when the server's PUSH_REPLY has been read.
	HandshakeComplete bool
	// TLS is the state of the TLS session of the control channel.
	TLS tls.ConnectionState
	// Cipher is the data cipher that the server chose, for example
	// "AES-256-GCM"; empty when it chose none.
	Cipher string
	// PeerID is the peer id that the server gave this client, or 0xffffff when
	// it gave none.
	PeerID uint32
	// Addrs are the addresses of the tunnel: the IPv4 address with the length of
	// its network (ifconfig and topology) and the IPv6 address (ifconfig-ipv6).
	Addrs []netip.Prefix
	// Gateway is the address of the server inside the tunnel (route-gateway).
	Gateway netip.Addr
	// Routes are the routes that the server pushed.
	Routes []Route
	// RedirectGateway is true when the server asks for all the traffic of the
	// client to go through the VPN.
	RedirectGateway bool
	// DNSServers are the DNS servers that the server pushed (dhcp-option DNS and
	// DNS6, and the dns option).
	DNSServers []netip.Addr
	// SearchDomains are the DNS search domains that the server pushed
	// (dhcp-option DOMAIN and DOMAIN-SEARCH, and the dns option).
	SearchDomains []string
	// MTU is the MTU of the tunnel: the one the server pushed, or the one of the
	// Config. It is the size of the largest IP packet that Write takes.
	MTU int
	// MSS is the largest MSS that a TCP SYN over IPv4 in the tunnel may announce:
	// the client lowers a larger one in the packets that it reads and writes, as
	// OpenVPN's mssfix does (a SYN over IPv6 gets 20 less). Zero before the
	// handshake is complete and when Config.MSSFix turns the clamp off.
	MSS int
	// PingInterval is the keepalive interval that the server pushed (ping); zero
	// when it pushed none.
	PingInterval time.Duration
	// PingTimeout is the keepalive timeout that the server pushed (ping-restart);
	// zero when it pushed none.
	PingTimeout time.Duration
	// PushedOptions are the options of the PUSH_REPLY as the server sent them,
	// the unknown ones too. The value of auth-token is left out: it is a secret.
	PushedOptions []string
}

ConnectionState is what was negotiated and what the server pushed. Before the handshake is complete only the MTU of the Config is set.

type ControlWrap

type ControlWrap interface {
	// contains filtered or unexported methods
}

ControlWrap is a protection of the control channel (OpenVPN's tls-auth, tls-crypt and tls-crypt-v2). Make one with NewTLSAuth, NewTLSCrypt or NewTLSCryptV2. A ControlWrap holds a key and no connection state, so one value may be in the Config of many connections.

func NewTLSAuth

func NewTLSAuth(key []byte, direction KeyDirection, digest crypto.Hash) (ControlWrap, error)

NewTLSAuth makes the protection of tls-auth. key is the contents of the static key file (the text between the "OpenVPN Static key V1" lines, as `openvpn --genkey tls-auth` writes it). digest is the profile's auth option: crypto.SHA1 (OpenVPN's default), SHA256, SHA384 or SHA512.

Draft: "tls-auth".

func NewTLSCrypt

func NewTLSCrypt(key []byte) (ControlWrap, error)

NewTLSCrypt makes the protection of tls-crypt. key is the contents of the static key file that `openvpn --genkey tls-crypt` writes.

Draft: "tls-crypt".

func NewTLSCryptV2

func NewTLSCryptV2(key []byte) (ControlWrap, error)

NewTLSCryptV2 makes the protection of tls-crypt-v2. key is the contents of the client key file that `openvpn --genkey tls-crypt-v2-client` writes (a PEM block, "OpenVPN tls-crypt-v2 client key").

Draft: "tls-crypt-v2".

type Credentials added in v0.2.0

type Credentials struct {
	// Username is the user name.
	Username string
	// Password is the password. It is never logged and never in an error.
	Password string
}

Credentials are the user name and password of auth-user-pass. They travel in one message of at most 2048 bytes, with the peer info and the options string, which leaves about 1400 bytes for the two together; a longer one makes the handshake fail before anything of it is sent. A server may accept less: an OpenVPN that was built without PKCS#11 takes 127 bytes of each, and answers a longer one with TagAuthFailed.

type Dialer

type Dialer struct {
	// NetDialer makes the connection to the server (the link). Nil means the
	// zero net.Dialer. It is not used when DialContext is set.
	NetDialer *net.Dialer
	// DialContext, when set, makes the link in place of NetDialer: a way to
	// go through a proxy, or to use a link of the caller's own. It gets the
	// address as Dial got it: a name is not looked up, so its other addresses
	// are DialContext's to try.
	DialContext func(ctx context.Context, network, address string) (net.Conn, error)
	// Config is the configuration of the connections; nil is the zero Config.
	Config *Config
	// contains filtered or unexported fields
}

Dialer makes connections to servers with the same settings, as net.Dialer does.

func (*Dialer) Dial

func (d *Dialer) Dial(ctx context.Context, network, address string) (*Conn, error)

Dial is the function Dial with the settings of the Dialer.

type KeyDirection

type KeyDirection int

KeyDirection is the direction of the keys of a static key file, OpenVPN's key-direction: which half of the file this side sends with.

const (
	// KeyDirectionNone uses the first keys of the file in both directions: the
	// profile has no key-direction.
	KeyDirectionNone KeyDirection = iota
	// KeyDirection0 sends with the first keys and receives with the second:
	// key-direction 0, the usual setting of a server.
	KeyDirection0
	// KeyDirection1 sends with the second keys and receives with the first:
	// key-direction 1, the usual setting of a client.
	KeyDirection1
)

type MSSFixMode added in v1.0.2

type MSSFixMode int

MSSFixMode is what Config.MSSFix counts: the second argument of the profile's mssfix.

const (
	// MSSFixPacket: MSSFix is the largest OpenVPN packet, without the IP and the
	// UDP or TCP headers of the link ("mssfix N").
	MSSFixPacket MSSFixMode = iota
	// MSSFixMTU: MSSFix is the largest IP packet on the network under the
	// tunnel, the headers of the link counted ("mssfix N mtu").
	MSSFixMTU
	// MSSFixFixed: MSSFix is the largest IP packet in the tunnel, whatever the
	// overhead; the MSS is MSSFix less 40 ("mssfix N fixed").
	MSSFixFixed
)

The modes of Config.MSSFix.

type NameMatch added in v0.3.0

type NameMatch int

NameMatch is how TLSOptions.VerifyName is compared with the server's certificate (the type of verify-x509-name).

const (
	// MatchSubject compares the whole subject, written as OpenVPN writes it: the
	// attributes in the order of the certificate as short-name=value, separated by a
	// comma and a space (for example "C=KG, ST=NA, L=Bishkek, CN=Server-1").
	MatchSubject NameMatch = iota
	// MatchCommonName compares the common name (type name).
	MatchCommonName
	// MatchCommonNamePrefix takes a common name that starts with the name (type
	// name-prefix).
	MatchCommonNamePrefix
)

type PullAction added in v0.3.0

type PullAction int

PullAction is what a PullFilter does with the pushed options that it matches.

const (
	// PullAccept keeps the option; it is there to let some options through a later
	// filter that ignores more.
	PullAccept PullAction = iota
	// PullIgnore removes the option, as if the server had not pushed it.
	PullIgnore
	// PullReject ends the handshake with TagPushedOptionRejected.
	PullReject
)

type PullFilter added in v0.3.0

type PullFilter struct {
	// Action is what is done with a matching option.
	Action PullAction
	// Prefix is compared with the start of the pushed option as the server sent it
	// (for example "route " or "dhcp-option DNS").
	Prefix string
}

PullFilter is one pull-filter line of a profile: the pushed options that start with Prefix get Action.

type Route added in v0.2.0

type Route struct {
	// Prefix is the network that the route leads to.
	Prefix netip.Prefix
	// Gateway is the next hop when the server named one; the zero Addr means
	// the gateway of the VPN (ConnectionState.Gateway).
	Gateway netip.Addr
	// Metric is the metric, or 0 when the server gave none.
	Metric int
}

Route is a route that the server pushed.

type TLSOptions

type TLSOptions struct {
	// RootCAs are the authorities that sign the server's certificate (the
	// profile's ca). Nil means the roots of the system.
	RootCAs *x509.CertPool
	// Certificates is the client's certificate and key (the profile's cert and
	// key). The servers that are set up as usual refuse a client without one.
	Certificates []tls.Certificate
	// RemoteCertTLSServer requires the server's certificate to be one for a TLS
	// server, as --remote-cert-tls server does: it must have a key usage
	// extension and the extended key usage "TLS Web Server Authentication". A
	// certificate with no extended key usage is refused. Without it a client's
	// certificate of the same authority can pass for the server's.
	RemoteCertTLSServer bool
	// MinVersion is the lowest TLS version, tls.VersionTLS12 or
	// tls.VersionTLS13; zero means TLS 1.2, which is also the lowest that the
	// library accepts.
	MinVersion uint16
	// VerifyName, when it is not empty, must match the server's certificate in the
	// way that VerifyNameMatch says (--verify-x509-name). It is checked after the
	// chain and the usage, and only for the server's own certificate.
	VerifyName string
	// VerifyNameMatch is how VerifyName is compared; the zero value compares the whole
	// subject.
	VerifyNameMatch NameMatch
	// PeerFingerprints are the SHA-256 fingerprints of the certificates that are
	// accepted as the server's (--peer-fingerprint); the server's certificate must be
	// one of them. When RootCAs is nil as well the chain is not verified, as OpenVPN
	// does for a profile that has a fingerprint and no ca: the fingerprint is the trust,
	// and the dates of the certificate are still checked. With RootCAs both are
	// checked.
	PeerFingerprints [][sha256.Size]byte
	// CurvePreferences are the key exchange groups of TLS, best first (--tls-groups);
	// nil means those of crypto/tls.
	CurvePreferences []tls.CurveID
}

TLSOptions say how NewTLSConfig builds the TLS configuration of a client, in the terms of the options of an OpenVPN profile.

Directories

Path Synopsis
examples
http command
Command http reads an OpenVPN profile, connects to its server and gets a web page through the tunnel, with no root and no change to the machine.
Command http reads an OpenVPN profile, connects to its server and gets a web page through the tunnel, with no root and no change to the machine.
ping command
Command ping connects to an OpenVPN server and sends ICMP echo requests through the tunnel with no root and no change to the machine.
Command ping connects to an OpenVPN server and sends ICMP echo requests through the tunnel with no root and no change to the machine.
internal
ctrlmsg
Package ctrlmsg has the messages that travel inside the TLS session of the control channel: the key exchange message (OpenVPN's "key method 2"), the options string and the peer info that go in it, and, in later steps, the text messages (PUSH_REPLY, AUTH_FAILED, HALT, RESTART).
Package ctrlmsg has the messages that travel inside the TLS session of the control channel: the key exchange message (OpenVPN's "key method 2"), the options string and the peer info that go in it, and, in later steps, the text messages (PUSH_REPLY, AUTH_FAILED, HALT, RESTART).
ctrlwrap
Package ctrlwrap protects the packets of the control channel: it adds the authentication (tls-auth) or the encryption and authentication (tls-crypt, tls-crypt-v2) that a pre-shared key gives, and takes it off again, with the replay protection that goes with it.
Package ctrlwrap protects the packets of the control channel: it adds the authentication (tls-auth) or the encryption and authentication (tls-crypt, tls-crypt-v2) that a pre-shared key gives, and takes it off again, with the replay protection that goes with it.
datachan
Package datachan seals and opens the packets of the data channel: the 32-bit packet id AEAD format of OpenVPN's DATA_V1 and DATA_V2 packets, with AES-GCM and ChaCha20-Poly1305, and the replay protection of the receiver.
Package datachan seals and opens the packets of the data channel: the 32-bit packet id AEAD format of OpenVPN's DATA_V1 and DATA_V2 packets, with AES-GCM and ChaCha20-Poly1305, and the replay protection of the receiver.
keys
Package keys reads the key files of OpenVPN and derives the keys that the protocol uses from them: the static key file of tls-auth and tls-crypt, and (from step 1.7) the tls-crypt-v2 client key.
Package keys reads the key files of OpenVPN and derives the keys that the protocol uses from them: the static key file of tls-auth and tls-crypt, and (from step 1.7) the tls-crypt-v2 client key.
mss
Package mss lowers the TCP maximum segment size that the SYN packets of a tunnel announce, so that a TCP segment and the OpenVPN packet around it fit in one packet of the network under the tunnel (SPEC §10).
Package mss lowers the TCP maximum segment size that the SYN packets of a tunnel announce, so that a TCP segment and the OpenVPN packet around it fit in one packet of the network under the tunnel (SPEC §10).
reliable
Package reliable is the reliability layer of the control channel: it makes a link that loses, repeats and reorders packets deliver the control payloads exactly once and in order.
Package reliable is the reliability layer of the control channel: it makes a link that loses, repeats and reorders packets deliver the control payloads exactly once and in order.
replay
Package replay protects against replayed packets: a Window decides whether a received packet counter is new, and a Sender makes the packet ids of the packets this side sends.
Package replay protects against replayed packets: a Window decides whether a received packet counter is new, and a Sender makes the packet ids of the packets this side sends.
servertest
Package servertest starts a real OpenVPN server for the tests of gopenvpn-conn (SPEC §17).
Package servertest starts a real OpenVPN server for the tests of gopenvpn-conn (SPEC §17).
session
Package session is the state machine of one connection to a server: it owns the link, reads and writes control packets through the control channel protection and the reliability layer, and runs the handshake.
Package session is the state machine of one connection to a server: it owns the link, reads and writes control packets through the control channel protection and the reliability layer, and runs the handshake.
tools/errcheck command
Command errcheck checks the error rules of SPEC §14.1 on the Go files of the module: the ones that a program can check.
Command errcheck checks the error rules of SPEC §14.1 on the Go files of the module: the ones that a program can check.
vpntest
Package vpntest is the in-process peer of the unit tests: links in memory (datagrams with loss, duplicates and reordering from a seed, and streams) and a small server side made of the packet packages of this module, so that the unit tests need no openvpn binary and no privileges.
Package vpntest is the in-process peer of the unit tests: links in memory (datagrams with loss, duplicates and reordering from a seed, and streams) and a small server side made of the packet packages of this module, so that the unit tests need no openvpn binary and no privileges.
wire
Package wire has the formats of OpenVPN packets as pure functions from bytes to structs and back: the first byte (opcode and key id), session ids, the control packet with its acknowledgement array, and the 16-bit length that frames packets on a TCP stream.
Package wire has the formats of OpenVPN packets as pure functions from bytes to structs and back: the first byte (opcode and key id), session ids, the control packet with its acknowledgement array, and the 16-bit length that frames packets on a TCP stream.
Package ovpn reads OpenVPN client profiles (.ovpn files) and turns them into a configuration for package openvpn.
Package ovpn reads OpenVPN client profiles (.ovpn files) and turns them into a configuration for package openvpn.
Package vpnnet is a userspace network over an *openvpn.Conn: it makes TCP and UDP connections, listeners and packet connections that go through the VPN, with no TUN device, no root and no change to the machine.
Package vpnnet is a userspace network over an *openvpn.Conn: it makes TCP and UDP connections, listeners and packet connections that go through the VPN, with no TUN device, no root and no change to the machine.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL