Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 60 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,22 +45,25 @@ of wireproxy by [@artem-russkikh](https://github.com/artem-russkikh).

```bash
usage: wireproxy [-h|--help] [-c|--config "<value>"] [-s|--silent]
[-d|--daemon] [-i|--info "<value>"] [-v|--version]
[-n|--configtest]
[-d|--daemon] [-i|--info "<value>"] [-H|--healthcheck
"<value>"] [-v|--version] [-n|--configtest]

Userspace wireguard client for proxying

Arguments:

-h --help Print help information
-c --config Path of configuration file
Default paths: /etc/wireproxy/wireproxy.conf, $HOME/.config/wireproxy.conf
-s --silent Silent mode
-d --daemon Make wireproxy run in background
-i --info Specify the address and port for exposing health status
-v --version Print version
-n --configtest Configtest mode. Only check the configuration file for
validity.
-h --help Print help information
-c --config Path of configuration file
Default paths: /etc/wireproxy/wireproxy.conf, $HOME/.config/wireproxy.conf
-s --silent Silent mode
-d --daemon Make wireproxy run in background
-i --info Specify the address and port for exposing health status
-H --healthcheck Request /readyz from the health endpoint at the given
address and port (see --info), exit 0 if healthy and 1
otherwise
-v --version Print version
-n --configtest Configtest mode. Only check the configuration file for
validity.
```

# Build instruction
Expand Down Expand Up @@ -91,6 +94,7 @@ Instructions for using wireproxy with Firefox container tabs and auto-start on M
[Interface]
Address = 10.200.200.2/32 # The subnet should be /32 and /128 for IPv4 and v6 respectively
# MTU = 1420 (optional)
# MaxHandshakeAge = 180 (optional, see "Health endpoint" below)
PrivateKey = uCTIK+56CPyCvwJxmU5dBfuyJvPuSXAq1FzHdnIxe1Q=
# PrivateKey = $MY_WIREGUARD_PRIVATE_KEY # Alternatively, reference environment variables
DNS = 10.200.200.1
Expand Down Expand Up @@ -320,3 +324,48 @@ CheckAlive = 1.1.1.1
If nothing is set for `CheckAlive`, an empty JSON object with 200 will be the response.

The peer which the ICMP ping packet is routed to depends on the `AllowedIPs` set for each peers.

## MaxHandshakeAge

`MaxHandshakeAge` (`[Interface]`, in seconds, disabled by default) makes `/readyz` also
respond with a 503 if the last handshake of any peer is older than that many seconds, or
if a peer has never completed a handshake. This works without `CheckAlive`. The last
handshake time (unix seconds, `0` if none) of each peer is added to the response under
`handshake:<public key>`. Peers with no `Endpoint` in the config only answer handshakes,
so they are not checked: they are listed with a `handshake_skipped:<public key>` entry of
`1` and never make `/readyz` fail, even if they connected once and have a learned endpoint:

```ini
[Interface]
PrivateKey = censored
Address = 10.2.0.2/32
MaxHandshakeAge = 180
```

```text
< HTTP/1.1 503 Service Unavailable
<
{"handshake:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=":0}
```

Note that wireguard only handshakes while there is traffic, so set `PersistentKeepalive`
on peers that may be idle for longer than `MaxHandshakeAge`.

## Health check in a container

`--healthcheck/-H <address>` requests `/readyz` from the given address (the same value as
`--info`) and exits with 0 if the response is a 200, otherwise with 1. It does not read a
configuration file. As the container image has no shell, `curl` or `wget`, this is how to
use `/readyz` as a Docker health check:

```dockerfile
CMD [ "--config", "/etc/wireproxy/config", "--info", "127.0.0.1:9080" ]
HEALTHCHECK CMD [ "/usr/bin/wireproxy", "--healthcheck", "127.0.0.1:9080" ]
```

or with Compose:

```yaml
healthcheck:
test: ["CMD", "/usr/bin/wireproxy", "--healthcheck", "127.0.0.1:9080"]
```
10 changes: 10 additions & 0 deletions cmd/wireproxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"os/signal"
"strconv"
"syscall"
"time"

"github.com/landlock-lsm/go-landlock/landlock"

Expand Down Expand Up @@ -213,6 +214,7 @@ func main() {
silent := parser.Flag("s", "silent", &argparse.Options{Help: "Silent mode"})
daemon := parser.Flag("d", "daemon", &argparse.Options{Help: "Make wireproxy run in background"})
info := parser.String("i", "info", &argparse.Options{Help: "Specify the address and port for exposing health status"})
healthcheck := parser.String("H", "healthcheck", &argparse.Options{Help: "Request /readyz from the health endpoint at the given address and port (see --info), exit 0 if healthy and 1 otherwise"})
printVerison := parser.Flag("v", "version", &argparse.Options{Help: "Print version"})
configTest := parser.Flag("n", "configtest", &argparse.Options{Help: "Configtest mode. Only check the configuration file for validity."})

Expand All @@ -227,6 +229,14 @@ func main() {
return
}

if *healthcheck != "" {
if err := wireproxy.Healthcheck(*healthcheck, 3*time.Second); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}

if *config == "" {
if path, config_exist := configFilePath(); config_exist {
*config = path
Expand Down
15 changes: 15 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ type DeviceConfig struct {
ListenPort *int
CheckAlive []netip.Addr
CheckAliveInterval int
// MaxHandshakeAge is the age, in seconds, of the last handshake of a peer
// after which /readyz reports unavailable. 0 disables the check.
MaxHandshakeAge int
}

type UDPProxyTunnelConfig struct {
Expand Down Expand Up @@ -326,6 +329,18 @@ func ParseInterface(cfg *ini.File, device *DeviceConfig) error {
device.CheckAliveInterval = value
}

if sectionKey, err := section.GetKey("MaxHandshakeAge"); err == nil {
value, err := sectionKey.Int()
if err != nil {
return err
}
if value < 0 {
return errors.New("MaxHandshakeAge should not be negative")
}

device.MaxHandshakeAge = value
}

return nil
}

Expand Down
92 changes: 92 additions & 0 deletions health.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package wireproxy

import (
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)

// handshakeRecords reports the last handshake time of every peer found in an
// IpcGet response as unix seconds (0 if there has never been one), keyed by
// "handshake:<base64 public key>". stale is true if any checked peer has no
// handshake or one older than maxAge.
//
// Peers with no Endpoint in the configuration only answer handshakes and have
// never connected out, so none can be expected of them: they are left out of the
// verdict and flagged in records with a "handshake_skipped:<base64 public key>"
// entry of 1. The configuration is consulted rather than the IPC "endpoint" line,
// which wireguard also reports for endpoints learned from incoming packets.
func handshakeRecords(ipc string, peers []PeerConfig, maxAge time.Duration, now time.Time) (records map[string]uint64, stale bool) {
configured := make(map[string]bool)
for _, peer := range peers {
if peer.Endpoint != nil {
configured[base64Key(peer.PublicKey)] = true
}
}

records = make(map[string]uint64)
skipped := make(map[string]bool)
var key64 string
for _, line := range strings.Split(ipc, "\n") {
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
switch key {
case "public_key":
key64 = base64Key(value)
records["handshake:"+key64] = 0
if !configured[key64] {
skipped[key64] = true
}
case "last_handshake_time_sec":
if sec, err := strconv.ParseUint(value, 10, 63); err == nil && key64 != "" {
records["handshake:"+key64] = sec
}
}
}

for peer, record := range records {
if skipped[strings.TrimPrefix(peer, "handshake:")] {
continue
}
if record == 0 || now.Sub(time.Unix(int64(record), 0)) > maxAge {
stale = true
}
}
for peer := range skipped {
records["handshake_skipped:"+peer] = 1
}
return records, stale
}

// base64Key converts a wireguard key given as hex (as in IpcGet and the parsed
// configuration) to base64; a key that is not hex is returned unchanged.
func base64Key(key string) string {
if raw, err := hex.DecodeString(key); err == nil {
return base64.StdEncoding.EncodeToString(raw)
}
return key
}

// Healthcheck requests /readyz from the health endpoint listening on addr
// (the value of --info) and returns an error unless it responds with 200.
func Healthcheck(addr string, timeout time.Duration) error {
client := http.Client{Timeout: timeout}
resp, err := client.Get("http://" + addr + "/readyz")
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
return fmt.Errorf("unhealthy: %s: %s", resp.Status, strings.TrimSpace(string(body)))
}
return nil
}
Loading