mirror of
https://github.com/h44z/wg-portal.git
synced 2026-12-05 11:46:09 +01:00
feat: add support for AmneziaWG (#649)
This commit is contained in:
@@ -89,6 +89,38 @@ jobs:
|
|||||||
build-args: |
|
build-args: |
|
||||||
BUILD_VERSION=${{ env.BUILD_VERSION }}
|
BUILD_VERSION=${{ env.BUILD_VERSION }}
|
||||||
|
|
||||||
|
- name: Extract metadata for AmneziaWG image
|
||||||
|
id: meta-awg
|
||||||
|
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
|
||||||
|
with:
|
||||||
|
images: |
|
||||||
|
wgportal/wg-portal
|
||||||
|
ghcr.io/${{ github.repository }}
|
||||||
|
flavor: |
|
||||||
|
latest=auto
|
||||||
|
suffix=-amneziawg,onlatest=true
|
||||||
|
tags: |
|
||||||
|
type=ref,event=tag
|
||||||
|
type=ref,event=branch
|
||||||
|
type=semver,pattern={{version}}
|
||||||
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
|
type=semver,pattern={{major}}
|
||||||
|
type=semver,pattern=v{{major}}.{{minor}}
|
||||||
|
type=semver,pattern=v{{major}}
|
||||||
|
|
||||||
|
- name: Build and push AmneziaWG Docker image
|
||||||
|
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
target: amneziawg
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
tags: ${{ steps.meta-awg.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta-awg.outputs.labels }}
|
||||||
|
annotations: ${{ steps.meta-awg.outputs.annotations }}
|
||||||
|
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||||
|
build-args: |
|
||||||
|
BUILD_VERSION=${{ env.BUILD_VERSION }}
|
||||||
|
|
||||||
- name: Rename binaries
|
- name: Rename binaries
|
||||||
run: |
|
run: |
|
||||||
for file in binaries/linux*/wg-portal; do
|
for file in binaries/linux*/wg-portal; do
|
||||||
|
|||||||
+24
-1
@@ -47,10 +47,23 @@ RUN CGO_ENABLED=0 GOARCH=${TARGETARCH} go build -o /build/dist/wg-portal \
|
|||||||
FROM scratch AS binaries
|
FROM scratch AS binaries
|
||||||
COPY --from=builder /build/dist/wg-portal /
|
COPY --from=builder /build/dist/wg-portal /
|
||||||
|
|
||||||
|
######
|
||||||
|
# Build the optional official AmneziaWG tools for the target architecture.
|
||||||
|
# These are diagnostic tools; the portal's native backend does not need them.
|
||||||
|
# The kernel module belongs on the host and is not built into this image.
|
||||||
|
######
|
||||||
|
FROM alpine:3.24 AS amneziawg-tools
|
||||||
|
RUN apk add --no-cache build-base linux-headers
|
||||||
|
ADD --checksum=sha256:22438f231d39ea27e4bdc69707ec3103357f3cecc9ad3eecba18a61e5b39c9b9 \
|
||||||
|
https://codeload.github.com/amnezia-vpn/amneziawg-tools/tar.gz/ee0f0a9aa34ff0a0da4b3433b9512781cfe02843 /tmp/amneziawg-tools.tar.gz
|
||||||
|
RUN mkdir /build && tar -xzf /tmp/amneziawg-tools.tar.gz -C /build --strip-components=1 \
|
||||||
|
&& make -C /build/src \
|
||||||
|
&& make -C /build/src install DESTDIR=/out PREFIX=/usr WITH_WGQUICK=yes WITH_BASHCOMPLETION=no WITH_SYSTEMDUNITS=no
|
||||||
|
|
||||||
######
|
######
|
||||||
# Final image
|
# Final image
|
||||||
######
|
######
|
||||||
FROM alpine:3.24
|
FROM alpine:3.24 AS runtime
|
||||||
# Install OS-level dependencies
|
# Install OS-level dependencies
|
||||||
RUN apk add --no-cache bash curl iptables nftables openresolv wireguard-tools tzdata
|
RUN apk add --no-cache bash curl iptables nftables openresolv wireguard-tools tzdata
|
||||||
# Setup timezone
|
# Setup timezone
|
||||||
@@ -67,3 +80,13 @@ EXPOSE 51820/udp
|
|||||||
VOLUME [ "/app/data", "/app/config" ]
|
VOLUME [ "/app/data", "/app/config" ]
|
||||||
# Command to run the executable
|
# Command to run the executable
|
||||||
ENTRYPOINT [ "/app/wg-portal" ]
|
ENTRYPOINT [ "/app/wg-portal" ]
|
||||||
|
|
||||||
|
# Optional image, built with --target amneziawg and published as *-amneziawg.
|
||||||
|
FROM runtime AS amneziawg
|
||||||
|
RUN apk add --no-cache iproute2
|
||||||
|
COPY --from=amneziawg-tools /out/usr/bin/awg /usr/bin/awg
|
||||||
|
COPY --from=amneziawg-tools /out/usr/bin/awg-quick /usr/bin/awg-quick
|
||||||
|
COPY --from=amneziawg-tools /build/COPYING /usr/share/licenses/amneziawg-tools/COPYING
|
||||||
|
|
||||||
|
# Keep the default image and its dependencies unchanged.
|
||||||
|
FROM runtime AS standard
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ backend:
|
|||||||
default: local
|
default: local
|
||||||
rekey_timeout_interval: 125s
|
rekey_timeout_interval: 125s
|
||||||
local_resolvconf_prefix: tun.
|
local_resolvconf_prefix: tun.
|
||||||
|
amneziawg:
|
||||||
|
enabled: false
|
||||||
|
ignored_interfaces: []
|
||||||
|
|
||||||
advanced:
|
advanced:
|
||||||
log_level: info
|
log_level: info
|
||||||
@@ -219,7 +222,7 @@ The current MikroTik backend is in **BETA** and may not support all features.
|
|||||||
### `default`
|
### `default`
|
||||||
- **Default:** `local`
|
- **Default:** `local`
|
||||||
- **Description:** The default backend to use for managing WireGuard interfaces.
|
- **Description:** The default backend to use for managing WireGuard interfaces.
|
||||||
Valid options are: `local`, or other backend id's configured in the `mikrotik`, `pfsense` or `opnsense` sections.
|
Valid options are: `local`, `amneziawg` when enabled, or other backend IDs configured in the `mikrotik`, `pfsense` or `opnsense` sections.
|
||||||
|
|
||||||
### `rekey_timeout_interval`
|
### `rekey_timeout_interval`
|
||||||
- **Default:** `180s`
|
- **Default:** `180s`
|
||||||
@@ -241,6 +244,22 @@ The current MikroTik backend is in **BETA** and may not support all features.
|
|||||||
- **Description:** A list of interface names to exclude when enumerating local interfaces.
|
- **Description:** A list of interface names to exclude when enumerating local interfaces.
|
||||||
This is useful if you want to prevent certain interfaces from being imported from the local system.
|
This is useful if you want to prevent certain interfaces from being imported from the local system.
|
||||||
|
|
||||||
|
### AmneziaWG
|
||||||
|
|
||||||
|
#### `enabled`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **Environment Variable:** `WG_PORTAL_BACKEND_AMNEZIAWG_ENABLED`
|
||||||
|
- **Description:** Enable the optional local `amneziawg` backend. Requires a loaded AmneziaWG host
|
||||||
|
kernel module. The portal checks its Generic Netlink interface at startup and communicates
|
||||||
|
with it directly; no AmneziaWG userspace tools are required.
|
||||||
|
|
||||||
|
#### `ignored_interfaces`
|
||||||
|
- **Default:** *(empty)*
|
||||||
|
- **Environment Variable:** `WG_PORTAL_BACKEND_IGNORED_AMNEZIAWG_INTERFACES`
|
||||||
|
- **Description:** AmneziaWG interface names excluded from automatic import.
|
||||||
|
|
||||||
|
See [AmneziaWG backend setup](../usage/backends.md#configuring-the-amneziawg-backend) for details.
|
||||||
|
|
||||||
### Mikrotik
|
### Mikrotik
|
||||||
|
|
||||||
The `mikrotik` array contains a list of MikroTik backend definitions. Each entry describes how to connect to a MikroTik RouterOS instance that hosts WireGuard interfaces.
|
The `mikrotik` array contains a list of MikroTik backend definitions. Each entry describes how to connect to a MikroTik RouterOS instance that hosts WireGuard interfaces.
|
||||||
|
|||||||
@@ -115,6 +115,20 @@ WireGuard Portal supports managing WireGuard interfaces through three distinct d
|
|||||||
config_storage_path: /etc/wireguard/
|
config_storage_path: /etc/wireguard/
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## AmneziaWG image
|
||||||
|
|
||||||
|
The optional AmneziaWG variant is built with `docker build --target amneziawg -t wg-portal:amneziawg .`.
|
||||||
|
It is published on the same registries with an `-amneziawg` tag suffix, for example
|
||||||
|
`wgportal/wg-portal:master-amneziawg` and `ghcr.io/h44z/wg-portal:latest-amneziawg`.
|
||||||
|
It includes the official `awg` and `awg-quick` tools for manual diagnostics.
|
||||||
|
The portal manages AmneziaWG directly via Generic Netlink and does not invoke these tools.
|
||||||
|
|
||||||
|
Install and load the AmneziaWG kernel module **on the Docker host**, then enable
|
||||||
|
`backend.amneziawg.enabled` in the [backend configuration](../usage/backends.md#configuring-the-amneziawg-backend).
|
||||||
|
The image shares the host kernel; it cannot provide a portable, precompiled kernel module.
|
||||||
|
Use the same `NET_ADMIN`, port mappings, persistent volumes, and network mode as the ordinary image.
|
||||||
|
The portal checks kernel support on startup when this backend is enabled.
|
||||||
|
|
||||||
## Image Versioning
|
## Image Versioning
|
||||||
|
|
||||||
All images are hosted on Docker Hub at [https://hub.docker.com/r/wgportal/wg-portal](https://hub.docker.com/r/wgportal/wg-portal) or in the [GitHub Container Registry](https://github.com/h44z/wg-portal/pkgs/container/wg-portal).
|
All images are hosted on Docker Hub at [https://hub.docker.com/r/wgportal/wg-portal](https://hub.docker.com/r/wgportal/wg-portal) or in the [GitHub Container Registry](https://github.com/h44z/wg-portal/pkgs/container/wg-portal).
|
||||||
|
|||||||
@@ -51,6 +51,13 @@ definitions:
|
|||||||
items:
|
items:
|
||||||
type: string
|
type: string
|
||||||
type: array
|
type: array
|
||||||
|
AmneziaWG:
|
||||||
|
additionalProperties:
|
||||||
|
type: string
|
||||||
|
description: |-
|
||||||
|
AmneziaWG contains per-interface obfuscation options for the amneziawg backend.
|
||||||
|
Omitted options preserve the current kernel settings. Values use awg configuration syntax.
|
||||||
|
type: object
|
||||||
Backend:
|
Backend:
|
||||||
description: Backend is the configured backend ID used to manage this interface. Omit it on create to use the local backend, or on update to preserve the current backend.
|
description: Backend is the configured backend ID used to manage this interface. Omit it on create to use the local backend, or on update to preserve the current backend.
|
||||||
example: local
|
example: local
|
||||||
|
|||||||
@@ -7,15 +7,73 @@ A global default backend determines where newly created interfaces go (unless yo
|
|||||||
|
|
||||||
**Supported backends:**
|
**Supported backends:**
|
||||||
- **Local** (default): Manages interfaces on the host running WireGuard Portal (Linux WireGuard via wgctrl). Use this when the portal should directly configure wg devices on the same server.
|
- **Local** (default): Manages interfaces on the host running WireGuard Portal (Linux WireGuard via wgctrl). Use this when the portal should directly configure wg devices on the same server.
|
||||||
|
- **AmneziaWG** (optional): Manages local AmneziaWG kernel interfaces directly via Generic Netlink, alongside ordinary WireGuard.
|
||||||
- **MikroTik** RouterOS (_beta_): Manages interfaces and peers on MikroTik devices via the RouterOS REST API. Use this to control WG interfaces on RouterOS v7+.
|
- **MikroTik** RouterOS (_beta_): Manages interfaces and peers on MikroTik devices via the RouterOS REST API. Use this to control WG interfaces on RouterOS v7+.
|
||||||
- **pfSense** (_alpha_): Manages interfaces and peers on pfSense firewalls via the pfSense REST API.
|
- **pfSense** (_alpha_): Manages interfaces and peers on pfSense firewalls via the pfSense REST API.
|
||||||
- **OPNsense** (_alpha_): Manages interfaces and peers on OPNsense firewalls via the WireGuard API built into OPNsense core. Unlike the pfSense backend, no add-on package is required on the firewall.
|
- **OPNsense** (_alpha_): Manages interfaces and peers on OPNsense firewalls via the WireGuard API built into OPNsense core. Unlike the pfSense backend, no add-on package is required on the firewall.
|
||||||
|
|
||||||
How backend selection works:
|
How backend selection works:
|
||||||
- The default backend is configured at `backend.default` (_local_ or the id of a defined MikroTik, pfSense or OPNsense backend).
|
- The default backend is configured at `backend.default` (`local`, enabled `amneziawg`, or the id of a defined remote backend).
|
||||||
New interfaces created in the UI will use this backend by default.
|
New interfaces created in the UI will use this backend by default.
|
||||||
- Each interface stores its backend. You can select a different backend when creating a new interface.
|
- Each interface stores its backend. You can select a different backend when creating a new interface.
|
||||||
|
|
||||||
|
## Configuring the AmneziaWG backend
|
||||||
|
|
||||||
|
Install the official [AmneziaWG kernel module](https://github.com/amnezia-vpn/amneziawg-linux-kernel-module)
|
||||||
|
for the running **host** kernel and load it with `modprobe amneziawg` before starting the portal.
|
||||||
|
The portal communicates with the kernel directly, following the same client contract as `wgctrl`.
|
||||||
|
No `awg`, `awg-quick`, or other AmneziaWG userspace executable is required.
|
||||||
|
The ordinary Docker image supports this backend too; the separate
|
||||||
|
[AmneziaWG Docker image](../getting-started/docker.md#amneziawg-image) includes optional diagnostic tools.
|
||||||
|
The portal needs `NET_ADMIN` in the network namespace containing the interfaces.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
backend:
|
||||||
|
default: amneziawg # optional; local remains available
|
||||||
|
amneziawg:
|
||||||
|
enabled: true
|
||||||
|
ignored_interfaces: []
|
||||||
|
```
|
||||||
|
|
||||||
|
The backend is disabled by default. `WG_PORTAL_BACKEND_AMNEZIAWG_ENABLED=true` can also enable it.
|
||||||
|
When enabled, the portal checks for the kernel's `amneziawg` Generic Netlink family and its version (1, 2, or 3).
|
||||||
|
Startup fails with a diagnostic if kernel support is missing or its interface version is unsupported. It does not install or load kernel modules,
|
||||||
|
and does not fall back to a userspace implementation. Ordinary WireGuard and AmneziaWG interfaces
|
||||||
|
are discovered and managed by their respective backends. `local` and `amneziawg` are reserved backend IDs.
|
||||||
|
|
||||||
|
Select **Local AmneziaWG Controller** when creating an interface. In its **AmneziaWG** section,
|
||||||
|
enter [obfuscation options](https://docs.amnezia.org/documentation/amnezia-wg#configuration-parameters) as `Name = Value`, one per line. For example:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
Jc = 4
|
||||||
|
Jmin = 40
|
||||||
|
Jmax = 70
|
||||||
|
S1 = 86
|
||||||
|
S2 = 94
|
||||||
|
H1 = 123456789
|
||||||
|
H2 = 234567890
|
||||||
|
H3 = 345678901
|
||||||
|
H4 = 456789012
|
||||||
|
```
|
||||||
|
|
||||||
|
Choose suitable values for your deployment. An empty options section keeps the kernel defaults;
|
||||||
|
enabling the backend alone does not select an obfuscation profile.
|
||||||
|
The supported interface options include `Jc`, `Jmin`, `Jmax`, `S1`–`S4`, `H1`–`H4`, `I1`–`I5`,
|
||||||
|
and the header protection, padding, timer, and boolean options in the official tools.
|
||||||
|
Header and timer ranges are preserved as strings. The installed kernel must support the options used:
|
||||||
|
v1 uses fixed headers, v2 adds header ranges and CPS packets, and v3 adds header protection and timer ranges.
|
||||||
|
Options requiring a newer kernel interface are rejected before configuration is applied.
|
||||||
|
Peer keepalive intervals are represented as single values in the portal; importing a keepalive range
|
||||||
|
reports its lower bound, and editing that peer replaces the range with a single interval.
|
||||||
|
|
||||||
|
Existing interface settings are imported and stored in the database. Updates apply supplied options
|
||||||
|
and retain omitted kernel values; use explicit values to reset an option. Both API versions expose
|
||||||
|
the same options through an `AmneziaWG` object, for example `{"Jc":"4","H1":"100-200"}`.
|
||||||
|
The portal includes these settings in saved interface configurations, peer downloads, QR codes,
|
||||||
|
and emailed configurations. Clients must support AmneziaWG and the configured protocol version.
|
||||||
|
These files can be consumed by AmneziaWG clients or, optionally, `awg`/`awg-quick`. Linux routing, DNS, hooks, interface enable/disable,
|
||||||
|
peer management, and handshake/traffic statistics follow the local backend's behavior.
|
||||||
|
|
||||||
## Configuring MikroTik backends (RouterOS v7+)
|
## Configuring MikroTik backends (RouterOS v7+)
|
||||||
|
|
||||||
> :warning: The MikroTik backend is currently marked beta. While basic functionality is implemented, some advanced features are not yet implemented or contain bugs. Please test carefully before using in production.
|
> :warning: The MikroTik backend is currently marked beta. While basic functionality is implemented, some advanced features are not yet implemented or contain bugs. Please test carefully before using in production.
|
||||||
|
|||||||
@@ -50,6 +50,8 @@ const currentTags = ref({
|
|||||||
PeerDefDnsSearch: ""
|
PeerDefDnsSearch: ""
|
||||||
})
|
})
|
||||||
const formData = ref(freshInterface())
|
const formData = ref(freshInterface())
|
||||||
|
const amneziaWGText = ref("")
|
||||||
|
const isAmneziaWG = computed(() => formData.value.Backend === 'amneziawg')
|
||||||
const isSaving = ref(false)
|
const isSaving = ref(false)
|
||||||
const isDeleting = ref(false)
|
const isDeleting = ref(false)
|
||||||
const isApplyingDefaults = ref(false)
|
const isApplyingDefaults = ref(false)
|
||||||
@@ -77,7 +79,7 @@ const isHookSupported = computed(() => {
|
|||||||
let availableBackends = settings.Setting('AvailableBackends') || [];
|
let availableBackends = settings.Setting('AvailableBackends') || [];
|
||||||
let backend = availableBackends.find(b => b.Id === formData.value.Backend);
|
let backend = availableBackends.find(b => b.Id === formData.value.Backend);
|
||||||
if (!backend) return false;
|
if (!backend) return false;
|
||||||
return backend.Type === 'local' || backend.Type === 'mikrotik';
|
return backend.Type === 'local' || backend.Type === 'amneziawg' || backend.Type === 'mikrotik';
|
||||||
})
|
})
|
||||||
|
|
||||||
// functions
|
// functions
|
||||||
@@ -169,6 +171,8 @@ watch(() => props.visible, async (newValue, oldValue) => {
|
|||||||
formData.value.PeerDefPostDown = selectedInterface.value.PeerDefPostDown
|
formData.value.PeerDefPostDown = selectedInterface.value.PeerDefPostDown
|
||||||
|
|
||||||
}
|
}
|
||||||
|
const options = (selectedInterface.value ? selectedInterface.value.AmneziaWG : interfaces.Prepared?.AmneziaWG) || {}
|
||||||
|
amneziaWGText.value = Object.entries(options).map(([key, value]) => `${key} = ${value}`).join('\n')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -275,6 +279,18 @@ async function save() {
|
|||||||
if (isSaving.value) return
|
if (isSaving.value) return
|
||||||
isSaving.value = true
|
isSaving.value = true
|
||||||
try {
|
try {
|
||||||
|
const options = {}
|
||||||
|
if (isAmneziaWG.value) {
|
||||||
|
for (const line of amneziaWGText.value.split('\n')) {
|
||||||
|
if (!line.trim() || line.trim().startsWith('#')) continue
|
||||||
|
const match = line.match(/^\s*([A-Za-z][A-Za-z0-9]*)\s*=\s*(.*?)\s*$/)
|
||||||
|
if (!match || Object.hasOwn(options, match[1])) {
|
||||||
|
throw new Error(t('modals.interface-edit.amneziawg.invalid'))
|
||||||
|
}
|
||||||
|
options[match[1]] = match[2]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
formData.value.AmneziaWG = options
|
||||||
if (props.interfaceId!=='#NEW#') {
|
if (props.interfaceId!=='#NEW#') {
|
||||||
await interfaces.UpdateInterface(selectedInterface.value.Identifier, formData.value)
|
await interfaces.UpdateInterface(selectedInterface.value.Identifier, formData.value)
|
||||||
} else {
|
} else {
|
||||||
@@ -427,6 +443,12 @@ async function del() {
|
|||||||
<input v-model="formData.DisplayName" class="form-control" :placeholder="$t('modals.interface-edit.display-name.placeholder')" type="text">
|
<input v-model="formData.DisplayName" class="form-control" :placeholder="$t('modals.interface-edit.display-name.placeholder')" type="text">
|
||||||
</div>
|
</div>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
<fieldset v-if="isAmneziaWG">
|
||||||
|
<legend class="mt-4">AmneziaWG</legend>
|
||||||
|
<label class="form-label" for="amneziaWGOptions">{{ $t('modals.interface-edit.amneziawg.label') }}</label>
|
||||||
|
<textarea id="amneziaWGOptions" v-model="amneziaWGText" class="form-control font-monospace" rows="8" placeholder="Jc = 4 Jmin = 40 Jmax = 70 S1 = 86 S2 = 94 H1 = 123456789 H2 = 234567890 H3 = 345678901 H4 = 456789012"></textarea>
|
||||||
|
<small class="form-text">{{ $t('modals.interface-edit.amneziawg.help') }}</small>
|
||||||
|
</fieldset>
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend class="mt-4">{{ $t('modals.interface-edit.header-crypto') }}</legend>
|
<legend class="mt-4">{{ $t('modals.interface-edit.header-crypto') }}</legend>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ export function freshInterface() {
|
|||||||
CreateDefaultPeer: false,
|
CreateDefaultPeer: false,
|
||||||
Mode: "server",
|
Mode: "server",
|
||||||
Backend: "local",
|
Backend: "local",
|
||||||
|
AmneziaWG: {},
|
||||||
|
|
||||||
PublicKey: "",
|
PublicKey: "",
|
||||||
PrivateKey: "",
|
PrivateKey: "",
|
||||||
|
|||||||
@@ -425,6 +425,7 @@
|
|||||||
"tab-peerdef": "Peer-Standardeinstellungen",
|
"tab-peerdef": "Peer-Standardeinstellungen",
|
||||||
"header-general": "Allgemein",
|
"header-general": "Allgemein",
|
||||||
"header-network": "Netzwerk",
|
"header-network": "Netzwerk",
|
||||||
|
"amneziawg": {"label": "Verschleierungsoptionen", "help": "Eine Option pro Zeile (zum Beispiel H1 = 123456789). Ausgelassene Optionen behalten ihren aktuellen Kernelwert. Zum Zurücksetzen explizite Werte angeben. Diese Einstellungen werden in Client-Konfigurationen übernommen; Clients benötigen AmneziaWG-Unterstützung.", "invalid": "Eine AmneziaWG-Option pro Zeile als Name = Wert angeben, ohne doppelte Namen."},
|
||||||
"header-crypto": "Kryptografie",
|
"header-crypto": "Kryptografie",
|
||||||
"header-hooks": "Schnittstellen-Hooks",
|
"header-hooks": "Schnittstellen-Hooks",
|
||||||
"header-peer-hooks": "Hooks",
|
"header-peer-hooks": "Hooks",
|
||||||
|
|||||||
@@ -425,6 +425,7 @@
|
|||||||
"tab-peerdef": "Peer Defaults",
|
"tab-peerdef": "Peer Defaults",
|
||||||
"header-general": "General",
|
"header-general": "General",
|
||||||
"header-network": "Network",
|
"header-network": "Network",
|
||||||
|
"amneziawg": {"label": "Obfuscation options", "help": "One option per line (for example H1 = 123456789). Omitted options keep their current kernel values. Use explicit values to reset options. These settings are included in client configurations; clients need AmneziaWG support.", "invalid": "Use one AmneziaWG option per line as Name = Value, without duplicate names."},
|
||||||
"header-crypto": "Cryptography",
|
"header-crypto": "Cryptography",
|
||||||
"header-hooks": "Interface Hooks",
|
"header-hooks": "Interface Hooks",
|
||||||
"header-peer-hooks": "Hooks",
|
"header-peer-hooks": "Hooks",
|
||||||
|
|||||||
@@ -0,0 +1,207 @@
|
|||||||
|
package wgcontroller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
|
|
||||||
|
"github.com/h44z/wg-portal/internal/config"
|
||||||
|
"github.com/h44z/wg-portal/internal/domain"
|
||||||
|
"github.com/h44z/wg-portal/internal/lowlevel"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AmneziaWGRepo interface {
|
||||||
|
WgCtrlRepo
|
||||||
|
AmneziaWGOptions(string) (domain.AmneziaWGOptions, error)
|
||||||
|
ConfigureAmneziaWGDevice(string, wgtypes.Config, domain.AmneziaWGOptions) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// AmneziaWGController manages AmneziaWG kernel interfaces and their obfuscation
|
||||||
|
// options. Its local helper uses the same AWG client for Linux routing, DNS,
|
||||||
|
// hooks, and peer lifecycle operations.
|
||||||
|
type AmneziaWGController struct {
|
||||||
|
awg AmneziaWGRepo
|
||||||
|
local LocalController
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAmneziaWGController(cfg *config.Config) (*AmneziaWGController, error) {
|
||||||
|
awg, err := lowlevel.NewAmneziaWGClient()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newAmneziaWGController(cfg, awg, &lowlevel.NetlinkManager{}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAmneziaWGController(cfg *config.Config, awg AmneziaWGRepo, nl NetlinkClient) *AmneziaWGController {
|
||||||
|
return &AmneziaWGController{
|
||||||
|
awg: awg,
|
||||||
|
local: LocalController{
|
||||||
|
cfg: cfg,
|
||||||
|
wg: awg,
|
||||||
|
nl: nl,
|
||||||
|
shellCmd: "bash", // we only support bash at the moment
|
||||||
|
resolvConfIfacePrefix: cfg.Backend.LocalResolvconfPrefix, // WireGuard interfaces have a tun. prefix in resolvconf
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) GetId() domain.InterfaceBackend {
|
||||||
|
return config.AmneziaWGBackendName
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) GetInterfaces(_ context.Context) ([]domain.PhysicalInterface, error) {
|
||||||
|
devices, err := c.awg.Devices()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("AmneziaWG device list error: %w", err)
|
||||||
|
}
|
||||||
|
interfaces := make([]domain.PhysicalInterface, 0, len(devices))
|
||||||
|
for _, device := range devices {
|
||||||
|
iface, err := c.convertInterface(device)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
interfaces = append(interfaces, iface)
|
||||||
|
}
|
||||||
|
return interfaces, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) GetInterface(_ context.Context, id domain.InterfaceIdentifier) (*domain.PhysicalInterface, error) {
|
||||||
|
device, err := c.awg.Device(string(id))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
iface, err := c.convertInterface(device)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &iface, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) convertInterface(device *wgtypes.Device) (domain.PhysicalInterface, error) {
|
||||||
|
iface, err := c.local.convertWireGuardInterface(device)
|
||||||
|
if err != nil {
|
||||||
|
return domain.PhysicalInterface{}, err
|
||||||
|
}
|
||||||
|
iface.ImportSource = domain.ControllerTypeAmneziaWG
|
||||||
|
options, err := c.awg.AmneziaWGOptions(device.Name)
|
||||||
|
if err != nil {
|
||||||
|
return domain.PhysicalInterface{}, fmt.Errorf("AmneziaWG options for %s: %w", device.Name, err)
|
||||||
|
}
|
||||||
|
iface.SetExtras(domain.AmneziaWGInterfaceExtras{Options: options})
|
||||||
|
return iface, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) SaveInterface(ctx context.Context, id domain.InterfaceIdentifier,
|
||||||
|
updateFunc func(*domain.PhysicalInterface) (*domain.PhysicalInterface, error),
|
||||||
|
) error {
|
||||||
|
iface, err := c.GetInterface(ctx, id)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
if err := c.local.nl.LinkAdd(&netlink.GenericLink{Name: string(id), LinkType: "amneziawg"}); err != nil {
|
||||||
|
return fmt.Errorf("AmneziaWG link add failed: %w", err)
|
||||||
|
}
|
||||||
|
iface, err = c.GetInterface(ctx, id)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if updateFunc != nil {
|
||||||
|
iface, err = updateFunc(iface)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
extras := iface.GetExtras().(domain.AmneziaWGInterfaceExtras)
|
||||||
|
if err := extras.Options.Validate(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
privateKey, err := wgtypes.NewKey(iface.KeyPair.GetPrivateKeyBytes())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var fwMark *int
|
||||||
|
if iface.FirewallMark != 0 {
|
||||||
|
value := int(iface.FirewallMark)
|
||||||
|
fwMark = &value
|
||||||
|
}
|
||||||
|
if err := c.local.updateLowLevelInterface(iface); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.awg.ConfigureAmneziaWGDevice(string(id), wgtypes.Config{
|
||||||
|
PrivateKey: &privateKey, ListenPort: &iface.ListenPort, FirewallMark: fwMark,
|
||||||
|
}, extras.Options)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) DeleteInterface(_ context.Context, id domain.InterfaceIdentifier) error {
|
||||||
|
link, err := c.local.nl.LinkByName(string(id))
|
||||||
|
if err != nil {
|
||||||
|
if _, ok := errors.AsType[netlink.LinkNotFoundError](err); ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if link.Type() != "amneziawg" {
|
||||||
|
return fmt.Errorf("interface %s is not an AmneziaWG kernel device", id)
|
||||||
|
}
|
||||||
|
return c.local.nl.LinkDel(link)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) GetPeers(ctx context.Context, id domain.InterfaceIdentifier) ([]domain.PhysicalPeer, error) {
|
||||||
|
peers, err := c.local.GetPeers(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for i := range peers {
|
||||||
|
peers[i].ImportSource = domain.ControllerTypeAmneziaWG
|
||||||
|
}
|
||||||
|
return peers, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) GetPeer(ctx context.Context, id domain.InterfaceIdentifier, peerID domain.PeerIdentifier) (*domain.PhysicalPeer, error) {
|
||||||
|
peer, err := c.local.getPeer(id, peerID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
peer.ImportSource = domain.ControllerTypeAmneziaWG
|
||||||
|
return peer, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) SavePeer(ctx context.Context, id domain.InterfaceIdentifier, peerID domain.PeerIdentifier,
|
||||||
|
updateFunc func(*domain.PhysicalPeer) (*domain.PhysicalPeer, error),
|
||||||
|
) error {
|
||||||
|
return c.local.SavePeer(ctx, id, peerID, func(peer *domain.PhysicalPeer) (*domain.PhysicalPeer, error) {
|
||||||
|
peer.ImportSource = domain.ControllerTypeAmneziaWG
|
||||||
|
return updateFunc(peer)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) DeletePeer(ctx context.Context, id domain.InterfaceIdentifier, peerID domain.PeerIdentifier) error {
|
||||||
|
return c.local.DeletePeer(ctx, id, peerID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) ExecuteInterfaceHook(ctx context.Context, id domain.InterfaceIdentifier, command string) error {
|
||||||
|
return c.local.ExecuteInterfaceHook(ctx, id, command)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) SetDNS(ctx context.Context, id domain.InterfaceIdentifier, dns, search string) error {
|
||||||
|
return c.local.SetDNS(ctx, id, dns, search)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) UnsetDNS(ctx context.Context, id domain.InterfaceIdentifier, dns, search string) error {
|
||||||
|
return c.local.UnsetDNS(ctx, id, dns, search)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) SetRoutes(ctx context.Context, info domain.RoutingTableInfo) error {
|
||||||
|
return c.local.SetRoutes(ctx, info)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) RemoveRoutes(ctx context.Context, info domain.RoutingTableInfo) error {
|
||||||
|
return c.local.RemoveRoutes(ctx, info)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c AmneziaWGController) PingAddresses(ctx context.Context, addr string) (*domain.PingerResult, error) {
|
||||||
|
return c.local.PingAddresses(ctx, addr)
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package wgcontroller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
|
|
||||||
|
"github.com/h44z/wg-portal/internal/config"
|
||||||
|
"github.com/h44z/wg-portal/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
type awgControllerNetlink struct {
|
||||||
|
NetlinkClient
|
||||||
|
link netlink.Link
|
||||||
|
deleted bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *awgControllerNetlink) LinkAdd(link netlink.Link) error { n.link = link; return nil }
|
||||||
|
func (n *awgControllerNetlink) LinkByName(string) (netlink.Link, error) {
|
||||||
|
if n.link == nil {
|
||||||
|
return nil, netlink.LinkNotFoundError{}
|
||||||
|
}
|
||||||
|
return n.link, nil
|
||||||
|
}
|
||||||
|
func (n *awgControllerNetlink) LinkDel(netlink.Link) error {
|
||||||
|
n.deleted = true
|
||||||
|
n.link = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (n *awgControllerNetlink) AddrList(netlink.Link) ([]netlink.Addr, error) { return nil, nil }
|
||||||
|
func (n *awgControllerNetlink) LinkSetUp(netlink.Link) error { return nil }
|
||||||
|
func (n *awgControllerNetlink) LinkSetDown(netlink.Link) error { return nil }
|
||||||
|
|
||||||
|
type awgControllerClient struct {
|
||||||
|
WgCtrlRepo
|
||||||
|
nl *awgControllerNetlink
|
||||||
|
options domain.AmneziaWGOptions
|
||||||
|
configured domain.AmneziaWGOptions
|
||||||
|
deleted bool
|
||||||
|
peer *wgtypes.Peer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *awgControllerClient) Devices() ([]*wgtypes.Device, error) {
|
||||||
|
device, err := w.Device("awg0")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return []*wgtypes.Device{device}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *awgControllerClient) Device(name string) (*wgtypes.Device, error) {
|
||||||
|
if w.nl.link == nil {
|
||||||
|
return nil, os.ErrNotExist
|
||||||
|
}
|
||||||
|
device := &wgtypes.Device{Name: name, Type: wgtypes.LinuxKernel}
|
||||||
|
if w.peer != nil {
|
||||||
|
device.Peers = []wgtypes.Peer{*w.peer}
|
||||||
|
}
|
||||||
|
return device, nil
|
||||||
|
}
|
||||||
|
func (w *awgControllerClient) AmneziaWGOptions(string) (domain.AmneziaWGOptions, error) {
|
||||||
|
return w.options, nil
|
||||||
|
}
|
||||||
|
func (w *awgControllerClient) ConfigureAmneziaWGDevice(_ string, _ wgtypes.Config, options domain.AmneziaWGOptions) error {
|
||||||
|
w.configured = options
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (w *awgControllerClient) ConfigureDevice(_ string, cfg wgtypes.Config) error {
|
||||||
|
for _, peer := range cfg.Peers {
|
||||||
|
if peer.Remove {
|
||||||
|
w.deleted = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGControllerCreatesCorrectLinkAndPreservesOptions(t *testing.T) {
|
||||||
|
nl := &awgControllerNetlink{}
|
||||||
|
wg := &awgControllerClient{nl: nl, options: domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4"}}
|
||||||
|
controller := newAmneziaWGController(&config.Config{}, wg, nl)
|
||||||
|
key, err := wgtypes.GeneratePrivateKey()
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, controller.SaveInterface(context.Background(), "awg0", func(pi *domain.PhysicalInterface) (*domain.PhysicalInterface, error) {
|
||||||
|
require.Equal(t, domain.AmneziaWGInterfaceExtras{Options: wg.options}, pi.GetExtras())
|
||||||
|
domain.MergeToPhysicalInterface(pi, &domain.Interface{Backend: config.AmneziaWGBackendName, Identifier: "awg0", PrivateKey: key.String(), AmneziaWG: domain.AmneziaWGOptions{"Jc": "6"}})
|
||||||
|
return pi, nil
|
||||||
|
}))
|
||||||
|
require.Equal(t, "amneziawg", nl.link.Type())
|
||||||
|
require.Equal(t, domain.InterfaceBackend(config.AmneziaWGBackendName), controller.GetId())
|
||||||
|
require.Equal(t, domain.AmneziaWGOptions{"H1": "100-200", "Jc": "6"}, wg.configured)
|
||||||
|
physical, err := controller.GetInterface(context.Background(), "awg0")
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, domain.ControllerTypeAmneziaWG, physical.ImportSource)
|
||||||
|
require.Equal(t, domain.AmneziaWGInterfaceExtras{Options: wg.options}, physical.GetExtras())
|
||||||
|
require.Equal(t, wg.options, domain.ConvertPhysicalInterface(physical).AmneziaWG)
|
||||||
|
interfaces, err := controller.GetInterfaces(context.Background())
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Len(t, interfaces, 1)
|
||||||
|
require.Equal(t, *physical, interfaces[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGDisabledPeersUseLocalDeletion(t *testing.T) {
|
||||||
|
key, err := wgtypes.GeneratePrivateKey()
|
||||||
|
require.NoError(t, err)
|
||||||
|
public := key.PublicKey()
|
||||||
|
nl := &awgControllerNetlink{link: &netlink.GenericLink{Name: "awg0", LinkType: "amneziawg"}}
|
||||||
|
wg := &awgControllerClient{nl: nl, peer: &wgtypes.Peer{PublicKey: public}}
|
||||||
|
controller := newAmneziaWGController(&config.Config{}, wg, nl)
|
||||||
|
id := domain.PeerIdentifier(public.String())
|
||||||
|
physical, err := controller.GetPeer(context.Background(), "awg0", id)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, domain.ControllerTypeAmneziaWG, physical.ImportSource)
|
||||||
|
peers, err := controller.GetPeers(context.Background(), "awg0")
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Len(t, peers, 1)
|
||||||
|
require.Equal(t, domain.ControllerTypeAmneziaWG, peers[0].ImportSource)
|
||||||
|
require.False(t, domain.ConvertPhysicalPeer(&peers[0]).IsDisabled())
|
||||||
|
disabled := time.Now()
|
||||||
|
require.NoError(t, controller.SavePeer(context.Background(), "awg0", id, func(peer *domain.PhysicalPeer) (*domain.PhysicalPeer, error) {
|
||||||
|
require.Equal(t, domain.ControllerTypeAmneziaWG, peer.ImportSource)
|
||||||
|
domain.MergeToPhysicalPeer(peer, &domain.Peer{Identifier: id, Disabled: &disabled})
|
||||||
|
return peer, nil
|
||||||
|
}))
|
||||||
|
require.True(t, wg.deleted)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGControllerDeletesOnlyAmneziaWGLinks(t *testing.T) {
|
||||||
|
nl := &awgControllerNetlink{}
|
||||||
|
controller := newAmneziaWGController(&config.Config{}, &awgControllerClient{nl: nl}, nl)
|
||||||
|
require.NoError(t, controller.DeleteInterface(context.Background(), "missing"))
|
||||||
|
nl.link = &netlink.GenericLink{Name: "wg0", LinkType: "wireguard"}
|
||||||
|
require.ErrorContains(t, controller.DeleteInterface(context.Background(), "wg0"), "not an AmneziaWG kernel device")
|
||||||
|
require.False(t, nl.deleted)
|
||||||
|
nl.link = &netlink.GenericLink{Name: "awg0", LinkType: "amneziawg"}
|
||||||
|
require.NoError(t, controller.DeleteInterface(context.Background(), "awg0"))
|
||||||
|
require.True(t, nl.deleted)
|
||||||
|
}
|
||||||
@@ -2033,6 +2033,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"definitions": {
|
"definitions": {
|
||||||
|
"domain.AmneziaWGOptions": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
"model.AuditEntry": {
|
"model.AuditEntry": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -2150,6 +2156,9 @@
|
|||||||
"type": "string"
|
"type": "string"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"AmneziaWG": {
|
||||||
|
"$ref": "#/definitions/domain.AmneziaWGOptions"
|
||||||
|
},
|
||||||
"Backend": {
|
"Backend": {
|
||||||
"description": "the backend used for this interface e.g., local, mikrotik, ...",
|
"description": "the backend used for this interface e.g., local, mikrotik, ...",
|
||||||
"type": "string",
|
"type": "string",
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
basePath: /api/v0
|
basePath: /api/v0
|
||||||
definitions:
|
definitions:
|
||||||
|
domain.AmneziaWGOptions:
|
||||||
|
additionalProperties:
|
||||||
|
type: string
|
||||||
|
type: object
|
||||||
model.AuditEntry:
|
model.AuditEntry:
|
||||||
properties:
|
properties:
|
||||||
ContextUser:
|
ContextUser:
|
||||||
@@ -76,6 +80,8 @@ definitions:
|
|||||||
items:
|
items:
|
||||||
type: string
|
type: string
|
||||||
type: array
|
type: array
|
||||||
|
AmneziaWG:
|
||||||
|
$ref: '#/definitions/domain.AmneziaWGOptions'
|
||||||
Backend:
|
Backend:
|
||||||
description: the backend used for this interface e.g., local, mikrotik, ...
|
description: the backend used for this interface e.g., local, mikrotik, ...
|
||||||
example: local
|
example: local
|
||||||
|
|||||||
@@ -1601,6 +1601,13 @@
|
|||||||
"10.11.12.1/24"
|
"10.11.12.1/24"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"AmneziaWG": {
|
||||||
|
"description": "AmneziaWG contains per-interface obfuscation options for the amneziawg backend.\nOmitted options preserve the current kernel settings. Values use awg configuration syntax.",
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
"Backend": {
|
"Backend": {
|
||||||
"description": "Backend is the configured backend ID used to manage this interface. Omit it on create to use the local backend, or on update to preserve the current backend.",
|
"description": "Backend is the configured backend ID used to manage this interface. Omit it on create to use the local backend, or on update to preserve the current backend.",
|
||||||
"type": "string",
|
"type": "string",
|
||||||
|
|||||||
@@ -52,6 +52,13 @@ definitions:
|
|||||||
items:
|
items:
|
||||||
type: string
|
type: string
|
||||||
type: array
|
type: array
|
||||||
|
AmneziaWG:
|
||||||
|
additionalProperties:
|
||||||
|
type: string
|
||||||
|
description: |-
|
||||||
|
AmneziaWG contains per-interface obfuscation options for the amneziawg backend.
|
||||||
|
Omitted options preserve the current kernel settings. Values use awg configuration syntax.
|
||||||
|
type: object
|
||||||
Backend:
|
Backend:
|
||||||
description: Backend is the configured backend ID used to manage this interface.
|
description: Backend is the configured backend ID used to manage this interface.
|
||||||
Omit it on create to use the local backend, or on update to preserve the
|
Omit it on create to use the local backend, or on update to preserve the
|
||||||
|
|||||||
@@ -49,6 +49,8 @@ type Interface struct {
|
|||||||
PeerDefPreDown string `json:"PeerDefPreDown"` // default action that is executed before the device is down
|
PeerDefPreDown string `json:"PeerDefPreDown"` // default action that is executed before the device is down
|
||||||
PeerDefPostDown string `json:"PeerDefPostDown"` // default action that is executed after the device is down
|
PeerDefPostDown string `json:"PeerDefPostDown"` // default action that is executed after the device is down
|
||||||
|
|
||||||
|
AmneziaWG domain.AmneziaWGOptions `json:"AmneziaWG,omitempty"`
|
||||||
|
|
||||||
// Calculated values
|
// Calculated values
|
||||||
|
|
||||||
EnabledPeers int `json:"EnabledPeers"`
|
EnabledPeers int `json:"EnabledPeers"`
|
||||||
@@ -94,6 +96,8 @@ func NewInterface(src *domain.Interface, peers []domain.Peer) *Interface {
|
|||||||
PeerDefPreDown: src.PeerDefPreDown,
|
PeerDefPreDown: src.PeerDefPreDown,
|
||||||
PeerDefPostDown: src.PeerDefPostDown,
|
PeerDefPostDown: src.PeerDefPostDown,
|
||||||
|
|
||||||
|
AmneziaWG: src.AmneziaWG,
|
||||||
|
|
||||||
EnabledPeers: 0,
|
EnabledPeers: 0,
|
||||||
TotalPeers: 0,
|
TotalPeers: 0,
|
||||||
Filename: src.GetConfigFileName(),
|
Filename: src.GetConfigFileName(),
|
||||||
@@ -174,6 +178,7 @@ func NewDomainInterface(src *Interface) *domain.Interface {
|
|||||||
PeerDefPostUp: src.PeerDefPostUp,
|
PeerDefPostUp: src.PeerDefPostUp,
|
||||||
PeerDefPreDown: src.PeerDefPreDown,
|
PeerDefPreDown: src.PeerDefPreDown,
|
||||||
PeerDefPostDown: src.PeerDefPostDown,
|
PeerDefPostDown: src.PeerDefPostDown,
|
||||||
|
AmneziaWG: src.AmneziaWG,
|
||||||
}
|
}
|
||||||
|
|
||||||
if src.Disabled {
|
if src.Disabled {
|
||||||
|
|||||||
@@ -118,6 +118,9 @@ func (s InterfaceService) Update(ctx context.Context, id domain.InterfaceIdentif
|
|||||||
iface.IsDynamic = existingInterface.IsDynamic
|
iface.IsDynamic = existingInterface.IsDynamic
|
||||||
iface.DriverType = existingInterface.DriverType
|
iface.DriverType = existingInterface.DriverType
|
||||||
iface.LdapAllowedUsers = existingInterface.LdapAllowedUsers
|
iface.LdapAllowedUsers = existingInterface.LdapAllowedUsers
|
||||||
|
if iface.AmneziaWG == nil {
|
||||||
|
iface.AmneziaWG = existingInterface.AmneziaWG
|
||||||
|
}
|
||||||
|
|
||||||
updatedInterface, updatedPeers, err := s.interfaces.UpdateInterface(ctx, iface)
|
updatedInterface, updatedPeers, err := s.interfaces.UpdateInterface(ctx, iface)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -134,6 +137,7 @@ func (s InterfaceService) validateBackend(backend domain.InterfaceBackend) error
|
|||||||
|
|
||||||
// Empty is the legacy representation of the local backend in domain objects.
|
// Empty is the legacy representation of the local backend in domain objects.
|
||||||
if id == "" || id == config.LocalBackendName ||
|
if id == "" || id == config.LocalBackendName ||
|
||||||
|
(id == config.AmneziaWGBackendName && s.cfg.Backend.AmneziaWG.Enabled) ||
|
||||||
slices.ContainsFunc(s.cfg.Backend.Mikrotik, func(b config.BackendMikrotik) bool { return b.Id == id }) ||
|
slices.ContainsFunc(s.cfg.Backend.Mikrotik, func(b config.BackendMikrotik) bool { return b.Id == id }) ||
|
||||||
slices.ContainsFunc(s.cfg.Backend.Pfsense, func(b config.BackendPfsense) bool { return b.Id == id }) ||
|
slices.ContainsFunc(s.cfg.Backend.Pfsense, func(b config.BackendPfsense) bool { return b.Id == id }) ||
|
||||||
slices.ContainsFunc(s.cfg.Backend.Opnsense, func(b config.BackendOpnsense) bool { return b.Id == id }) {
|
slices.ContainsFunc(s.cfg.Backend.Opnsense, func(b config.BackendOpnsense) bool { return b.Id == id }) {
|
||||||
|
|||||||
@@ -83,6 +83,10 @@ type Interface struct {
|
|||||||
// PeerDefPostDown specifies the default action that is executed after the device is down for a new peer.
|
// PeerDefPostDown specifies the default action that is executed after the device is down for a new peer.
|
||||||
PeerDefPostDown string `json:"PeerDefPostDown"`
|
PeerDefPostDown string `json:"PeerDefPostDown"`
|
||||||
|
|
||||||
|
// AmneziaWG contains per-interface obfuscation options for the amneziawg backend.
|
||||||
|
// Omitted options preserve the current kernel settings. Values use awg configuration syntax.
|
||||||
|
AmneziaWG domain.AmneziaWGOptions `json:"AmneziaWG,omitempty" swaggertype:"object,string"`
|
||||||
|
|
||||||
// Calculated values
|
// Calculated values
|
||||||
|
|
||||||
// EnabledPeers is the number of enabled peers for this interface. Only enabled peers are able to connect.
|
// EnabledPeers is the number of enabled peers for this interface. Only enabled peers are able to connect.
|
||||||
@@ -135,6 +139,8 @@ func NewInterface(src *domain.Interface, peers []domain.Peer) *Interface {
|
|||||||
PeerDefPreDown: src.PeerDefPreDown,
|
PeerDefPreDown: src.PeerDefPreDown,
|
||||||
PeerDefPostDown: src.PeerDefPostDown,
|
PeerDefPostDown: src.PeerDefPostDown,
|
||||||
|
|
||||||
|
AmneziaWG: src.AmneziaWG,
|
||||||
|
|
||||||
EnabledPeers: 0,
|
EnabledPeers: 0,
|
||||||
TotalPeers: 0,
|
TotalPeers: 0,
|
||||||
Filename: src.GetConfigFileName(),
|
Filename: src.GetConfigFileName(),
|
||||||
@@ -204,6 +210,7 @@ func NewDomainInterface(src *Interface) *domain.Interface {
|
|||||||
PeerDefPostUp: src.PeerDefPostUp,
|
PeerDefPostUp: src.PeerDefPostUp,
|
||||||
PeerDefPreDown: src.PeerDefPreDown,
|
PeerDefPreDown: src.PeerDefPreDown,
|
||||||
PeerDefPostDown: src.PeerDefPostDown,
|
PeerDefPostDown: src.PeerDefPostDown,
|
||||||
|
AmneziaWG: src.AmneziaWG,
|
||||||
}
|
}
|
||||||
|
|
||||||
if src.Disabled {
|
if src.Disabled {
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package configfile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"github.com/h44z/wg-portal/internal/config"
|
||||||
|
"github.com/h44z/wg-portal/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAmneziaWGConfigTemplates(t *testing.T) {
|
||||||
|
tpl, err := newTemplateHandler()
|
||||||
|
require.NoError(t, err)
|
||||||
|
options := domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4", "I1": "<b 0x1234>"}
|
||||||
|
iface := &domain.Interface{Identifier: "awg0", Backend: config.AmneziaWGBackendName, AmneziaWG: options, PrivateKey: "private"}
|
||||||
|
reader, err := tpl.GetInterfaceConfig(iface, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
contents, err := io.ReadAll(reader)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Contains(t, string(contents), "PrivateKey = private\nH1 = 100-200\nI1 = <b 0x1234>\nJc = 4\n")
|
||||||
|
require.Contains(t, string(contents), "\nAddress = ")
|
||||||
|
peer := &domain.Peer{AmneziaWG: options}
|
||||||
|
peer.Interface.PrivateKey = "private"
|
||||||
|
for _, style := range []string{domain.ConfigStyleWgQuick, domain.ConfigStyleRaw} {
|
||||||
|
reader, err := tpl.GetPeerConfig(peer, style)
|
||||||
|
require.NoError(t, err)
|
||||||
|
contents, err := io.ReadAll(reader)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Contains(t, string(contents), "PrivateKey = private\nH1 = 100-200\nI1 = <b 0x1234>\nJc = 4\n")
|
||||||
|
require.True(t, strings.Index(string(contents), "H1 =") < strings.Index(string(contents), "[Peer]"))
|
||||||
|
}
|
||||||
|
peer.AmneziaWG = nil
|
||||||
|
reader, err = tpl.GetPeerConfig(peer, domain.ConfigStyleWgQuick)
|
||||||
|
require.NoError(t, err)
|
||||||
|
contents, err = io.ReadAll(reader)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotContains(t, string(contents), "H1 =")
|
||||||
|
require.Contains(t, string(contents), "PrivateKey = private\nAddress =")
|
||||||
|
}
|
||||||
|
|
||||||
|
type amneziaConfigRepo struct {
|
||||||
|
iface domain.Interface
|
||||||
|
peer domain.Peer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *amneziaConfigRepo) GetInterface(context.Context, domain.InterfaceIdentifier) (*domain.Interface, error) {
|
||||||
|
return &r.iface, nil
|
||||||
|
}
|
||||||
|
func (r *amneziaConfigRepo) GetPeer(context.Context, domain.PeerIdentifier) (*domain.Peer, error) {
|
||||||
|
peer := r.peer
|
||||||
|
return &peer, nil
|
||||||
|
}
|
||||||
|
func (r *amneziaConfigRepo) GetInterfaceAndPeers(context.Context, domain.InterfaceIdentifier) (*domain.Interface, []domain.Peer, error) {
|
||||||
|
return &r.iface, []domain.Peer{r.peer}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGDownloadsAndQRUseParentOptions(t *testing.T) {
|
||||||
|
tpl, err := newTemplateHandler()
|
||||||
|
require.NoError(t, err)
|
||||||
|
repo := &amneziaConfigRepo{
|
||||||
|
iface: domain.Interface{Identifier: "awg0", Backend: config.AmneziaWGBackendName, AmneziaWG: domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4"}},
|
||||||
|
peer: domain.Peer{Identifier: "peer", InterfaceIdentifier: "awg0"},
|
||||||
|
}
|
||||||
|
manager := Manager{wg: repo, tplHandler: tpl}
|
||||||
|
ctx := domain.SetUserInfo(context.Background(), domain.SystemAdminContextUserInfo())
|
||||||
|
reader, err := manager.GetPeerConfig(ctx, "peer", domain.ConfigStyleWgQuick)
|
||||||
|
require.NoError(t, err)
|
||||||
|
contents, err := io.ReadAll(reader)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Contains(t, string(contents), "H1 = 100-200")
|
||||||
|
reader, err = manager.GetPeerConfigQrCode(ctx, "peer", domain.ConfigStyleWgQuick)
|
||||||
|
require.NoError(t, err)
|
||||||
|
contents, err = io.ReadAll(reader)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotEmpty(t, contents)
|
||||||
|
// Changing parent options affects the next download without editing peers.
|
||||||
|
repo.iface.AmneziaWG["H1"] = "300-400"
|
||||||
|
reader, err = manager.GetPeerConfig(ctx, "peer", domain.ConfigStyleWgQuick)
|
||||||
|
require.NoError(t, err)
|
||||||
|
contents, err = io.ReadAll(reader)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Contains(t, string(contents), "H1 = 300-400")
|
||||||
|
}
|
||||||
@@ -195,6 +195,9 @@ func (m Manager) GetPeerConfig(ctx context.Context, id domain.PeerIdentifier, st
|
|||||||
if err := domain.ValidateUserAccessRights(ctx, peer.UserIdentifier); err != nil {
|
if err := domain.ValidateUserAccessRights(ctx, peer.UserIdentifier); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := m.loadAmneziaWGOptions(ctx, peer); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return m.tplHandler.GetPeerConfig(peer, style)
|
return m.tplHandler.GetPeerConfig(peer, style)
|
||||||
}
|
}
|
||||||
@@ -209,6 +212,9 @@ func (m Manager) GetPeerConfigQrCode(ctx context.Context, id domain.PeerIdentifi
|
|||||||
if err := domain.ValidateUserAccessRights(ctx, peer.UserIdentifier); err != nil {
|
if err := domain.ValidateUserAccessRights(ctx, peer.UserIdentifier); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := m.loadAmneziaWGOptions(ctx, peer); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
cfgData, err := m.tplHandler.GetPeerConfig(peer, style)
|
cfgData, err := m.tplHandler.GetPeerConfig(peer, style)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -250,6 +256,17 @@ func (m Manager) GetPeerConfigQrCode(ctx context.Context, id domain.PeerIdentifi
|
|||||||
return buf, nil
|
return buf, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m Manager) loadAmneziaWGOptions(ctx context.Context, peer *domain.Peer) error {
|
||||||
|
iface, err := m.wg.GetInterface(ctx, peer.InterfaceIdentifier)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to load parent interface: %w", err)
|
||||||
|
}
|
||||||
|
if iface.Backend == config.AmneziaWGBackendName {
|
||||||
|
peer.Interface.AmneziaWG = iface.AmneziaWG
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// PersistInterfaceConfig writes the configuration file for the given interface to the file system.
|
// PersistInterfaceConfig writes the configuration file for the given interface to the file system.
|
||||||
func (m Manager) PersistInterfaceConfig(ctx context.Context, id domain.InterfaceIdentifier) error {
|
func (m Manager) PersistInterfaceConfig(ctx context.Context, id domain.InterfaceIdentifier) error {
|
||||||
iface, peers, err := m.wg.GetInterfaceAndPeers(ctx, id)
|
iface, peers, err := m.wg.GetInterfaceAndPeers(ctx, id)
|
||||||
|
|||||||
@@ -38,6 +38,9 @@ func newTemplateHandler() (*TemplateHandler, error) {
|
|||||||
|
|
||||||
// GetInterfaceConfig returns the rendered configuration file for a WireGuard interface.
|
// GetInterfaceConfig returns the rendered configuration file for a WireGuard interface.
|
||||||
func (c TemplateHandler) GetInterfaceConfig(cfg *domain.Interface, peers []domain.Peer) (io.Reader, error) {
|
func (c TemplateHandler) GetInterfaceConfig(cfg *domain.Interface, peers []domain.Peer) (io.Reader, error) {
|
||||||
|
if err := cfg.AmneziaWG.Validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
var tplBuff bytes.Buffer
|
var tplBuff bytes.Buffer
|
||||||
|
|
||||||
err := c.templates.ExecuteTemplate(&tplBuff, "wg_interface.tpl", map[string]any{
|
err := c.templates.ExecuteTemplate(&tplBuff, "wg_interface.tpl", map[string]any{
|
||||||
@@ -56,6 +59,9 @@ func (c TemplateHandler) GetInterfaceConfig(cfg *domain.Interface, peers []domai
|
|||||||
|
|
||||||
// GetPeerConfig returns the rendered configuration file for a WireGuard peer.
|
// GetPeerConfig returns the rendered configuration file for a WireGuard peer.
|
||||||
func (c TemplateHandler) GetPeerConfig(peer *domain.Peer, style string) (io.Reader, error) {
|
func (c TemplateHandler) GetPeerConfig(peer *domain.Peer, style string) (io.Reader, error) {
|
||||||
|
if err := peer.Interface.AmneziaWG.Validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
var tplBuff bytes.Buffer
|
var tplBuff bytes.Buffer
|
||||||
|
|
||||||
err := c.templates.ExecuteTemplate(&tplBuff, "wg_peer.tpl", map[string]any{
|
err := c.templates.ExecuteTemplate(&tplBuff, "wg_peer.tpl", map[string]any{
|
||||||
|
|||||||
@@ -17,6 +17,9 @@
|
|||||||
|
|
||||||
# Core settings
|
# Core settings
|
||||||
PrivateKey = {{ .Interface.KeyPair.PrivateKey }}
|
PrivateKey = {{ .Interface.KeyPair.PrivateKey }}
|
||||||
|
{{- if .Interface.AmneziaWG }}
|
||||||
|
{{ .Interface.AmneziaWG.ConfigLines -}}
|
||||||
|
{{- end }}
|
||||||
Address = {{ CidrsToString .Interface.Addresses }}
|
Address = {{ CidrsToString .Interface.Addresses }}
|
||||||
|
|
||||||
# Misc. settings (optional)
|
# Misc. settings (optional)
|
||||||
|
|||||||
@@ -23,6 +23,9 @@
|
|||||||
|
|
||||||
# Core settings
|
# Core settings
|
||||||
PrivateKey = {{ .Peer.Interface.KeyPair.PrivateKey }}
|
PrivateKey = {{ .Peer.Interface.KeyPair.PrivateKey }}
|
||||||
|
{{- if .Peer.Interface.AmneziaWG }}
|
||||||
|
{{ .Peer.Interface.AmneziaWG.ConfigLines -}}
|
||||||
|
{{- end }}
|
||||||
{{- if eq .Style "wgquick"}}
|
{{- if eq .Style "wgquick"}}
|
||||||
Address = {{ CidrsToString .Peer.Interface.Addresses }}
|
Address = {{ CidrsToString .Peer.Interface.Addresses }}
|
||||||
{{- end}}
|
{{- end}}
|
||||||
|
|||||||
@@ -40,6 +40,10 @@ func (c *ControllerManager) init() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := c.registerAmneziaWGController(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
if err := c.registerMikrotikControllers(); err != nil {
|
if err := c.registerMikrotikControllers(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -136,6 +140,26 @@ func (c *ControllerManager) registerOpnsenseControllers() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *ControllerManager) registerAmneziaWGController() error {
|
||||||
|
if !c.cfg.Backend.AmneziaWG.Enabled {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
controller, err := wgcontroller.NewAmneziaWGController(c.cfg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create AmneziaWG controller: %w", err)
|
||||||
|
}
|
||||||
|
c.controllers[config.AmneziaWGBackendName] = backendInstance{
|
||||||
|
Config: config.BackendBase{
|
||||||
|
Id: config.AmneziaWGBackendName,
|
||||||
|
DisplayName: "AmneziaWG",
|
||||||
|
Type: "amneziawg",
|
||||||
|
IgnoredInterfaces: c.cfg.Backend.AmneziaWG.IgnoredInterfaces,
|
||||||
|
},
|
||||||
|
Implementation: controller,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (c *ControllerManager) logRegisteredControllers() {
|
func (c *ControllerManager) logRegisteredControllers() {
|
||||||
for backend, controller := range c.controllers {
|
for backend, controller := range c.controllers {
|
||||||
slog.Debug("backend controller registered",
|
slog.Debug("backend controller registered",
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import (
|
|||||||
|
|
||||||
"github.com/h44z/wg-portal/internal/app"
|
"github.com/h44z/wg-portal/internal/app"
|
||||||
"github.com/h44z/wg-portal/internal/app/audit"
|
"github.com/h44z/wg-portal/internal/app/audit"
|
||||||
"github.com/h44z/wg-portal/internal/config"
|
|
||||||
"github.com/h44z/wg-portal/internal/domain"
|
"github.com/h44z/wg-portal/internal/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -284,7 +283,7 @@ func (m Manager) RestoreInterfaceState(
|
|||||||
// restore peers
|
// restore peers
|
||||||
for _, peer := range peers {
|
for _, peer := range peers {
|
||||||
switch {
|
switch {
|
||||||
case iface.IsDisabled() && iface.Backend == config.LocalBackendName: // if interface is disabled, delete all peers
|
case iface.IsDisabled() && iface.Backend.IsLocal(): // if interface is disabled, delete all peers
|
||||||
if err := controller.DeletePeer(ctx, iface.Identifier,
|
if err := controller.DeletePeer(ctx, iface.Identifier,
|
||||||
peer.Identifier); err != nil {
|
peer.Identifier); err != nil {
|
||||||
return fmt.Errorf("failed to remove peer %s for disabled interface %s: %w",
|
return fmt.Errorf("failed to remove peer %s for disabled interface %s: %w",
|
||||||
@@ -380,6 +379,7 @@ func (m Manager) PrepareInterface(ctx context.Context) (*domain.Interface, error
|
|||||||
CreatedAt: time.Now(),
|
CreatedAt: time.Now(),
|
||||||
UpdatedAt: time.Now(),
|
UpdatedAt: time.Now(),
|
||||||
Identifier: id,
|
Identifier: id,
|
||||||
|
Backend: domain.InterfaceBackend(m.cfg.Backend.Default),
|
||||||
KeyPair: kp,
|
KeyPair: kp,
|
||||||
ListenPort: port,
|
ListenPort: port,
|
||||||
Addresses: ips,
|
Addresses: ips,
|
||||||
@@ -563,6 +563,9 @@ func (m Manager) saveInterface(ctx context.Context, iface *domain.Interface) (
|
|||||||
err := m.wg.GetController(*iface).SaveInterface(ctx, iface.Identifier,
|
err := m.wg.GetController(*iface).SaveInterface(ctx, iface.Identifier,
|
||||||
func(pi *domain.PhysicalInterface) (*domain.PhysicalInterface, error) {
|
func(pi *domain.PhysicalInterface) (*domain.PhysicalInterface, error) {
|
||||||
domain.MergeToPhysicalInterface(pi, iface)
|
domain.MergeToPhysicalInterface(pi, iface)
|
||||||
|
if extras, ok := pi.GetExtras().(domain.AmneziaWGInterfaceExtras); ok {
|
||||||
|
iface.AmneziaWG = extras.Options
|
||||||
|
}
|
||||||
return pi, nil
|
return pi, nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -633,7 +636,7 @@ func (m Manager) saveInterface(ctx context.Context, iface *domain.Interface) (
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If the interface has just been enabled, restore its peers on the physical controller
|
// If the interface has just been enabled, restore its peers on the physical controller
|
||||||
if !oldEnabled && newEnabled && iface.Backend == config.LocalBackendName {
|
if !oldEnabled && newEnabled && iface.Backend.IsLocal() {
|
||||||
peers, err := m.db.GetInterfacePeers(ctx, iface.Identifier)
|
peers, err := m.db.GetInterfacePeers(ctx, iface.Identifier)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to load peers for interface %s: %w", iface.Identifier, err)
|
return nil, fmt.Errorf("failed to load peers for interface %s: %w", iface.Identifier, err)
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package wireguard
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"github.com/h44z/wg-portal/internal/config"
|
||||||
|
"github.com/h44z/wg-portal/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
type amneziaWGExtrasController struct {
|
||||||
|
mockController
|
||||||
|
physical domain.PhysicalInterface
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *amneziaWGExtrasController) SaveInterface(_ context.Context, _ domain.InterfaceIdentifier,
|
||||||
|
update func(*domain.PhysicalInterface) (*domain.PhysicalInterface, error),
|
||||||
|
) error {
|
||||||
|
physical, err := update(&c.physical)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.physical = *physical
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSaveInterfacePersistsAmneziaWGExtras(t *testing.T) {
|
||||||
|
for name, options := range map[string]domain.AmneziaWGOptions{
|
||||||
|
"omitted options": nil,
|
||||||
|
"partial update": {"Jc": "6"},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
controller := &amneziaWGExtrasController{physical: domain.PhysicalInterface{
|
||||||
|
Identifier: "awg0", ImportSource: domain.ControllerTypeAmneziaWG,
|
||||||
|
}}
|
||||||
|
controller.physical.SetExtras(domain.AmneziaWGInterfaceExtras{
|
||||||
|
Options: domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4"},
|
||||||
|
})
|
||||||
|
db := &mockDB{iface: &domain.Interface{
|
||||||
|
Identifier: "awg0", Backend: config.AmneziaWGBackendName, Type: domain.InterfaceTypeServer,
|
||||||
|
}}
|
||||||
|
manager := Manager{
|
||||||
|
cfg: &config.Config{}, db: db, bus: &mockBus{},
|
||||||
|
wg: &ControllerManager{controllers: map[domain.InterfaceBackend]backendInstance{
|
||||||
|
config.AmneziaWGBackendName: {Implementation: controller},
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
update := *db.iface
|
||||||
|
update.AmneziaWG = options
|
||||||
|
ctx := domain.SetUserInfo(context.Background(), domain.SystemAdminContextUserInfo())
|
||||||
|
saved, err := manager.saveInterface(ctx, &update)
|
||||||
|
require.NoError(t, err)
|
||||||
|
expected := domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4"}
|
||||||
|
if options != nil {
|
||||||
|
expected["Jc"] = "6"
|
||||||
|
}
|
||||||
|
require.Equal(t, expected, saved.AmneziaWG)
|
||||||
|
require.Equal(t, expected, db.iface.AmneziaWG)
|
||||||
|
require.Equal(t, domain.AmneziaWGInterfaceExtras{Options: expected}, controller.physical.GetExtras())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const LocalBackendName = "local"
|
const LocalBackendName = "local"
|
||||||
|
const AmneziaWGBackendName = "amneziawg"
|
||||||
|
|
||||||
type Backend struct {
|
type Backend struct {
|
||||||
Default string `yaml:"default"` // The default backend to use (defaults to the internal backend)
|
Default string `yaml:"default"` // The default backend to use (defaults to the internal backend)
|
||||||
@@ -19,9 +20,10 @@ type Backend struct {
|
|||||||
|
|
||||||
// External Backend-specific configuration
|
// External Backend-specific configuration
|
||||||
|
|
||||||
Mikrotik []BackendMikrotik `yaml:"mikrotik"`
|
Mikrotik []BackendMikrotik `yaml:"mikrotik"`
|
||||||
Pfsense []BackendPfsense `yaml:"pfsense"`
|
Pfsense []BackendPfsense `yaml:"pfsense"`
|
||||||
Opnsense []BackendOpnsense `yaml:"opnsense"`
|
Opnsense []BackendOpnsense `yaml:"opnsense"`
|
||||||
|
AmneziaWG BackendAmneziaWG `yaml:"amneziawg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate checks the backend configuration for errors.
|
// Validate checks the backend configuration for errors.
|
||||||
@@ -31,9 +33,12 @@ func (b *Backend) Validate() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uniqueMap := make(map[string]struct{})
|
uniqueMap := make(map[string]struct{})
|
||||||
|
if b.AmneziaWG.Enabled {
|
||||||
|
uniqueMap[AmneziaWGBackendName] = struct{}{}
|
||||||
|
}
|
||||||
checkBackendId := func(id string) error {
|
checkBackendId := func(id string) error {
|
||||||
if id == LocalBackendName {
|
if id == LocalBackendName || id == AmneziaWGBackendName {
|
||||||
return fmt.Errorf("backend ID %q is a reserved keyword", LocalBackendName)
|
return fmt.Errorf("backend ID %q is a reserved keyword", id)
|
||||||
}
|
}
|
||||||
if _, exists := uniqueMap[id]; exists {
|
if _, exists := uniqueMap[id]; exists {
|
||||||
return fmt.Errorf("backend ID %q is not unique", id)
|
return fmt.Errorf("backend ID %q is not unique", id)
|
||||||
@@ -197,3 +202,8 @@ func (b *BackendOpnsense) GetApiTimeout() time.Duration {
|
|||||||
}
|
}
|
||||||
return b.ApiTimeout
|
return b.ApiTimeout
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type BackendAmneziaWG struct {
|
||||||
|
Enabled bool `yaml:"enabled"` // Requires a loaded AmneziaWG host kernel module.
|
||||||
|
IgnoredInterfaces []string `yaml:"ignored_interfaces"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -165,6 +165,10 @@ func defaultConfig() *Config {
|
|||||||
// Most resolconf implementations use "tun." as a prefix for interface names.
|
// Most resolconf implementations use "tun." as a prefix for interface names.
|
||||||
// But systemd's implementation uses no prefix, for example.
|
// But systemd's implementation uses no prefix, for example.
|
||||||
LocalResolvconfPrefix: getEnvStr("WG_PORTAL_BACKEND_LOCAL_RESOLVCONF_PREFIX", "tun."),
|
LocalResolvconfPrefix: getEnvStr("WG_PORTAL_BACKEND_LOCAL_RESOLVCONF_PREFIX", "tun."),
|
||||||
|
AmneziaWG: BackendAmneziaWG{
|
||||||
|
Enabled: getEnvBool("WG_PORTAL_BACKEND_AMNEZIAWG_ENABLED", false),
|
||||||
|
IgnoredInterfaces: getEnvStrSlice("WG_PORTAL_BACKEND_IGNORED_AMNEZIAWG_INTERFACES", nil),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg.Web = WebConfig{
|
cfg.Web = WebConfig{
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"maps"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AmneziaWGOptions contains [Interface] options understood by the official awg tool.
|
||||||
|
// See: https://docs.amnezia.org/documentation/amnezia-wg#configuration-parameters
|
||||||
|
type AmneziaWGOptions map[string]string
|
||||||
|
|
||||||
|
// Validate checks the custom parameters against the official limits.
|
||||||
|
func (o AmneziaWGOptions) Validate() error {
|
||||||
|
if len(o) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for key, value := range o {
|
||||||
|
if strings.ContainsAny(value, "\r\n\x00#") || len(value) > 4096 {
|
||||||
|
return fmt.Errorf("invalid AmneziaWG option %s: %w", key, ErrInvalidData)
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
switch key {
|
||||||
|
case "Jc", "Jmin", "Jmax", "S1", "S2", "S3", "S4":
|
||||||
|
_, err = strconv.ParseUint(value, 10, 16)
|
||||||
|
case "H1", "H2", "H3", "H4":
|
||||||
|
err = validateAmneziaWGRange(value, 32)
|
||||||
|
case "ContentPaddingAddition", "RekeyAfterTime", "RekeyTimeout", "RejectAfterTime", "KeepaliveTimeout", "MaxHandshakeAttempts":
|
||||||
|
err = validateAmneziaWGRange(value, 16)
|
||||||
|
case "I1", "I2", "I3", "I4", "I5":
|
||||||
|
// The kernel validates the CPS description; it must stay on one line.
|
||||||
|
if value == "" {
|
||||||
|
err = fmt.Errorf("empty CPS description")
|
||||||
|
}
|
||||||
|
case "HeaderProtectionKey":
|
||||||
|
_, err = wgtypes.ParseKey(value)
|
||||||
|
case "RandomTrailers", "DisableCookies":
|
||||||
|
if value != "on" && value != "off" && value != "0" && value != "1" {
|
||||||
|
err = fmt.Errorf("expected on/off or 0/1")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unknown AmneziaWG option %q: %w", key, ErrInvalidData)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid AmneziaWG option %s: %w", key, ErrInvalidData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if min, ok := o["Jmin"]; ok {
|
||||||
|
if max, ok := o["Jmax"]; ok {
|
||||||
|
lo, _ := strconv.ParseUint(min, 10, 16)
|
||||||
|
hi, _ := strconv.ParseUint(max, 10, 16)
|
||||||
|
if lo > hi {
|
||||||
|
return fmt.Errorf("AmneziaWG Jmin exceeds Jmax: %w", ErrInvalidData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateAmneziaWGRange(value string, bits int) error {
|
||||||
|
parts := strings.Split(value, "-")
|
||||||
|
if len(parts) > 2 {
|
||||||
|
return fmt.Errorf("invalid range")
|
||||||
|
}
|
||||||
|
lo, err := strconv.ParseUint(parts[0], 10, bits)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(parts) == 2 {
|
||||||
|
hi, err := strconv.ParseUint(parts[1], 10, bits)
|
||||||
|
if err != nil || lo > hi {
|
||||||
|
return fmt.Errorf("invalid range")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfigLines is deterministic so saved files and QR codes use the same options.
|
||||||
|
func (o AmneziaWGOptions) ConfigLines() string {
|
||||||
|
var result strings.Builder
|
||||||
|
for _, key := range slices.Sorted(maps.Keys(o)) {
|
||||||
|
_, _ = fmt.Fprintf(&result, "%s = %s\n", key, o[key])
|
||||||
|
}
|
||||||
|
return result.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/h44z/wg-portal/internal/config"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAmneziaWGOptionsValidation(t *testing.T) {
|
||||||
|
require.NoError(t, (AmneziaWGOptions{"Jc": "4", "Jmin": "40", "Jmax": "70", "H1": "100-200", "S4": "16", "I1": "<b 0x1234>", "ContentPaddingAddition": "0-16", "RandomTrailers": "on"}).Validate())
|
||||||
|
for _, options := range []AmneziaWGOptions{
|
||||||
|
{"H1": "4294967296"}, {"H1": "200-100"}, {"Jc": "-1"}, {"Jc": "65536"},
|
||||||
|
{"Jmin": "71", "Jmax": "70"}, {"RekeyTimeout": "x"}, {"PreUp": "evil"},
|
||||||
|
{"I1": "abc\n[Peer]"}, {"I1": "abc#comment"}, {"RandomTrailers": "bad"}, {"HeaderProtectionKey": "bad"},
|
||||||
|
} {
|
||||||
|
require.ErrorIs(t, options.Validate(), ErrInvalidData)
|
||||||
|
}
|
||||||
|
iface := &Interface{Backend: config.LocalBackendName, AmneziaWG: AmneziaWGOptions{"Jc": "4"}}
|
||||||
|
require.ErrorIs(t, iface.Validate(), ErrInvalidData)
|
||||||
|
iface.Backend = config.AmneziaWGBackendName
|
||||||
|
require.NoError(t, iface.Validate())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGInterfaceImportMergeAndRouting(t *testing.T) {
|
||||||
|
options := AmneziaWGOptions{"H1": "100-200", "Jc": "4"}
|
||||||
|
physical := &PhysicalInterface{ImportSource: ControllerTypeAmneziaWG}
|
||||||
|
physical.SetExtras(AmneziaWGInterfaceExtras{Options: options})
|
||||||
|
iface := ConvertPhysicalInterface(physical)
|
||||||
|
require.Equal(t, options, iface.AmneziaWG)
|
||||||
|
iface.AmneziaWG["Jc"] = "5"
|
||||||
|
require.Equal(t, "4", options["Jc"], "imported settings must not mutate physical extras")
|
||||||
|
iface.Backend = config.AmneziaWGBackendName
|
||||||
|
iface.AmneziaWG = AmneziaWGOptions{"Jc": "6"}
|
||||||
|
MergeToPhysicalInterface(physical, iface)
|
||||||
|
require.Equal(t, AmneziaWGInterfaceExtras{Options: AmneziaWGOptions{"H1": "100-200", "Jc": "6"}}, physical.GetExtras())
|
||||||
|
require.Equal(t, "4", options["Jc"], "merging must not mutate the previous extras snapshot")
|
||||||
|
iface.RoutingTable = "12345"
|
||||||
|
require.Equal(t, 12345, iface.GetRoutingTable())
|
||||||
|
iface.RoutingTable = "0x1234"
|
||||||
|
require.Equal(t, 0x1234, iface.GetRoutingTable())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGInterfaceMergeInitializesExtras(t *testing.T) {
|
||||||
|
for _, existing := range []any{nil, AmneziaWGInterfaceExtras{}} {
|
||||||
|
physical := &PhysicalInterface{ImportSource: ControllerTypeAmneziaWG}
|
||||||
|
if existing != nil {
|
||||||
|
physical.SetExtras(existing)
|
||||||
|
}
|
||||||
|
iface := &Interface{Backend: config.AmneziaWGBackendName, AmneziaWG: AmneziaWGOptions{"Jc": "4"}}
|
||||||
|
MergeToPhysicalInterface(physical, iface)
|
||||||
|
require.Equal(t, AmneziaWGInterfaceExtras{Options: iface.AmneziaWG}, physical.GetExtras())
|
||||||
|
iface.AmneziaWG["Jc"] = "6"
|
||||||
|
require.Equal(t, "4", physical.GetExtras().(AmneziaWGInterfaceExtras).Options["Jc"])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,10 +3,11 @@ package domain
|
|||||||
// ControllerType defines the type of controller used to manage interfaces.
|
// ControllerType defines the type of controller used to manage interfaces.
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ControllerTypeMikrotik = "mikrotik"
|
ControllerTypeMikrotik = "mikrotik"
|
||||||
ControllerTypeLocal = "wgctrl"
|
ControllerTypeLocal = "wgctrl"
|
||||||
ControllerTypePfsense = "pfsense"
|
ControllerTypeAmneziaWG = "amneziawg"
|
||||||
ControllerTypeOpnsense = "opnsense"
|
ControllerTypePfsense = "pfsense"
|
||||||
|
ControllerTypeOpnsense = "opnsense"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Controller extras can be used to store additional information available for specific controllers only.
|
// Controller extras can be used to store additional information available for specific controllers only.
|
||||||
@@ -17,6 +18,10 @@ type MikrotikInterfaceExtras struct {
|
|||||||
Disabled bool
|
Disabled bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type AmneziaWGInterfaceExtras struct {
|
||||||
|
Options AmneziaWGOptions
|
||||||
|
}
|
||||||
|
|
||||||
type MikrotikPeerExtras struct {
|
type MikrotikPeerExtras struct {
|
||||||
Id string // internal mikrotik ID
|
Id string // internal mikrotik ID
|
||||||
Name string
|
Name string
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package domain
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"maps"
|
||||||
"math"
|
"math"
|
||||||
"net"
|
"net"
|
||||||
"regexp"
|
"regexp"
|
||||||
@@ -29,6 +30,12 @@ type InterfaceIdentifier string
|
|||||||
type InterfaceType string
|
type InterfaceType string
|
||||||
type InterfaceBackend string
|
type InterfaceBackend string
|
||||||
|
|
||||||
|
// IsLocal includes both kernel backends, which share Linux routing and peer
|
||||||
|
// disable/restore behavior. The empty backend is the legacy local backend.
|
||||||
|
func (b InterfaceBackend) IsLocal() bool {
|
||||||
|
return b == "" || b == config.LocalBackendName || b == config.AmneziaWGBackendName
|
||||||
|
}
|
||||||
|
|
||||||
type Interface struct {
|
type Interface struct {
|
||||||
BaseModel
|
BaseModel
|
||||||
|
|
||||||
@@ -37,6 +44,7 @@ type Interface struct {
|
|||||||
Identifier InterfaceIdentifier `gorm:"primaryKey"` // device name, for example: wg0
|
Identifier InterfaceIdentifier `gorm:"primaryKey"` // device name, for example: wg0
|
||||||
KeyPair // private/public Key of the server interface
|
KeyPair // private/public Key of the server interface
|
||||||
ListenPort int // the listening port, for example: 51820
|
ListenPort int // the listening port, for example: 51820
|
||||||
|
AmneziaWG AmneziaWGOptions `gorm:"serializer:json"` // AmneziaWG obfuscation options, nil for ordinary WireGuard.
|
||||||
|
|
||||||
Addresses []Cidr `gorm:"many2many:interface_addresses;"` // the interface ip addresses
|
Addresses []Cidr `gorm:"many2many:interface_addresses;"` // the interface ip addresses
|
||||||
DnsStr string // the dns server that should be set if the interface is up, comma separated
|
DnsStr string // the dns server that should be set if the interface is up, comma separated
|
||||||
@@ -121,6 +129,12 @@ func (i *Interface) PublicInfo() Interface {
|
|||||||
|
|
||||||
// Validate performs checks to ensure that the interface is valid.
|
// Validate performs checks to ensure that the interface is valid.
|
||||||
func (i *Interface) Validate() error {
|
func (i *Interface) Validate() error {
|
||||||
|
if len(i.AmneziaWG) > 0 && i.Backend != config.AmneziaWGBackendName {
|
||||||
|
return fmt.Errorf("AmneziaWG options require the amneziawg backend: %w", ErrInvalidData)
|
||||||
|
}
|
||||||
|
if err := i.AmneziaWG.Validate(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
// validate peer default endpoint, add port if needed
|
// validate peer default endpoint, add port if needed
|
||||||
if i.PeerDefEndpoint != "" {
|
if i.PeerDefEndpoint != "" {
|
||||||
host, port, err := net.SplitHostPort(i.PeerDefEndpoint)
|
host, port, err := net.SplitHostPort(i.PeerDefEndpoint)
|
||||||
@@ -210,7 +224,7 @@ func (i *Interface) GetRoutingTable() int {
|
|||||||
case routingTableStr == "off":
|
case routingTableStr == "off":
|
||||||
return -1
|
return -1
|
||||||
case strings.HasPrefix(routingTableStr, "0x"):
|
case strings.HasPrefix(routingTableStr, "0x"):
|
||||||
if i.Backend != config.LocalBackendName {
|
if !i.Backend.IsLocal() {
|
||||||
return 0 // ignore numeric routing table numbers for non-local controllers
|
return 0 // ignore numeric routing table numbers for non-local controllers
|
||||||
}
|
}
|
||||||
numberStr := strings.ReplaceAll(routingTableStr, "0x", "")
|
numberStr := strings.ReplaceAll(routingTableStr, "0x", "")
|
||||||
@@ -225,7 +239,7 @@ func (i *Interface) GetRoutingTable() int {
|
|||||||
}
|
}
|
||||||
return int(routingTable)
|
return int(routingTable)
|
||||||
default:
|
default:
|
||||||
if i.Backend != config.LocalBackendName {
|
if !i.Backend.IsLocal() {
|
||||||
return 0 // ignore numeric routing table numbers for non-local controllers
|
return 0 // ignore numeric routing table numbers for non-local controllers
|
||||||
}
|
}
|
||||||
routingTable, err := strconv.Atoi(routingTableStr)
|
routingTable, err := strconv.Atoi(routingTableStr)
|
||||||
@@ -283,7 +297,8 @@ func (p *PhysicalInterface) SetExtras(extras any) {
|
|||||||
case MikrotikInterfaceExtras: // OK
|
case MikrotikInterfaceExtras: // OK
|
||||||
case PfsenseInterfaceExtras: // OK
|
case PfsenseInterfaceExtras: // OK
|
||||||
case OpnsenseInterfaceExtras: // OK
|
case OpnsenseInterfaceExtras: // OK
|
||||||
default: // we only support Mikrotik, Pfsense and Opnsense interface extras for now
|
case AmneziaWGInterfaceExtras: // OK
|
||||||
|
default:
|
||||||
panic(fmt.Sprintf("unsupported interface backend extras type %T", extras))
|
panic(fmt.Sprintf("unsupported interface backend extras type %T", extras))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -362,6 +377,9 @@ func ConvertPhysicalInterface(pi *PhysicalInterface) *Interface {
|
|||||||
} else {
|
} else {
|
||||||
iface.Disabled = nil
|
iface.Disabled = nil
|
||||||
}
|
}
|
||||||
|
case ControllerTypeAmneziaWG:
|
||||||
|
extras := pi.GetExtras().(AmneziaWGInterfaceExtras)
|
||||||
|
iface.AmneziaWG = maps.Clone(extras.Options)
|
||||||
}
|
}
|
||||||
|
|
||||||
return iface
|
return iface
|
||||||
@@ -403,6 +421,13 @@ func MergeToPhysicalInterface(pi *PhysicalInterface, i *Interface) {
|
|||||||
extras.Instance = existing.Instance
|
extras.Instance = existing.Instance
|
||||||
}
|
}
|
||||||
pi.SetExtras(extras)
|
pi.SetExtras(extras)
|
||||||
|
case ControllerTypeAmneziaWG:
|
||||||
|
extras := AmneziaWGInterfaceExtras{Options: AmneziaWGOptions{}}
|
||||||
|
if existing, ok := pi.GetExtras().(AmneziaWGInterfaceExtras); ok && existing.Options != nil {
|
||||||
|
extras.Options = maps.Clone(existing.Options)
|
||||||
|
}
|
||||||
|
maps.Copy(extras.Options, i.AmneziaWG)
|
||||||
|
pi.SetExtras(extras)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -167,6 +167,8 @@ type PeerInterfaceConfig struct {
|
|||||||
PostUp ConfigOption[string] `gorm:"embedded;embeddedPrefix:iface_post_up_"` // action that is executed after the device is up
|
PostUp ConfigOption[string] `gorm:"embedded;embeddedPrefix:iface_post_up_"` // action that is executed after the device is up
|
||||||
PreDown ConfigOption[string] `gorm:"embedded;embeddedPrefix:iface_pre_down_"` // action that is executed before the device is down
|
PreDown ConfigOption[string] `gorm:"embedded;embeddedPrefix:iface_pre_down_"` // action that is executed before the device is down
|
||||||
PostDown ConfigOption[string] `gorm:"embedded;embeddedPrefix:iface_post_down_"` // action that is executed after the device is down
|
PostDown ConfigOption[string] `gorm:"embedded;embeddedPrefix:iface_post_down_"` // action that is executed after the device is down
|
||||||
|
|
||||||
|
AmneziaWG AmneziaWGOptions `gorm:"-" json:"-"` // Filled from the parent interface when exporting a client configuration.
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *PeerInterfaceConfig) AddressStr() string {
|
func (p *PeerInterfaceConfig) AddressStr() string {
|
||||||
@@ -298,7 +300,7 @@ func ConvertPhysicalPeer(pp *PhysicalPeer) *Peer {
|
|||||||
peer.Disabled = nil
|
peer.Disabled = nil
|
||||||
peer.DisabledReason = ""
|
peer.DisabledReason = ""
|
||||||
}
|
}
|
||||||
case ControllerTypeLocal:
|
case ControllerTypeLocal, ControllerTypeAmneziaWG:
|
||||||
extras := pp.GetExtras().(LocalPeerExtras)
|
extras := pp.GetExtras().(LocalPeerExtras)
|
||||||
if extras.Disabled {
|
if extras.Disabled {
|
||||||
peer.Disabled = &now
|
peer.Disabled = &now
|
||||||
@@ -397,7 +399,7 @@ func MergeToPhysicalPeer(pp *PhysicalPeer, p *Peer) {
|
|||||||
Dynamic: p.IsDynamic,
|
Dynamic: p.IsDynamic,
|
||||||
}
|
}
|
||||||
pp.SetExtras(extras)
|
pp.SetExtras(extras)
|
||||||
case ControllerTypeLocal:
|
case ControllerTypeLocal, ControllerTypeAmneziaWG:
|
||||||
extras := LocalPeerExtras{
|
extras := LocalPeerExtras{
|
||||||
Disabled: p.IsDisabled(),
|
Disabled: p.IsDisabled(),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
package lowlevel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
"github.com/vishvananda/netlink/nl"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
|
|
||||||
|
"github.com/h44z/wg-portal/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AmneziaWGClient implements the wgctrl client contract using the AmneziaWG
|
||||||
|
// kernel's Generic Netlink family.
|
||||||
|
type AmneziaWGClient struct {
|
||||||
|
version uint8
|
||||||
|
exchange func(command uint8, flags uint16, attrs []*nl.RtAttr) ([][]byte, error)
|
||||||
|
linkByName func(string) (netlink.Link, error)
|
||||||
|
links func() ([]netlink.Link, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAmneziaWGClient() (*AmneziaWGClient, error) {
|
||||||
|
family, err := amneziaWGFamily(netlink.GenlFamilyGet)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &AmneziaWGClient{
|
||||||
|
version: uint8(family.Version), linkByName: netlink.LinkByName, links: netlink.LinkList,
|
||||||
|
exchange: func(command uint8, flags uint16, attrs []*nl.RtAttr) ([][]byte, error) {
|
||||||
|
req := nl.NewNetlinkRequest(int(family.ID), int(flags))
|
||||||
|
req.AddData(&nl.Genlmsg{Command: command, Version: uint8(family.Version)})
|
||||||
|
for _, attr := range attrs {
|
||||||
|
req.AddData(attr)
|
||||||
|
}
|
||||||
|
return req.Execute(unix.NETLINK_GENERIC, family.ID)
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func amneziaWGFamily(lookup func(string) (*netlink.GenlFamily, error)) (*netlink.GenlFamily, error) {
|
||||||
|
family, err := lookup("amneziawg")
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("AmneziaWG kernel support is unavailable; install and load the amneziawg module on the host (modprobe amneziawg): %w", err)
|
||||||
|
}
|
||||||
|
if family == nil || family.Version < 1 || family.Version > 3 {
|
||||||
|
return nil, fmt.Errorf("unsupported AmneziaWG Generic Netlink version (supported: 1, 2, 3)")
|
||||||
|
}
|
||||||
|
return family, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Requests use their own short-lived sockets, which the netlink library closes.
|
||||||
|
func (c *AmneziaWGClient) Close() error { return nil }
|
||||||
|
|
||||||
|
func (c *AmneziaWGClient) kernelLink(name string) error {
|
||||||
|
link, err := c.linkByName(name)
|
||||||
|
if err != nil {
|
||||||
|
if _, ok := errors.AsType[netlink.LinkNotFoundError](err); ok {
|
||||||
|
return os.ErrNotExist
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if link.Type() != "amneziawg" {
|
||||||
|
return fmt.Errorf("interface %s is not an AmneziaWG kernel device", name)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *AmneziaWGClient) Devices() ([]*wgtypes.Device, error) {
|
||||||
|
links, err := c.links()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var devices []*wgtypes.Device
|
||||||
|
for _, link := range links {
|
||||||
|
if link.Type() != "amneziawg" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
device, err := c.Device(link.Attrs().Name)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
devices = append(devices, device)
|
||||||
|
}
|
||||||
|
return devices, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *AmneziaWGClient) Device(name string) (*wgtypes.Device, error) {
|
||||||
|
device, _, err := c.readDevice(name)
|
||||||
|
return device, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *AmneziaWGClient) AmneziaWGOptions(name string) (domain.AmneziaWGOptions, error) {
|
||||||
|
_, options, err := c.readDevice(name)
|
||||||
|
return options, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *AmneziaWGClient) readDevice(name string) (*wgtypes.Device, domain.AmneziaWGOptions, error) {
|
||||||
|
if err := c.kernelLink(name); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
messages, err := c.exchange(awgGetDevice, unix.NLM_F_DUMP, []*nl.RtAttr{nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, nl.ZeroTerminated(name))})
|
||||||
|
if errors.Is(err, unix.ENODEV) || errors.Is(err, unix.ENOENT) {
|
||||||
|
return nil, nil, os.ErrNotExist
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("AmneziaWG device read: %w", err)
|
||||||
|
}
|
||||||
|
if len(messages) == 0 {
|
||||||
|
return nil, nil, os.ErrNotExist
|
||||||
|
}
|
||||||
|
device, options, err := parseAmneziaWGDevice(messages, c.version)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("invalid AmneziaWG device response: %w", err)
|
||||||
|
}
|
||||||
|
if device.Name != name {
|
||||||
|
return nil, nil, fmt.Errorf("unexpected AmneziaWG interface in response")
|
||||||
|
}
|
||||||
|
return device, options, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *AmneziaWGClient) ConfigureDevice(name string, cfg wgtypes.Config) error {
|
||||||
|
return c.ConfigureAmneziaWGDevice(name, cfg, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *AmneziaWGClient) ConfigureAmneziaWGDevice(name string, cfg wgtypes.Config, options domain.AmneziaWGOptions) error {
|
||||||
|
// Encode every batch before changing the device, so invalid input cannot
|
||||||
|
// leave an otherwise valid prefix of the configuration applied.
|
||||||
|
batches, err := amneziaWGConfigBatches(name, cfg, options, c.version)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := c.kernelLink(name); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, attrs := range batches {
|
||||||
|
if _, err := c.exchange(awgSetDevice, unix.NLM_F_ACK, attrs); err != nil {
|
||||||
|
if errors.Is(err, unix.ENODEV) || errors.Is(err, unix.ENOENT) {
|
||||||
|
return os.ErrNotExist
|
||||||
|
}
|
||||||
|
return fmt.Errorf("AmneziaWG device configuration: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,410 @@
|
|||||||
|
package lowlevel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/vishvananda/netlink/nl"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
|
|
||||||
|
"github.com/h44z/wg-portal/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
awgGetDevice uint8 = 0
|
||||||
|
awgSetDevice uint8 = 1
|
||||||
|
awgMaxPayload = 60000
|
||||||
|
awgIPChunk = 256
|
||||||
|
)
|
||||||
|
|
||||||
|
func amneziaWGConfigBatches(name string, cfg wgtypes.Config, options domain.AmneziaWGOptions, version uint8) ([][]*nl.RtAttr, error) {
|
||||||
|
if len(name) == 0 || len(name) >= unix.IFNAMSIZ || strings.ContainsRune(name, 0) {
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG interface name")
|
||||||
|
}
|
||||||
|
attrs := []*nl.RtAttr{nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, nl.ZeroTerminated(name))}
|
||||||
|
if cfg.PrivateKey != nil {
|
||||||
|
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_PRIVATE_KEY, cfg.PrivateKey[:]))
|
||||||
|
}
|
||||||
|
if cfg.ListenPort != nil {
|
||||||
|
if *cfg.ListenPort < 0 || *cfg.ListenPort > 65535 {
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG listen port")
|
||||||
|
}
|
||||||
|
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_LISTEN_PORT, awgNumber(uint64(*cfg.ListenPort), 2)))
|
||||||
|
}
|
||||||
|
if cfg.FirewallMark != nil {
|
||||||
|
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_FWMARK, awgNumber(uint64(uint32(*cfg.FirewallMark)), 4)))
|
||||||
|
}
|
||||||
|
if cfg.ReplacePeers {
|
||||||
|
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_FLAGS, awgNumber(unix.WGDEVICE_F_REPLACE_PEERS, 4)))
|
||||||
|
}
|
||||||
|
custom, err := encodeAmneziaWGOptions(options, version)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
attrs = append(attrs, custom...)
|
||||||
|
var batches [][]*nl.RtAttr
|
||||||
|
var peers *nl.RtAttr
|
||||||
|
size := nl.SizeofGenlmsg
|
||||||
|
for _, attr := range attrs {
|
||||||
|
size += len(attr.Serialize())
|
||||||
|
}
|
||||||
|
flush := func() {
|
||||||
|
if peers != nil {
|
||||||
|
attrs = append(attrs, peers)
|
||||||
|
}
|
||||||
|
batches = append(batches, attrs)
|
||||||
|
// Destructive replacement flags and interface options belong only in
|
||||||
|
// the first message. Later messages append peer/IP continuations.
|
||||||
|
attrs = []*nl.RtAttr{nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, nl.ZeroTerminated(name))}
|
||||||
|
size = nl.SizeofGenlmsg + len(attrs[0].Serialize())
|
||||||
|
peers = nil
|
||||||
|
}
|
||||||
|
for _, peer := range cfg.Peers {
|
||||||
|
for start, first := 0, true; first || start < len(peer.AllowedIPs); first = false {
|
||||||
|
end := min(start+awgIPChunk, len(peer.AllowedIPs))
|
||||||
|
chunk, err := encodeAmneziaWGPeer(peer, peer.AllowedIPs[start:end], first, version)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
length := len(chunk.Serialize())
|
||||||
|
if size+length+unix.SizeofRtAttr > awgMaxPayload {
|
||||||
|
flush()
|
||||||
|
}
|
||||||
|
if peers == nil {
|
||||||
|
peers = nl.NewRtAttr(unix.WGDEVICE_A_PEERS|unix.NLA_F_NESTED, nil)
|
||||||
|
size += unix.SizeofRtAttr
|
||||||
|
}
|
||||||
|
peers.AddChild(chunk)
|
||||||
|
size += length
|
||||||
|
start = end
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
return batches, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeAmneziaWGPeer(peer wgtypes.PeerConfig, ips []net.IPNet, first bool, version uint8) (*nl.RtAttr, error) {
|
||||||
|
attr := nl.NewRtAttr(unix.NLA_F_NESTED, nil)
|
||||||
|
attr.AddRtAttr(unix.WGPEER_A_PUBLIC_KEY, peer.PublicKey[:])
|
||||||
|
var flags uint32
|
||||||
|
if peer.Remove {
|
||||||
|
flags |= unix.WGPEER_F_REMOVE_ME
|
||||||
|
}
|
||||||
|
if peer.UpdateOnly {
|
||||||
|
flags |= unix.WGPEER_F_UPDATE_ONLY
|
||||||
|
}
|
||||||
|
if first && peer.ReplaceAllowedIPs {
|
||||||
|
flags |= unix.WGPEER_F_REPLACE_ALLOWEDIPS
|
||||||
|
}
|
||||||
|
if flags != 0 {
|
||||||
|
attr.AddRtAttr(unix.WGPEER_A_FLAGS, awgNumber(uint64(flags), 4))
|
||||||
|
}
|
||||||
|
if first {
|
||||||
|
if peer.PresharedKey != nil {
|
||||||
|
attr.AddRtAttr(unix.WGPEER_A_PRESHARED_KEY, peer.PresharedKey[:])
|
||||||
|
}
|
||||||
|
if peer.Endpoint != nil {
|
||||||
|
data, err := encodeAmneziaWGSockaddr(peer.Endpoint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
attr.AddRtAttr(unix.WGPEER_A_ENDPOINT, data)
|
||||||
|
}
|
||||||
|
if peer.PersistentKeepaliveInterval != nil {
|
||||||
|
interval := *peer.PersistentKeepaliveInterval
|
||||||
|
if interval < 0 || interval > 65535*time.Second || interval%time.Second != 0 {
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG keepalive interval")
|
||||||
|
}
|
||||||
|
value, size := uint64(interval/time.Second), 2
|
||||||
|
if version >= 3 {
|
||||||
|
value |= value << 16
|
||||||
|
size = 4
|
||||||
|
}
|
||||||
|
attr.AddRtAttr(unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, awgNumber(value, size))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(ips) != 0 {
|
||||||
|
allowed := attr.AddRtAttr(unix.WGPEER_A_ALLOWEDIPS|unix.NLA_F_NESTED, nil)
|
||||||
|
for _, ip := range ips {
|
||||||
|
address, family, bits := ip.IP.To4(), uint64(unix.AF_INET), 32
|
||||||
|
if address == nil {
|
||||||
|
address, family, bits = ip.IP.To16(), unix.AF_INET6, 128
|
||||||
|
}
|
||||||
|
ones, maskBits := ip.Mask.Size()
|
||||||
|
if address == nil || maskBits != bits {
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG allowed IP")
|
||||||
|
}
|
||||||
|
entry := allowed.AddRtAttr(unix.NLA_F_NESTED, nil)
|
||||||
|
entry.AddRtAttr(unix.WGALLOWEDIP_A_FAMILY, awgNumber(family, 2))
|
||||||
|
entry.AddRtAttr(unix.WGALLOWEDIP_A_IPADDR, address)
|
||||||
|
entry.AddRtAttr(unix.WGALLOWEDIP_A_CIDR_MASK, []byte{byte(ones)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return attr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeAmneziaWGSockaddr(endpoint *net.UDPAddr) ([]byte, error) {
|
||||||
|
if endpoint.Port < 0 || endpoint.Port > 65535 {
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG endpoint port")
|
||||||
|
}
|
||||||
|
if ip := endpoint.IP.To4(); ip != nil {
|
||||||
|
data := make([]byte, unix.SizeofSockaddrInet4)
|
||||||
|
nl.NativeEndian().PutUint16(data, unix.AF_INET)
|
||||||
|
binary.BigEndian.PutUint16(data[2:], uint16(endpoint.Port))
|
||||||
|
copy(data[4:], ip)
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
ip := endpoint.IP.To16()
|
||||||
|
if ip == nil {
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG endpoint IP")
|
||||||
|
}
|
||||||
|
data := make([]byte, unix.SizeofSockaddrInet6)
|
||||||
|
nl.NativeEndian().PutUint16(data, unix.AF_INET6)
|
||||||
|
binary.BigEndian.PutUint16(data[2:], uint16(endpoint.Port))
|
||||||
|
copy(data[8:], ip)
|
||||||
|
if endpoint.Zone != "" {
|
||||||
|
index, err := strconv.ParseUint(endpoint.Zone, 10, 32)
|
||||||
|
if err != nil {
|
||||||
|
iface, err := net.InterfaceByName(endpoint.Zone)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG endpoint zone")
|
||||||
|
}
|
||||||
|
index = uint64(iface.Index)
|
||||||
|
}
|
||||||
|
nl.NativeEndian().PutUint32(data[24:], uint32(index))
|
||||||
|
}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate lengths before using netlink's attribute decoder, including padding
|
||||||
|
// that would otherwise let a truncated attribute panic during decoding.
|
||||||
|
func amneziaWGAttrs(data []byte) ([]syscall.NetlinkRouteAttr, error) {
|
||||||
|
for rest := data; len(rest) != 0; {
|
||||||
|
if len(rest) < unix.SizeofRtAttr {
|
||||||
|
return nil, fmt.Errorf("truncated AmneziaWG attribute")
|
||||||
|
}
|
||||||
|
length := int(nl.NativeEndian().Uint16(rest))
|
||||||
|
padded := (length + 3) &^ 3
|
||||||
|
if length < unix.SizeofRtAttr || padded > len(rest) {
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG attribute length")
|
||||||
|
}
|
||||||
|
rest = rest[padded:]
|
||||||
|
}
|
||||||
|
return nl.ParseRouteAttr(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseAmneziaWGDevice(messages [][]byte, version uint8) (*wgtypes.Device, domain.AmneziaWGOptions, error) {
|
||||||
|
device := &wgtypes.Device{Type: wgtypes.LinuxKernel}
|
||||||
|
options := domain.AmneziaWGOptions{}
|
||||||
|
known := make(map[wgtypes.Key]int)
|
||||||
|
for _, message := range messages {
|
||||||
|
if len(message) < nl.SizeofGenlmsg || message[0] != awgGetDevice {
|
||||||
|
return nil, nil, fmt.Errorf("invalid AmneziaWG message header")
|
||||||
|
}
|
||||||
|
attrs, err := amneziaWGAttrs(message[nl.SizeofGenlmsg:])
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
for _, attr := range attrs {
|
||||||
|
kind, data := attr.Attr.Type&0x3fff, attr.Value
|
||||||
|
switch kind {
|
||||||
|
case unix.WGDEVICE_A_IFNAME:
|
||||||
|
var name string
|
||||||
|
name, err = awgString(data)
|
||||||
|
if device.Name != "" && name != device.Name {
|
||||||
|
return nil, nil, fmt.Errorf("mixed AmneziaWG interfaces in dump")
|
||||||
|
}
|
||||||
|
device.Name = name
|
||||||
|
case unix.WGDEVICE_A_PRIVATE_KEY:
|
||||||
|
device.PrivateKey, err = wgtypes.NewKey(data)
|
||||||
|
case unix.WGDEVICE_A_PUBLIC_KEY:
|
||||||
|
device.PublicKey, err = wgtypes.NewKey(data)
|
||||||
|
case unix.WGDEVICE_A_LISTEN_PORT:
|
||||||
|
var v uint64
|
||||||
|
v, err = awgReadNumber(data, 2)
|
||||||
|
device.ListenPort = int(v)
|
||||||
|
case unix.WGDEVICE_A_FWMARK:
|
||||||
|
var v uint64
|
||||||
|
v, err = awgReadNumber(data, 4)
|
||||||
|
device.FirewallMark = int(v)
|
||||||
|
case unix.WGDEVICE_A_PEERS:
|
||||||
|
var peers []syscall.NetlinkRouteAttr
|
||||||
|
peers, err = amneziaWGAttrs(data)
|
||||||
|
for _, raw := range peers {
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
var peer wgtypes.Peer
|
||||||
|
peer, err = parseAmneziaWGPeer(raw.Value, version)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if index, ok := known[peer.PublicKey]; ok {
|
||||||
|
device.Peers[index].AllowedIPs = append(device.Peers[index].AllowedIPs, peer.AllowedIPs...)
|
||||||
|
} else {
|
||||||
|
known[peer.PublicKey] = len(device.Peers)
|
||||||
|
device.Peers = append(device.Peers, peer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
for _, spec := range awgOptions {
|
||||||
|
if int(kind) == spec.attr {
|
||||||
|
options[spec.name], err = spec.decode(data, version)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("invalid AmneziaWG attribute %d", kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := options.Validate(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return device, options, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseAmneziaWGPeer(data []byte, version uint8) (wgtypes.Peer, error) {
|
||||||
|
peer := wgtypes.Peer{ProtocolVersion: 1}
|
||||||
|
attrs, err := amneziaWGAttrs(data)
|
||||||
|
if err != nil {
|
||||||
|
return peer, err
|
||||||
|
}
|
||||||
|
keyFound := false
|
||||||
|
for _, attr := range attrs {
|
||||||
|
kind, value := attr.Attr.Type&0x3fff, attr.Value
|
||||||
|
switch kind {
|
||||||
|
case unix.WGPEER_A_PUBLIC_KEY:
|
||||||
|
peer.PublicKey, err = wgtypes.NewKey(value)
|
||||||
|
keyFound = true
|
||||||
|
case unix.WGPEER_A_PRESHARED_KEY:
|
||||||
|
peer.PresharedKey, err = wgtypes.NewKey(value)
|
||||||
|
case unix.WGPEER_A_ENDPOINT:
|
||||||
|
peer.Endpoint, err = parseAmneziaWGSockaddr(value)
|
||||||
|
case unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL:
|
||||||
|
size := 2
|
||||||
|
if version >= 3 {
|
||||||
|
size = 4
|
||||||
|
}
|
||||||
|
var v uint64
|
||||||
|
v, err = awgReadNumber(value, size)
|
||||||
|
// The portal exposes a single interval; report a range's lower bound.
|
||||||
|
peer.PersistentKeepaliveInterval = time.Duration(v&0xffff) * time.Second
|
||||||
|
case unix.WGPEER_A_LAST_HANDSHAKE_TIME:
|
||||||
|
peer.LastHandshakeTime, err = parseAmneziaWGTime(value)
|
||||||
|
case unix.WGPEER_A_RX_BYTES:
|
||||||
|
var v uint64
|
||||||
|
v, err = awgReadNumber(value, 8)
|
||||||
|
peer.ReceiveBytes = int64(v)
|
||||||
|
case unix.WGPEER_A_TX_BYTES:
|
||||||
|
var v uint64
|
||||||
|
v, err = awgReadNumber(value, 8)
|
||||||
|
peer.TransmitBytes = int64(v)
|
||||||
|
case unix.WGPEER_A_PROTOCOL_VERSION:
|
||||||
|
var v uint64
|
||||||
|
v, err = awgReadNumber(value, 4)
|
||||||
|
peer.ProtocolVersion = int(v)
|
||||||
|
case unix.WGPEER_A_ALLOWEDIPS:
|
||||||
|
peer.AllowedIPs, err = parseAmneziaWGAllowedIPs(value)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return peer, fmt.Errorf("invalid AmneziaWG peer attribute %d", kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !keyFound {
|
||||||
|
return peer, fmt.Errorf("missing AmneziaWG peer public key")
|
||||||
|
}
|
||||||
|
return peer, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseAmneziaWGAllowedIPs(data []byte) ([]net.IPNet, error) {
|
||||||
|
entries, err := amneziaWGAttrs(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var ips []net.IPNet
|
||||||
|
for _, entry := range entries {
|
||||||
|
attrs, err := amneziaWGAttrs(entry.Value)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var family, prefix uint64
|
||||||
|
var address net.IP
|
||||||
|
familyFound, prefixFound := false, false
|
||||||
|
for _, attr := range attrs {
|
||||||
|
switch attr.Attr.Type & 0x3fff {
|
||||||
|
case unix.WGALLOWEDIP_A_FAMILY:
|
||||||
|
family, err = awgReadNumber(attr.Value, 2)
|
||||||
|
familyFound = true
|
||||||
|
case unix.WGALLOWEDIP_A_CIDR_MASK:
|
||||||
|
prefix, err = awgReadNumber(attr.Value, 1)
|
||||||
|
prefixFound = true
|
||||||
|
case unix.WGALLOWEDIP_A_IPADDR:
|
||||||
|
address = append(net.IP(nil), attr.Value...)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bits := 0
|
||||||
|
if family == unix.AF_INET && len(address) == net.IPv4len {
|
||||||
|
bits = 32
|
||||||
|
}
|
||||||
|
if family == unix.AF_INET6 && len(address) == net.IPv6len {
|
||||||
|
bits = 128
|
||||||
|
}
|
||||||
|
if !familyFound || !prefixFound || bits == 0 || prefix > uint64(bits) {
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG allowed IP")
|
||||||
|
}
|
||||||
|
ips = append(ips, net.IPNet{IP: address, Mask: net.CIDRMask(int(prefix), bits)})
|
||||||
|
}
|
||||||
|
return ips, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseAmneziaWGSockaddr(data []byte) (*net.UDPAddr, error) {
|
||||||
|
if len(data) < 4 {
|
||||||
|
return nil, fmt.Errorf("truncated AmneziaWG endpoint")
|
||||||
|
}
|
||||||
|
family := nl.NativeEndian().Uint16(data)
|
||||||
|
endpoint := &net.UDPAddr{Port: int(binary.BigEndian.Uint16(data[2:]))}
|
||||||
|
switch {
|
||||||
|
case family == unix.AF_INET && len(data) == unix.SizeofSockaddrInet4:
|
||||||
|
endpoint.IP = append(net.IP(nil), data[4:8]...)
|
||||||
|
case family == unix.AF_INET6 && len(data) == unix.SizeofSockaddrInet6:
|
||||||
|
endpoint.IP = append(net.IP(nil), data[8:24]...)
|
||||||
|
if zone := nl.NativeEndian().Uint32(data[24:]); zone != 0 {
|
||||||
|
endpoint.Zone = strconv.FormatUint(uint64(zone), 10)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG endpoint")
|
||||||
|
}
|
||||||
|
return endpoint, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseAmneziaWGTime(data []byte) (time.Time, error) {
|
||||||
|
var seconds, nanos int64
|
||||||
|
switch len(data) {
|
||||||
|
case 8:
|
||||||
|
seconds = int64(int32(nl.NativeEndian().Uint32(data)))
|
||||||
|
nanos = int64(int32(nl.NativeEndian().Uint32(data[4:])))
|
||||||
|
case 16:
|
||||||
|
seconds = int64(nl.NativeEndian().Uint64(data))
|
||||||
|
nanos = int64(nl.NativeEndian().Uint64(data[8:]))
|
||||||
|
default:
|
||||||
|
return time.Time{}, fmt.Errorf("invalid AmneziaWG handshake timestamp")
|
||||||
|
}
|
||||||
|
if seconds < 0 || nanos < 0 || nanos >= int64(time.Second) {
|
||||||
|
return time.Time{}, fmt.Errorf("invalid AmneziaWG handshake timestamp")
|
||||||
|
}
|
||||||
|
if seconds == 0 && nanos == 0 {
|
||||||
|
return time.Time{}, nil
|
||||||
|
}
|
||||||
|
return time.Unix(seconds, nanos), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
package lowlevel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/vishvananda/netlink/nl"
|
||||||
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
|
|
||||||
|
"github.com/h44z/wg-portal/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Attribute numbers follow the official AmneziaWG UAPI, which extends the
|
||||||
|
// WireGuard attributes without changing their IDs.
|
||||||
|
// https://github.com/amnezia-vpn/amneziawg-tools/blob/ee0f0a9aa34ff0a0da4b3433b9512781cfe02843/src/uapi/linux/linux/wireguard.h
|
||||||
|
const (
|
||||||
|
awgOptionU16 = iota
|
||||||
|
awgOptionHeader
|
||||||
|
awgOptionString
|
||||||
|
awgOptionKey
|
||||||
|
awgOptionRange16
|
||||||
|
awgOptionBool
|
||||||
|
)
|
||||||
|
|
||||||
|
type awgOption struct {
|
||||||
|
name string
|
||||||
|
attr int
|
||||||
|
kind int
|
||||||
|
minVersion uint8
|
||||||
|
}
|
||||||
|
|
||||||
|
var awgOptions = []awgOption{
|
||||||
|
{"Jc", 9, awgOptionU16, 1}, {"Jmin", 10, awgOptionU16, 1}, {"Jmax", 11, awgOptionU16, 1},
|
||||||
|
{"S1", 12, awgOptionU16, 1}, {"S2", 13, awgOptionU16, 1},
|
||||||
|
{"H1", 14, awgOptionHeader, 1}, {"H2", 15, awgOptionHeader, 1},
|
||||||
|
{"H3", 16, awgOptionHeader, 1}, {"H4", 17, awgOptionHeader, 1},
|
||||||
|
// Attribute 18 describes an unknown peer notification, not an option.
|
||||||
|
{"S3", 19, awgOptionU16, 2}, {"S4", 20, awgOptionU16, 2},
|
||||||
|
{"I1", 21, awgOptionString, 2}, {"I2", 22, awgOptionString, 2},
|
||||||
|
{"I3", 23, awgOptionString, 2}, {"I4", 24, awgOptionString, 2}, {"I5", 25, awgOptionString, 2},
|
||||||
|
{"HeaderProtectionKey", 26, awgOptionKey, 3},
|
||||||
|
{"ContentPaddingAddition", 27, awgOptionRange16, 3}, {"RekeyAfterTime", 28, awgOptionRange16, 3},
|
||||||
|
{"RekeyTimeout", 29, awgOptionRange16, 3}, {"RejectAfterTime", 30, awgOptionRange16, 3},
|
||||||
|
{"KeepaliveTimeout", 31, awgOptionRange16, 3}, {"MaxHandshakeAttempts", 32, awgOptionRange16, 3},
|
||||||
|
{"RandomTrailers", 33, awgOptionBool, 3}, {"DisableCookies", 34, awgOptionBool, 3},
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeAmneziaWGOptions(options domain.AmneziaWGOptions, version uint8) ([]*nl.RtAttr, error) {
|
||||||
|
if err := options.Validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var attrs []*nl.RtAttr
|
||||||
|
for _, spec := range awgOptions {
|
||||||
|
value, ok := options[spec.name]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if version < spec.minVersion {
|
||||||
|
return nil, fmt.Errorf("AmneziaWG option %s requires kernel netlink version %d: %w", spec.name, spec.minVersion, domain.ErrInvalidData)
|
||||||
|
}
|
||||||
|
data, err := spec.encode(value, version)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid AmneziaWG option %s: %v: %w", spec.name, err, domain.ErrInvalidData)
|
||||||
|
}
|
||||||
|
attrs = append(attrs, nl.NewRtAttr(spec.attr, data))
|
||||||
|
}
|
||||||
|
return attrs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o awgOption) encode(value string, version uint8) ([]byte, error) {
|
||||||
|
switch o.kind {
|
||||||
|
case awgOptionU16:
|
||||||
|
v, err := strconv.ParseUint(value, 10, 16)
|
||||||
|
return awgNumber(v, 2), err
|
||||||
|
case awgOptionHeader:
|
||||||
|
lo, hi, err := awgRange(value, 32)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
switch version {
|
||||||
|
case 1:
|
||||||
|
if lo != hi {
|
||||||
|
return nil, fmt.Errorf("header ranges require AmneziaWG v2 or newer")
|
||||||
|
}
|
||||||
|
return awgNumber(lo, 4), nil
|
||||||
|
case 2:
|
||||||
|
return nl.ZeroTerminated(awgRangeString(lo, hi)), nil
|
||||||
|
default:
|
||||||
|
return awgNumber(lo|hi<<32, 8), nil
|
||||||
|
}
|
||||||
|
case awgOptionString:
|
||||||
|
return nl.ZeroTerminated(value), nil
|
||||||
|
case awgOptionKey:
|
||||||
|
key, err := wgtypes.ParseKey(value)
|
||||||
|
return key[:], err
|
||||||
|
case awgOptionRange16:
|
||||||
|
lo, hi, err := awgRange(value, 16)
|
||||||
|
return awgNumber(lo|hi<<16, 4), err
|
||||||
|
case awgOptionBool:
|
||||||
|
if value == "1" || value == "on" {
|
||||||
|
return []byte{1}, nil
|
||||||
|
}
|
||||||
|
return []byte{0}, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("unknown AmneziaWG option kind")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o awgOption) decode(data []byte, version uint8) (string, error) {
|
||||||
|
switch o.kind {
|
||||||
|
case awgOptionU16:
|
||||||
|
v, err := awgReadNumber(data, 2)
|
||||||
|
return strconv.FormatUint(v, 10), err
|
||||||
|
case awgOptionHeader:
|
||||||
|
switch version {
|
||||||
|
case 1:
|
||||||
|
v, err := awgReadNumber(data, 4)
|
||||||
|
return strconv.FormatUint(v, 10), err
|
||||||
|
case 2:
|
||||||
|
value, err := awgString(data)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
lo, hi, err := awgRange(value, 32)
|
||||||
|
return awgRangeString(lo, hi), err
|
||||||
|
default:
|
||||||
|
v, err := awgReadNumber(data, 8)
|
||||||
|
return awgRangeString(v&0xffffffff, v>>32), err
|
||||||
|
}
|
||||||
|
case awgOptionString:
|
||||||
|
return awgString(data)
|
||||||
|
case awgOptionKey:
|
||||||
|
key, err := wgtypes.NewKey(data)
|
||||||
|
return key.String(), err
|
||||||
|
case awgOptionRange16:
|
||||||
|
v, err := awgReadNumber(data, 4)
|
||||||
|
return awgRangeString(v&0xffff, v>>16), err
|
||||||
|
case awgOptionBool:
|
||||||
|
v, err := awgReadNumber(data, 1)
|
||||||
|
if v != 0 {
|
||||||
|
return "on", err
|
||||||
|
}
|
||||||
|
return "off", err
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("unknown AmneziaWG option kind")
|
||||||
|
}
|
||||||
|
|
||||||
|
func awgNumber(v uint64, size int) []byte {
|
||||||
|
b := make([]byte, size)
|
||||||
|
switch size {
|
||||||
|
case 1:
|
||||||
|
b[0] = byte(v)
|
||||||
|
case 2:
|
||||||
|
nl.NativeEndian().PutUint16(b, uint16(v))
|
||||||
|
case 4:
|
||||||
|
nl.NativeEndian().PutUint32(b, uint32(v))
|
||||||
|
case 8:
|
||||||
|
nl.NativeEndian().PutUint64(b, v)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func awgReadNumber(b []byte, size int) (uint64, error) {
|
||||||
|
if len(b) != size {
|
||||||
|
return 0, fmt.Errorf("invalid AmneziaWG numeric attribute size")
|
||||||
|
}
|
||||||
|
switch size {
|
||||||
|
case 1:
|
||||||
|
return uint64(b[0]), nil
|
||||||
|
case 2:
|
||||||
|
return uint64(nl.NativeEndian().Uint16(b)), nil
|
||||||
|
case 4:
|
||||||
|
return uint64(nl.NativeEndian().Uint32(b)), nil
|
||||||
|
case 8:
|
||||||
|
return nl.NativeEndian().Uint64(b), nil
|
||||||
|
}
|
||||||
|
return 0, fmt.Errorf("invalid AmneziaWG numeric size")
|
||||||
|
}
|
||||||
|
|
||||||
|
func awgString(data []byte) (string, error) {
|
||||||
|
if len(data) == 0 || data[len(data)-1] != 0 || strings.IndexByte(string(data[:len(data)-1]), 0) >= 0 {
|
||||||
|
return "", fmt.Errorf("invalid AmneziaWG string attribute")
|
||||||
|
}
|
||||||
|
return string(data[:len(data)-1]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func awgRange(value string, bits int) (uint64, uint64, error) {
|
||||||
|
parts := strings.Split(value, "-")
|
||||||
|
if len(parts) > 2 {
|
||||||
|
return 0, 0, fmt.Errorf("invalid range")
|
||||||
|
}
|
||||||
|
lo, err := strconv.ParseUint(parts[0], 10, bits)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
hi := lo
|
||||||
|
if len(parts) == 2 {
|
||||||
|
hi, err = strconv.ParseUint(parts[1], 10, bits)
|
||||||
|
}
|
||||||
|
if err != nil || lo > hi {
|
||||||
|
return 0, 0, fmt.Errorf("invalid range")
|
||||||
|
}
|
||||||
|
return lo, hi, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func awgRangeString(lo, hi uint64) string {
|
||||||
|
if lo == hi {
|
||||||
|
return strconv.FormatUint(lo, 10)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d-%d", lo, hi)
|
||||||
|
}
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
package lowlevel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
"github.com/vishvananda/netlink/nl"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
|
|
||||||
|
"github.com/h44z/wg-portal/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
const awgTestPrivateKey = "gI6EdUSYvn8ugXOt8QQD6Yc+JyiZxIhp3GInSWRfWGE="
|
||||||
|
const awgTestPublicKey = "HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw="
|
||||||
|
|
||||||
|
func awgKernelLink(name string) (netlink.Link, error) {
|
||||||
|
return &netlink.GenericLink{Name: name, LinkType: "amneziawg"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func awgTestReply(version uint8, attrs ...*nl.RtAttr) []byte {
|
||||||
|
data := []byte{0, version, 0, 0}
|
||||||
|
for _, attr := range attrs {
|
||||||
|
data = append(data, attr.Serialize()...)
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
func awgTestAttrMap(t *testing.T, data []byte) map[uint16][]byte {
|
||||||
|
t.Helper()
|
||||||
|
attrs, err := nl.ParseRouteAttr(data)
|
||||||
|
require.NoError(t, err)
|
||||||
|
result := map[uint16][]byte{}
|
||||||
|
for _, attr := range attrs {
|
||||||
|
result[attr.Attr.Type&0x3fff] = attr.Value
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func awgTestSerialize(attrs []*nl.RtAttr) []byte {
|
||||||
|
var data []byte
|
||||||
|
for _, attr := range attrs {
|
||||||
|
data = append(data, attr.Serialize()...)
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
func awgTestIPs(address string, prefix byte) *nl.RtAttr {
|
||||||
|
allowed := nl.NewRtAttr(unix.WGPEER_A_ALLOWEDIPS|unix.NLA_F_NESTED, nil)
|
||||||
|
entry := allowed.AddRtAttr(unix.NLA_F_NESTED, nil)
|
||||||
|
ip, family := net.ParseIP(address).To4(), uint16(unix.AF_INET)
|
||||||
|
if ip == nil {
|
||||||
|
ip, family = net.ParseIP(address).To16(), unix.AF_INET6
|
||||||
|
}
|
||||||
|
entry.AddRtAttr(unix.WGALLOWEDIP_A_FAMILY, binary.NativeEndian.AppendUint16(nil, family))
|
||||||
|
entry.AddRtAttr(unix.WGALLOWEDIP_A_IPADDR, ip)
|
||||||
|
entry.AddRtAttr(unix.WGALLOWEDIP_A_CIDR_MASK, []byte{prefix})
|
||||||
|
return allowed
|
||||||
|
}
|
||||||
|
|
||||||
|
func awgTestDeviceReplies(t *testing.T, version uint8) [][]byte {
|
||||||
|
t.Helper()
|
||||||
|
private, err := wgtypes.ParseKey(awgTestPrivateKey)
|
||||||
|
require.NoError(t, err)
|
||||||
|
public, err := wgtypes.ParseKey(awgTestPublicKey)
|
||||||
|
require.NoError(t, err)
|
||||||
|
peers := nl.NewRtAttr(unix.WGDEVICE_A_PEERS|unix.NLA_F_NESTED, nil)
|
||||||
|
peer := peers.AddRtAttr(unix.NLA_F_NESTED, nil)
|
||||||
|
peer.AddRtAttr(unix.WGPEER_A_PUBLIC_KEY, public[:])
|
||||||
|
peer.AddRtAttr(unix.WGPEER_A_RX_BYTES, binary.NativeEndian.AppendUint64(nil, 123))
|
||||||
|
peer.AddRtAttr(unix.WGPEER_A_TX_BYTES, binary.NativeEndian.AppendUint64(nil, 456))
|
||||||
|
peer.AddRtAttr(unix.WGPEER_A_LAST_HANDSHAKE_TIME, append(binary.NativeEndian.AppendUint64(nil, 1700000000), binary.NativeEndian.AppendUint64(nil, 42)...))
|
||||||
|
keepalive := binary.NativeEndian.AppendUint16(nil, 25)
|
||||||
|
if version >= 3 {
|
||||||
|
keepalive = binary.NativeEndian.AppendUint32(nil, 35<<16|25)
|
||||||
|
}
|
||||||
|
peer.AddRtAttr(unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, keepalive)
|
||||||
|
endpoint := make([]byte, 28)
|
||||||
|
binary.NativeEndian.PutUint16(endpoint, unix.AF_INET6)
|
||||||
|
binary.BigEndian.PutUint16(endpoint[2:], 1234)
|
||||||
|
copy(endpoint[8:], net.ParseIP("2001:db8::1").To16())
|
||||||
|
peer.AddRtAttr(unix.WGPEER_A_ENDPOINT, endpoint)
|
||||||
|
peer.AddChild(awgTestIPs("10.0.0.2", 32))
|
||||||
|
header := binary.NativeEndian.AppendUint32(nil, 100)
|
||||||
|
if version == 2 {
|
||||||
|
header = []byte("100-200\x00")
|
||||||
|
}
|
||||||
|
if version == 3 {
|
||||||
|
header = binary.NativeEndian.AppendUint64(nil, 200<<32|100)
|
||||||
|
}
|
||||||
|
first := awgTestReply(version,
|
||||||
|
nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, []byte("awg0\x00")),
|
||||||
|
nl.NewRtAttr(unix.WGDEVICE_A_PRIVATE_KEY, private[:]),
|
||||||
|
nl.NewRtAttr(unix.WGDEVICE_A_PUBLIC_KEY, public[:]),
|
||||||
|
nl.NewRtAttr(unix.WGDEVICE_A_LISTEN_PORT, binary.NativeEndian.AppendUint16(nil, 51820)),
|
||||||
|
nl.NewRtAttr(unix.WGDEVICE_A_FWMARK, binary.NativeEndian.AppendUint32(nil, 0xca6c)),
|
||||||
|
nl.NewRtAttr(9, binary.NativeEndian.AppendUint16(nil, 4)), nl.NewRtAttr(14, header), peers,
|
||||||
|
nl.NewRtAttr(255, []byte("future attribute")),
|
||||||
|
)
|
||||||
|
continuation := nl.NewRtAttr(unix.WGDEVICE_A_PEERS|unix.NLA_F_NESTED, nil)
|
||||||
|
peer = continuation.AddRtAttr(unix.NLA_F_NESTED, nil)
|
||||||
|
peer.AddRtAttr(unix.WGPEER_A_PUBLIC_KEY, public[:])
|
||||||
|
peer.AddChild(awgTestIPs("fd00::2", 128))
|
||||||
|
return [][]byte{first, awgTestReply(version, nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, []byte("awg0\x00")), continuation)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGNativeDeviceVersionsAndMultipartDump(t *testing.T) {
|
||||||
|
for version := uint8(1); version <= 3; version++ {
|
||||||
|
t.Run(fmt.Sprint(version), func(t *testing.T) {
|
||||||
|
client := &AmneziaWGClient{version: version, linkByName: awgKernelLink,
|
||||||
|
exchange: func(command uint8, flags uint16, attrs []*nl.RtAttr) ([][]byte, error) {
|
||||||
|
require.Equal(t, uint8(0), command)
|
||||||
|
require.Equal(t, uint16(unix.NLM_F_DUMP), flags)
|
||||||
|
require.Equal(t, []byte("awg0\x00"), awgTestAttrMap(t, awgTestSerialize(attrs))[unix.WGDEVICE_A_IFNAME])
|
||||||
|
return awgTestDeviceReplies(t, version), nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
device, err := client.Device("awg0")
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, awgTestPrivateKey, device.PrivateKey.String())
|
||||||
|
require.Equal(t, awgTestPublicKey, device.PublicKey.String())
|
||||||
|
require.Equal(t, wgtypes.LinuxKernel, device.Type)
|
||||||
|
require.Equal(t, 51820, device.ListenPort)
|
||||||
|
require.Equal(t, 51820, device.FirewallMark)
|
||||||
|
require.Len(t, device.Peers, 1)
|
||||||
|
peer := device.Peers[0]
|
||||||
|
require.Len(t, peer.AllowedIPs, 2)
|
||||||
|
require.Equal(t, "10.0.0.2/32", peer.AllowedIPs[0].String())
|
||||||
|
require.Equal(t, "fd00::2/128", peer.AllowedIPs[1].String())
|
||||||
|
require.Equal(t, "[2001:db8::1]:1234", peer.Endpoint.String())
|
||||||
|
require.Equal(t, time.Unix(1700000000, 42), peer.LastHandshakeTime)
|
||||||
|
require.Equal(t, int64(123), peer.ReceiveBytes)
|
||||||
|
require.Equal(t, int64(456), peer.TransmitBytes)
|
||||||
|
require.Equal(t, 25*time.Second, peer.PersistentKeepaliveInterval)
|
||||||
|
options, err := client.AmneziaWGOptions("awg0")
|
||||||
|
require.NoError(t, err)
|
||||||
|
header := "100"
|
||||||
|
if version >= 2 {
|
||||||
|
header = "100-200"
|
||||||
|
}
|
||||||
|
require.Equal(t, domain.AmneziaWGOptions{"H1": header, "Jc": "4"}, options)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGKernelSupportWithoutTools(t *testing.T) {
|
||||||
|
t.Setenv("PATH", t.TempDir())
|
||||||
|
missing := errors.New("family not found")
|
||||||
|
_, err := amneziaWGFamily(func(name string) (*netlink.GenlFamily, error) {
|
||||||
|
require.Equal(t, "amneziawg", name)
|
||||||
|
return nil, missing
|
||||||
|
})
|
||||||
|
require.ErrorIs(t, err, missing)
|
||||||
|
require.ErrorContains(t, err, "modprobe amneziawg")
|
||||||
|
for _, version := range []uint32{1, 2, 3} {
|
||||||
|
family, err := amneziaWGFamily(func(string) (*netlink.GenlFamily, error) { return &netlink.GenlFamily{ID: 42, Version: version}, nil })
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, version, family.Version)
|
||||||
|
}
|
||||||
|
_, err = amneziaWGFamily(func(string) (*netlink.GenlFamily, error) { return &netlink.GenlFamily{Version: 4}, nil })
|
||||||
|
require.ErrorContains(t, err, "unsupported")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGNativeConfigurationFlagsAndExplicitZeroes(t *testing.T) {
|
||||||
|
t.Setenv("PATH", t.TempDir())
|
||||||
|
key, err := wgtypes.ParseKey(awgTestPublicKey)
|
||||||
|
require.NoError(t, err)
|
||||||
|
private, err := wgtypes.ParseKey(awgTestPrivateKey)
|
||||||
|
require.NoError(t, err)
|
||||||
|
var captured []byte
|
||||||
|
client := &AmneziaWGClient{version: 3, linkByName: awgKernelLink,
|
||||||
|
exchange: func(command uint8, flags uint16, attrs []*nl.RtAttr) ([][]byte, error) {
|
||||||
|
require.Equal(t, uint8(1), command, "configuration must not read and rewrite existing peers")
|
||||||
|
require.Equal(t, uint16(unix.NLM_F_ACK), flags)
|
||||||
|
captured = awgTestSerialize(attrs)
|
||||||
|
return nil, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
zero, mark, keepalive := 0, -1, time.Duration(0)
|
||||||
|
require.NoError(t, client.ConfigureAmneziaWGDevice("awg0", wgtypes.Config{
|
||||||
|
PrivateKey: &private, ListenPort: &zero, FirewallMark: &mark,
|
||||||
|
Peers: []wgtypes.PeerConfig{{PublicKey: key, UpdateOnly: true, ReplaceAllowedIPs: true, PresharedKey: &wgtypes.Key{}, PersistentKeepaliveInterval: &keepalive}},
|
||||||
|
}, domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4"}))
|
||||||
|
attrs := awgTestAttrMap(t, captured)
|
||||||
|
require.Equal(t, private[:], attrs[unix.WGDEVICE_A_PRIVATE_KEY])
|
||||||
|
require.Equal(t, []byte{0, 0}, attrs[unix.WGDEVICE_A_LISTEN_PORT])
|
||||||
|
require.Equal(t, []byte{255, 255, 255, 255}, attrs[unix.WGDEVICE_A_FWMARK])
|
||||||
|
require.NotContains(t, attrs, uint16(unix.WGDEVICE_A_FLAGS))
|
||||||
|
peers, err := nl.ParseRouteAttr(attrs[unix.WGDEVICE_A_PEERS])
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Len(t, peers, 1)
|
||||||
|
peer := awgTestAttrMap(t, peers[0].Value)
|
||||||
|
require.Equal(t, uint32(unix.WGPEER_F_UPDATE_ONLY|unix.WGPEER_F_REPLACE_ALLOWEDIPS), binary.NativeEndian.Uint32(peer[unix.WGPEER_A_FLAGS]))
|
||||||
|
require.Equal(t, make([]byte, 32), peer[unix.WGPEER_A_PRESHARED_KEY])
|
||||||
|
require.Equal(t, make([]byte, 4), peer[unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL])
|
||||||
|
require.NotContains(t, peer, uint16(unix.WGPEER_A_ALLOWEDIPS))
|
||||||
|
// Removal is a native peer flag, and needs no extra process or state read.
|
||||||
|
require.NoError(t, client.ConfigureDevice("awg0", wgtypes.Config{Peers: []wgtypes.PeerConfig{{PublicKey: key, Remove: true}}}))
|
||||||
|
peers, err = nl.ParseRouteAttr(awgTestAttrMap(t, captured)[unix.WGDEVICE_A_PEERS])
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, uint32(unix.WGPEER_F_REMOVE_ME), binary.NativeEndian.Uint32(awgTestAttrMap(t, peers[0].Value)[unix.WGPEER_A_FLAGS]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGNativeBatchingPreservesReplacementSemantics(t *testing.T) {
|
||||||
|
key, err := wgtypes.ParseKey(awgTestPublicKey)
|
||||||
|
require.NoError(t, err)
|
||||||
|
ips := make([]net.IPNet, 4096)
|
||||||
|
for i := range ips {
|
||||||
|
ips[i] = net.IPNet{IP: net.ParseIP(fmt.Sprintf("fd00::%x", i)), Mask: net.CIDRMask(128, 128)}
|
||||||
|
}
|
||||||
|
interval := 25 * time.Second
|
||||||
|
cfg := wgtypes.Config{ReplacePeers: true, Peers: []wgtypes.PeerConfig{{PublicKey: key, UpdateOnly: true, ReplaceAllowedIPs: true, PersistentKeepaliveInterval: &interval, AllowedIPs: ips}}}
|
||||||
|
batches, err := amneziaWGConfigBatches("awg0", cfg, domain.AmneziaWGOptions{"Jc": "4"}, 3)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Greater(t, len(batches), 1)
|
||||||
|
firstPeer, count := true, 0
|
||||||
|
for i, batch := range batches {
|
||||||
|
data := awgTestSerialize(batch)
|
||||||
|
require.LessOrEqual(t, len(data)+4, awgMaxPayload)
|
||||||
|
attrs := awgTestAttrMap(t, data)
|
||||||
|
if i == 0 {
|
||||||
|
require.Equal(t, uint32(unix.WGDEVICE_F_REPLACE_PEERS), binary.NativeEndian.Uint32(attrs[unix.WGDEVICE_A_FLAGS]))
|
||||||
|
require.Contains(t, attrs, uint16(9))
|
||||||
|
} else {
|
||||||
|
require.NotContains(t, attrs, uint16(unix.WGDEVICE_A_FLAGS))
|
||||||
|
require.NotContains(t, attrs, uint16(9))
|
||||||
|
}
|
||||||
|
peers, err := nl.ParseRouteAttr(attrs[unix.WGDEVICE_A_PEERS])
|
||||||
|
require.NoError(t, err)
|
||||||
|
for _, raw := range peers {
|
||||||
|
peer := awgTestAttrMap(t, raw.Value)
|
||||||
|
flags := binary.NativeEndian.Uint32(peer[unix.WGPEER_A_FLAGS])
|
||||||
|
require.NotZero(t, flags&unix.WGPEER_F_UPDATE_ONLY)
|
||||||
|
require.Equal(t, firstPeer, flags&unix.WGPEER_F_REPLACE_ALLOWEDIPS != 0)
|
||||||
|
if firstPeer {
|
||||||
|
require.Equal(t, uint32(25<<16|25), binary.NativeEndian.Uint32(peer[unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL]))
|
||||||
|
} else {
|
||||||
|
require.NotContains(t, peer, uint16(unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL))
|
||||||
|
}
|
||||||
|
entries, err := nl.ParseRouteAttr(peer[unix.WGPEER_A_ALLOWEDIPS])
|
||||||
|
require.NoError(t, err)
|
||||||
|
count += len(entries)
|
||||||
|
firstPeer = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require.Equal(t, len(ips), count)
|
||||||
|
require.True(t, cfg.ReplacePeers)
|
||||||
|
require.True(t, cfg.Peers[0].ReplaceAllowedIPs)
|
||||||
|
require.Len(t, cfg.Peers[0].AllowedIPs, 4096)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGNativeLinkIsolationAndErrors(t *testing.T) {
|
||||||
|
for _, kind := range []string{"wireguard", "tun"} {
|
||||||
|
client := &AmneziaWGClient{version: 3,
|
||||||
|
linkByName: func(name string) (netlink.Link, error) {
|
||||||
|
return &netlink.GenericLink{Name: name, LinkType: kind}, nil
|
||||||
|
},
|
||||||
|
exchange: func(uint8, uint16, []*nl.RtAttr) ([][]byte, error) {
|
||||||
|
t.Fatal("must not touch other link types")
|
||||||
|
return nil, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
_, err := client.Device("wg0")
|
||||||
|
require.ErrorContains(t, err, "not an AmneziaWG kernel device")
|
||||||
|
require.Error(t, client.ConfigureDevice("wg0", wgtypes.Config{}))
|
||||||
|
}
|
||||||
|
client := &AmneziaWGClient{version: 3, linkByName: awgKernelLink,
|
||||||
|
exchange: func(uint8, uint16, []*nl.RtAttr) ([][]byte, error) { return nil, unix.ENODEV },
|
||||||
|
}
|
||||||
|
_, err := client.Device("missing")
|
||||||
|
require.ErrorIs(t, err, os.ErrNotExist)
|
||||||
|
require.ErrorIs(t, client.ConfigureDevice("missing", wgtypes.Config{}), os.ErrNotExist)
|
||||||
|
client.links = func() ([]netlink.Link, error) {
|
||||||
|
wg, _ := awgKernelLink("gone")
|
||||||
|
return []netlink.Link{&netlink.Dummy{Name: "ordinary"}, wg}, nil
|
||||||
|
}
|
||||||
|
devices, err := client.Devices()
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Empty(t, devices)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGRejectsInvalidConfigurationBeforeSending(t *testing.T) {
|
||||||
|
client := &AmneziaWGClient{version: 1, linkByName: awgKernelLink,
|
||||||
|
exchange: func(uint8, uint16, []*nl.RtAttr) ([][]byte, error) {
|
||||||
|
t.Fatal("invalid input sent to kernel")
|
||||||
|
return nil, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, options := range []domain.AmneziaWGOptions{{"H1": "100-200"}, {"I1": "<b 0x12>"}, {"RekeyTimeout": "5"}, {"Jc": "65536"}, {"I1": "bad\n[Peer]"}} {
|
||||||
|
require.Error(t, client.ConfigureAmneziaWGDevice("awg0", wgtypes.Config{}, options))
|
||||||
|
}
|
||||||
|
badPort := 65536
|
||||||
|
require.Error(t, client.ConfigureDevice("awg0", wgtypes.Config{ListenPort: &badPort}))
|
||||||
|
require.Error(t, client.ConfigureDevice("awg0", wgtypes.Config{Peers: []wgtypes.PeerConfig{{Endpoint: &net.UDPAddr{IP: nil, Port: 1}}}}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGNativeOptionEncodings(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
version uint8
|
||||||
|
value string
|
||||||
|
wire []byte
|
||||||
|
}{
|
||||||
|
{1, "305419896", binary.NativeEndian.AppendUint32(nil, 0x12345678)},
|
||||||
|
{2, "100-200", []byte("100-200\x00")},
|
||||||
|
{3, "100-200", binary.NativeEndian.AppendUint64(nil, 200<<32|100)},
|
||||||
|
} {
|
||||||
|
attrs, err := encodeAmneziaWGOptions(domain.AmneziaWGOptions{"H1": test.value}, test.version)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, test.wire, awgTestAttrMap(t, awgTestSerialize(attrs))[14])
|
||||||
|
}
|
||||||
|
options := domain.AmneziaWGOptions{"Jc": "4", "S3": "16", "I1": "<b 0x1234>", "ContentPaddingAddition": "10-20", "RekeyTimeout": "5", "RandomTrailers": "on", "DisableCookies": "off", "HeaderProtectionKey": awgTestPrivateKey}
|
||||||
|
attrs, err := encodeAmneziaWGOptions(options, 3)
|
||||||
|
require.NoError(t, err)
|
||||||
|
_, parsed, err := parseAmneziaWGDevice([][]byte{awgTestReply(3, attrs...)}, 3)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, options, parsed)
|
||||||
|
encoded := awgTestAttrMap(t, awgTestSerialize(attrs))
|
||||||
|
require.Equal(t, uint32(20<<16|10), binary.NativeEndian.Uint32(encoded[27]))
|
||||||
|
require.Equal(t, uint32(5<<16|5), binary.NativeEndian.Uint32(encoded[29]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGSockaddrsAndTimes(t *testing.T) {
|
||||||
|
for _, endpoint := range []*net.UDPAddr{
|
||||||
|
{IP: net.ParseIP("192.0.2.1"), Port: 51820},
|
||||||
|
{IP: net.ParseIP("2001:db8::1"), Port: 1234},
|
||||||
|
{IP: net.ParseIP("fe80::1"), Port: 1234, Zone: "3"},
|
||||||
|
} {
|
||||||
|
data, err := encodeAmneziaWGSockaddr(endpoint)
|
||||||
|
require.NoError(t, err)
|
||||||
|
parsed, err := parseAmneziaWGSockaddr(data)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, endpoint.String(), parsed.String())
|
||||||
|
}
|
||||||
|
zero, err := parseAmneziaWGTime(make([]byte, 16))
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.True(t, zero.IsZero())
|
||||||
|
parsed, err := parseAmneziaWGTime(append(binary.NativeEndian.AppendUint32(nil, 1700000000), binary.NativeEndian.AppendUint32(nil, 42)...))
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, time.Unix(1700000000, 42), parsed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmneziaWGMalformedMessages(t *testing.T) {
|
||||||
|
for _, data := range [][]byte{
|
||||||
|
{}, {0, 1, 0}, {0, 1, 0, 0, 1}, {0, 1, 0, 0, 3, 0, 0, 0},
|
||||||
|
awgTestReply(1, nl.NewRtAttr(unix.WGDEVICE_A_PRIVATE_KEY, []byte{1})),
|
||||||
|
awgTestReply(3, nl.NewRtAttr(14, []byte{1})),
|
||||||
|
} {
|
||||||
|
_, _, err := parseAmneziaWGDevice([][]byte{data}, 3)
|
||||||
|
require.Error(t, err)
|
||||||
|
require.NotContains(t, err.Error(), awgTestPrivateKey)
|
||||||
|
}
|
||||||
|
_, err := parseAmneziaWGPeer(nil, 3)
|
||||||
|
require.ErrorContains(t, err, "public key")
|
||||||
|
_, err = parseAmneziaWGAllowedIPs(nl.NewRtAttr(unix.NLA_F_NESTED, nil).Serialize())
|
||||||
|
require.Error(t, err)
|
||||||
|
_, err = parseAmneziaWGTime([]byte{1})
|
||||||
|
require.Error(t, err)
|
||||||
|
_, err = parseAmneziaWGSockaddr([]byte{1})
|
||||||
|
require.Error(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func FuzzAmneziaWGDeviceDecoder(f *testing.F) {
|
||||||
|
f.Add([]byte{0, 3, 0, 0})
|
||||||
|
f.Add(awgTestReply(3, nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, []byte("awg0\x00"))))
|
||||||
|
f.Fuzz(func(t *testing.T, data []byte) { _, _, _ = parseAmneziaWGDevice([][]byte{data}, 3) })
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user