From 3e6bb79515e3919eaee80397a115b6a4f9f2b96a Mon Sep 17 00:00:00 2001 From: "Jason A. Donenfeld" Date: Mon, 14 May 2018 18:14:55 +0200 Subject: tools: reorganize for multiplatform wg-quick --- src/tools/Makefile | 12 +- src/tools/man/wg-quick.8 | 237 +++++++++++++++++++++++++ src/tools/man/wg.8 | 230 +++++++++++++++++++++++++ src/tools/systemd/wg-quick@.service | 19 ++ src/tools/wg-quick.8 | 237 ------------------------- src/tools/wg-quick.bash | 334 ------------------------------------ src/tools/wg-quick/linux.bash | 334 ++++++++++++++++++++++++++++++++++++ src/tools/wg-quick@.service | 19 -- src/tools/wg.8 | 230 ------------------------- 9 files changed, 827 insertions(+), 825 deletions(-) create mode 100644 src/tools/man/wg-quick.8 create mode 100644 src/tools/man/wg.8 create mode 100644 src/tools/systemd/wg-quick@.service delete mode 100644 src/tools/wg-quick.8 delete mode 100755 src/tools/wg-quick.bash create mode 100755 src/tools/wg-quick/linux.bash delete mode 100644 src/tools/wg-quick@.service delete mode 100644 src/tools/wg.8 diff --git a/src/tools/Makefile b/src/tools/Makefile index 72296aa..241293f 100644 --- a/src/tools/Makefile +++ b/src/tools/Makefile @@ -35,6 +35,8 @@ WITH_SYSTEMDUNITS := yes endif endif +PLATFORM ?= $(shell uname -s | tr '[:upper:]' '[:lower:]') + CFLAGS ?= -O3 CFLAGS += -std=gnu11 -D_GNU_SOURCE CFLAGS += -Wall -Wextra @@ -43,7 +45,7 @@ CFLAGS += -DRUNSTATEDIR="\"$(RUNSTATEDIR)\"" ifeq ($(DEBUG_TOOLS),y) CFLAGS += -g endif -ifeq ($(shell uname -s),Linux) +ifeq ($(PLATFORM),linux) LIBMNL_CFLAGS := $(shell $(PKG_CONFIG) --cflags libmnl 2>/dev/null) LIBMNL_LDLIBS := $(shell $(PKG_CONFIG) --libs libmnl 2>/dev/null || echo -lmnl) CFLAGS += $(LIBMNL_CFLAGS) @@ -72,17 +74,17 @@ endif install: wg @install -v -d "$(DESTDIR)$(BINDIR)" && install -m 0755 -v wg "$(DESTDIR)$(BINDIR)/wg" - @install -v -d "$(DESTDIR)$(MANDIR)/man8" && install -m 0644 -v wg.8 "$(DESTDIR)$(MANDIR)/man8/wg.8" + @install -v -d "$(DESTDIR)$(MANDIR)/man8" && install -m 0644 -v man/wg.8 "$(DESTDIR)$(MANDIR)/man8/wg.8" @[ "$(WITH_BASHCOMPLETION)" = "yes" ] || exit 0; \ install -v -d "$(DESTDIR)$(BASHCOMPDIR)" && install -m 0644 -v completion/wg.bash-completion "$(DESTDIR)$(BASHCOMPDIR)/wg" @[ "$(WITH_WGQUICK)" = "yes" ] || exit 0; \ - install -m 0755 -v wg-quick.bash "$(DESTDIR)$(BINDIR)/wg-quick" && install -m 0700 -v -d "$(DESTDIR)$(SYSCONFDIR)/wireguard" + install -m 0755 -v wg-quick/$(PLATFORM).bash "$(DESTDIR)$(BINDIR)/wg-quick" && install -m 0700 -v -d "$(DESTDIR)$(SYSCONFDIR)/wireguard" @[ "$(WITH_WGQUICK)" = "yes" ] || exit 0; \ - install -m 0644 -v wg-quick.8 "$(DESTDIR)$(MANDIR)/man8/wg-quick.8" + install -m 0644 -v man/wg-quick.8 "$(DESTDIR)$(MANDIR)/man8/wg-quick.8" @[ "$(WITH_WGQUICK)" = "yes" -a "$(WITH_BASHCOMPLETION)" = "yes" ] || exit 0; \ install -m 0644 -v completion/wg-quick.bash-completion "$(DESTDIR)$(BASHCOMPDIR)/wg-quick" @[ "$(WITH_WGQUICK)" = "yes" -a "$(WITH_SYSTEMDUNITS)" = "yes" ] || exit 0; \ - install -v -d "$(DESTDIR)$(SYSTEMDUNITDIR)" && install -m 0644 -v wg-quick@.service "$(DESTDIR)$(SYSTEMDUNITDIR)/wg-quick@.service" + install -v -d "$(DESTDIR)$(SYSTEMDUNITDIR)" && install -m 0644 -v systemd/wg-quick@.service "$(DESTDIR)$(SYSTEMDUNITDIR)/wg-quick@.service" help: @cat INSTALL diff --git a/src/tools/man/wg-quick.8 b/src/tools/man/wg-quick.8 new file mode 100644 index 0000000..5e27d10 --- /dev/null +++ b/src/tools/man/wg-quick.8 @@ -0,0 +1,237 @@ +.TH WG-QUICK 8 "2016 January 1" ZX2C4 "WireGuard" + +.SH NAME +wg-quick - set up a WireGuard interface simply + +.SH SYNOPSIS +.B wg-quick +[ +.I up +| +.I down +| +.I save +] [ +.I CONFIG_FILE +| +.I INTERFACE +] + +.SH DESCRIPTION + +This is an extremely simple script for easily bringing up a WireGuard interface, +suitable for a few common use cases. + +Use \fIup\fP to add and set up an interface, and use \fIdown\fP to tear down and remove +an interface. Running \fIup\fP adds a WireGuard interface, brings up the interface with the +supplied IP addresses, sets up mtu and routes, and optionally runs pre/post up scripts. Running \fIdown\fP +optionally saves the current configuration, removes the WireGuard interface, and optionally +runs pre/post down scripts. Running \fIsave\fP saves the configuration of an existing +interface without bringing the interface down. + +\fICONFIG_FILE\fP is a configuration file, whose filename is the interface name +followed by `.conf'. Otherwise, \fIINTERFACE\fP is an interface name, with configuration +found at `/etc/wireguard/\fIINTERFACE\fP.conf'. + +Generally speaking, this utility is just a simple script that wraps invocations to +.BR wg (8) +and +.BR ip (8) +in order to set up a WireGuard interface. It is designed for users with simple +needs, and users with more advanced needs are highly encouraged to use a more +specific tool, a more complete network manager, or otherwise just use +.BR wg (8) +and +.BR ip (8), +as usual. + +.SH CONFIGURATION + +The configuration file adds a few extra configuration values to the format understood by +.BR wg (8) +in order to configure additional attribute of an interface. It handles the +values that it understands, and then it passes the remaining ones directly to +.BR wg (8) +for further processing. + +It infers all routes from the list of peers' allowed IPs, and automatically adds +them to the system routing table. If one of those routes is the default route +(0.0.0.0/0 or ::/0), then it uses +.BR ip-rule (8) +to handle overriding of the default gateway. + +The configuration file will be passed directly to \fBwg\fP(8)'s `setconf' +sub-command, with the exception of the following additions to the \fIInterface\fP section, +which are handled by this tool: + +.IP \(bu +Address \(em a comma-separated list of IP (v4 or v6) addresses (optionally with CIDR masks) +to be assigned to the interface. May be specified multiple times. +.IP \(bu +DNS \(em a comma-separated list of IP (v4 or v6) addresses to be set as the interface's +DNS servers. May be specified multiple times. Upon bringing the interface up, this runs +`resolvconf -a tun.\fIINTERFACE\fP -m 0 -x` and upon bringing it down, this runs +`resolvconf -d tun.\fIINTERFACE\fP`. If these particular invocations of +.BR resolvconf (8) +are undesirable, the PostUp and PostDown keys below may be used instead. +.IP \(bu +MTU \(em if not specified, the MTU is automatically determined from the endpoint addresses +or the system default route, which is usually a sane choice. However, to manually specify +an MTU to override this automatic discovery, this value may be specified explicitly. +.IP \(bu +Table \(em Controls the routing table to which routes are added. There are two +special values: `off' disables the creation of routes altogether, and `auto' +(the default) adds routes to the default table and enables special handling of +default routes. +.IP \(bu +PreUp, PostUp, PreDown, PostDown \(em script snippets which will be executed by +.BR bash (1) +before/after setting up/tearing down the interface, most commonly used +to configure custom DNS options or firewall rules. The special string `%i' +is expanded to \fIINTERFACE\fP. Each one may be specified multiple times, in which case +the commands are executed in order. +.IP \(bu +SaveConfig \(em if set to `true', the configuration is saved from the current state of the +interface upon shutdown. + +.P +Recommended \fIINTERFACE\fP names include `wg0' or `wgvpn0' or even `wgmgmtlan0'. +However, the number at the end is in fact optional, and really +any free-form string [a-zA-Z0-9_=+.-]{1,15} will work. So even interface names corresponding +to geographic locations would suffice, such as `cincinnati', `nyc', or `paris', if that's +somehow desirable. + +.SH EXAMPLES + +These examples draw on the same syntax found for +.BR wg (8), +and a more complete description may be found there. Bold lines below are for options that extend +.BR wg (8). + +The following might be used for connecting as a client to a VPN gateway for tunneling all +traffic: + + [Interface] +.br + \fBAddress = 10.200.100.8/24\fP +.br + \fBDNS = 10.200.100.1\fP +.br + PrivateKey = oK56DE9Ue9zK76rAc8pBl6opph+1v36lm7cXXsQKrQM= +.br + +.br + [Peer] +.br + PublicKey = GtL7fZc/bLnqZldpVofMCD6hDjrK28SsdLxevJ+qtKU= +.br + PresharedKey = /UwcSPg38hW/D9Y3tcS1FOV0K1wuURMbS0sesJEP5ak= +.br + AllowedIPs = 0.0.0.0/0 +.br + Endpoint = demo.wireguard.com:51820 +.br + +The `Address` field is added here in order to set up the address for the interface. The `DNS` field +indicates that a DNS server for the interface should be configured via +.BR resolvconf (8). +The peer's allowed IPs entry implies that this interface should be configured as the default gateway, +which this script does. + +Building on the last example, one might attempt the so-called ``kill-switch'', in order +to prevent the flow of unencrypted packets through the non-WireGuard interfaces, by adding the following +two lines `PostUp` and `PreDown` lines to the `[Interface]` section: + + \fBPostUp = iptables -I OUTPUT ! -o %i -m mark ! --mark $(wg show %i fwmark) -m addrtype ! --dst-type LOCAL -j REJECT\fP +.br + \fBPreDown = iptables -D OUTPUT ! -o %i -m mark ! --mark $(wg show %i fwmark) -m addrtype ! --dst-type LOCAL -j REJECT\fP +.br + +The `PostUp' and `PreDown' fields have been added to specify an +.BR iptables (8) +command which, when used with interfaces that have a peer that specifies 0.0.0.0/0 as part of the +`AllowedIPs', works together with wg-quick's fwmark usage in order to drop all packets that +are either not coming out of the tunnel encrypted or not going through the tunnel itself. (Note +that this continues to allow most DHCP traffic through, since most DHCP clients make use of PF_PACKET +sockets, which bypass Netfilter.) When IPv6 is in use, additional similar lines could be added using +.BR ip6tables (8). + +Or, perhaps it is desirable to store private keys in encrypted form, such as through use of +.BR pass (1): + + \fBPostUp = wg set %i private-key <(pass WireGuard/private-keys/%i)\fP +.br + +For use on a server, the following is a more complicated example involving multiple peers: + + [Interface] +.br + \fBAddress = 10.192.122.1/24\fP +.br + \fBAddress = 10.10.0.1/16\fP +.br + \fBSaveConfig = true\fP +.br + PrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= +.br + ListenPort = 51820 +.br + +.br + [Peer] +.br + PublicKey = xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= +.br + AllowedIPs = 10.192.122.3/32, 10.192.124.1/24 +.br + +.br + [Peer] +.br + PublicKey = TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0= +.br + AllowedIPs = 10.192.122.4/32, 192.168.0.0/16 +.br + +.br + [Peer] +.br + PublicKey = gN65BkIKy1eCE9pP1wdc8ROUtkHLF2PfAqYdyYBz6EA= +.br + AllowedIPs = 10.10.10.230/32 + +Notice the two `Address' lines at the top, and that `SaveConfig' is set to `true', indicating +that the configuration file should be saved on shutdown using the current status of the +interface. + +These configuration files may be placed in any directory, putting the desired interface name +in the filename: + +\fB # wg-quick up /path/to/wgnet0.conf\fP + +For convenience, if only an interface name is supplied, it automatically chooses a path in +`/etc/wireguard/': + +\fB # wg-quick up wgnet0\fP + +This will load the configuration file `/etc/wireguard/wgnet0.conf'. + +.SH SEE ALSO +.BR wg (8), +.BR ip (8), +.BR ip-link (8), +.BR ip-address (8), +.BR ip-route (8), +.BR ip-rule (8), +.BR resolvconf (8). + +.SH AUTHOR +.B wg-quick +was written by +.MT Jason@zx2c4.com +Jason A. Donenfeld +.ME . +For updates and more information, a project page is available on the +.UR https://\:www.wireguard.com/ +World Wide Web +.UE . diff --git a/src/tools/man/wg.8 b/src/tools/man/wg.8 new file mode 100644 index 0000000..49dc15b --- /dev/null +++ b/src/tools/man/wg.8 @@ -0,0 +1,230 @@ +.TH WG 8 "2015 August 13" ZX2C4 "WireGuard" + +.SH NAME +wg - set and retrieve configuration of WireGuard interfaces + +.SH SYNOPSIS +.B wg +[ +.I COMMAND +] [ +.I OPTIONS +]... [ +.I ARGS +]... + +.SH DESCRIPTION + +.B wg +is the configuration utility for getting and setting the configuration of +WireGuard tunnel interfaces. The interfaces themselves can be added and removed +using +.BR ip-link (8) +and their IP addresses and routing tables can be set using +.BR ip-address (8) +and +.BR ip-route (8). +The +.B wg +utility provides a series of sub-commands for changing WireGuard-specific +aspects of WireGuard interfaces. + +If no COMMAND is specified, COMMAND defaults to +.BR show . +Sub-commands that take an INTERFACE must be passed a WireGuard interface. + +.SH COMMANDS + +.TP +\fBshow\fP { \fI\fP | \fIall\fP | \fIinterfaces\fP } [\fIpublic-key\fP | \fIprivate-key\fP | \fIlisten-port\fP | \fIfwmark\fP | \fIpeers\fP | \fIpreshared-keys\fP | \fIendpoints\fP | \fIallowed-ips\fP | \fIlatest-handshakes\fP | \fIpersistent-keepalive\fP | \fItransfer\fP | \fIdump\fP] +Shows current WireGuard configuration of specified \fI\fP. +If no \fI\fP is specified, \fI\fP defaults to \fIall\fP. +If \fIinterfaces\fP is specified, prints a list of all WireGuard interfaces, +one per line, and quit. If no options are given after the interface +specification, then prints a list of all attributes in a visually pleasing way +meant for the terminal. Otherwise, prints specified information grouped by +newlines and tabs, meant to be used in scripts. For this script-friendly display, +if \fIall\fP is specified, then the first field for all categories of information +is the interface name. If \fPdump\fP is specified, then several lines are printed; +the first contains in order separated by tab: private-key, public-key, listen-port, +fwmark. Subsequent lines are printed for each peer and contain in order separated +by tab: public-key, preshared-key, endpoint, allowed-ips, latest-handshake, +transfer-rx, transfer-tx, persistent-keepalive. +.TP +\fBshowconf\fP \fI\fP +Shows the current configuration of \fI\fP in the format described +by \fICONFIGURATION FILE FORMAT\fP below. +.TP +\fBset\fP \fI\fP [\fIlisten-port\fP \fI\fP] [\fIfwmark\fP \fI\fP] [\fIprivate-key\fP \fI\fP] [\fIpeer\fP \fI\fP [\fIremove\fP] [\fIpreshared-key\fP \fI\fP] [\fIendpoint\fP \fI:\fP] [\fIpersistent-keepalive\fP \fI\fP] [\fIallowed-ips\fP \fI/\fP[,\fI/\fP]...] ]... +Sets configuration values for the specified \fI\fP. Multiple +\fIpeer\fPs may be specified, and if the \fIremove\fP argument is given +for a peer, that peer is removed, not configured. If \fIlisten-port\fP +is not specified, the port will be chosen randomly when the +interface comes up. Both \fIprivate-key\fP and \fIpreshared-key\fP must +be a files, because command line arguments are not considered private on +most systems but if you are using +.BR bash (1), +you may safely pass in a string by specifying as \fIprivate-key\fP or +\fIpreshared-key\fP the expression: <(echo PRIVATEKEYSTRING). If +\fI/dev/null\fP or another empty file is specified as the filename for +either \fIprivate-key\fP or \fIpreshared-key\fP, the key is removed from +the device. The use of \fIpreshared-key\fP is optional, and may be omitted; +it adds an additional layer of symmetric-key cryptography to be mixed into +the already existing public-key cryptography, for post-quantum resistance. +If \fIallowed-ips\fP is specified, but the value is the empty string, all +allowed ips are removed from the peer. The use of \fIpersistent-keepalive\fP +is optional and is by default off; setting it to 0 or "off" disables it. +Otherwise it represents, in seconds, between 1 and 65535 inclusive, how often +to send an authenticated empty packet to the peer, for the purpose of keeping +a stateful firewall or NAT mapping valid persistently. For example, if the +interface very rarely sends traffic, but it might at anytime receive traffic +from a peer, and it is behind NAT, the interface might benefit from having a +persistent keepalive interval of 25 seconds; however, most users will not need +this. The use of \fIfwmark\fP is optional and is by default off; setting it to +0 or "off" disables it. Otherwise it is a 32-bit fwmark for outgoing packets +and may be specified in hexadecimal by prepending "0x". +.TP +\fBsetconf\fP \fI\fP \fI\fP +Sets the current configuration of \fI\fP to the contents of +\fI\fP, which must be in the format described +by \fICONFIGURATION FILE FORMAT\fP below. +.TP +\fBaddconf\fP \fI\fP \fI\fP +Appends the contents of \fI\fP, which must +be in the format described by \fICONFIGURATION FILE FORMAT\fP below, +to the current configuration of \fI\fP. +.TP +\fBgenkey\fP +Generates a random \fIprivate\fP key in base64 and prints it to +standard output. +.TP +\fBgenpsk\fP +Generates a random \fIpreshared\fP key in base64 and prints it to +standard output. +.TP +\fBpubkey\fP +Calculates a \fIpublic\fP key and prints it in base64 to standard +output from a corresponding \fIprivate\fP key (generated with +\fIgenkey\fP) given in base64 on standard input. + +A private key and a corresponding public key may be generated at once by calling: +.br + $ umask 077 +.br + $ wg genkey | tee private.key | wg pubkey > public.key +.TP +\fBhelp\fP +Show usage message. + +.SH CONFIGURATION FILE FORMAT +The configuration file format is based on \fIINI\fP. There are two top level sections +-- \fIInterface\fP and \fIPeer\fP. Multiple \fIPeer\fP sections may be specified, but +only one \fIInterface\fP section may be specified. + +.P +The \fIInterface\fP section may contain the following fields: +.IP \(bu +PrivateKey \(em a base64 private key generated by \fIwg genkey\fP. Required. +.IP \(bu +ListenPort \(em a 16-bit port for listening. Optional; if not specified, chosen +randomly. +.IP \(bu +FwMark \(em a 32-bit fwmark for outgoing packets. If set to 0 or "off", this +option is disabled. May be specified in hexadecimal by prepending "0x". Optional. +.P +The \fIPeer\fP sections may contain the following fields: +.IP \(bu +PublicKey \(em a base64 public key calculated by \fIwg pubkey\fP from a +private key, and usually transmitted out of band to the author of the +configuration file. Required. +.IP \(bu +PresharedKey \(em a base64 preshared key generated by \fIwg genpsk\fP. Optional, +and may be omitted. This option adds an additional layer of symmetric-key +cryptography to be mixed into the already existing public-key cryptography, +for post-quantum resistance. +.IP \(bu +AllowedIPs \(em a comma-separated list of IP (v4 or v6) addresses with +CIDR masks from which incoming traffic for this peer is allowed and to +which outgoing traffic for this peer is directed. The catch-all +\fI0.0.0.0/0\fP may be specified for matching all IPv4 addresses, and +\fI::/0\fP may be specified for matching all IPv6 addresses. May be specified +multiple times. Required. +.IP \(bu +Endpoint \(em an endpoint IP or hostname, followed by a colon, and then a +port number. This endpoint will be updated automatically to the most recent +source IP address and port of correctly authenticated packets from the peer. +Optional. +.IP \(bu +PersistentKeepalive \(em a seconds interval, between 1 and 65535 inclusive, of +how often to send an authenticated empty packet to the peer for the purpose of keeping a +stateful firewall or NAT mapping valid persistently. For example, if the interface +very rarely sends traffic, but it might at anytime receive traffic from a peer, +and it is behind NAT, the interface might benefit from having a persistent keepalive +interval of 25 seconds. If set to 0 or "off", this option is disabled. By default or +when unspecified, this option is off. Most users will not need this. Optional. + +.SH CONFIGURATION FILE FORMAT EXAMPLE +This example may be used as a model for writing configuration files, following an +INI-like syntax. Characters after and including a '#' are considered comments and +are thus ignored. + + [Interface] +.br + PrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= +.br + ListenPort = 51820 +.br + +.br + [Peer] +.br + PublicKey = xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= +.br + Endpoint = 192.95.5.67:1234 +.br + AllowedIPs = 10.192.122.3/32, 10.192.124.1/24 +.br + +.br + [Peer] +.br + PublicKey = TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0= +.br + Endpoint = [2607:5300:60:6b0::c05f:543]:2468 +.br + AllowedIPs = 10.192.122.4/32, 192.168.0.0/16 +.br + +.br + [Peer] +.br + PublicKey = gN65BkIKy1eCE9pP1wdc8ROUtkHLF2PfAqYdyYBz6EA= +.br + Endpoint = test.wireguard.com:18981 +.br + AllowedIPs = 10.10.10.230/32 + +.SH ENVIRONMENT VARIABLES +.TP +.I WG_COLOR_MODE +If set to \fIalways\fP, always print ANSI colorized output. If set to \fInever\fP, never print ANSI colorized output. If set to \fIauto\fP, something invalid, or unset, then print ANSI colorized output only when writing to a TTY. +.TP +.I WG_HIDE_KEYS +If set to \fInever\fP, then the pretty-printing \fBshow\fP sub-command will show private and preshared keys in the output. If set to \fIalways\fP, something invalid, or unset, then private and preshared keys will be printed as "(hidden)". + +.SH SEE ALSO +.BR ip (8), +.BR ip-link (8), +.BR ip-address (8), +.BR ip-route (8). + +.SH AUTHOR +.B wg +was written by +.MT Jason@zx2c4.com +Jason A. Donenfeld +.ME . +For updates and more information, a project page is available on the +.UR https://\:www.wireguard.com/ +World Wide Web +.UE . diff --git a/src/tools/systemd/wg-quick@.service b/src/tools/systemd/wg-quick@.service new file mode 100644 index 0000000..da5d787 --- /dev/null +++ b/src/tools/systemd/wg-quick@.service @@ -0,0 +1,19 @@ +[Unit] +Description=WireGuard via wg-quick(8) for %I +After=network-online.target +Wants=network-online.target +Documentation=man:wg-quick(8) +Documentation=man:wg(8) +Documentation=https://www.wireguard.com/ +Documentation=https://www.wireguard.com/quickstart/ +Documentation=https://git.zx2c4.com/WireGuard/about/src/tools/man/wg-quick.8 +Documentation=https://git.zx2c4.com/WireGuard/about/src/tools/man/wg.8 + +[Service] +Type=oneshot +RemainAfterExit=yes +ExecStart=/usr/bin/wg-quick up %i +ExecStop=/usr/bin/wg-quick down %i + +[Install] +WantedBy=multi-user.target diff --git a/src/tools/wg-quick.8 b/src/tools/wg-quick.8 deleted file mode 100644 index 5e27d10..0000000 --- a/src/tools/wg-quick.8 +++ /dev/null @@ -1,237 +0,0 @@ -.TH WG-QUICK 8 "2016 January 1" ZX2C4 "WireGuard" - -.SH NAME -wg-quick - set up a WireGuard interface simply - -.SH SYNOPSIS -.B wg-quick -[ -.I up -| -.I down -| -.I save -] [ -.I CONFIG_FILE -| -.I INTERFACE -] - -.SH DESCRIPTION - -This is an extremely simple script for easily bringing up a WireGuard interface, -suitable for a few common use cases. - -Use \fIup\fP to add and set up an interface, and use \fIdown\fP to tear down and remove -an interface. Running \fIup\fP adds a WireGuard interface, brings up the interface with the -supplied IP addresses, sets up mtu and routes, and optionally runs pre/post up scripts. Running \fIdown\fP -optionally saves the current configuration, removes the WireGuard interface, and optionally -runs pre/post down scripts. Running \fIsave\fP saves the configuration of an existing -interface without bringing the interface down. - -\fICONFIG_FILE\fP is a configuration file, whose filename is the interface name -followed by `.conf'. Otherwise, \fIINTERFACE\fP is an interface name, with configuration -found at `/etc/wireguard/\fIINTERFACE\fP.conf'. - -Generally speaking, this utility is just a simple script that wraps invocations to -.BR wg (8) -and -.BR ip (8) -in order to set up a WireGuard interface. It is designed for users with simple -needs, and users with more advanced needs are highly encouraged to use a more -specific tool, a more complete network manager, or otherwise just use -.BR wg (8) -and -.BR ip (8), -as usual. - -.SH CONFIGURATION - -The configuration file adds a few extra configuration values to the format understood by -.BR wg (8) -in order to configure additional attribute of an interface. It handles the -values that it understands, and then it passes the remaining ones directly to -.BR wg (8) -for further processing. - -It infers all routes from the list of peers' allowed IPs, and automatically adds -them to the system routing table. If one of those routes is the default route -(0.0.0.0/0 or ::/0), then it uses -.BR ip-rule (8) -to handle overriding of the default gateway. - -The configuration file will be passed directly to \fBwg\fP(8)'s `setconf' -sub-command, with the exception of the following additions to the \fIInterface\fP section, -which are handled by this tool: - -.IP \(bu -Address \(em a comma-separated list of IP (v4 or v6) addresses (optionally with CIDR masks) -to be assigned to the interface. May be specified multiple times. -.IP \(bu -DNS \(em a comma-separated list of IP (v4 or v6) addresses to be set as the interface's -DNS servers. May be specified multiple times. Upon bringing the interface up, this runs -`resolvconf -a tun.\fIINTERFACE\fP -m 0 -x` and upon bringing it down, this runs -`resolvconf -d tun.\fIINTERFACE\fP`. If these particular invocations of -.BR resolvconf (8) -are undesirable, the PostUp and PostDown keys below may be used instead. -.IP \(bu -MTU \(em if not specified, the MTU is automatically determined from the endpoint addresses -or the system default route, which is usually a sane choice. However, to manually specify -an MTU to override this automatic discovery, this value may be specified explicitly. -.IP \(bu -Table \(em Controls the routing table to which routes are added. There are two -special values: `off' disables the creation of routes altogether, and `auto' -(the default) adds routes to the default table and enables special handling of -default routes. -.IP \(bu -PreUp, PostUp, PreDown, PostDown \(em script snippets which will be executed by -.BR bash (1) -before/after setting up/tearing down the interface, most commonly used -to configure custom DNS options or firewall rules. The special string `%i' -is expanded to \fIINTERFACE\fP. Each one may be specified multiple times, in which case -the commands are executed in order. -.IP \(bu -SaveConfig \(em if set to `true', the configuration is saved from the current state of the -interface upon shutdown. - -.P -Recommended \fIINTERFACE\fP names include `wg0' or `wgvpn0' or even `wgmgmtlan0'. -However, the number at the end is in fact optional, and really -any free-form string [a-zA-Z0-9_=+.-]{1,15} will work. So even interface names corresponding -to geographic locations would suffice, such as `cincinnati', `nyc', or `paris', if that's -somehow desirable. - -.SH EXAMPLES - -These examples draw on the same syntax found for -.BR wg (8), -and a more complete description may be found there. Bold lines below are for options that extend -.BR wg (8). - -The following might be used for connecting as a client to a VPN gateway for tunneling all -traffic: - - [Interface] -.br - \fBAddress = 10.200.100.8/24\fP -.br - \fBDNS = 10.200.100.1\fP -.br - PrivateKey = oK56DE9Ue9zK76rAc8pBl6opph+1v36lm7cXXsQKrQM= -.br - -.br - [Peer] -.br - PublicKey = GtL7fZc/bLnqZldpVofMCD6hDjrK28SsdLxevJ+qtKU= -.br - PresharedKey = /UwcSPg38hW/D9Y3tcS1FOV0K1wuURMbS0sesJEP5ak= -.br - AllowedIPs = 0.0.0.0/0 -.br - Endpoint = demo.wireguard.com:51820 -.br - -The `Address` field is added here in order to set up the address for the interface. The `DNS` field -indicates that a DNS server for the interface should be configured via -.BR resolvconf (8). -The peer's allowed IPs entry implies that this interface should be configured as the default gateway, -which this script does. - -Building on the last example, one might attempt the so-called ``kill-switch'', in order -to prevent the flow of unencrypted packets through the non-WireGuard interfaces, by adding the following -two lines `PostUp` and `PreDown` lines to the `[Interface]` section: - - \fBPostUp = iptables -I OUTPUT ! -o %i -m mark ! --mark $(wg show %i fwmark) -m addrtype ! --dst-type LOCAL -j REJECT\fP -.br - \fBPreDown = iptables -D OUTPUT ! -o %i -m mark ! --mark $(wg show %i fwmark) -m addrtype ! --dst-type LOCAL -j REJECT\fP -.br - -The `PostUp' and `PreDown' fields have been added to specify an -.BR iptables (8) -command which, when used with interfaces that have a peer that specifies 0.0.0.0/0 as part of the -`AllowedIPs', works together with wg-quick's fwmark usage in order to drop all packets that -are either not coming out of the tunnel encrypted or not going through the tunnel itself. (Note -that this continues to allow most DHCP traffic through, since most DHCP clients make use of PF_PACKET -sockets, which bypass Netfilter.) When IPv6 is in use, additional similar lines could be added using -.BR ip6tables (8). - -Or, perhaps it is desirable to store private keys in encrypted form, such as through use of -.BR pass (1): - - \fBPostUp = wg set %i private-key <(pass WireGuard/private-keys/%i)\fP -.br - -For use on a server, the following is a more complicated example involving multiple peers: - - [Interface] -.br - \fBAddress = 10.192.122.1/24\fP -.br - \fBAddress = 10.10.0.1/16\fP -.br - \fBSaveConfig = true\fP -.br - PrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= -.br - ListenPort = 51820 -.br - -.br - [Peer] -.br - PublicKey = xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= -.br - AllowedIPs = 10.192.122.3/32, 10.192.124.1/24 -.br - -.br - [Peer] -.br - PublicKey = TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0= -.br - AllowedIPs = 10.192.122.4/32, 192.168.0.0/16 -.br - -.br - [Peer] -.br - PublicKey = gN65BkIKy1eCE9pP1wdc8ROUtkHLF2PfAqYdyYBz6EA= -.br - AllowedIPs = 10.10.10.230/32 - -Notice the two `Address' lines at the top, and that `SaveConfig' is set to `true', indicating -that the configuration file should be saved on shutdown using the current status of the -interface. - -These configuration files may be placed in any directory, putting the desired interface name -in the filename: - -\fB # wg-quick up /path/to/wgnet0.conf\fP - -For convenience, if only an interface name is supplied, it automatically chooses a path in -`/etc/wireguard/': - -\fB # wg-quick up wgnet0\fP - -This will load the configuration file `/etc/wireguard/wgnet0.conf'. - -.SH SEE ALSO -.BR wg (8), -.BR ip (8), -.BR ip-link (8), -.BR ip-address (8), -.BR ip-route (8), -.BR ip-rule (8), -.BR resolvconf (8). - -.SH AUTHOR -.B wg-quick -was written by -.MT Jason@zx2c4.com -Jason A. Donenfeld -.ME . -For updates and more information, a project page is available on the -.UR https://\:www.wireguard.com/ -World Wide Web -.UE . diff --git a/src/tools/wg-quick.bash b/src/tools/wg-quick.bash deleted file mode 100755 index cd66b4d..0000000 --- a/src/tools/wg-quick.bash +++ /dev/null @@ -1,334 +0,0 @@ -#!/bin/bash -# SPDX-License-Identifier: GPL-2.0 -# -# Copyright (C) 2015-2018 Jason A. Donenfeld . All Rights Reserved. -# - -set -e -o pipefail -shopt -s extglob -export LC_ALL=C - -SELF="$(readlink -f "${BASH_SOURCE[0]}")" -export PATH="${SELF%/*}:$PATH" - -WG_CONFIG="" -INTERFACE="" -ADDRESSES=( ) -MTU="" -DNS=( ) -TABLE="" -PRE_UP=( ) -POST_UP=( ) -PRE_DOWN=( ) -POST_DOWN=( ) -SAVE_CONFIG=0 -CONFIG_FILE="" -PROGRAM="${0##*/}" -ARGS=( "$@" ) - -parse_options() { - local interface_section=0 line key value stripped - CONFIG_FILE="$1" - [[ $CONFIG_FILE =~ ^[a-zA-Z0-9_=+.-]{1,15}$ ]] && CONFIG_FILE="/etc/wireguard/$CONFIG_FILE.conf" - [[ -e $CONFIG_FILE ]] || die "\`$CONFIG_FILE' does not exist" - [[ $CONFIG_FILE =~ (^|/)([a-zA-Z0-9_=+.-]{1,15})\.conf$ ]] || die "The config file must be a valid interface name, followed by .conf" - CONFIG_FILE="$(readlink -f "$CONFIG_FILE")" - ((($(stat -c '0%#a' "$CONFIG_FILE") & $(stat -c '0%#a' "${CONFIG_FILE%/*}") & 0007) == 0)) || echo "Warning: \`$CONFIG_FILE' is world accessible" >&2 - INTERFACE="${BASH_REMATCH[2]}" - shopt -s nocasematch - while read -r line || [[ -n $line ]]; do - stripped="${line%%\#*}" - key="${stripped%%=*}"; key="${key##*([[:space:]])}"; key="${key%%*([[:space:]])}" - value="${stripped#*=}"; value="${value##*([[:space:]])}"; value="${value%%*([[:space:]])}" - [[ $key == "["* ]] && interface_section=0 - [[ $key == "[Interface]" ]] && interface_section=1 - if [[ $interface_section -eq 1 ]]; then - case "$key" in - Address) ADDRESSES+=( ${value//,/ } ); continue ;; - MTU) MTU="$value"; continue ;; - DNS) DNS+=( ${value//,/ } ); continue ;; - Table) TABLE="$value"; continue ;; - PreUp) PRE_UP+=( "$value" ); continue ;; - PreDown) PRE_DOWN+=( "$value" ); continue ;; - PostUp) POST_UP+=( "$value" ); continue ;; - PostDown) POST_DOWN+=( "$value" ); continue ;; - SaveConfig) read_bool SAVE_CONFIG "$value"; continue ;; - esac - fi - WG_CONFIG+="$line"$'\n' - done < "$CONFIG_FILE" - shopt -u nocasematch -} - -read_bool() { - case "$2" in - true) printf -v "$1" 1 ;; - false) printf -v "$1" 0 ;; - *) die "\`$2' is neither true nor false" - esac -} - -cmd() { - echo "[#] $*" >&2 - "$@" -} - -die() { - echo "$PROGRAM: $*" >&2 - exit 1 -} - -auto_su() { - [[ $UID == 0 ]] || exec sudo -p "$PROGRAM must be run as root. Please enter the password for %u to continue: " "$SELF" "${ARGS[@]}" -} - -add_if() { - local ret - if ! cmd ip link add "$INTERFACE" type wireguard; then - ret=$? - [[ -e /sys/module/wireguard ]] || ! command -v wireguard-go >/dev/null && return $ret - echo "[!] Missing WireGuard kernel module. Falling back to slow userspace implementation." - cmd wireguard-go "$INTERFACE" - fi -} - -del_if() { - local table - [[ $HAVE_SET_DNS -eq 0 ]] || unset_dns - if [[ -z $TABLE || $TABLE == auto ]] && get_fwmark table && [[ $(wg show "$INTERFACE" allowed-ips) =~ /0(\ |$'\n'|$) ]]; then - while [[ $(ip -4 rule show) == *"lookup $table"* ]]; do - cmd ip -4 rule delete table $table - done - while [[ $(ip -4 rule show) == *"from all lookup main suppress_prefixlength 0"* ]]; do - cmd ip -4 rule delete table main suppress_prefixlength 0 - done - while [[ $(ip -6 rule show) == *"lookup $table"* ]]; do - cmd ip -6 rule delete table $table - done - while [[ $(ip -6 rule show) == *"from all lookup main suppress_prefixlength 0"* ]]; do - cmd ip -6 rule delete table main suppress_prefixlength 0 - done - fi - cmd ip link delete dev "$INTERFACE" -} - -up_if() { - cmd ip link set "$INTERFACE" up -} - -add_addr() { - cmd ip address add "$1" dev "$INTERFACE" -} - -set_mtu() { - local mtu=0 endpoint output - if [[ -n $MTU ]]; then - cmd ip link set mtu "$MTU" dev "$INTERFACE" - return - fi - while read -r _ endpoint; do - [[ $endpoint =~ ^\[?([a-z0-9:.]+)\]?:[0-9]+$ ]] || continue - output="$(ip route get "${BASH_REMATCH[1]}" || true)" - [[ ( $output =~ mtu\ ([0-9]+) || ( $output =~ dev\ ([^ ]+) && $(ip link show dev "${BASH_REMATCH[1]}") =~ mtu\ ([0-9]+) ) ) && ${BASH_REMATCH[1]} -gt $mtu ]] && mtu="${BASH_REMATCH[1]}" - done < <(wg show "$INTERFACE" endpoints) - if [[ $mtu -eq 0 ]]; then - read -r output < <(ip route show default || true) || true - [[ ( $output =~ mtu\ ([0-9]+) || ( $output =~ dev\ ([^ ]+) && $(ip link show dev "${BASH_REMATCH[1]}") =~ mtu\ ([0-9]+) ) ) && ${BASH_REMATCH[1]} -gt $mtu ]] && mtu="${BASH_REMATCH[1]}" - fi - [[ $mtu -gt 0 ]] || mtu=1500 - cmd ip link set mtu $(( mtu - 80 )) dev "$INTERFACE" -} - -resolvconf_iface_prefix() { - [[ -f /etc/resolvconf/interface-order ]] || return 0 - local iface - while read -r iface; do - [[ $iface =~ ^([A-Za-z0-9-]+)\*$ ]] || continue - echo "${BASH_REMATCH[1]}." && return 0 - done < /etc/resolvconf/interface-order -} - -HAVE_SET_DNS=0 -set_dns() { - [[ ${#DNS[@]} -gt 0 ]] || return 0 - printf 'nameserver %s\n' "${DNS[@]}" | cmd resolvconf -a "$(resolvconf_iface_prefix)$INTERFACE" -m 0 -x - HAVE_SET_DNS=1 -} - -unset_dns() { - [[ ${#DNS[@]} -gt 0 ]] || return 0 - cmd resolvconf -d "$(resolvconf_iface_prefix)$INTERFACE" -} - -add_route() { - [[ $TABLE != off ]] || return 0 - - if [[ -n $TABLE && $TABLE != auto ]]; then - cmd ip route add "$1" dev "$INTERFACE" table "$TABLE" - elif [[ $1 == */0 ]]; then - add_default "$1" - else - [[ $(ip route get "$i" 2>/dev/null) == *dev\ $INTERFACE\ * ]] || cmd ip route add "$1" dev "$INTERFACE" - fi -} - -get_fwmark() { - local fwmark - fwmark="$(wg show "$INTERFACE" fwmark)" || return 1 - [[ -n $fwmark && $fwmark != off ]] || return 1 - printf -v "$1" "%d" "$fwmark" - return 0 -} - -add_default() { - local table proto key value - if ! get_fwmark table; then - table=51820 - while [[ -n $(ip -4 route show table $table) || -n $(ip -6 route show table $table) ]]; do - ((table++)) - done - cmd wg set "$INTERFACE" fwmark $table - fi - proto=-4 - [[ $1 == *:* ]] && proto=-6 - cmd ip $proto route add "$1" dev "$INTERFACE" table $table - cmd ip $proto rule add not fwmark $table table $table - cmd ip $proto rule add table main suppress_prefixlength 0 - while read -r key _ value; do - [[ $value -eq 1 ]] && sysctl -q "$key=2" - done < <(sysctl -a -r '^net\.ipv4.conf\.[^ .=]+\.rp_filter$') - return 0 -} - -set_config() { - cmd wg setconf "$INTERFACE" <(echo "$WG_CONFIG") -} - -save_config() { - local old_umask new_config current_config address cmd - [[ $(ip -all -brief address show dev "$INTERFACE") =~ ^$INTERFACE\ +\ [A-Z]+\ +(.+)$ ]] || true - new_config=$'[Interface]\n' - for address in ${BASH_REMATCH[1]}; do - new_config+="Address = $address"$'\n' - done - while read -r address; do - [[ $address =~ ^nameserver\ ([a-zA-Z0-9_=+:%.-]+)$ ]] && new_config+="DNS = ${BASH_REMATCH[1]}"$'\n' - done < <(resolvconf -l "$(resolvconf_iface_prefix)$INTERFACE" 2>/dev/null || cat "/etc/resolvconf/run/interface/$(resolvconf_iface_prefix)$INTERFACE" 2>/dev/null) - [[ -n $MTU && $(ip link show dev "$INTERFACE") =~ mtu\ ([0-9]+) ]] && new_config+="MTU = ${BASH_REMATCH[1]}"$'\n' - [[ -n $TABLE ]] && new_config+="Table = $TABLE"$'\n' - [[ $SAVE_CONFIG -eq 0 ]] || new_config+=$'SaveConfig = true\n' - for cmd in "${PRE_UP[@]}"; do - new_config+="PreUp = $cmd"$'\n' - done - for cmd in "${POST_UP[@]}"; do - new_config+="PostUp = $cmd"$'\n' - done - for cmd in "${PRE_DOWN[@]}"; do - new_config+="PreDown = $cmd"$'\n' - done - for cmd in "${POST_DOWN[@]}"; do - new_config+="PostDown = $cmd"$'\n' - done - old_umask="$(umask)" - umask 077 - current_config="$(cmd wg showconf "$INTERFACE")" - trap 'rm -f "$CONFIG_FILE.tmp"; exit' INT TERM EXIT - echo "${current_config/\[Interface\]$'\n'/$new_config}" > "$CONFIG_FILE.tmp" || die "Could not write configuration file" - sync "$CONFIG_FILE.tmp" - mv "$CONFIG_FILE.tmp" "$CONFIG_FILE" || die "Could not move configuration file" - trap - INT TERM EXIT - umask "$old_umask" -} - -execute_hooks() { - local hook - for hook in "$@"; do - hook="${hook//%i/$INTERFACE}" - echo "[#] $hook" >&2 - (eval "$hook") - done -} - -cmd_usage() { - cat >&2 <<-_EOF - Usage: $PROGRAM [ up | down | save ] [ CONFIG_FILE | INTERFACE ] - - CONFIG_FILE is a configuration file, whose filename is the interface name - followed by \`.conf'. Otherwise, INTERFACE is an interface name, with - configuration found at /etc/wireguard/INTERFACE.conf. It is to be readable - by wg(8)'s \`setconf' sub-command, with the exception of the following additions - to the [Interface] section, which are handled by $PROGRAM: - - - Address: may be specified one or more times and contains one or more - IP addresses (with an optional CIDR mask) to be set for the interface. - - DNS: an optional DNS server to use while the device is up. - - MTU: an optional MTU for the interface; if unspecified, auto-calculated. - - Table: an optional routing table to which routes will be added; if - unspecified or \`auto', the default table is used. If \`off', no routes - are added. - - PreUp, PostUp, PreDown, PostDown: script snippets which will be executed - by bash(1) at the corresponding phases of the link, most commonly used - to configure DNS. The string \`%i' is expanded to INTERFACE. - - SaveConfig: if set to \`true', the configuration is saved from the current - state of the interface upon shutdown. - - See wg-quick(8) for more info and examples. - _EOF -} - -cmd_up() { - local i - [[ -z $(ip link show dev "$INTERFACE" 2>/dev/null) ]] || die "\`$INTERFACE' already exists" - trap 'del_if; exit' INT TERM EXIT - execute_hooks "${PRE_UP[@]}" - add_if - set_config - for i in "${ADDRESSES[@]}"; do - add_addr "$i" - done - set_mtu - up_if - set_dns - for i in $(while read -r _ i; do for i in $i; do [[ $i =~ ^[0-9a-z:.]+/[0-9]+$ ]] && echo "$i"; done; done < <(wg show "$INTERFACE" allowed-ips) | sort -nr -k 2 -t /); do - add_route "$i" - done - execute_hooks "${POST_UP[@]}" - trap - INT TERM EXIT -} - -cmd_down() { - [[ " $(wg show interfaces) " == *" $INTERFACE "* ]] || die "\`$INTERFACE' is not a WireGuard interface" - execute_hooks "${PRE_DOWN[@]}" - [[ $SAVE_CONFIG -eq 0 ]] || save_config - del_if - unset_dns - execute_hooks "${POST_DOWN[@]}" -} - -cmd_save() { - [[ " $(wg show interfaces) " == *" $INTERFACE "* ]] || die "\`$INTERFACE' is not a WireGuard interface" - save_config -} - -# ~~ function override insertion point ~~ - -if [[ $# -eq 1 && ( $1 == --help || $1 == -h || $1 == help ) ]]; then - cmd_usage -elif [[ $# -eq 2 && $1 == up ]]; then - auto_su - parse_options "$2" - cmd_up -elif [[ $# -eq 2 && $1 == down ]]; then - auto_su - parse_options "$2" - cmd_down -elif [[ $# -eq 2 && $1 == save ]]; then - auto_su - parse_options "$2" - cmd_save -else - cmd_usage - exit 1 -fi - -exit 0 diff --git a/src/tools/wg-quick/linux.bash b/src/tools/wg-quick/linux.bash new file mode 100755 index 0000000..cd66b4d --- /dev/null +++ b/src/tools/wg-quick/linux.bash @@ -0,0 +1,334 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 +# +# Copyright (C) 2015-2018 Jason A. Donenfeld . All Rights Reserved. +# + +set -e -o pipefail +shopt -s extglob +export LC_ALL=C + +SELF="$(readlink -f "${BASH_SOURCE[0]}")" +export PATH="${SELF%/*}:$PATH" + +WG_CONFIG="" +INTERFACE="" +ADDRESSES=( ) +MTU="" +DNS=( ) +TABLE="" +PRE_UP=( ) +POST_UP=( ) +PRE_DOWN=( ) +POST_DOWN=( ) +SAVE_CONFIG=0 +CONFIG_FILE="" +PROGRAM="${0##*/}" +ARGS=( "$@" ) + +parse_options() { + local interface_section=0 line key value stripped + CONFIG_FILE="$1" + [[ $CONFIG_FILE =~ ^[a-zA-Z0-9_=+.-]{1,15}$ ]] && CONFIG_FILE="/etc/wireguard/$CONFIG_FILE.conf" + [[ -e $CONFIG_FILE ]] || die "\`$CONFIG_FILE' does not exist" + [[ $CONFIG_FILE =~ (^|/)([a-zA-Z0-9_=+.-]{1,15})\.conf$ ]] || die "The config file must be a valid interface name, followed by .conf" + CONFIG_FILE="$(readlink -f "$CONFIG_FILE")" + ((($(stat -c '0%#a' "$CONFIG_FILE") & $(stat -c '0%#a' "${CONFIG_FILE%/*}") & 0007) == 0)) || echo "Warning: \`$CONFIG_FILE' is world accessible" >&2 + INTERFACE="${BASH_REMATCH[2]}" + shopt -s nocasematch + while read -r line || [[ -n $line ]]; do + stripped="${line%%\#*}" + key="${stripped%%=*}"; key="${key##*([[:space:]])}"; key="${key%%*([[:space:]])}" + value="${stripped#*=}"; value="${value##*([[:space:]])}"; value="${value%%*([[:space:]])}" + [[ $key == "["* ]] && interface_section=0 + [[ $key == "[Interface]" ]] && interface_section=1 + if [[ $interface_section -eq 1 ]]; then + case "$key" in + Address) ADDRESSES+=( ${value//,/ } ); continue ;; + MTU) MTU="$value"; continue ;; + DNS) DNS+=( ${value//,/ } ); continue ;; + Table) TABLE="$value"; continue ;; + PreUp) PRE_UP+=( "$value" ); continue ;; + PreDown) PRE_DOWN+=( "$value" ); continue ;; + PostUp) POST_UP+=( "$value" ); continue ;; + PostDown) POST_DOWN+=( "$value" ); continue ;; + SaveConfig) read_bool SAVE_CONFIG "$value"; continue ;; + esac + fi + WG_CONFIG+="$line"$'\n' + done < "$CONFIG_FILE" + shopt -u nocasematch +} + +read_bool() { + case "$2" in + true) printf -v "$1" 1 ;; + false) printf -v "$1" 0 ;; + *) die "\`$2' is neither true nor false" + esac +} + +cmd() { + echo "[#] $*" >&2 + "$@" +} + +die() { + echo "$PROGRAM: $*" >&2 + exit 1 +} + +auto_su() { + [[ $UID == 0 ]] || exec sudo -p "$PROGRAM must be run as root. Please enter the password for %u to continue: " "$SELF" "${ARGS[@]}" +} + +add_if() { + local ret + if ! cmd ip link add "$INTERFACE" type wireguard; then + ret=$? + [[ -e /sys/module/wireguard ]] || ! command -v wireguard-go >/dev/null && return $ret + echo "[!] Missing WireGuard kernel module. Falling back to slow userspace implementation." + cmd wireguard-go "$INTERFACE" + fi +} + +del_if() { + local table + [[ $HAVE_SET_DNS -eq 0 ]] || unset_dns + if [[ -z $TABLE || $TABLE == auto ]] && get_fwmark table && [[ $(wg show "$INTERFACE" allowed-ips) =~ /0(\ |$'\n'|$) ]]; then + while [[ $(ip -4 rule show) == *"lookup $table"* ]]; do + cmd ip -4 rule delete table $table + done + while [[ $(ip -4 rule show) == *"from all lookup main suppress_prefixlength 0"* ]]; do + cmd ip -4 rule delete table main suppress_prefixlength 0 + done + while [[ $(ip -6 rule show) == *"lookup $table"* ]]; do + cmd ip -6 rule delete table $table + done + while [[ $(ip -6 rule show) == *"from all lookup main suppress_prefixlength 0"* ]]; do + cmd ip -6 rule delete table main suppress_prefixlength 0 + done + fi + cmd ip link delete dev "$INTERFACE" +} + +up_if() { + cmd ip link set "$INTERFACE" up +} + +add_addr() { + cmd ip address add "$1" dev "$INTERFACE" +} + +set_mtu() { + local mtu=0 endpoint output + if [[ -n $MTU ]]; then + cmd ip link set mtu "$MTU" dev "$INTERFACE" + return + fi + while read -r _ endpoint; do + [[ $endpoint =~ ^\[?([a-z0-9:.]+)\]?:[0-9]+$ ]] || continue + output="$(ip route get "${BASH_REMATCH[1]}" || true)" + [[ ( $output =~ mtu\ ([0-9]+) || ( $output =~ dev\ ([^ ]+) && $(ip link show dev "${BASH_REMATCH[1]}") =~ mtu\ ([0-9]+) ) ) && ${BASH_REMATCH[1]} -gt $mtu ]] && mtu="${BASH_REMATCH[1]}" + done < <(wg show "$INTERFACE" endpoints) + if [[ $mtu -eq 0 ]]; then + read -r output < <(ip route show default || true) || true + [[ ( $output =~ mtu\ ([0-9]+) || ( $output =~ dev\ ([^ ]+) && $(ip link show dev "${BASH_REMATCH[1]}") =~ mtu\ ([0-9]+) ) ) && ${BASH_REMATCH[1]} -gt $mtu ]] && mtu="${BASH_REMATCH[1]}" + fi + [[ $mtu -gt 0 ]] || mtu=1500 + cmd ip link set mtu $(( mtu - 80 )) dev "$INTERFACE" +} + +resolvconf_iface_prefix() { + [[ -f /etc/resolvconf/interface-order ]] || return 0 + local iface + while read -r iface; do + [[ $iface =~ ^([A-Za-z0-9-]+)\*$ ]] || continue + echo "${BASH_REMATCH[1]}." && return 0 + done < /etc/resolvconf/interface-order +} + +HAVE_SET_DNS=0 +set_dns() { + [[ ${#DNS[@]} -gt 0 ]] || return 0 + printf 'nameserver %s\n' "${DNS[@]}" | cmd resolvconf -a "$(resolvconf_iface_prefix)$INTERFACE" -m 0 -x + HAVE_SET_DNS=1 +} + +unset_dns() { + [[ ${#DNS[@]} -gt 0 ]] || return 0 + cmd resolvconf -d "$(resolvconf_iface_prefix)$INTERFACE" +} + +add_route() { + [[ $TABLE != off ]] || return 0 + + if [[ -n $TABLE && $TABLE != auto ]]; then + cmd ip route add "$1" dev "$INTERFACE" table "$TABLE" + elif [[ $1 == */0 ]]; then + add_default "$1" + else + [[ $(ip route get "$i" 2>/dev/null) == *dev\ $INTERFACE\ * ]] || cmd ip route add "$1" dev "$INTERFACE" + fi +} + +get_fwmark() { + local fwmark + fwmark="$(wg show "$INTERFACE" fwmark)" || return 1 + [[ -n $fwmark && $fwmark != off ]] || return 1 + printf -v "$1" "%d" "$fwmark" + return 0 +} + +add_default() { + local table proto key value + if ! get_fwmark table; then + table=51820 + while [[ -n $(ip -4 route show table $table) || -n $(ip -6 route show table $table) ]]; do + ((table++)) + done + cmd wg set "$INTERFACE" fwmark $table + fi + proto=-4 + [[ $1 == *:* ]] && proto=-6 + cmd ip $proto route add "$1" dev "$INTERFACE" table $table + cmd ip $proto rule add not fwmark $table table $table + cmd ip $proto rule add table main suppress_prefixlength 0 + while read -r key _ value; do + [[ $value -eq 1 ]] && sysctl -q "$key=2" + done < <(sysctl -a -r '^net\.ipv4.conf\.[^ .=]+\.rp_filter$') + return 0 +} + +set_config() { + cmd wg setconf "$INTERFACE" <(echo "$WG_CONFIG") +} + +save_config() { + local old_umask new_config current_config address cmd + [[ $(ip -all -brief address show dev "$INTERFACE") =~ ^$INTERFACE\ +\ [A-Z]+\ +(.+)$ ]] || true + new_config=$'[Interface]\n' + for address in ${BASH_REMATCH[1]}; do + new_config+="Address = $address"$'\n' + done + while read -r address; do + [[ $address =~ ^nameserver\ ([a-zA-Z0-9_=+:%.-]+)$ ]] && new_config+="DNS = ${BASH_REMATCH[1]}"$'\n' + done < <(resolvconf -l "$(resolvconf_iface_prefix)$INTERFACE" 2>/dev/null || cat "/etc/resolvconf/run/interface/$(resolvconf_iface_prefix)$INTERFACE" 2>/dev/null) + [[ -n $MTU && $(ip link show dev "$INTERFACE") =~ mtu\ ([0-9]+) ]] && new_config+="MTU = ${BASH_REMATCH[1]}"$'\n' + [[ -n $TABLE ]] && new_config+="Table = $TABLE"$'\n' + [[ $SAVE_CONFIG -eq 0 ]] || new_config+=$'SaveConfig = true\n' + for cmd in "${PRE_UP[@]}"; do + new_config+="PreUp = $cmd"$'\n' + done + for cmd in "${POST_UP[@]}"; do + new_config+="PostUp = $cmd"$'\n' + done + for cmd in "${PRE_DOWN[@]}"; do + new_config+="PreDown = $cmd"$'\n' + done + for cmd in "${POST_DOWN[@]}"; do + new_config+="PostDown = $cmd"$'\n' + done + old_umask="$(umask)" + umask 077 + current_config="$(cmd wg showconf "$INTERFACE")" + trap 'rm -f "$CONFIG_FILE.tmp"; exit' INT TERM EXIT + echo "${current_config/\[Interface\]$'\n'/$new_config}" > "$CONFIG_FILE.tmp" || die "Could not write configuration file" + sync "$CONFIG_FILE.tmp" + mv "$CONFIG_FILE.tmp" "$CONFIG_FILE" || die "Could not move configuration file" + trap - INT TERM EXIT + umask "$old_umask" +} + +execute_hooks() { + local hook + for hook in "$@"; do + hook="${hook//%i/$INTERFACE}" + echo "[#] $hook" >&2 + (eval "$hook") + done +} + +cmd_usage() { + cat >&2 <<-_EOF + Usage: $PROGRAM [ up | down | save ] [ CONFIG_FILE | INTERFACE ] + + CONFIG_FILE is a configuration file, whose filename is the interface name + followed by \`.conf'. Otherwise, INTERFACE is an interface name, with + configuration found at /etc/wireguard/INTERFACE.conf. It is to be readable + by wg(8)'s \`setconf' sub-command, with the exception of the following additions + to the [Interface] section, which are handled by $PROGRAM: + + - Address: may be specified one or more times and contains one or more + IP addresses (with an optional CIDR mask) to be set for the interface. + - DNS: an optional DNS server to use while the device is up. + - MTU: an optional MTU for the interface; if unspecified, auto-calculated. + - Table: an optional routing table to which routes will be added; if + unspecified or \`auto', the default table is used. If \`off', no routes + are added. + - PreUp, PostUp, PreDown, PostDown: script snippets which will be executed + by bash(1) at the corresponding phases of the link, most commonly used + to configure DNS. The string \`%i' is expanded to INTERFACE. + - SaveConfig: if set to \`true', the configuration is saved from the current + state of the interface upon shutdown. + + See wg-quick(8) for more info and examples. + _EOF +} + +cmd_up() { + local i + [[ -z $(ip link show dev "$INTERFACE" 2>/dev/null) ]] || die "\`$INTERFACE' already exists" + trap 'del_if; exit' INT TERM EXIT + execute_hooks "${PRE_UP[@]}" + add_if + set_config + for i in "${ADDRESSES[@]}"; do + add_addr "$i" + done + set_mtu + up_if + set_dns + for i in $(while read -r _ i; do for i in $i; do [[ $i =~ ^[0-9a-z:.]+/[0-9]+$ ]] && echo "$i"; done; done < <(wg show "$INTERFACE" allowed-ips) | sort -nr -k 2 -t /); do + add_route "$i" + done + execute_hooks "${POST_UP[@]}" + trap - INT TERM EXIT +} + +cmd_down() { + [[ " $(wg show interfaces) " == *" $INTERFACE "* ]] || die "\`$INTERFACE' is not a WireGuard interface" + execute_hooks "${PRE_DOWN[@]}" + [[ $SAVE_CONFIG -eq 0 ]] || save_config + del_if + unset_dns + execute_hooks "${POST_DOWN[@]}" +} + +cmd_save() { + [[ " $(wg show interfaces) " == *" $INTERFACE "* ]] || die "\`$INTERFACE' is not a WireGuard interface" + save_config +} + +# ~~ function override insertion point ~~ + +if [[ $# -eq 1 && ( $1 == --help || $1 == -h || $1 == help ) ]]; then + cmd_usage +elif [[ $# -eq 2 && $1 == up ]]; then + auto_su + parse_options "$2" + cmd_up +elif [[ $# -eq 2 && $1 == down ]]; then + auto_su + parse_options "$2" + cmd_down +elif [[ $# -eq 2 && $1 == save ]]; then + auto_su + parse_options "$2" + cmd_save +else + cmd_usage + exit 1 +fi + +exit 0 diff --git a/src/tools/wg-quick@.service b/src/tools/wg-quick@.service deleted file mode 100644 index ce6d70a..0000000 --- a/src/tools/wg-quick@.service +++ /dev/null @@ -1,19 +0,0 @@ -[Unit] -Description=WireGuard via wg-quick(8) for %I -After=network-online.target -Wants=network-online.target -Documentation=man:wg-quick(8) -Documentation=man:wg(8) -Documentation=https://www.wireguard.com/ -Documentation=https://www.wireguard.com/quickstart/ -Documentation=https://git.zx2c4.com/WireGuard/about/src/tools/wg-quick.8 -Documentation=https://git.zx2c4.com/WireGuard/about/src/tools/wg.8 - -[Service] -Type=oneshot -RemainAfterExit=yes -ExecStart=/usr/bin/wg-quick up %i -ExecStop=/usr/bin/wg-quick down %i - -[Install] -WantedBy=multi-user.target diff --git a/src/tools/wg.8 b/src/tools/wg.8 deleted file mode 100644 index 49dc15b..0000000 --- a/src/tools/wg.8 +++ /dev/null @@ -1,230 +0,0 @@ -.TH WG 8 "2015 August 13" ZX2C4 "WireGuard" - -.SH NAME -wg - set and retrieve configuration of WireGuard interfaces - -.SH SYNOPSIS -.B wg -[ -.I COMMAND -] [ -.I OPTIONS -]... [ -.I ARGS -]... - -.SH DESCRIPTION - -.B wg -is the configuration utility for getting and setting the configuration of -WireGuard tunnel interfaces. The interfaces themselves can be added and removed -using -.BR ip-link (8) -and their IP addresses and routing tables can be set using -.BR ip-address (8) -and -.BR ip-route (8). -The -.B wg -utility provides a series of sub-commands for changing WireGuard-specific -aspects of WireGuard interfaces. - -If no COMMAND is specified, COMMAND defaults to -.BR show . -Sub-commands that take an INTERFACE must be passed a WireGuard interface. - -.SH COMMANDS - -.TP -\fBshow\fP { \fI\fP | \fIall\fP | \fIinterfaces\fP } [\fIpublic-key\fP | \fIprivate-key\fP | \fIlisten-port\fP | \fIfwmark\fP | \fIpeers\fP | \fIpreshared-keys\fP | \fIendpoints\fP | \fIallowed-ips\fP | \fIlatest-handshakes\fP | \fIpersistent-keepalive\fP | \fItransfer\fP | \fIdump\fP] -Shows current WireGuard configuration of specified \fI\fP. -If no \fI\fP is specified, \fI\fP defaults to \fIall\fP. -If \fIinterfaces\fP is specified, prints a list of all WireGuard interfaces, -one per line, and quit. If no options are given after the interface -specification, then prints a list of all attributes in a visually pleasing way -meant for the terminal. Otherwise, prints specified information grouped by -newlines and tabs, meant to be used in scripts. For this script-friendly display, -if \fIall\fP is specified, then the first field for all categories of information -is the interface name. If \fPdump\fP is specified, then several lines are printed; -the first contains in order separated by tab: private-key, public-key, listen-port, -fwmark. Subsequent lines are printed for each peer and contain in order separated -by tab: public-key, preshared-key, endpoint, allowed-ips, latest-handshake, -transfer-rx, transfer-tx, persistent-keepalive. -.TP -\fBshowconf\fP \fI\fP -Shows the current configuration of \fI\fP in the format described -by \fICONFIGURATION FILE FORMAT\fP below. -.TP -\fBset\fP \fI\fP [\fIlisten-port\fP \fI\fP] [\fIfwmark\fP \fI\fP] [\fIprivate-key\fP \fI\fP] [\fIpeer\fP \fI\fP [\fIremove\fP] [\fIpreshared-key\fP \fI\fP] [\fIendpoint\fP \fI:\fP] [\fIpersistent-keepalive\fP \fI\fP] [\fIallowed-ips\fP \fI/\fP[,\fI/\fP]...] ]... -Sets configuration values for the specified \fI\fP. Multiple -\fIpeer\fPs may be specified, and if the \fIremove\fP argument is given -for a peer, that peer is removed, not configured. If \fIlisten-port\fP -is not specified, the port will be chosen randomly when the -interface comes up. Both \fIprivate-key\fP and \fIpreshared-key\fP must -be a files, because command line arguments are not considered private on -most systems but if you are using -.BR bash (1), -you may safely pass in a string by specifying as \fIprivate-key\fP or -\fIpreshared-key\fP the expression: <(echo PRIVATEKEYSTRING). If -\fI/dev/null\fP or another empty file is specified as the filename for -either \fIprivate-key\fP or \fIpreshared-key\fP, the key is removed from -the device. The use of \fIpreshared-key\fP is optional, and may be omitted; -it adds an additional layer of symmetric-key cryptography to be mixed into -the already existing public-key cryptography, for post-quantum resistance. -If \fIallowed-ips\fP is specified, but the value is the empty string, all -allowed ips are removed from the peer. The use of \fIpersistent-keepalive\fP -is optional and is by default off; setting it to 0 or "off" disables it. -Otherwise it represents, in seconds, between 1 and 65535 inclusive, how often -to send an authenticated empty packet to the peer, for the purpose of keeping -a stateful firewall or NAT mapping valid persistently. For example, if the -interface very rarely sends traffic, but it might at anytime receive traffic -from a peer, and it is behind NAT, the interface might benefit from having a -persistent keepalive interval of 25 seconds; however, most users will not need -this. The use of \fIfwmark\fP is optional and is by default off; setting it to -0 or "off" disables it. Otherwise it is a 32-bit fwmark for outgoing packets -and may be specified in hexadecimal by prepending "0x". -.TP -\fBsetconf\fP \fI\fP \fI\fP -Sets the current configuration of \fI\fP to the contents of -\fI\fP, which must be in the format described -by \fICONFIGURATION FILE FORMAT\fP below. -.TP -\fBaddconf\fP \fI\fP \fI\fP -Appends the contents of \fI\fP, which must -be in the format described by \fICONFIGURATION FILE FORMAT\fP below, -to the current configuration of \fI\fP. -.TP -\fBgenkey\fP -Generates a random \fIprivate\fP key in base64 and prints it to -standard output. -.TP -\fBgenpsk\fP -Generates a random \fIpreshared\fP key in base64 and prints it to -standard output. -.TP -\fBpubkey\fP -Calculates a \fIpublic\fP key and prints it in base64 to standard -output from a corresponding \fIprivate\fP key (generated with -\fIgenkey\fP) given in base64 on standard input. - -A private key and a corresponding public key may be generated at once by calling: -.br - $ umask 077 -.br - $ wg genkey | tee private.key | wg pubkey > public.key -.TP -\fBhelp\fP -Show usage message. - -.SH CONFIGURATION FILE FORMAT -The configuration file format is based on \fIINI\fP. There are two top level sections --- \fIInterface\fP and \fIPeer\fP. Multiple \fIPeer\fP sections may be specified, but -only one \fIInterface\fP section may be specified. - -.P -The \fIInterface\fP section may contain the following fields: -.IP \(bu -PrivateKey \(em a base64 private key generated by \fIwg genkey\fP. Required. -.IP \(bu -ListenPort \(em a 16-bit port for listening. Optional; if not specified, chosen -randomly. -.IP \(bu -FwMark \(em a 32-bit fwmark for outgoing packets. If set to 0 or "off", this -option is disabled. May be specified in hexadecimal by prepending "0x". Optional. -.P -The \fIPeer\fP sections may contain the following fields: -.IP \(bu -PublicKey \(em a base64 public key calculated by \fIwg pubkey\fP from a -private key, and usually transmitted out of band to the author of the -configuration file. Required. -.IP \(bu -PresharedKey \(em a base64 preshared key generated by \fIwg genpsk\fP. Optional, -and may be omitted. This option adds an additional layer of symmetric-key -cryptography to be mixed into the already existing public-key cryptography, -for post-quantum resistance. -.IP \(bu -AllowedIPs \(em a comma-separated list of IP (v4 or v6) addresses with -CIDR masks from which incoming traffic for this peer is allowed and to -which outgoing traffic for this peer is directed. The catch-all -\fI0.0.0.0/0\fP may be specified for matching all IPv4 addresses, and -\fI::/0\fP may be specified for matching all IPv6 addresses. May be specified -multiple times. Required. -.IP \(bu -Endpoint \(em an endpoint IP or hostname, followed by a colon, and then a -port number. This endpoint will be updated automatically to the most recent -source IP address and port of correctly authenticated packets from the peer. -Optional. -.IP \(bu -PersistentKeepalive \(em a seconds interval, between 1 and 65535 inclusive, of -how often to send an authenticated empty packet to the peer for the purpose of keeping a -stateful firewall or NAT mapping valid persistently. For example, if the interface -very rarely sends traffic, but it might at anytime receive traffic from a peer, -and it is behind NAT, the interface might benefit from having a persistent keepalive -interval of 25 seconds. If set to 0 or "off", this option is disabled. By default or -when unspecified, this option is off. Most users will not need this. Optional. - -.SH CONFIGURATION FILE FORMAT EXAMPLE -This example may be used as a model for writing configuration files, following an -INI-like syntax. Characters after and including a '#' are considered comments and -are thus ignored. - - [Interface] -.br - PrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= -.br - ListenPort = 51820 -.br - -.br - [Peer] -.br - PublicKey = xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= -.br - Endpoint = 192.95.5.67:1234 -.br - AllowedIPs = 10.192.122.3/32, 10.192.124.1/24 -.br - -.br - [Peer] -.br - PublicKey = TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0= -.br - Endpoint = [2607:5300:60:6b0::c05f:543]:2468 -.br - AllowedIPs = 10.192.122.4/32, 192.168.0.0/16 -.br - -.br - [Peer] -.br - PublicKey = gN65BkIKy1eCE9pP1wdc8ROUtkHLF2PfAqYdyYBz6EA= -.br - Endpoint = test.wireguard.com:18981 -.br - AllowedIPs = 10.10.10.230/32 - -.SH ENVIRONMENT VARIABLES -.TP -.I WG_COLOR_MODE -If set to \fIalways\fP, always print ANSI colorized output. If set to \fInever\fP, never print ANSI colorized output. If set to \fIauto\fP, something invalid, or unset, then print ANSI colorized output only when writing to a TTY. -.TP -.I WG_HIDE_KEYS -If set to \fInever\fP, then the pretty-printing \fBshow\fP sub-command will show private and preshared keys in the output. If set to \fIalways\fP, something invalid, or unset, then private and preshared keys will be printed as "(hidden)". - -.SH SEE ALSO -.BR ip (8), -.BR ip-link (8), -.BR ip-address (8), -.BR ip-route (8). - -.SH AUTHOR -.B wg -was written by -.MT Jason@zx2c4.com -Jason A. Donenfeld -.ME . -For updates and more information, a project page is available on the -.UR https://\:www.wireguard.com/ -World Wide Web -.UE . -- cgit v1.2.3-59-g8ed1b