HUB
Sign inSign up
openconnect logo

jesusdf/openconnect

By jesusdf

•Updated 11 days ago

https://github.com/jesusdf/openconnect - Forked from aw1cks/openconnect

Image
0

3.4K

jesusdf/openconnect repository overview

⁠OpenConnect Docker Container

Forked from https://github.com/aw1cks/openconnect⁠ to meet custom needs.

github

⁠Why?

OpenConnect doesn't ship with any init scripts or systemd units. It's also not easy to non-interactively provide username, password and especially OTP. Additionally, running in a docker container gives some extra flexibility with routing.

Additionally, this fork allows split-tunneling, that is only routing traffic through the VPN for specific hostnames or subnets using vpn-splice⁠.

Also, you can specify the tun device name, in case you are using multiple VPNs on the same machine.

⁠Where can I download it?

The image is built by GitHub Actions for amd64 & arm64 and pushed to the following repositories:

Each release is tagged with its version (e.g. 2.0.0), the commit hash and latest.

⁠How do I use it?

You can run the container using the specified arguments below.

⁠Basic container command
docker run -d \
--cap-add NET_ADMIN \
-e TZ=Europe/Madrid \
-e TUN_DEVICE=tun127 \
-e URL=https://my.vpn.com \
-e USER=myuser \
-e AUTH_GROUP=mygroup \
-e PASS=mypassword \
-e SPLICE_ARGS="server1.vpn.com 192.168.100.0/24" \
-e TOKEN_MODE=totp \
-e TOKEN_SECRET=base32:JBSWY3DPEHPK3PXP \
-e SEARCH_DOMAINS="my.corporate-domain.com subdomain.my.corporate-domain.com" \
-e EXTRA_ARGS="--no-dtls" \
-e SERVERCERT=auto \
-e MIN_SESSION_TIME=600 \
-e RECONNECT_DELAY=600 \
docker.io/jesusdf/openconnect'
⁠docker compose

docker-compose.example.yml⁠ is a ready-to-adapt setup: the VPN with the 2FA options, plus another container that uses the VPN by sharing its network namespace (network_mode: service:vpn). Those containers get the VPN's routes and /etc/hosts, but when the VPN container restarts they keep the old, disconnected namespace until they are restarted too.

⁠All container arguments
VariableExplanationExample Value
TZTimezone informationEurope/Madrid
TUN_DEVICEName of the tun device to usetun127
URLURL of AnyConnect VPNhttps://my.vpn.com
USERUser to authenticate withmyuser
AUTH_GROUPAuthentication Group to use when connecting to VPN (optional)mygroup
PASSPassword to authenticate withmypassword
SPLICE_ARGSSpace separated list of hostnames or networks that should be routed through (or excluded of) the VPNserver1.vpn.com 192.168.100.0/24
TOKEN_MODETwo-factor authentication (optional): totp, hotp or email (see below)totp
TOKEN_SECRETToken seed for totp (optional). Prefer TOKEN_SECRET_FILE to keep it out of docker inspectbase32:JBSWY3DPEHPK3PXP
TOKEN_SECRET_FILEPath (inside the container) of a file with the token seed. Required, and writable, for hotp/run/secrets/token
IMAP_HOSTIMAP server where the 2FA emails arrive (required for email)imap.my-company.com
IMAP_USERIMAP user (required for email)[email protected]
IMAP_PASSIMAP password (required for email)mailpassword
IMAP_PORTIMAP port (optional, default 993, or 143 with IMAP_SSL=no)993
IMAP_SSLUse implicit TLS for IMAP (optional, default yes)yes
IMAP_FOLDERFolder where the 2FA emails arrive (optional, default INBOX)INBOX
IMAP_FROMOnly accept 2FA emails whose sender contains this text (optional, recommended)[email protected]
IMAP_CODE_REGEXRegex that extracts the code from the email; its first group is used if any (optional, default \b(\d{6})\b)code is (\d+)
IMAP_TIMEOUTSeconds to wait for the 2FA email (optional, default 120)120
SEARCH_DOMAINSSearch domains to use. DNS for these domains will be routed via the VPN's DNS servers (optional). Separate with a space for multiple domainsmy.corporate-domain.com subdomain.my.corporate-domain.com
EXTRA_ARGSAny additional arguments to be passed to the OpenConnect client (optional). Only use this if you need something specific--verbose
SERVERCERTServer certificate pin handling (optional). auto enables trust-on-first-use pinning (see below); or pass an explicit pin-sha256:... valueauto
MIN_SESSION_TIMEMinimum time required to not being threated as premature failure, in seconds (optional).600
RECONNECT_DELAYDelay time to wait until container shuts down after a premature failure, in seconds (optional).600

Notice that vpn-slice accepts several different kinds of routes and hostnames on the command line (via SPLICE_ARGS environment variable):

  • Hostnames alone (hostname1) as well as host-to-IP aliases (alias2=alias2.bigcorp.com=192.168.1.43). The former are first looked up using the VPN's DNS servers. Both are also added to the routing table, as well as to /etc/hosts (unless --no-host-names is specified). As in this example, multiple aliases can be specified for a single IP address.
  • Subnets to include (10.0.0.0/8) in the VPN routes as well as subnets to explicitly exclude (%10.123.0.0/24).

There are many command-line options to alter the behavior of vpn-slice; try vpn-slice --help to show them all.

⁠Automatic server certificate pinning (SERVERCERT=auto)

Many private servers use self-signed certificates, which OpenConnect will not trust unless you pin them with --servercert pin-sha256:.... Maintaining that pin by hand is annoying, so SERVERCERT=auto makes the container manage it for you (trust-on-first-use):

  1. On first start, the container does a TLS-handshake-only probe (no credentials are sent, so no OTP is consumed) to discover the server's pin, then caches it in /vpn/servercert.pin and connects using it.
  2. On later starts it reuses the cached pin.
  3. If the cached pin ever stops matching (the server rotated its key), OpenConnect reports it; the container re-discovers the new pin, logs the change loudly, updates the cache and retries.

The cache lives inside the container filesystem: it survives restarts, and is re-discovered from scratch whenever the container is recreated (e.g. an image update).

The discovery probe is protocol-aware: any protocol-selecting flag you put in EXTRA_ARGS is honored while probing. For non-AnyConnect servers set it there, e.g. EXTRA_ARGS="--protocol=fortinet". As a safety net, if OpenConnect cannot report the pin the container falls back to computing it with openssl, which is protocol-agnostic.

Security note. pin-sha256 is a hash of the server's public key, not of the certificate, so a normal certificate renewal that reuses the same key does not change the pin. Auto-pinning only re-trusts on the very first connection (or when the key actually changes), which is a trust-on-first-use model: convenient, but it cannot detect a man-in-the-middle present at that first moment. If you need strict protection, pass an explicit SERVERCERT=pin-sha256:... (or the --servercert flag via EXTRA_ARGS) obtained through a trusted channel instead.

⁠Two-factor authentication (TOKEN_MODE)

The 2FA code must be obtained again on every login, so a fixed code can't be used: it expires in seconds and the server rejects reused codes. Instead, the container obtains a fresh code each time it connects, so --restart keeps working unattended. Short network drops don't even need a new code: OpenConnect reconnects reusing the session cookie; a new login (and code) is only needed when the server's session expires or the outage is long.

Breaking change in 2.0. The OTP variable is no longer supported. If it is set, the container exits with an error. Use one of the modes below.

⁠totp / hotp: OpenConnect generates the code from the token seed

Use this when you have the seed of a standard OATH token (e.g. a TOTP token served by FortiAuthenticator or a third-party RADIUS/MFA provider). The seed is passed to OpenConnect as a file (--token-secret=@file), so it never shows up in the logs or in ps. Accepted formats: base32:XXXX, hexadecimal 0xXXXX, or the raw secret. For hotp, append the counter: base32:XXXX,0.

  • totp: set TOKEN_SECRET, or TOKEN_SECRET_FILE to keep the seed out of the container's environment (docker inspect shows environment variables).
  • hotp: requires a writable TOKEN_SECRET_FILE. OpenConnect writes the incremented counter back to it after every login, so mount it from the host to keep the counter when the container is recreated:
printf 'base32:JBSWY3DPEHPK3PXP,0' > /srv/vpn/token
docker run ... -e TOKEN_MODE=hotp -e TOKEN_SECRET_FILE=/run/secrets/token \
  -v /srv/vpn/token:/run/secrets/token ...

FortiToken Mobile and FortiToken hardware tokens are not supported: their seeds can't be exported.

⁠email: the code is read from the mailbox over IMAP

For servers that send the code by email (e.g. FortiGate email token). Right before logging in, the container records where the mailbox ends; after sending the password it waits for a new email, extracts the code and sends it to the server. Emails that were already there (old, used codes) are never used, and the email with the code is marked as read.

Use a mailbox dedicated to the VPN user if possible, and set IMAP_FROM to the sender of the 2FA emails, so other emails with numbers in them are ignored. If the code has a format other than 6 digits, adjust IMAP_CODE_REGEX.

docker run ... -e TOKEN_MODE=email \
  -e IMAP_HOST=imap.my-company.com -e [email protected] \
  -e IMAP_PASS=mailpassword -e [email protected] ...

SMS, push notifications and authenticator apps need a person to act, so they are not supported.

⁠Requirements
  • docker
  • sudo (and permissions to run ip and docker as root)
  • iproute2
  • jq

⁠Building the container yourself

The following build args are used:

  • BUILD_DATE (RFC3339 timestamp)
  • COMMIT_SHA (commit hash from which image was built)
docker build \
  --build-arg BUILD_DATE="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
  --build-arg COMMIT_SHA="$(git rev-parse HEAD 2>/dev/null || echo 'null')" \
  -t openconnect .

⁠Tests

tests/run.sh builds the image and runs end-to-end tests against local test servers, started as containers on a private docker network:

  • ocserv, a real VPN server with a fake internal network and DNS: tunnel, routes, DNS resolution through the VPN and vpn-slice.
  • A fake FortiGate (fake-fortinet-server.py from OpenConnect's own test suite, authentication phase only): login, totp/hotp codes checked against independently computed values, HOTP counter persistence, email mode, and server key rotation with SERVERCERT=auto.
  • GreenMail, an SMTP/IMAP server for the email mode.
tests/run.sh                 # build the repository and test it
tests/run.sh my/image:tag    # test an existing image

It needs docker with permission to use NET_ADMIN and /dev/net/tun, and takes about a minute. Run it after any base image or package upgrade: it catches the kind of breakage that only shows up at runtime.

⁠Releases

The image is only tested and published when a version tag is pushed. The CI runs shellcheck, then the tests, and only if they pass, builds and publishes the image:

git tag -a v2.0.0 -m "Version 2.0.0"
git push origin v2.0.0

The workflow can also be run by hand (Actions → Build → Run workflow). It always runs shellcheck and the tests; check publish to also build and publish the image, e.g. to pick up Alpine security updates without a new release. Choose a tag in "Use workflow from" to regenerate that release (tagged with its version, commit and latest); from a branch, only the commit and latest tags are published.

Keep org.opencontainers.image.version in the Dockerfile in sync with the tag.

⁠Known issues

OpenConnect logs this warning on startup:

Failed to open /dev/vhost-net: No such file or directory

This is normal and does not impact the operation of the VPN: OpenConnect falls back to regular tun I/O. vhost-net is only an optional performance improvement.

Against ocserv servers, DTLS may fail with DTLS handshake failed and the VPN falls back to TLS (it still works, just slower). This is a client-side regression in the default PSK-NEGOTIATE DTLS mode; it does not affect Cisco or Fortinet servers. To get DTLS back, select the cipher explicitly: EXTRA_ARGS="--dtls-ciphers=OC-DTLS1_2-AES256-GCM".

The image patches vpn-slice so it no longer flushes the IPv4 route cache: that cache does not exist since Linux 3.6, and with recent iproute2 the flush fails in unprivileged containers (read-only /proc/sys), aborting the tunnel setup. Running with --privileged is therefore not required.

Tag summary

Content type

Image

Digest

sha256:93a5f9e78…

Size

34.3 MB

Last updated

11 days ago

docker pull jesusdf/openconnect