fix: hardening

This commit is contained in:
FUFSoB committed 2026-10-05 22:44:09 +05:00
1 parent 017a947a18
commit a435942b4f
168 files changed
+9166 -1644

No files matched your search

+68 -11
View File
@@ -10,9 +10,11 @@ on:
type: boolean
default: false
# Read-only by default: the job that runs fetched code (flake updates, update-pins.sh, nix
# builds and checks) never holds a token that can push. Only the last job may, and it runs
# nothing it fetched: it applies the first job's diff and opens the pull request.
permissions:
contents: write
pull-requests: write
contents: read
concurrency:
group: dependency-updates
@@ -21,12 +23,18 @@ concurrency:
jobs:
update-dependencies:
runs-on: ubuntu-latest
outputs:
has_changes: ${{ steps.changes.outputs.has_changes }}
steps:
# No token left in .git/config for the steps that run fetched code (flake updates,
# update-pins.sh, nix builds); create-pull-request authenticates on its own.
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
persist-credentials: false
- name: Install Nix
uses: DeterminateSystems/nix-installer-action@v22
uses: DeterminateSystems/nix-installer-action@ef8a148080ab6020fd15196c2084a2eea5ff2d25 # v22
- name: Decide whether nixpkgs should be updated
id: nixpkgs_gate
@@ -112,9 +120,62 @@ jobs:
} > "$RUNNER_TEMP/pr-body.md"
cat "$RUNNER_TEMP/pr-body.md" >> "$GITHUB_STEP_SUMMARY"
- name: Create or update pull request
# The changes as a patch, new files included, for the job that may push.
- name: Export the changes
if: steps.changes.outputs.has_changes == 'true'
uses: peter-evans/create-pull-request@v8
run: |
set -euo pipefail
git add -A -- flake.lock '*.nix'
git diff --cached --binary > "$RUNNER_TEMP/dependency-updates.patch"
cp "$RUNNER_TEMP/pr-body.md" "$RUNNER_TEMP/dependency-updates.md"
- name: Upload the changes
if: steps.changes.outputs.has_changes == 'true'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: dependency-updates
path: |
${{ runner.temp }}/dependency-updates.patch
${{ runner.temp }}/dependency-updates.md
retention-days: 1
- name: No dependency changes
if: steps.changes.outputs.has_changes != 'true'
run: echo "No dependency updates detected."
open-pull-request:
needs: update-dependencies
if: needs.update-dependencies.outputs.has_changes == 'true'
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
persist-credentials: false
- name: Download the changes
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: dependency-updates
path: ${{ runner.temp }}/dependency-updates
# Data only: git applies the diff; nothing from it runs.
- name: Apply the changes
run: |
set -euo pipefail
git apply --index "$RUNNER_TEMP/dependency-updates/dependency-updates.patch"
# The commit takes the whole index, whatever add-paths says: refuse a patch
# that reaches past the lock file and the Nix files the updates and nix fmt touch.
if git diff --cached --name-only | grep -vxE 'flake\.lock|.+\.nix'; then
echo "The patch changes files other than flake.lock and *.nix (above)." >&2
exit 1
fi
- name: Create or update pull request
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
with:
branch: ci/update-dependencies
delete-branch: false
@@ -124,11 +185,7 @@ jobs:
*.nix
commit-message: "chore(deps): refresh flake inputs and pinned sources"
title: "chore(deps): refresh flake inputs and pinned sources"
body-path: ${{ runner.temp }}/pr-body.md
body-path: ${{ runner.temp }}/dependency-updates/dependency-updates.md
labels: |
dependencies
nix
- name: No dependency changes
if: steps.changes.outputs.has_changes != 'true'
run: echo "No dependency updates detected."
+1 -1
View File
@@ -173,7 +173,7 @@ Changes and secrets need root or the userControl group.
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
show or override the routing mode
proxy subs [list|update] subscriptions; update refetches them
proxy subs add [tag] <url> add a subscription (no tag: named after its host)
proxy subs add [tag] <url|-> add a subscription (no tag: named after its host; -: stdin)
proxy subs rm <tag> remove a runtime subscription
proxy subs link <tag> [--qr] its URL
proxy rulesets [list|update] rule sets and when they were fetched; update refetches
+2
View File
@@ -20,6 +20,7 @@
mkpasswd,
nix,
nixos-install-tools,
openssh,
openssl,
systemd,
util-linux,
@@ -43,6 +44,7 @@ import ./script.nix { inherit lib writeShellApplication; } {
mkpasswd
nix
nixos-install-tools
openssh
openssl
systemd
util-linux
+30 -5
View File
@@ -107,7 +107,8 @@ ask_all() {
done
while true; do
ask SSH_PORT "SSH port" "22"
if [[ $SSH_PORT =~ ^[0-9]+$ ]] && ((SSH_PORT >= 1 && SSH_PORT <= 65535)) &&
# No leading zero: bash would read 0443 as octal, Nix as 443.
if [[ $SSH_PORT =~ ^[1-9][0-9]{0,4}$ ]] && ((SSH_PORT <= 65535)) &&
[[ ! " 80 443 2053 8443 18533 18534 18535 " == *" $SSH_PORT "* ]]; then
break
fi
@@ -149,7 +150,7 @@ ask_all() {
warn "$DOMAIN does not resolve to $PUBLIC_IP (yet). The certificate order retries until it does."
ask_yes KEEP_DOMAIN "Keep $DOMAIN anyway" "y"
[[ $KEEP_DOMAIN == true ]] && break
unset PSI_DOMAIN PSI_KEEP_DOMAIN
retry "Give another domain, or none." DOMAIN KEEP_DOMAIN
forget KEEP_DOMAIN
done
@@ -174,18 +175,30 @@ ask_all() {
warn "$REALITY_SNI did not answer over TLS 1.3 from here; REALITY needs TLS 1.3 and HTTP/2."
ask_yes KEEP_SNI "Keep $REALITY_SNI anyway" "n"
[[ $KEEP_SNI == true ]] && break
unset PSI_REALITY_SNI PSI_KEEP_SNI
retry "Give another REALITY site." REALITY_SNI KEEP_SNI
forget KEEP_SNI
done
# --- Disk ---------------------------------------------------------------------
step "Disk"
mapfile -t disks < <(lsblk -dnpo NAME,TYPE,RO | awk '$2 == "disk" && $3 == 0 && $1 !~ /\/(zram|loop|sr|fd)[0-9]/ { print $1 }')
# The medium this installer runs from, which some VPS panels attach as a writable disk
# rather than a CD: erasing it would kill the install halfway.
local live_majmin live_disk=""
if live_majmin=$(findmnt -no MAJ:MIN /iso 2>/dev/null) && [[ -e /dev/block/$live_majmin ]]; then
live_disk=$(lsblk -ndpo PKNAME "/dev/block/$live_majmin" 2>/dev/null || true)
[[ -n $live_disk ]] || live_disk=$(readlink -f "/dev/block/$live_majmin")
fi
mapfile -t disks < <(lsblk -dnpo NAME,TYPE,RO | awk -v live="$live_disk" '$2 == "disk" && $3 == 0 && $1 != live && $1 !~ /\/(zram|loop|sr|fd)[0-9]/ { print $1 }')
if ((${#disks[@]} == 0)); then
warn "No writable disk found."
exit 1
fi
lsblk -dpo NAME,SIZE,MODEL "${disks[@]}"
# Unattended, the disk to erase is never guessed, even when there is only one.
if [[ -n ${PSI_UNATTENDED-} && -z ${PSI_DISK-} ]]; then
warn "PSI_UNATTENDED: set PSI_DISK to the disk to erase."
exit 1
fi
while true; do
ask DISK "Disk to install on (ERASED)" "$(if ((${#disks[@]} == 1)); then printf '%s' "${disks[0]}"; fi)"
[[ -b $DISK && " ${disks[*]} " == *" $DISK "* ]] && break
@@ -260,6 +273,11 @@ fi
xray uuid >"$MNT$SECRETS_DIR/uuid"
printf '%s\n' "$private_key" >"$MNT$SECRETS_DIR/reality-key"
)
# The SSH host keys, made here rather than by sshd on the first boot, so the first
# login (with the password, when no key was given) can be checked against them.
install -d -m 0755 "$MNT/etc/ssh"
ssh-keygen -q -t ed25519 -N "" -C "root@$HOST_NAME" -f "$MNT/etc/ssh/ssh_host_ed25519_key"
ssh-keygen -q -t rsa -b 4096 -N "" -C "root@$HOST_NAME" -f "$MNT/etc/ssh/ssh_host_rsa_key"
short_id=$(openssl rand -hex 8)
ws_path="/$(openssl rand -hex 6)"
@@ -267,6 +285,9 @@ ws_path="/$(openssl rand -hex 6)"
step "Writing /etc/nixos"
etc_nixos="$MNT/etc/nixos"
# Root's alone: it names the REALITY shortId and the WS path, which a local user could
# otherwise read and probe with.
install -m 0600 /dev/null "$etc_nixos/host.nix"
cat >"$etc_nixos/host.nix" <<HOST
# Written by proxy-suite-install on $(date -u +%Y-%m-%d). Edit it, then apply with:
# sudo nixos-rebuild switch --flake /etc/nixos
@@ -360,7 +381,9 @@ TMPDIR="$MNT/tmp" nixos-install \
rm -rf "$MNT/tmp"
step "Setting the admin password"
password="$(xkcdpass -n 3 --min 4 --max 6 -d -)-$((RANDOM % 90 + 10))"
# Four words: three of 4-6 letters and two digits come to some 40 bits, which SSH takes
# guesses against whenever no key was given.
password="$(xkcdpass -n 4 --min 4 --max 6 -d -)-$((RANDOM % 90 + 10))"
password=${password,,}
hash=$(mkpasswd -m yescrypt --stdin <<<"$password")
nixos-enter --root "$MNT" -- usermod -p "$hash" "$ADMIN_USER"
@@ -374,6 +397,8 @@ cat <<DONE
SSH: ssh -p $SSH_PORT $ADMIN_USER@$PUBLIC_IP
User: $ADMIN_USER
Host keys (compare with what ssh shows on the first login):
$(for key in "$MNT"/etc/ssh/ssh_host_{ed25519,rsa}_key.pub; do printf ' %s\n' "$(ssh-keygen -lf "$key")"; done)
DONE
printf ' Password: \033[1;32m%s\033[0m\n\n' "$password"
cat <<DONE
+13 -2
View File
@@ -56,6 +56,16 @@ ask() {
if [[ -n ${3+x} && -z $3 ]]; then
__optional=true
fi
# Unattended never reads stdin, where it would hang on a terminal or take the default
# unseen: a missing answer takes the default, and a question without one fails.
if [[ -n ${PSI_UNATTENDED-} ]]; then
if [[ -z $__default && $__optional == false ]]; then
warn "PSI_UNATTENDED: $__preset is not set, and \"$2\" has no default."
exit 1
fi
printf -v "$1" '%s' "$__default"
return 0
fi
if [[ -n ${REMEMBERED[$1]-} ]]; then
__default=${REMEMBERED[$1]}
fi
@@ -119,7 +129,8 @@ reject() {
is_ipv4() {
local IFS=. octet
[[ $1 =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || return 1
# No leading zeros: bash would read 010 as octal, networkd as written.
[[ $1 =~ ^(0|[1-9][0-9]{0,2})(\.(0|[1-9][0-9]{0,2})){3}$ ]] || return 1
for octet in $1; do ((octet <= 255)) || return 1; done
}
@@ -137,7 +148,7 @@ is_dns_list() {
mask_to_prefix() {
local mask=$1 IFS=. octet bits=0
if [[ $mask =~ ^[0-9]+$ ]]; then
((mask <= 32)) && printf '%s' "$mask" && return 0
[[ $mask =~ ^(0|[1-9][0-9]?)$ ]] && ((mask <= 32)) && printf '%s' "$mask" && return 0
return 1
fi
is_ipv4 "$mask" || return 1
+18
View File
@@ -214,6 +214,24 @@ in
};
config = lib.mkIf cfg.enable {
# Two listeners on one port: whichever binds second fails, and with it SSH may go.
assertions = [
{
assertion =
let
taken = [
80
cfg.sshPort
cfg.ports.reality
cfg.ports.tls
cfg.ports.ws
];
in
lib.unique taken == taken;
message = "proxy-suite server: sshPort, ports.reality, ports.tls, ports.ws and 80 (ACME) must all differ";
}
];
disko.devices =
lib.mkIf cfg.disko.enable
(import ./disk-layout.nix {
+27 -4
View File
@@ -9,6 +9,7 @@ Part of the [proxy-suite options reference](./index.md).
- inbounds
- [enable](#services-proxy-suite-inbounds-enable)
- [package](#services-proxy-suite-inbounds-package)
- [accessLog](#services-proxy-suite-inbounds-accesslog)
- [listeners](#services-proxy-suite-inbounds-listeners)
- `<name>`
- [acceptProxyProtocol](#services-proxy-suite-inbounds-listeners-name-acceptproxyprotocol)
@@ -172,6 +173,16 @@ XRay package that runs the inbounds, whichever client backend is used\.
**Default:** proxy-suite’s ` xray ` (` pkgs/xray.nix `)\
**Example:** `pkgs.xray`
<a id="services-proxy-suite-inbounds-accesslog"></a>
## services\.proxy-suite\.inbounds\.accessLog
Log every connection, with the user, their address and the site, to the journal of
proxy-suite-inbounds: who went where, for anyone who can read the journal\. On with
` proxy.autoProxy ` whatever this says, which learns from those lines\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-inbounds-listeners"></a>
## services\.proxy-suite\.inbounds\.listeners
@@ -531,7 +542,7 @@ clients the rest\.
Tunnel IPv6 subnet (ULA)\. ` null `: IPv4 only\. With ` mode = "lan" ` it turns on IPv6
forwarding, which stops this host from configuring itself from router advertisements\.
**Type:** null or string\
**Type:** null or IPv6 CIDR\
**Default:** `null`\
**Example:** `"fd66:66::/64"`
@@ -1106,7 +1117,10 @@ Open the firewall for every listener not on loopback\.
<a id="services-proxy-suite-inbounds-routing-blockprivate"></a>
## services\.proxy-suite\.inbounds\.routing\.blockPrivate
Block private and loopback addresses, so clients cannot reach this host’s LAN or local services\.
Block private and loopback addresses, so clients cannot reach this host’s LAN or local
services\. Off, the LAN is open but this host is not\. Either way, this host’s own
addresses (loopback, and its public ones as its interfaces carry them at start) are
reachable only on the listener ports and ` serverPorts `, whichever ` via ` a client takes\.
**Type:** boolean\
**Default:** `true`
@@ -1228,7 +1242,10 @@ fallbacks\. Members of ` userControl.group ` need the “inbounds” scope\.
## services\.proxy-suite\.inbounds\.runtime\.fallbackDests
` dest ` values a runtime listener’s fallbacks may use, such as a decoy site\. A
fallback to a ` listener ` must name another runtime listener\.
fallback to a ` listener ` must name another runtime listener\. A runtime listener’s
` reality.dest ` may be any public site on port 443; one on another port, on this host
or on a private network must be listed here\. Its ` hysteria.masquerade ` must be a
public http(s) site, on port 80 or 443 unless its ` host:port ` is listed here\.
**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string)\
**Default:** `[ ]`\
@@ -1336,7 +1353,13 @@ covers that name and every name under it, for a host behind a wildcard record\.
Ports of this host’s other services that clients reach through the tunnel on
` serverAddress ` and ` serverAliases `, such as mail, beside the listeners’ own\. Direct
like those: a connection to this host from itself skips its firewall, so list only
what the firewall already opens to the internet\. TCP and UDP alike\.
what the firewall already opens to the internet\. TCP and UDP alike\. Any other port on
any address of this host is refused where the inbounds dial “direct” themselves; the
addresses are read as the inbounds start, so restart them after one changes (DHCP)\.
Without ` routing.serverSource ` these connections come from this host’s own address,
which its services may trust: a mail server that relays for its own host (Postfix’s
default ` mynetworks `) relays for every inbound user then\. Set ` serverSource `, or keep
such services from trusting this host’s own addresses\.
**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string matching the pattern \[0-9]±\[0-9]+)\
**Default:** `[ ]`\
+21 -1
View File
@@ -23,6 +23,7 @@ Update the module option docs there instead of editing these files by hand.
| [userControl](./userControl.md) | Let a group use `proxy-ctl` without root. |
| [gui](./gui.md) | The desktop app with a tray icon. |
| [tui](./tui.md) | The `proxy-tui` terminal UI. |
| [tools](./tools.md) | Heavy helpers `proxy-ctl` can do without: lnav and curl-impersonate. |
<a id="services-proxy-suite-enable"></a>
## services\.proxy-suite\.enable
@@ -69,6 +70,7 @@ services.proxy-suite = {
refreshInterval = 3;
};
inbounds = {
accessLog = false;
enable = false;
listeners = { };
openFirewall = true;
@@ -109,7 +111,12 @@ services.proxy-suite = {
users = { };
};
killSwitch = {
allowedSubnets = config.services.proxy-suite.proxy.tproxy.localSubnets;
directFallbacks = true;
enable = false;
timeSyncUsers = ‹the users of the enabled timesyncd, chrony, ntp and openntpd on NixOS; elsewhere
[ "systemd-timesync" "chrony" "_chrony" "ntp" "ntpsec" ]
›;
};
perAppRouting = {
createDefaultProfiles = false;
@@ -228,6 +235,11 @@ services.proxy-suite = {
ruleSets = { };
rules = [ ];
};
runtimeSubscriptions = {
allowHttp = false;
allowInsecure = false;
allowPrivateServers = false;
};
selection = "first";
selectionExclude = [ ];
singBox = {
@@ -281,7 +293,7 @@ services.proxy-suite = {
user = null;
};
serviceUser = "proxy-suite-daemon";
strictHostKeyChecking = "accept-new";
strictHostKeyChecking = "yes";
};
tgWsProxy = {
bufferKiB = 256;
@@ -310,6 +322,14 @@ services.proxy-suite = {
secret = null;
secretFile = null;
};
tools = {
curlImpersonate = {
enable = ‹true, false on nix-on-droid›;
};
lnav = {
enable = ‹true, false on nix-on-droid›;
};
};
tor = {
asOutbound = false;
bridges = {
+44 -3
View File
@@ -8,14 +8,55 @@ Part of the [proxy-suite options reference](./index.md).
- killSwitch
- [enable](#services-proxy-suite-killswitch-enable)
- [allowedSubnets](#services-proxy-suite-killswitch-allowedsubnets)
- [directFallbacks](#services-proxy-suite-killswitch-directfallbacks)
- [timeSyncUsers](#services-proxy-suite-killswitch-timesyncusers)
<a id="services-proxy-suite-killswitch-enable"></a>
## services\.proxy-suite\.killSwitch\.enable
Block outgoing traffic that bypasses the active global tunnel (TUN, TProxy or a global
AmneziaWG profile), including while it restarts or after it fails\. LAN, DHCP and NTP stay
open; ` proxy.tproxy.lanInterfaces ` devices keep the LAN but lose the internet\. Only turning
the tunnel off, or ` proxy-ctl killswitch off `, lifts it\.
AmneziaWG profile) from boot until the tunnel is up, while it restarts and after it
fails\. LAN, DHCP and the time daemons’ NTP stay open\. Forwarded traffic TProxy does not
divert reaches the LAN only from ` proxy.tproxy.lanInterfaces `\. With TUN or a global
AmneziaWG profile configured, containers’ and VMs’ traffic is held to the LAN too while
neither that tunnel nor TProxy is up\. Only turning the tunnel off with ` proxy-ctl `, or
` proxy-ctl killswitch off `, lifts it, until the next boot or tunnel start\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-killswitch-allowedsubnets"></a>
## services\.proxy-suite\.killSwitch\.allowedSubnets
Networks the kill switch leaves open besides the private and reserved ranges, such as
a routed IPv6 prefix on a VM bridge, whichever global mode is on\. The default keeps
what TProxy leaves out reachable; set it to open a network without also taking it out
of TProxy\.
**Type:** list of IPv4 or IPv6 address or CIDR\
**Default:** `config.services.proxy-suite.proxy.tproxy.localSubnets`\
**Example:** `[ "192.168.0.0/16" "2001:db8:1::/64" ]`
<a id="services-proxy-suite-killswitch-directfallbacks"></a>
## services\.proxy-suite\.killSwitch\.directFallbacks
Whether, with the kill switch on, a subscription that cannot be fetched through the
tunnel is fetched once more directly, and WARP registers directly when the local proxy
cannot carry it\. Either shows that server this host’s own address\. Off, both go through
the tunnel or not at all: a cold start with nothing cached then has no outbounds from
that subscription, and a WARP device that is itself the tunnel cannot register\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-killswitch-timesyncusers"></a>
## services\.proxy-suite\.killSwitch\.timeSyncUsers
Users that may send NTP (UDP port 123) past the kill switch\. Users that do not exist
are skipped when it starts\. A daemon sending from port 123 itself, as ntpd does, needs
no entry\.
**Type:** list of string\
**Default:** the users of the enabled timesyncd, chrony, ntp and openntpd on NixOS; elsewhere ` [ "systemd-timesync" "chrony" "_chrony" "ntp" "ntpsec" ] `\
**Example:** `[ "chrony" ]`
+6 -6
View File
@@ -141,7 +141,7 @@ Firewall mark for wrapped apps’ traffic\.
Subnets that skip the proxy (DNS still goes through it)\.
**Type:** list of string\
**Type:** list of IPv4 or IPv6 address or CIDR\
**Default:** `[ "192.168.0.0/16" ]`\
**Example:** `[ "192.168.0.0/16" "10.0.0.0/8" ]`
@@ -164,9 +164,9 @@ Whether to enable per-app TUN\.
<a id="services-proxy-suite-perapprouting-tun-address"></a>
## services\.proxy-suite\.perAppRouting\.tun\.address
Interface address (CIDR)\.
Interface IPv4 address (CIDR)\.
**Type:** string\
**Type:** IPv4 CIDR\
**Default:** `"172.20.0.1/30"`
<a id="services-proxy-suite-perapprouting-tun-fwmark"></a>
@@ -182,7 +182,7 @@ Firewall mark for wrapped apps’ traffic\.
Interface name\.
**Type:** string\
**Type:** network interface name\
**Default:** `"psperapptun0"`
<a id="services-proxy-suite-perapprouting-tun-localsubnets"></a>
@@ -190,7 +190,7 @@ Interface name\.
Subnets that skip the proxy (DNS still goes through it)\.
**Type:** list of string\
**Type:** list of IPv4 or IPv6 address or CIDR\
**Default:** `[ "192.168.0.0/16" ]`\
**Example:** `[ "192.168.0.0/16" "10.0.0.0/8" ]`
@@ -217,7 +217,7 @@ Subnets an app run ` --via ` an AmneziaWG interface (an “interface” outbound
profile) still reaches directly; DNS still goes through the tunnel\. Every other
address goes through it, private ones included, as the server may serve them\.
**Type:** list of string\
**Type:** list of IPv4 or IPv6 address or CIDR\
**Default:** `[ "192.168.0.0/16" ]`\
**Example:** `[ "192.168.0.0/16" "10.0.0.0/8" ]`
+74 -12
View File
@@ -103,6 +103,10 @@ Part of the [proxy-suite options reference](./index.md).
- [ips](#services-proxy-suite-proxy-routing-rules-ips)
- [outbound](#services-proxy-suite-proxy-routing-rules-outbound)
- [ruleSets](#services-proxy-suite-proxy-routing-rules-rulesets)
- runtimeSubscriptions
- [allowHttp](#services-proxy-suite-proxy-runtimesubscriptions-allowhttp)
- [allowInsecure](#services-proxy-suite-proxy-runtimesubscriptions-allowinsecure)
- [allowPrivateServers](#services-proxy-suite-proxy-runtimesubscriptions-allowprivateservers)
- [selection](#services-proxy-suite-proxy-selection)
- [selectionExclude](#services-proxy-suite-proxy-selectionexclude)
- singBox
@@ -111,6 +115,8 @@ Part of the [proxy-suite options reference](./index.md).
- [subscriptionUpdateInterval](#services-proxy-suite-proxy-subscriptionupdateinterval)
- [subscriptions](#services-proxy-suite-proxy-subscriptions)
- item
- [allowInsecure](#services-proxy-suite-proxy-subscriptions-allowinsecure)
- [allowPrivateServers](#services-proxy-suite-proxy-subscriptions-allowprivateservers)
- [detour](#services-proxy-suite-proxy-subscriptions-detour)
- [tag](#services-proxy-suite-proxy-subscriptions-tag)
- [url](#services-proxy-suite-proxy-subscriptions-url)
@@ -192,7 +198,8 @@ authentication, even with ` proxy.listener.auth ` set\.
<a id="services-proxy-suite-proxy-autoproxy-probesperrun"></a>
## services\.proxy-suite\.proxy\.autoProxy\.probesPerRun
Maximum destinations probed per run\. The rest wait for the next run, most-used first\.
Maximum destinations probed per run: of those asked for with ` proxy-ctl proxy auto learn `, and again of those queued from traffic\. The rest wait for the next run, the
queued ones most-used first\. A run also ends after two hours, its probes kept\.
**Type:** positive integer, meaning >0\
**Default:** `200`
@@ -449,9 +456,10 @@ Subscriptions whose every entry is a member, as the subscription holds them at s
<a id="services-proxy-suite-proxy-ipv6"></a>
## services\.proxy-suite\.proxy\.ipv6
Route IPv6 through TUN and TProxy too\. When off, TProxy ignores IPv6 and the TUNs block
it, so apps fall back to IPv4\. If the uplink has no IPv6, also set
` proxy.dns.strategy = "ipv4_only" `, or direct IPv6 connections hang instead of falling back\.
Route IPv6 through TUN and TProxy too\. When off, TProxy refuses IPv6 past the LAN and
on-link prefixes and the TUNs block it, so apps fall back to IPv4\. If the uplink has no
IPv6, also set ` proxy.dns.strategy = "ipv4_only" `, or direct IPv6 connections hang
instead of falling back\.
**Type:** boolean\
**Default:** `config.networking.enableIPv6`
@@ -461,7 +469,7 @@ it, so apps fall back to IPv4\. If the uplink has no IPv6, also set
Address of the local SOCKS5/HTTP proxy\. Use “0\.0\.0\.0” only to expose it to the network\.
**Type:** string\
**Type:** IP address or host name\
**Default:** `"127.0.0.1"`
<a id="services-proxy-suite-proxy-listener-auth-password"></a>
@@ -837,9 +845,9 @@ Download through the proxy or directly\.
<a id="services-proxy-suite-proxy-routing-rulesets-name-url"></a>
## services\.proxy-suite\.proxy\.routing\.ruleSets\.\<name>\.url
URL of the sing-box rule set\.
URL of the sing-box rule set (https only)\.
**Type:** string matching the pattern https?://\.+\
**Type:** string matching the pattern https://\.+\
**Example:** `"https://example.com/antifilter.srs"`
<a id="services-proxy-suite-proxy-routing-rules"></a>
@@ -921,6 +929,35 @@ Rule sets from ` proxy.routing.ruleSets ` that this rule matches (sing-box and h
**Default:** `[ ]`\
**Example:** `[ "antifilter" ]`
<a id="services-proxy-suite-proxy-runtimesubscriptions-allowhttp"></a>
## services\.proxy-suite\.proxy\.runtimeSubscriptions\.allowHttp
Let subscriptions added at runtime (` proxy-ctl proxy subs add `) be fetched over plain
http\. Anyone on the way can then add entries of their own\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-proxy-runtimesubscriptions-allowinsecure"></a>
## services\.proxy-suite\.proxy\.runtimeSubscriptions\.allowInsecure
Keep entries of subscriptions added at runtime that turn certificate checks off, as
` subscriptions.*.allowInsecure ` does for a declared one\. Anyone on the way can then
stand in for those servers\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-proxy-runtimesubscriptions-allowprivateservers"></a>
## services\.proxy-suite\.proxy\.runtimeSubscriptions\.allowPrivateServers
Keep entries of subscriptions added at runtime whose server is a private address, as
` subscriptions.*.allowPrivateServers ` does for a declared one\. Whoever can add a
subscription then picks servers on your network\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-proxy-selection"></a>
## services\.proxy-suite\.proxy\.selection
@@ -986,6 +1023,31 @@ start, cached, and refreshed on a timer\. ` proxy-ctl proxy subs add ` adds more
**Default:** `[ ]`\
**Example:** `[ { tag = "private"; urlFile = "/run/secrets/private-sub-url"; } ]`
<a id="services-proxy-suite-proxy-subscriptions-allowinsecure"></a>
## services\.proxy-suite\.proxy\.subscriptions\.\*\.allowInsecure
Keep entries that turn certificate checks off (` insecure=1 `, for hysteria2 and
AnyTLS on sing-box), as for a provider with self-signed certificates\. Anyone on the
way can then stand in for those servers\. Dropped otherwise\. For subscriptions added
at runtime, see ` proxy.runtimeSubscriptions.allowInsecure `\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-proxy-subscriptions-allowprivateservers"></a>
## services\.proxy-suite\.proxy\.subscriptions\.\*\.allowPrivateServers
Keep entries whose server is a private address (10\.0\.0\.0/8, 172\.16\.0\.0/12,
192\.168\.0\.0/16, 100\.64\.0\.0/10, fc00::/7), such as a subscription served on your own
network\. Entries pointing at this host (loopback, “localhost”, unspecified) or at a
link-local or multicast address are dropped either way: whoever serves the list picks
the servers, and the fastest wins\. Only literal addresses (and “localhost”) are
checked\. For subscriptions added at runtime, see
` proxy.runtimeSubscriptions.allowPrivateServers `\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-proxy-subscriptions-detour"></a>
## services\.proxy-suite\.proxy\.subscriptions\.\*\.detour
@@ -1047,7 +1109,7 @@ LAN interfaces whose devices use this host as their gateway\. Their TCP and UDP
proxy; everything else is forwarded as usual\. Turns on IP forwarding\. Needs the nftables
firewall on NixOS\.
**Type:** list of string\
**Type:** list of network interface name\
**Default:** `[ ]`\
**Example:** `[ "br0" ]`
@@ -1056,7 +1118,7 @@ firewall on NixOS\.
Subnets that skip the proxy, such as your LAN and VM bridges (DNS still goes through it)\. IPv6 works too\.
**Type:** list of string\
**Type:** list of IPv4 or IPv6 address or CIDR\
**Default:** `[ "192.168.0.0/16" ]`\
**Example:** `[ "192.168.0.0/16" "10.0.0.0/8" "fd00::/8" ]`
@@ -1095,9 +1157,9 @@ Whether to enable global TUN mode\.
<a id="services-proxy-suite-proxy-tun-address"></a>
## services\.proxy-suite\.proxy\.tun\.address
TUN interface address (CIDR)\.
TUN interface IPv4 address (CIDR)\.
**Type:** string\
**Type:** IPv4 CIDR\
**Default:** `"172.19.0.1/30"`
<a id="services-proxy-suite-proxy-tun-interface"></a>
@@ -1105,7 +1167,7 @@ TUN interface address (CIDR)\.
TUN interface name\.
**Type:** string\
**Type:** network interface name\
**Default:** `"singtun0"`
<a id="services-proxy-suite-proxy-tun-mtu"></a>
+14 -9
View File
@@ -64,8 +64,8 @@ Extra OpenSSH arguments\.
<a id="services-proxy-suite-sshproxy-hostkey"></a>
## services\.proxy-suite\.sshProxy\.hostKey
Accepted host keys, for sing-box\. List every key ` ssh-keyscan ` prints, since the key type
is negotiated\.
Accepted host keys, for sing-box, and for OpenSSH without ` knownHostsFile `\. List every
key ` ssh-keyscan ` prints, since the key type is negotiated\.
**Type:** list of string\
**Default:** `[ ]`\
@@ -74,7 +74,7 @@ is negotiated\.
<a id="services-proxy-suite-sshproxy-hostkeyfile"></a>
## services\.proxy-suite\.sshProxy\.hostKeyFile
Known-hosts file to read host keys from (sing-box)\. Takes priority over ` hostKey `\.
Known-hosts file to read host keys from (sing-box, and OpenSSH without ` knownHostsFile `)\. Takes priority over ` hostKey `\.
**Type:** null or string\
**Default:** `null`\
@@ -109,7 +109,9 @@ Address of the OpenSSH SOCKS5 listener\.
<a id="services-proxy-suite-sshproxy-listener-port"></a>
## services\.proxy-suite\.sshProxy\.listener\.port
Port of the OpenSSH SOCKS5 listener\.
Port of the OpenSSH SOCKS5 listener\. It takes no login: where it is the XRay backend’s
hop (` asOutbound `) on a host with root, only proxy-suite’s daemons and root may
connect to it\. A standalone tunnel stays open to every local user\.
**Type:** 16 bit unsigned integer; between 0 and 65535 (both inclusive)\
**Default:** `1091`
@@ -143,17 +145,20 @@ SSH login user\.
<a id="services-proxy-suite-sshproxy-serviceuser"></a>
## services\.proxy-suite\.sshProxy\.serviceUser
User that runs OpenSSH\. The default is sandboxed; ` null ` runs it as root\.
User that runs OpenSSH\. The default is sandboxed; ` null ` runs it as root\. Another user’s
traffic gets past the kill switch, all of it: never a login user’s\.
**Type:** null or string matching the pattern \[^\[:space:]]+\
**Type:** null or string matching the pattern \[a-z_]\[a-z0-9_-]\*\[$]?\
**Default:** `"proxy-suite-daemon"`\
**Example:** `"proxy"`
<a id="services-proxy-suite-sshproxy-stricthostkeychecking"></a>
## services\.proxy-suite\.sshProxy\.strictHostKeyChecking
OpenSSH host key policy\.
OpenSSH host key policy\. “yes” needs the server’s keys: ` knownHostsFile `, or else
` hostKeyFile ` or ` hostKey `\. “accept-new” takes whatever key the first connection
meets, which anyone on the way can answer then\.
**Type:** one of “yes”, “accept-new”, “no”\
**Default:** `"accept-new"`\
**Example:** `"yes"`
**Default:** `"yes"`\
**Example:** `"accept-new"`
+31
View File
@@ -0,0 +1,31 @@
# services.proxy-suite.tools
Heavy helpers `proxy-ctl` can do without: lnav and curl-impersonate.
Part of the [proxy-suite options reference](./index.md).
## Options
- tools
- curlImpersonate
- [enable](#services-proxy-suite-tools-curlimpersonate-enable)
- lnav
- [enable](#services-proxy-suite-tools-lnav-enable)
<a id="services-proxy-suite-tools-curlimpersonate-enable"></a>
## services\.proxy-suite\.tools\.curlImpersonate\.enable
Probe with curl-impersonate (` proxy-ctl proxy auto probe `, and autoProxy), which
presents a browser’s TLS fingerprint\. Without it probes use plain curl, which some
bot protection refuses, so a working exit can be judged blocked\.
**Type:** boolean\
**Default:** ` true `, ` false ` on nix-on-droid
<a id="services-proxy-suite-tools-lnav-enable"></a>
## services\.proxy-suite\.tools\.lnav\.enable
Follow ` proxy-ctl logs ` in lnav\. Without it they follow in less\.
**Type:** boolean\
**Default:** ` true `, ` false ` on nix-on-droid
+4 -2
View File
@@ -66,7 +66,7 @@ File with more bridge lines, one per line\. Blank lines and \# comments are skip
Bridge lines from https://bridges\.torproject\.org, without the leading “Bridge”\. Setting
any turns bridges on\.
**Type:** list of string\
**Type:** list of string matching the pattern \[^ ]\*\
**Default:** `[ ]`\
**Example:**
@@ -159,7 +159,9 @@ Bridge transport for snowflake\.
<a id="services-proxy-suite-tor-socksport"></a>
## services\.proxy-suite\.tor\.socksPort
Loopback SOCKS port of Tor\.
Loopback SOCKS port of Tor\. Tor takes no login on it, so with ` asOutbound ` on a host with
root only proxy-suite’s daemons and root may connect to it; other users reach Tor
through the proxy’s own listener\.
**Type:** 16 bit unsigned integer; between 0 and 65535 (both inclusive)\
**Default:** `18530`
+4 -4
View File
@@ -89,7 +89,7 @@ Whether to enable skipping zapret for some subnets, such as NATed VMs it would b
Subnets zapret skips\.
**Type:** list of string\
**Type:** list of IPv4 or IPv6 address or CIDR\
**Default:** `[ ]`\
**Example:** `[ "192.168.123.0/24" ]`
@@ -411,7 +411,7 @@ UDP packets sent, with at most ` udpIn ` replies, that count as a failure\.
Extra fake payloads by name (blob=\<name>): a file in zapret2’s files/fake, or an absolute path\.
**Type:** attribute set of string\
**Type:** attribute set of string matching the pattern \[^\[:space:]]+\
**Default:** `{ }`\
**Example:** `{ tls_clienthello = "/etc/proxy-suite/my_clienthello.bin"; }`
@@ -449,7 +449,7 @@ Log everything nfqws2 does to the journal, every packet included\. Very verbose:
Domains always treated as blocked\. At runtime: ` proxy-ctl zapret auto add `\.
**Type:** list of string\
**Type:** list of string matching the pattern \[^\[:space:]]+\
**Default:** `[ ]`\
**Example:** `[ "rutracker.org" ]`
@@ -458,7 +458,7 @@ Domains always treated as blocked\. At runtime: ` proxy-ctl zapret auto add `\.
Domains never touched or learned\. At runtime: ` proxy-ctl zapret auto exclude `\.
**Type:** list of string\
**Type:** list of string matching the pattern \[^\[:space:]]+\
**Default:** `[ ]`\
**Example:** `[ "bank.example.com" ]`
+2 -1
View File
@@ -112,7 +112,8 @@ proxy-ctl restart # restart what is running
In a terminal, `proxy-ctl logs` follows in [`lnav`](https://lnav.org): it follows while at
the bottom, scrolling back pauses it, `G` follows again, `e`/`E` jump between errors, `/`
searches, and `q` or Ctrl-C quits. `:enable-word-wrap` wraps long lines, and lnav remembers
it for the next time. Piped, it is plain `journalctl -f`.
it for the next time. Without lnav ([`tools.lnav.enable`](../options/tools.md#services-proxy-suite-tools-lnav-enable),
off on Nix-on-Droid) it follows in `less`. Piped, it is plain `journalctl -f`.
## See also
+3 -2
View File
@@ -84,8 +84,9 @@ The tray app shows the same, and switches with a click.
- `wrapEnv` sets the proxy variables for one program only, so the rest of the system keeps
its direct routing. `protocol = "all"` sets both kinds, for a program whose choice you
do not know.
- The kill switch guards whichever global tunnel is on (TUN or the VPN), and does nothing
while both are off.
- The kill switch guards whichever global tunnel is on (TUN or the VPN). It is up from boot,
so the internet stays blocked until one of them starts; turning a tunnel off with
`proxy-ctl` lifts it.
- While global TUN is on, per-app `tun` profiles run the app as it is. Everything already goes
through the proxy then.
- See [Wrap programs with the proxy](../wrap-apps.md) for the helpers, and
+9
View File
@@ -67,6 +67,15 @@ nixOnDroidConfigurations.default = nix-on-droid.lib.nixOnDroidConfiguration {
optimisation for it.
- Point other apps at `127.0.0.1:1080`, in their own proxy settings or in the Wi-Fi proxy
settings.
- To save space, `proxy-ctl` comes without lnav and curl-impersonate: `proxy-ctl logs`
follows in `less`, and probes use plain curl. Set
[`tools.lnav.enable`](../options/tools.md#services-proxy-suite-tools-lnav-enable) and
[`tools.curlImpersonate.enable`](../options/tools.md#services-proxy-suite-tools-curlimpersonate-enable)
to have them back.
- Every app on the phone can reach `127.0.0.1`, not only the ones you point at the proxy: set
`proxy.listener.auth` so that only those you give the login to can use it. The loopback
hops behind it take a login of their own, drawn per boot, except Tor's SOCKS port and the
OpenSSH tunnel's under XRay, which take none: any app reaches those exits.
## See also
+5 -2
View File
@@ -109,8 +109,11 @@ services.proxy-suite = {
the global mode already carries its traffic. `proxy-ctl` prints a note when it does. So
does `--via`, except that an "interface" AmneziaWG outbound still takes the app under a
global TProxy or AmneziaWG profile.
- If `/etc/resolv.conf` points only at a local resolver (such as systemd-resolved on
127.0.0.53), the app's DNS queries skip its route. `proxy-ctl` warns about this.
- With `tun` and `tproxy`, the app's DNS queries go through its route wherever its resolver
is, a local one (such as systemd-resolved on 127.0.0.53) or the LAN router. Lookups glibc
hands to nscd (NixOS's default) do not: nscd resolves them itself, outside the route.
`proxy-ctl` warns when nscd runs. Apps that resolve names themselves are not affected:
programs built with Go, and browsers using their own resolver or DNS-over-HTTPS.
- The app follows your [routing rules](./routing.md) like any other proxied traffic.
## See also
+3 -1
View File
@@ -7,7 +7,9 @@ applies to the local proxy, TUN, TProxy and per-app routing alike.
1. `proxy.routing.rules`, in order. The first match wins, and a rule can name a specific
outbound.
2. The `proxy`, `direct` and `block` lists.
2. The lists: `proxy.domains` and `proxy.ips` first, then `block`, then `direct`, then
`proxy.geosites`, `proxy.geoips` and `proxy.ruleSets`. A name in both a block and a direct
list (an ad domain under `category-ru`, say) is blocked.
3. Anything left goes to `proxy.routing.default`: `"proxy"` (the default) or `"direct"`.
Russian sites and IPs go direct unless you set `routing.directRu = false`.
+3
View File
@@ -148,6 +148,9 @@ Without root, members of `userControl.group` need the `inbounds` scope.
- Clients cannot reach this host's LAN or Russian sites by default
(`inbounds.routing.blockPrivate`, `blockRu`).
- Through "direct", clients reach this host itself only on the listeners' ports and
`inbounds.serverPorts` (80/443 with subscriptions), whatever it listens on. Its addresses
are read when the inbounds start: restart them after the address changes.
- With `routing.via = "proxy"` (the default), client traffic goes through this host's own
proxy instead, following its routing. That needs `proxy.enable`. A listener can also exit
through one outbound with `via = "<tag>"`.
+14 -2
View File
@@ -44,8 +44,20 @@ proxy-ctl killswitch off # lift the kill switch without stopping the tunnel
## Good to know
- The kill switch blocks outgoing traffic while the tunnel restarts or after it fails, so
nothing leaks. LAN, DHCP and NTP stay open. Turning the tunnel off lifts it.
- The kill switch blocks outgoing traffic from boot until the tunnel is up, while it restarts
and after it fails, so nothing leaks. LAN, DHCP and the time daemon's NTP stay open.
Subscriptions are fetched through the tunnel; only if that fails are they fetched
directly, so the proxy can come up from a cold cache. The subscription host then sees
your address. Turning the tunnel off with `proxy-ctl` lifts the kill switch until the
next boot or tunnel start.
- With TUN or a global AmneziaWG profile, the kill switch also holds forwarded traffic
(Docker, libvirt, podman) to the LAN while the tunnel is down. TProxy diverts only
`proxy.tproxy.lanInterfaces`, so in TProxy mode other containers and VMs bypass the proxy
whether the tunnel is up or not. With TProxy alone the kill switch lets them through, and
with TUN or AmneziaWG also configured it cuts them off in TProxy mode.
- Networks the kill switch should leave open besides the private ranges, such as a routed
IPv6 prefix on a VM bridge, go in `killSwitch.allowedSubnets`. It defaults to
`proxy.tproxy.localSubnets`, so what TProxy leaves out stays reachable.
- If the uplink has no IPv6, set `proxy.dns.strategy = "ipv4_only"` (sing-box). Otherwise
direct IPv6 connections hang instead of falling back to IPv4.
- `proxy.tproxy.localSubnets` lists networks that skip TProxy. Add your LAN and VM bridges if
+27 -3
View File
@@ -49,6 +49,10 @@ let
in
''
chain listener_${toString index} {
# Cloud instance metadata (credentials, IAM tokens): for this host alone, never
# for its clients, "lan" or not.
ip daddr { ${lib.concatStringsSep ", " derived.constants.cloudMetadata.ipv4} } drop
ip6 daddr { ${lib.concatStringsSep ", " derived.constants.cloudMetadata.ipv6} } drop
fib daddr type { local, broadcast, multicast } ${verdict}
ip daddr $RESERVED_IP ${verdict}
# Not in RESERVED_IP, whose other users route it by the local subnets instead.
@@ -97,6 +101,13 @@ let
}
'';
# The table swapped in whole, in one transaction, also after a firewall reload flushed it.
nftReplaceFile = pkgs.writeText "proxy-suite-routing" ''
table inet ${nftTable}
delete table inet ${nftTable}
include "${nftRulesFile}"
'';
routingDown =
lib.concatMapStrings
(family: ''
@@ -129,6 +140,10 @@ let
${stop}
# Before any interface is up: its iifname matches already, so no client packet comes
# in ahead of the confinement.
${nft} -f ${nftRulesFile}
PYTHONPATH=${scriptsDir} ${python3} ${scriptsDir}/awg_inbound.py prepare \
--spec ${proxyInboundsSpecFile} --awg ${awg} --runtime-dir "$RUNTIME_DIRECTORY" \
> "$RUNTIME_DIRECTORY/interfaces"
@@ -153,8 +168,6 @@ let
${ip} ${family} rule add pref ${toString awgInboundRulePriority} iif ${lib.escapeShellArg listener.interface} fwmark ${toString awgInboundFwmark} table ${toString awgInboundRouteTable}
'') listeners}
'') ([ "-4" ] ++ lib.optional ipv6 "-6")}
${nft} -f ${nftRulesFile}
'';
in
{
@@ -180,9 +193,19 @@ in
services.${unitName} = {
description = "proxy-suite AmneziaWG inbound interfaces";
after = [ "network-online.target" ];
# After nftables, whose start flushes what came before it on flushRuleset hosts.
after = [
"network-online.target"
"nftables.service"
];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
# Put back after a firewall reload that flushed the ruleset, and restarted along with a
# restart of nftables, which a reload hook never hears of.
unitConfig = {
ReloadPropagatedFrom = [ "nftables.service" ];
PartOf = [ "nftables.service" ];
};
path = [
awgCfg.toolsPackage
awgCfg.userspacePackage
@@ -199,6 +222,7 @@ in
StateDirectory = "proxy-suite";
UMask = "0077";
ExecStart = start;
ExecReload = "${nft} -f ${nftReplaceFile}";
ExecStop = stop;
LockPersonality = true;
ProtectClock = true;
+75 -26
View File
@@ -176,7 +176,9 @@ let
# O_NOFOLLOW: the spool is group-writable.
slot=$(${pkgs.coreutils}/bin/dd if="${runtimeOutboundsDir}/$profile_name.iface" iflag=nofollow,nonblock status=none 2>/dev/null | ${pkgs.coreutils}/bin/head -n 1 || true)
fi
if [[ ! $slot =~ ^[0-9]+$ ]] || (( slot >= ${toString awgRuntimeIfaceSlots} )); then
# No leading zero (bash reads it as octal) and three digits at most (a long one wraps
# around in bash arithmetic): an out-of-range table reaches `ip route flush` as root.
if [[ ! $slot =~ ^(0|[1-9][0-9]{0,2})$ ]] || (( slot >= ${toString awgRuntimeIfaceSlots} )); then
echo "proxy-suite: AmneziaWG outbound '$profile_name' needs a slot in 0-${
toString (awgRuntimeIfaceSlots - 1)
} in $profile_name.iface" >&2
@@ -258,7 +260,7 @@ let
fi
echo "$slot" > "$slot_file"
fi
if [[ ! $slot =~ ^[0-9]+$ ]]; then
if [[ ! $slot =~ ^(0|[1-9][0-9]{0,2})$ ]] || (( slot >= ${toString derived.constants.awgAppSlots} )); then
echo "proxy-suite: AmneziaWG profile '$profile_name' is not up for apps" >&2
exit 1
fi
@@ -387,6 +389,7 @@ let
fwmark=$(${awgCfg.toolsPackage}/bin/awg show ${lib.escapeShellArg profile.interfaceName} fwmark)
# Off when the profile routes nothing by default (a table of its own, or Table=off).
if [[ "$fwmark" != off ]]; then
${awgIPv6FallbackUp}
${serverUdpRulesUp}
${pkgs.nftables}/bin/nft -f - <<EOF
table inet ${repliesTable profile} {
@@ -406,6 +409,30 @@ let
repliesDown = profile: ''
${pkgs.nftables}/bin/nft delete table inet ${repliesTable profile} 2>/dev/null || true
${serverUdpRulesDown}
${awgIPv6FallbackDown}
'';
# A global profile without IPv6 (AllowedIPs 0.0.0.0/0 alone): IPv6 unreachable rather than
# out the uplink, behind the main table's more specific routes. $fwmark: the interface's.
ip6 = "${pkgs.iproute2}/bin/ip -6";
awgIPv6FallbackUp = ''
table=$((fwmark))
if [ -e /proc/net/if_inet6 ] && [ -z "$(${ip6} route show default table "$table" 2>/dev/null)" ]; then
${ip6} route replace unreachable default table "$table"
${ip6} rule add not fwmark "$table" table "$table"
${ip6} rule add table main suppress_prefixlength 0
fi
'';
# The interface (and its fwmark) may be gone: found by the rule naming its mark as its
# table and that table's unreachable default, which awg-quick's never has.
awgIPv6FallbackDown = ''
while read -r mark table; do
[[ $mark =~ ^(0x[0-9a-f]+|[0-9]+)$ && $table =~ ^[0-9]+$ ]] && (( mark == table )) || continue
${ip6} route show table "$table" 2>/dev/null | ${pkgs.gnugrep}/bin/grep -q '^unreachable default' || continue
while ${ip6} rule del not fwmark "$table" table "$table" 2>/dev/null; do :; done
${ip6} rule del table main suppress_prefixlength 0 2>/dev/null || true
${ip6} route flush table "$table" 2>/dev/null || true
done < <(${ip6} rule show 2>/dev/null | ${pkgs.gawk}/bin/awk '$2 == "not" && $5 == "fwmark" && $7 == "lookup" { print $6, $8 }')
'';
# awg-quick turns src_valid_mark on for a default route and never back off; left on, it
@@ -447,18 +474,9 @@ let
}
'';
# Under the kill switch, glibc would hand the Endpoint lookup to nscd or systemd-resolved,
# whose own queries the kill switch rejects. With both out of the way it asks resolved's
# upstreams itself, under the unit's group, and awg-quick gets the Endpoint as an address.
ownLookups = pkgs.writeShellScript "proxy-suite-awg" ''
mount=${pkgs.util-linux}/bin/mount
# Best effort: at worst the lookup goes the usual way.
if [ -S /run/nscd/socket ]; then $mount --bind /dev/null /run/nscd/socket || true; fi
if [ -s /run/systemd/resolve/resolv.conf ]; then
$mount --bind /run/systemd/resolve/resolv.conf /etc/resolv.conf || true
fi
exec "$@"
'';
# The Endpoint lookup under the kill switch, under the unit's group: awg-quick gets it as
# an address.
ownLookups = derived.constants.ownLookups pkgs;
# A global profile, or an "interface" outbound: a unit for a declared profile (staticSpec),
# or the template the runtime ones start from (runtimeSpec). `conflicts`: the global units
@@ -527,6 +545,9 @@ let
${spec.release or ""}
}
trap cleanup ERR
# Stopped (or conflicted out) during the handshake wait: no ExecStop follows a start
# that never finished, so what is up so far would stay up with the unit inactive.
trap 'cleanup; exit 143' TERM INT
${awgCommon.modprobe}
@@ -604,7 +625,6 @@ let
"proxy-suite-tun.service"
"proxy-suite-tproxy.service"
"proxy-suite-zapret.service"
"proxy-suite-per-app-zapret.service"
"proxy-suite-zapret-vm-exempt.service"
];
}
@@ -640,7 +660,15 @@ let
(withArg prepare)
]
++ lib.optionals (!outbound && derived.awgRuntimeGlobal) [ (withArg stopRuntimeProfiles) ]
++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ];
++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ]
# Per-app zapret and this profile's copy for apps have nothing to add once it is up,
# and never take it down themselves (constants.refuseUnderGlobal).
++ lib.optionals (!outbound) [
(derived.constants.stopPerAppUnits pkgs [
"proxy-suite-per-app-zapret.service"
"proxy-suite-awg-app@${if spec.template then "%i" else name}.service"
])
];
ExecStart = withArg start;
ExecStop = withArg stop;
}
@@ -696,7 +724,7 @@ let
unit = "proxy-suite-awg-tunnel@";
runtimeDirectory = "proxy-suite-awg-tunnel-%i";
engine = "userspace";
tag = "$TUNNEL_TAG";
# `profile` sets $TUNNEL_TAG.
tunnelPort = "$TUNNEL_PORT";
execArgs = " %i";
# The sync unit starts one per entry.
@@ -716,7 +744,7 @@ let
fi
# O_NOFOLLOW: the spool is group-writable, and the port is echoed back on error.
TUNNEL_PORT=$(${pkgs.coreutils}/bin/dd if="${runtimeOutboundsDir}/$TUNNEL_TAG.port" iflag=nofollow,nonblock status=none 2>/dev/null | ${pkgs.coreutils}/bin/head -n 1 || true)
if [[ ! $TUNNEL_PORT =~ ^[0-9]+$ ]] || (( TUNNEL_PORT < ${toString awgRuntimeTunnelBasePort} || TUNNEL_PORT > ${toString runtimeTunnelLastPort} )); then
if [[ ! $TUNNEL_PORT =~ ^[1-9][0-9]{0,4}$ ]] || (( TUNNEL_PORT < ${toString awgRuntimeTunnelBasePort} || TUNNEL_PORT > ${toString runtimeTunnelLastPort} )); then
echo "proxy-suite: AmneziaWG outbound '$TUNNEL_TAG' needs a port in ${toString awgRuntimeTunnelBasePort}-${toString runtimeTunnelLastPort} in $TUNNEL_TAG.port" >&2
exit 1
fi
@@ -790,7 +818,14 @@ let
# moves off it now rather than at its next test.
hint() {
local health="${runtimeDir}/proxy-suite-outbound-groups/health"
[[ -d $health ]] && ${pkgs.coreutils}/bin/touch "$health/$profile_name" 2>/dev/null || true
local hint="$health/$profile_name"
[[ -d $health ]] || return 0
# Never through a symlink the service user's group left: O_EXCL (noclobber), touch -h.
if [[ -e $hint || -L $hint ]]; then
${pkgs.coreutils}/bin/touch -h "$hint" 2>/dev/null || true
else
(set -C; : > "$hint") 2>/dev/null || true
fi
}
${lib.optionalString egressProbe ''
new_session() {
@@ -971,7 +1006,18 @@ in
(lib.mapAttrs' (
name: profile:
lib.nameValuePair (serviceName name) (
mkService (staticSpec name profile) (allProfileConflicts name)
lib.mkMerge [
(mkService (staticSpec name profile) (allProfileConflicts name))
{
# Ordered (one way, by name) so the old profile's cleanup of table 51820 ends before the
# new one starts; Conflicts= alone lets them overlap.
after = lib.optionals (builtins.elem name globalProfileNames) (
map (other: "${serviceName other}.service") (
builtins.filter (other: other < name) globalProfileNames
)
);
}
]
)
) interfaceProfiles)
(lib.mapAttrs' (
@@ -983,8 +1029,8 @@ in
(mkService runtimeSpec (map (other: "${serviceName other}.service") globalProfileNames))
{
wants = [ "proxy-suite-awg-watchdog@%i.service" ];
# The kill switch cannot order itself after instances it does not know.
before = [ killSwitchUnit ];
# After the declared ones it conflicts with: their stop goes first (as above).
after = map (other: "${serviceName other}.service") globalProfileNames;
}
];
"proxy-suite-awg-watchdog@" = mkWatchdog runtimeSpec;
@@ -998,10 +1044,13 @@ in
(mkService appSpec [ ])
{
wants = [ "proxy-suite-awg-app-watchdog@%i.service" ];
# The profile up globally, declared or added with `awg add`.
conflicts = [
"proxy-suite-awg-%i.service"
"proxy-suite-awg@%i.service"
# Not while the profile is up globally, declared or added with `awg add`: that
# carries the apps already, and takes this one down as it starts.
serviceConfig.ExecStartPre = lib.mkBefore [
(derived.constants.refuseUnderGlobal pkgs [
"proxy-suite-awg-%i.service"
"proxy-suite-awg@%i.service"
])
];
# Up only while proxy-ctl runs apps through it, which starts it again.
serviceConfig.Restart = lib.mkForce "no";
+15
View File
@@ -0,0 +1,15 @@
# Moves autoProxy's state dir from the old group-writable layout to root's alone, with the
# spool beside it. Run by the socks start script and the autoProxy units, whichever is first.
{ pkgs }:
let
fillTemplate = import ./lib/fill-template.nix;
in
pkgs.writeShellScript "proxy-suite-autoproxy-migrate" (
fillTemplate ./autoproxy-migrate.template.sh {
path = pkgs.lib.makeBinPath [
pkgs.coreutils
pkgs.findutils
];
}
)
@@ -0,0 +1,35 @@
set -euo pipefail
# $1 - autoProxy's state dir, $2 - the spool members queue requests in
export PATH=@path@
dir=$1
spool=$2
# Until the spool, the autoProxy scope's group wrote to the state dir too. A no-op once done.
# Root's alone now; 0751: the group reads it, sing-box searches through to rules/.
install -d -m 0751 "$dir"
# The old queues go to the spool, read through no link (to a file only root may read)
# and never blocking on a FIFO. With no spool to take them, they are dropped.
for name in requests edits requests.taking edits.taking; do
f="$dir/$name"
[ -e "$f" ] || [ -L "$f" ] || continue
if [ -d "$spool" ]; then
# The spool is sticky: no member can swap the name in the meantime.
tmp=$(mktemp "$spool/.migrated.XXXXXX")
dd if="$f" iflag=nofollow,nonblock status=none > "$tmp" 2>/dev/null || true
chmod 0640 "$tmp"
# -T: a directory (or a link to one) a member left under that name takes nothing in.
mv -fT "$tmp" "$spool/${name%.taking}.migrated${tmp##*/.migrated}"
fi
rm -rf -- "$f"
done
# Then whatever else a member left: links, files not root's, special files, and any of
# root's names holding the wrong kind of file.
find "$dir" -mindepth 1 -maxdepth 1 \( -type l -o ! -uid "$(id -u)" -o ! \( -type f -o -type d \) \) \
-exec rm -rf -- {} +
for name in state.json lock samples; do
[ ! -e "$dir/$name" ] || [ -f "$dir/$name" ] || rm -rf -- "${dir:?}/$name"
done
[ ! -e "$dir/rules" ] || [ -d "$dir/rules" ] || rm -f -- "$dir/rules"
+103 -34
View File
@@ -6,30 +6,41 @@ mode=${1:-full}
# Overridable to rehearse a run against a scratch copy; the units never set them.
state_dir=${AUTOPROXY_STATE_DIR:-@stateDir@}
spool=${AUTOPROXY_SPOOL_DIR:-@spoolDir@}
export PROBE_EXITS_FILE=${PROBE_EXITS_FILE:-@runtimeDir@/proxy-suite-socks/probe-exits.json}
index=$PROBE_EXITS_FILE
state="$state_dir/state.json"
requests="$state_dir/requests"
edits="$state_dir/edits"
now=$(date +%s)
ttl=$(( @ttlDays@ * 86400 ))
install -d -m @stateDirMode@ "$state_dir"
@migrate@ "$state_dir" "$spool"
# Timer runs and learn requests take turns on the state.
exec 9> "$state_dir/lock"
flock 9
# Leftovers of a run that died partway; taken requests go back in line.
# Leftovers of a run that died partway.
rm -f "$state_dir/verdicts.json" "$state_dir/proxied-domains.txt" "$state".?????? "$state_dir/samples.taking"
for queue in "$requests" "$edits"; do
if [ -e "$queue.taking" ]; then
cat "$queue.taking" >> "$queue"
rm -f "$queue.taking"
# Made here by root: the group appends to it too.
chmod 0660 "$queue"
fi
done
# `proxy-ctl proxy auto` requests: a file each in the spool, named to sort by time. Sets
# taken to queue $1's files, oldest first.
take() {
local f
taken=()
for f in "$spool/$1".*; do
[ -e "$f" ] || [ -L "$f" ] || continue
taken+=("$f")
done
}
# A spool file, read through no symlink, never blocking on a FIFO, 64 KiB at most.
read_queue() {
dd if="$1" iflag=nofollow,nonblock,fullblock bs=64K count=1 status=none 2>/dev/null || true
}
# Taken files go one argv at a time (xargs): a member can queue more of them than one
# command line holds, which would fail every run from then on.
drop_taken() {
[ "${#taken[@]}" -eq 0 ] || printf '%s\0' "${taken[@]}" | xargs -0 rm -rf --
}
if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then
echo "$state is unreadable; set aside as $state.broken, starting fresh" >&2
@@ -55,8 +66,8 @@ update() {
# Before anything else, and even with the proxy stopped: its start renders the
# rule-sets from the state again.
edited=""
if [ -s "$edits" ]; then
mv -f "$edits" "$edits.taking"
take edits
for f in "${taken[@]}"; do
while read -r op dom; do
case "$op" in
forget)
@@ -71,9 +82,11 @@ if [ -s "$edits" ]; then
*) continue ;;
esac
edited=1
done < "$edits.taking"
rm -f "$edits.taking"
fi
done < <(read_queue "$f")
# Once applied: a run killed before this applies it again, to the same end. -r: a
# directory a member left under such a name would fail the run each time.
rm -rf -- "$f"
done
if [ ! -r "$index" ]; then
echo "no probe listeners - is proxy-suite-socks running with autoProxy on?"
@@ -92,6 +105,16 @@ if [ -r "$inventory" ]; then
| (.domains // {}) | to_entries[] | select(.value.exit as $e | $off | index([$e]))
| "\(.key)\t\(.value.exit)"' "$state")
fi
# Once: routes learned under a public suffix (a whole workers.dev) before to_reg knew the
# list, to be learned again per site.
if ! jq -e '.suffixesForgotten' "$state" > /dev/null; then
while read -r dom; do
update --arg op forget --arg d "$dom" -f @editJq@
echo "forgot $dom: a public suffix, not one site"
edited=1
done < <(jq -r '(.domains // {}) | keys[]' "$state" | grep -xFf @publicSuffixes@ || true)
update '.suffixesForgotten = true'
fi
[ -z "$edited" ] || @render@ "$index" "$state"
# $1 JSON array of exit tags, $2 registrable domain, $3 wall:<page>|refused|slow.
@@ -132,28 +155,50 @@ record() {
end' <<<"$3")
}
# Prefixes each host line with "registrable-domain<TAB>".
# ponytail: last two labels, or three under a short list of two-label
# suffixes. Switch to the Public Suffix List if a domain gets merged wrongly.
# Prefixes each host line with "registrable-domain<TAB>", by the public suffix list (private
# section too: foo.workers.dev is a site). A public suffix itself is no site: skipped.
to_reg() {
awk -F'\t' '
awk -F'\t' -v list=@publicSuffixes@ '
BEGIN {
n = split("co.uk org.uk ac.uk gov.uk com.au net.au org.au co.jp ne.jp or.jp com.br com.tr co.kr com.cn com.hk co.in co.za com.ua com.mx co.nz", s, " ")
for (i = 1; i <= n; i++) two[s[i]] = 1
while ((getline rule < list) > 0) {
if (substr(rule, 1, 1) == "!") exc[substr(rule, 2)] = 1
else if (substr(rule, 1, 2) == "*.") wild[substr(rule, 3)] = 1
else exact[rule] = 1
}
}
{
n = split($1, l, ".")
host = tolower($1)
n = split(host, l, ".")
if (n < 2) next
k = (n >= 3 && (l[n - 1] "." l[n]) in two) ? l[n - 2] "." l[n - 1] "." l[n] : l[n - 1] "." l[n]
# Labels in the longest public suffix: an exception rule, an exact one, or a
# wildcard over the rest; none at all is the implicit "*".
s = 1
for (i = 1; i <= n; i++) {
c = l[i]
for (j = i + 1; j <= n; j++) c = c "." l[j]
rest = substr(c, length(l[i]) + 2)
if (c in exc) { s = n - i; break }
if ((c in exact) || (rest != "" && rest in wild)) { s = n - i + 1; break }
}
if (s >= n) next
k = l[n - s]; for (j = n - s + 1; j <= n; j++) k = k "." l[j]
print k "\t" $0
}'
}
# The pinned direct listener, since TUN/TProxy capture --noproxy too.
direct_url=$(jq -r '.[0] | "http://127.0.0.1:\(.port)"' "$index")
# The probe listeners' login, drawn per start (start-scripts.nix): to curl through a
# config on a pipe, as argv is public.
probe_login="$(dirname "$index")/probe-login"
probe_curlrc() {
if [ -r "$probe_login" ]; then
printf 'proxy-user = "%s"\n' "$(tr -d '\r\n"\\' < "$probe_login")"
fi
}
# --- 1. verdicts are about this host's address; drop them if it changed ---
egress=$(curl -sS -f --proxy "$direct_url" --max-time 10 https://api.ipify.org 2>/dev/null || true)
egress=$(curl -sS -f -K <(probe_curlrc) --proxy "$direct_url" --max-time 10 https://api.ipify.org 2>/dev/null || true)
# An error page or a captive portal must not pass for a new address: anything
# that is not one discards every verdict this host learned.
[[ "$egress" =~ ^[0-9a-fA-F.:]+$ ]] || egress=""
@@ -166,8 +211,11 @@ fi
# --- 2. which network (AS) each exit leaves from, once per TTL ---
while IFS=$'\t' read -r tag port; do
at=$(jq -r --arg t "$tag" '.exits[$t].at // 0' "$state")
# Digits only: a state.json from when the group could write it may hold anything, and
# $(( )) would run what a[$(...)] names.
[[ "$at" =~ ^[0-9]{1,12}$ ]] || at=0
[ $(( now - at )) -ge "$ttl" ] || continue
info=$(curl -sS --proxy "http://127.0.0.1:$port" --max-time 10 https://ipinfo.io/json 2>/dev/null || true)
info=$(curl -sS -K <(probe_curlrc) --proxy "http://127.0.0.1:$port" --max-time 10 https://ipinfo.io/json 2>/dev/null || true)
ip=$(jq -r '.ip // empty' <<<"$info" 2>/dev/null || true)
asn=$(jq -r '(.org // "") | split(" ")[0]' <<<"$info" 2>/dev/null || true)
[ -n "$ip" ] || continue
@@ -269,7 +317,11 @@ if [ "$mode" = full ]; then
first: (.[$e.key].first // $now)
} end))
| .backlog |= with_entries(select(.value.first + $ttl > $now
and $s.domains[.value.domain].exit == null))'
and $s.domains[.value.domain].exit == null))
# Bounded, as every distinct name dialled is an entry; the most dialled stay.
| if (.backlog | length) > 5000 then
.backlog |= (to_entries | sort_by(-.value.hits) | .[:5000] | from_entries)
else . end'
# --- 4b. what the sampler saw crawl (see autoproxy-slow-judge.jq) ---
if [ -s "$state_dir/samples" ]; then
@@ -324,19 +376,36 @@ if [ "$mode" = full ]; then
echo "slow $dom: crawls ${was:+via $was}${was:-directly}, and no other exit reaches it; left direct"
update --arg d "$dom" --argjson until $(( now + ttl )) '.slowSkip[$d] = $until | del(.slowWant[$d])'
fi
done < <(jq -r '(.slowWant // {}) | to_entries[]
# A few per run, each probed via every exit: the rest wait for the next run rather
# than hold the lock for hours.
done < <(jq -r '(.slowWant // {}) | to_entries[:20][]
| "\(.key)\t\(.value.host)\t\(.value.tried | join(","))"' "$state")
[ "$(jq -c '.domains' "$state")" = "$before" ] || publish
fi
fi
# --- 5. probe: requests (uncapped), then broken routes, then the backlog ---
# --- 5. probe: requests, then broken routes, then the backlog ---
asked=()
if [ -s "$requests" ]; then
mv -f "$requests" "$requests.taking"
mapfile -t asked < <(grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' "$requests.taking" | to_reg || true)
rm -f "$requests.taking"
take requests
if [ "${#taken[@]}" -gt 0 ]; then
mapfile -t asked < <(
for f in "${taken[@]}"; do
read_queue "$f"
echo
done | grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' | awk '!seen[$0]++' | to_reg || true
)
drop_taken
fi
# probesPerRun of them at most: a member could queue hosts by the hundred thousand, each a
# probe holding the lock. The rest go back to the spool, for the next run.
if [ "${#asked[@]}" -gt @probesPerRun@ ]; then
rest=$(mktemp "$spool/.requests.XXXXXX")
printf '%s\n' "${asked[@]:@probesPerRun@}" | cut -f2 > "$rest"
chmod 0640 "$rest"
mv -fT "$rest" "$spool/requests.$(date +%s%N).$$"
echo "$(( ${#asked[@]} - @probesPerRun@ )) requested host(s) past probesPerRun wait for the next run"
asked=("${asked[@]:0:@probesPerRun@}")
fi
backlog=()
if [ "$mode" = full ]; then
@@ -7,7 +7,8 @@ if [ -z "$clash_api" ]; then
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
exit 0
fi
install -d -m @stateDirMode@ "$state_dir"
# Before appending to samples by name: on an old install, a member may have left a link.
@migrate@ "$state_dir" "${AUTOPROXY_SPOOL_DIR:-@spoolDir@}"
# Eleven snapshots a second apart: ten one-second deltas per connection.
lines=$(
@@ -25,3 +25,6 @@
del(.domains[$e.key])
| .slowWant[$e.key] = {host: $e.value.host, tried: ($e.value.tried // [$e.value.exit])})
| .slowSkip = ((.slowSkip // {}) | with_entries(select(.value > $now)))
# Bounded, as the backlog: each crawling name a client loads would be an entry otherwise.
| if (.slowHits | length) > 5000 then .slowHits |= (to_entries | sort_by(-.value.n) | .[:5000] | from_entries) else . end
| if (.slowWant | length) > 500 then .slowWant |= (to_entries | .[:500] | from_entries) else . end
+86 -29
View File
@@ -7,6 +7,7 @@
cfg,
proxyCtl,
autoProxyStateDir,
autoProxySpoolDir,
runtimeDir,
journalctl,
userControlAllows,
@@ -17,14 +18,14 @@ let
apCfg = cfg.proxy.autoProxy;
derived = import ./derived.nix { inherit lib cfg; };
inherit (derived.constants) rootInSharedDirConfig;
# The autoProxy scope's groups write the directory: `proxy auto learn` queues there. Those
# in userControl.groups through ACLs, which the group bits (the ACL mask) leave open.
stateDirMode = if derived.userControlAnyAllows "autoProxy" then "0771" else "0751";
# The autoProxy scope's groups read the state (userControl.groups through ACLs), root alone
# writes it (autoproxy-migrate.nix sets the mode).
grantAcl = pkgs.writeShellScript "proxy-suite-autoproxy-acl" (
derived.constants.grantDirAcl pkgs (lib.escapeShellArg autoProxyStateDir)
(derived.userControlExtraGroupsFor "autoProxy")
"rwX"
"rX"
);
migrate = import ./autoproxy-migrate.nix { inherit pkgs; };
render = import ./autoproxy-render.nix {
inherit pkgs;
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser ifPrivileged;
@@ -36,20 +37,32 @@ let
inherit path;
};
bin = lib.makeBinPath [
pkgs.coreutils
pkgs.curl
pkgs.gawk
pkgs.gnugrep
pkgs.gnused
pkgs.jq
pkgs.systemd
pkgs.util-linux
proxyCtl
];
bin = lib.makeBinPath (
[
pkgs.coreutils
pkgs.curl
pkgs.findutils
pkgs.gawk
pkgs.gnugrep
pkgs.gnused
pkgs.jq
]
# journalctl; proxy-suitectl, by path, answers it on its own.
++ lib.optional (cfg.host.serviceManager != "supervisor") pkgs.systemd
++ [
pkgs.util-linux
proxyCtl
]
);
excludePattern = lib.concatStringsSep "|" (map lib.escapeRegex apCfg.exclude);
# Public suffixes, the private section's too, in the xn-- form names come in: to_reg groups
# a host under its registrable domain by them.
publicSuffixes =
pkgs.runCommand "proxy-suite-autoproxy-public-suffixes" { nativeBuildInputs = [ pkgs.python3 ]; }
"python3 ${./zapret2/public-suffixes.py} --private ${pkgs.publicsuffix-list}/share/publicsuffix/public_suffix_list.dat >$out";
# Sets $clash_api (empty when the API is off) and $clash_secret (curl sends it through
# clash_auth_header, never argv, which every local user can read).
clashApiBlock = ''
@@ -64,7 +77,8 @@ let
fillTemplate ./autoproxy-sample.template.sh {
path = bin;
stateDir = lib.escapeShellArg autoProxyStateDir;
inherit runtimeDir clashApiBlock stateDirMode;
spoolDir = lib.escapeShellArg autoProxySpoolDir;
inherit runtimeDir clashApiBlock migrate;
minBytes = toString (300 * 1024);
slowBelowBytes = toString (apCfg.slowBelowKiBps * 1024);
slowSampleJq = jqFile ./autoproxy-slow-sample.jq;
@@ -75,41 +89,77 @@ let
fillTemplate ./autoproxy-run.template.sh {
path = bin;
stateDir = lib.escapeShellArg autoProxyStateDir;
spoolDir = lib.escapeShellArg autoProxySpoolDir;
inherit runtimeDir;
ttlDays = toString apCfg.ttlDays;
inherit stateDirMode;
inherit migrate;
editJq = jqFile ./autoproxy-edit.jq;
inherit render;
strikeJq = jqFile ./autoproxy-strike.jq;
roundsJq = jqFile ./autoproxy-rounds.jq;
interval = apCfg.interval;
inherit journalctl;
excludeHosts = lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |";
# Quoted whole: escapeRegex leaves a quote or backtick in a name as it is.
excludeHosts = lib.optionalString (
excludePattern != ""
) "grep -vE ${lib.escapeShellArg "(^|\\.)(${excludePattern})$"} |";
excludeSampleHosts = lib.optionalString (
excludePattern != ""
) "grep -vE '(^|\\.)(${excludePattern})'$'\\t' |";
) "grep -vE ${lib.escapeShellArg "(^|\\.)(${excludePattern})"}$'\\t' |";
slowJudgeJq = jqFile ./autoproxy-slow-judge.jq;
probesPerRun = toString apCfg.probesPerRun;
inherit publicSuffixes;
}
);
# Group: `proxy-ctl proxy auto list|queue` reads state.json, `learn` queues requests.
# Set on every unit that declares the directory - systemd re-applies the ownership
# on each start.
# Group: `proxy-ctl proxy auto list|queue` reads state.json. Set on every unit that
# declares the directory - systemd re-applies the ownership on each start.
stateDirConfig = {
StateDirectory = "proxy-suite/autoproxy";
# 0751 and a 027 umask: sing-box (proxy-suite-daemon) reaches the rule-sets through
# rules/, which its group reads (autoproxy-render.nix), and nothing else.
StateDirectoryMode = stateDirMode;
# rules/, which its group reads (autoproxy-render.nix), and nothing else. An existing
# directory takes it from autoproxy-migrate.nix: systemd leaves its mode be.
StateDirectoryMode = "0751";
UMask = "0027";
# Inside the sandbox below, which keeps a name a member left there from leading it
# anywhere else.
ExecStartPre = "${grantAcl}";
}
// lib.optionalAttrs (userControlAllows "autoProxy") { Group = cfg.userControl.group; }
# Root writes by fixed names in a directory the group writes to: nowhere else, whatever
# a name there points at.
// rootInSharedDirConfig;
# Root works in the spool members write to: nothing else is writable.
// rootInSharedDirConfig
// lib.optionalAttrs cfg.host.privileged {
ReadWritePaths = [ "-${autoProxySpoolDir}" ];
# Nothing it runs (curl, jq, proxy-ctl, systemctl) is setuid.
NoNewPrivileges = true;
LockPersonality = true;
RestrictRealtime = true;
# Root for files alone: chgrp, ACLs, the spool and the Clash secret (CHOWN, FOWNER, DAC_*).
CapabilityBoundingSet = [
"CAP_CHOWN"
"CAP_DAC_OVERRIDE"
"CAP_DAC_READ_SEARCH"
"CAP_FOWNER"
];
ProtectKernelModules = true;
RestrictAddressFamilies = [
"AF_INET"
"AF_INET6"
"AF_UNIX"
"AF_NETLINK"
];
};
# Sticky, so no member takes another's request; setgid for the group. By tmpfiles, so the
# group can queue before any unit has run.
spoolMode =
if userControlAllows "autoProxy" then
"3770 root ${cfg.userControl.group}"
# userControl.groups only, through ACLs (proxy-suite-acls): the mode keeps them open.
else if derived.userControlAnyAllows "autoProxy" then
"3770 root root"
else if cfg.host.privileged then
"0700 root root"
else
"0700 - -";
mkUnit = description: args: {
inherit description;
@@ -122,11 +172,16 @@ let
serviceConfig = {
Type = "oneshot";
ExecStart = "${runner}${args}";
# A run of tarpits must not hold the lock for good; each probe's verdict is saved as it
# comes, so one cut short keeps what it learned. Far past any honest run's length.
TimeoutStartSec = "2h";
}
// stateDirConfig;
};
in
{
services.proxy-suite.internal.tmpfiles = [ "d ${autoProxySpoolDir} ${spoolMode} -" ];
services.proxy-suite.internal.services.proxy-suite-autoproxy =
mkUnit "proxy-suite - find the exit that reaches each destination, and remember it" "";
@@ -141,6 +196,8 @@ in
serviceConfig = {
Type = "oneshot";
ExecStart = "${sampler}";
# Its timer comes every minute.
TimeoutStartSec = "50s";
}
// stateDirConfig;
};
@@ -16,10 +16,19 @@ let
localProxyAddress = derived.localProxy.host;
# Checked on the address actually dialed, so a name resolving private is caught too
# (routing's geoip:private sees only literal IPs under AsIs). Explicit either way:
# XRay's own default blocks private for vless/vmess/trojan/shadowsocks only, which
# left socks/http open and ignored blockPrivate = false.
# Checked on the address actually dialed, so a name resolving private is caught too; explicit,
# as XRay's default covers some protocols only. This host's own addresses after it.
# AmneziaWG "proxy" peers: cut off from each other and this host's network, via "direct" too.
awgProxyPeerRules =
let
subnets = lib.concatMap (
listener: [ listener.subnet ] ++ lib.optional (listener.subnet6 != null) listener.subnet6
) (builtins.filter (listener: listener.mode != "lan") derived.proxyInboundsAwg);
in
lib.optional (subnets != [ ]) {
action = "block";
ip = subnets;
};
directFinalRules =
if derived.proxyInboundsCfg.routing.blockPrivate then
[
@@ -28,8 +37,38 @@ let
ip = [ "geoip:private" ];
}
]
++ awgProxyPeerRules
++ hostRules
else
[ { action = "allow"; } ];
# Cloud instance metadata (credentials, IAM tokens) stays this host's alone, as for
# the AmneziaWG listeners: blockPrivate = false opens the LAN, not that.
[
{
action = "block";
ip = derived.constants.cloudMetadata.ipv4 ++ derived.constants.cloudMetadata.ipv6;
}
]
++ awgProxyPeerRules
++ hostRules
++ [ { action = "allow"; } ];
# XRay's own queries to the resolvers below are routed too, through "direct" when that is
# the via: one on this host stays reachable on its own port.
isIpUpstream = upstream: builtins.match "[0-9.]+|[0-9a-fA-F:]+" upstream.address != null;
resolverRules = lib.unique (
map
(upstream: {
action = "allow";
ip = [ upstream.address ];
port = toString upstream.port;
})
(
builtins.filter isIpUpstream [
proxyCfg.dns.remote
proxyCfg.dns.local
]
)
);
hostRules = resolverRules ++ inboundRules.hostFenceRules;
# inbounds.routing.serverSource: a user's connections to this host, from the user's own
# address on the dummy interface. inbound_runtime.py makes the runtime users' the same way.
@@ -63,22 +102,26 @@ let
};
in
{
log.loglevel = "warning";
# Without "access" XRay logs every connection: its user, their address, the site.
log = {
loglevel = "warning";
}
// lib.optionalAttrs (!(derived.proxyInboundsCfg.accessLog || proxyCfg.autoProxy.enable)) {
access = "none";
};
dns.servers = [
(mkDnsServer "remote" proxyCfg.dns.remote)
(mkDnsServer "local" proxyCfg.dns.local)
];
# Counters per user, inbound and outbound for proxy-suite-inbound-stats, and who is
# connected right now, from where. A socket rather than loopback, which any local
# user could ask: the start script's setgid directory gives it the group that may
# read the stats. The listeners are appended at start.
# Counters and online users for proxy-suite-inbound-stats, on a root-only socket (asking
# resets counters). The listeners are appended at start.
inbounds = [
{
tag = "api-in";
protocol = "dokodemo-door";
listen = "${derived.constants.inboundStatsApiSocket},0660";
listen = "${derived.constants.inboundStatsApiSocket},0600";
settings = {
address = "127.0.0.1";
network = "unix";
@@ -118,6 +161,7 @@ in
settings = { };
}
]
++ inboundRules.exceptionOutbounds
++ selfOutbounds;
routing = {
+102 -7
View File
@@ -73,10 +73,9 @@ let
if fakeDnsOnly then
{
enabled = true;
destOverride = [ "fakedns" ];
# Fake IPs only live in memory: after a restart an app still holding one gets its
# domain back from TLS/HTTP/QUIC instead of a dead end. Real IPs are left alone;
# the cost is up to 200 ms before a server-speaks-first protocol (SSH, SMTP) starts.
# Fake IPs map back to names; real addresses (DoH, stale caches, a restart's lost fake IPs)
# get theirs sniffed. Costs up to 200 ms before a server-speaks-first protocol starts.
destOverride = [ "fakedns+others" ];
metadataOnly = false;
}
else
@@ -136,12 +135,46 @@ let
}
// target tag;
# No loopback by any name (sniffed, fake DNS, one resolving there): as the daemon it would
# reach the hops the nft guard keeps from other users. dns.*'s loopback resolver stays.
loopbackDnsPorts = lib.unique (
map (upstream: upstream.port) (
builtins.filter
(
upstream:
lib.hasPrefix "127." upstream.address
|| builtins.elem upstream.address [
"::1"
"localhost"
]
)
[
proxyCfg.dns.local
proxyCfg.dns.remote
]
)
);
directFinalRules = lib.optionals constants.privileged (
lib.optional (loopbackDnsPorts != [ ]) {
action = "allow";
ip = derived.proxyInboundsLoopback;
port = lib.concatMapStringsSep "," toString loopbackDnsPorts;
}
++ [
{
action = "block";
ip = derived.proxyInboundsLoopback;
blockDelay = 0;
}
]
);
directOutbound =
useOutboundRoutingMark:
{
protocol = "freedom";
tag = "direct";
settings = { };
settings = lib.optionalAttrs (directFinalRules != [ ]) { finalRules = directFinalRules; };
}
// lib.optionalAttrs useOutboundRoutingMark {
streamSettings.sockopt.mark = globalTproxy.proxyMark;
@@ -160,8 +193,14 @@ let
enableUrlTest ? proxyCfg.selection == "urltest",
domainStrategy ? "IPIfNonMatch",
enableTunFakeDns ? false,
# A loopback port of this config's own, where dns-out hands the queries XRay's resolver
# does not answer (HTTPS, MX, TXT, SRV...) to dns.remote through the proxy.
remoteDnsBridgePort ? null,
}:
let
remote = proxyCfg.dns.remote;
# With routing.default = "direct" they keep going where they were sent, as all else does.
remoteDnsBridge = remoteDnsBridgePort != null && proxyCfg.routing.default == "proxy";
tunSniffing = mkSniffing { fakeDnsOnly = enableTunFakeDns; };
tproxyInboundTags = [ "tproxy-in" ] ++ lib.optional proxyCfg.ipv6 "tproxy-in6";
# Every config takes packets for any destination, DNS included.
@@ -195,13 +234,64 @@ let
qType = "2-27,29-65535";
}
];
}
# "direct" would forward the query past routing and the kill switch: to the bridge
# instead, which routing takes through the proxy.
// lib.optionalAttrs remoteDnsBridge {
address = "127.0.0.1";
port = remoteDnsBridgePort;
network = if remote.type == "udp" then "udp" else "tcp";
};
}
];
remoteDnsBridgeInbound = lib.optional remoteDnsBridge {
tag = "dns-remote-in";
protocol = "tunnel";
listen = "127.0.0.1";
port = remoteDnsBridgePort;
# dns.remote as it is: pure XRay, the only user of this template, refuses "tls"
# (service-assertions.nix), as XRay's DNS has no DoT.
settings = {
inherit (remote) address port;
allowedNetwork = "tcp,udp";
};
};
remoteDnsBridgeRule = lib.optional remoteDnsBridge (
{
type = "field";
inboundTag = [ "dns-remote-in" ];
ruleTag = "dns-remote-bridge";
}
// target "proxy"
);
# inbounds.routing.blockPrivate for the names the server's listeners hand mixed-in, which
# this config looks up again (as backend-filter-private-guard.template.jq for sing-box).
inboundsPrivateGuard =
lib.optional
(
enableMixed
&& derived.pureXrayEnabled
&& derived.proxyInboundsEnabled
&& derived.proxyInboundsNeedLocalProxy
)
{
type = "field";
ruleTag = "inbounds-private-guard";
inboundTag = [ "mixed-in" ];
# Without blockPrivate, this host's loopback still, as the "direct" via's fence.
ip =
if derived.proxyInboundsCfg.routing.blockPrivate then
[ "geoip:private" ]
else
derived.proxyInboundsLoopback;
outboundTag = "block";
};
routingRules =
dnsUpstreamRules
remoteDnsBridgeRule
++ dnsUpstreamRules
++ lib.optional enableTun (dnsHijackRule [ "tun-in" ])
++ lib.optional enableTProxy (dnsHijackRule tproxyInboundTags)
++ inboundsPrivateGuard
++ rules.xrayRoutingRules
++ [ (finalRule (if (proxyCfg.routing.default == "proxy") then "proxy" else "direct")) ];
in
@@ -249,7 +339,8 @@ let
userLevel = 0;
};
sniffing = tunSniffing;
};
}
++ remoteDnsBridgeInbound;
outbounds = dnsOutbounds ++ [
(directOutbound useOutboundRoutingMark)
{
@@ -294,6 +385,8 @@ in
enableMixed = true;
enableTProxy = constants.privileged;
useOutboundRoutingMark = constants.privileged;
# Pure XRay only, where the hybrid sidecar's DNS bridge ports are free.
remoteDnsBridgePort = constants.xrayDnsBridgePorts.socks;
};
tun = mkConfig {
@@ -304,6 +397,7 @@ in
tunMtu = globalTun.mtu;
useOutboundRoutingMark = true;
enableTunFakeDns = true;
remoteDnsBridgePort = constants.xrayDnsBridgePorts.tun;
};
perAppTun = mkConfig {
@@ -314,5 +408,6 @@ in
tunMtu = perAppRoutingTun.mtu;
useOutboundRoutingMark = true;
enableTunFakeDns = true;
remoteDnsBridgePort = constants.xrayDnsBridgePorts.perAppTun;
};
}
+5 -1
View File
@@ -34,7 +34,8 @@ let
proxyInboundsSelfSources
proxyInboundsRuntimeEnabled
proxyInboundsRuntimeVias
proxyInboundRuntimePorts
proxyInboundsHostPorts
proxyInboundsLoopback
;
inherit (rules) zapretDirectRules;
};
@@ -99,6 +100,8 @@ let
in
{
spool = derived.constants.runtimeInboundsDir;
# Rootless, the spool is the user's alone: its own .lock serves.
lock = if cfg.host.privileged then derived.constants.runtimeInboundsLock else null;
inherit (rt) ports fallbackDests tlsCertificates;
vias = derived.proxyInboundsRuntimeVias;
defaultVia = derived.proxyInboundsCfg.routing.via;
@@ -125,6 +128,7 @@ let
shareLinks = derived.proxyInboundsCfg.shareLinks;
# Listeners the onion service carries, which get a second set of links to it.
onionListeners = map (ib: ib.tag) derived.torOnionInbounds;
inherit (inboundRules) sniffDomainsExcluded;
listeners = map (
ib:
{
+19
View File
@@ -10,6 +10,7 @@
{
config,
options,
lib,
pkgs,
...
@@ -94,6 +95,24 @@ in
inherit (assembly) context;
})
# Settings that work, but less safely than they look. Every host type has assertions;
# warnings, not all of them.
(lib.optionalAttrs (options ? warnings) {
warnings =
let
inbounds = derived.proxyInboundsCfg;
serverSource = inbounds.routing.serverSource;
in
lib.optional
(
derived.proxyInboundsEnabled
&& inbounds.serverPorts != [ ]
&& serverSource.ipv4 == null
&& serverSource.ipv6 == null
)
"proxy-suite: inbounds.serverPorts without inbounds.routing.serverSource: inbound users reach those services from this host's own address, which they may trust (a mail server relaying for its own host relays for every user then)";
})
(lib.mkIf (cfg.zapret.engine == "zapret-discord-youtube" && cfg.zapret.enable) (
import ./zapret.nix {
inherit
+253 -8
View File
@@ -60,6 +60,8 @@ let
killSwitchEnabled =
cfg.killSwitch.enable
&& (proxyEnabled && (globalTun.enable || globalTproxy.enable) || awgGlobalAvailable);
# Fetches that go directly, past it, when the tunnel cannot carry them (killSwitch.directFallbacks).
killSwitchDirectFallbacks = killSwitchEnabled && cfg.killSwitch.directFallbacks;
perAppRoutingTun = cfg.perAppRouting.tun;
perAppRoutingTproxy = cfg.perAppRouting.tproxy;
zapretCfg = cfg.zapret;
@@ -172,7 +174,8 @@ let
whitelistBypassCfg.joiners.${tag}
// {
inherit tag;
port = 18700 + i;
# Past the AmneziaWG listeners' loopback inbounds (awgInboundBasePort, 18700 up).
port = 18750 + i;
}
) (builtins.attrNames whitelistBypassCfg.joiners)
);
@@ -213,6 +216,28 @@ let
awgRuntimeEnabled = cfg.amneziaWg.enable && cfg.amneziaWg.runtime.enable;
awgRuntimeGlobal = awgRuntimeEnabled && cfg.host.privileged;
awgRuntimeOutbounds = awgRuntimeEnabled && proxyEnabled && cfg.host.serviceManager != "supervisor";
# The loopback hops the backends dial (tunnels, Tor, joiners, OpenSSH -D, the sidecar):
# on a root host only proxy-suite-daemon and root reach them (constants.daemonMetadataGuard).
hopPorts = lib.unique (
lib.optionals warpOutboundEnabled (
lib.concatMap (d: [
d.tunnelPort
d.directPort
]) warpDevices
)
++ lib.concatMap (ob: [
ob.tunnelPort
ob.directPort
]) awgTunnelOutbounds
++ lib.optionals awgRuntimeOutbounds (
lib.genList (i: constants.awgRuntimeTunnelBasePort + i) constants.awgRuntimeTunnelSlots
)
++ lib.optional torOutboundEnabled torCfg.socksPort
++ map (j: j.port) whitelistBypassJoiners
++ lib.optional (sshProxyOutboundEnabled && !sshProxyNativeOutbound) sshProxyCfg.listener.port
++ lib.optionals hybridEnabled (builtins.attrValues constants.xraySidecarPorts)
);
# Of those, ones on an AmneziaWG interface of their own (`outbounds add --interface`): root only.
awgRuntimeIfaceOutbounds = awgRuntimeOutbounds && cfg.host.privileged;
# Some global profile may run: declared, or added at runtime.
@@ -380,13 +405,16 @@ let
# Names pass unresolved unless XRay dials itself (a direct listener, or pure XRay).
proxyInboundsResolveInSingBox = !pureXrayEnabled && !builtins.elem "direct" proxyInboundsVias;
# Even when XRay resolves (a direct listener), it hands sing-box the name, which sing-box
# looks up again: guard there too.
proxyInboundsGuardPrivate =
proxyInboundsEnabled
&& proxyInboundsCfg.routing.blockPrivate
&& proxyInboundsNeedLocalProxy
&& !pureXrayEnabled;
# sing-box looks a name up again even when XRay resolved it: guard there too, the private
# ranges with blockPrivate, else this host's loopback still.
proxyInboundsGuardPrivate = proxyInboundsEnabled && proxyInboundsNeedLocalProxy && !pureXrayEnabled;
# This host's loopback and unspecified addresses (connecting to either reaches it).
proxyInboundsLoopback = [
"127.0.0.0/8"
"::1/128"
"0.0.0.0/32"
"::/128"
];
# The guard's resolved addresses are dialed in its order, so it follows WARP's preference.
proxyInboundsGuardStrategy =
if proxyCfg.dns.strategy == null && warpCfg.enable && warpCfg.asOutbound != null then
@@ -491,6 +519,61 @@ let
to = builtins.elemAt bounds 1;
}
) (builtins.filter builtins.isString proxyInboundRuntimePorts);
# The ports of this host its inbounds' clients may reach on its own addresses: the ones
# they dial and the public ones (rules/proxy-inbounds.nix fences the rest).
proxyInboundsHostPorts = lib.unique (
map (ib: if ib.listener.sharePort != null then ib.listener.sharePort else ib.listener.port) (
# AmneziaWG is UDP to the interface, never relayed through XRay.
builtins.filter (ib: ib.listener.type != "amneziawg") proxyInbounds
)
++ lib.optionals proxyInboundsCfg.subscriptions.enable [
80
443
]
++ proxyInboundsCfg.serverPorts
++ proxyInboundRuntimePorts
);
# Every other port, as ranges { from, to }, for the backends' guard: their rules cannot
# say "all but these".
proxyInboundsHostClosedPorts =
let
open = builtins.sort (a: b: a.from < b.from) (
map (
p:
if builtins.isInt p then
{
from = p;
to = p;
}
else
let
bounds = map lib.toInt (lib.splitString "-" p);
in
{
from = builtins.elemAt bounds 0;
to = builtins.elemAt bounds 1;
}
) proxyInboundsHostPorts
);
step = acc: r: {
next = lib.max acc.next (r.to + 1);
gaps =
acc.gaps
++ lib.optional (r.from > acc.next) {
from = acc.next;
to = r.from - 1;
};
};
swept = builtins.foldl' step {
next = 1;
gaps = [ ];
} open;
in
swept.gaps
++ lib.optional (swept.next <= 65535) {
from = swept.next;
to = 65535;
};
# A raw-JSON listener could serve anything, so open both protocols for it.
proxyInboundFirewallUdpPorts = lib.unique (
map (ib: ib.listener.port) (
@@ -590,10 +673,36 @@ let
builtins.attrNames userControlCfg.groups
);
managerFlag = lib.optionalString (cfg.host.serviceManager == "systemd-user") " --user";
resolvedUpstreams = "/run/systemd/resolve/resolv.conf";
constants = {
inherit stateDir runtimeDir;
inherit (cfg.host) privileged serviceManager;
# proxy-suite's tables that are up, included by a NixOS firewall's ruleset (hosts/nixos.nix)
# so a reload that flushes it puts them back in the same transaction.
persistedNftDir = "${runtimeDir}/proxy-suite-nft";
# A bit TProxy's table sets on forwarded packets while it is up, which the kill switch's
# forward chain lets past (nftables.nix): no ip rule or other mark here uses it.
killSwitchForwardMark = 16777216; # 0x1000000
# Cloud instance metadata endpoints (AWS and most others, ECS, Tencent, Alibaba, Azure's
# WireServer, OCI; IPv6 for AWS, GCP, OCI): this host's alone, not its daemons'.
cloudMetadata = {
ipv4 = [
"169.254.169.254"
"169.254.170.2"
"169.254.0.23"
"100.100.100.200"
"168.63.129.16"
"192.0.0.192"
];
ipv6 = [
"fd00:ec2::254"
"fd20:ce::254"
"fd00:c1::a9fe:a9fe"
];
};
# Daemons (sing-box, XRay, the WARP tunnel, OpenSSH, tg-ws-proxy, wgcf) run as this
# user. Its group is not the userControl group: backend configs hold credentials. Start
# scripts still read secrets and program routing as root, then exec the daemon through
@@ -601,6 +710,19 @@ let
# On a rootless host everything already runs as the user: no service user, and
# nothing to hand files over to it.
serviceUser = "proxy-suite-daemon";
# Tor's own user, apart from the other daemons and their credentials.
torUser = "proxy-suite-tor";
# Whose traffic is proxy-suite's own, kept out of TUN and TProxy and past the kill switch.
# Not Tor's through the local proxy: whatever else it dialled would leave by the uplink.
ownTrafficUsers = [
"proxy-suite-daemon"
]
++ lib.optional (
cfg.host.privileged && torCfg.enable && torCfg.upstream != "proxy"
) "proxy-suite-tor";
ownTrafficUsersNft = "{ ${
lib.concatMapStringsSep ", " (u: ''"${u}"'') constants.ownTrafficUsers
} }";
# Shell text that only matters when the services run as root.
ifPrivileged = lib.optionalString cfg.host.privileged;
# The commands scripts manage units and read their logs with: the units live in the
@@ -616,6 +738,76 @@ let
"${pkgs.util-linux}/bin/setpriv --reuid=proxy-suite-daemon --regid=proxy-suite-daemon --clear-groups"
+ " --inh-caps=-all${keep} --ambient-caps=-all${keep} --bounding-set=-all${keep} --no-new-privs --"
);
# A per-app unit refuses to start under a global mode carrying the same traffic (not
# Conflicts=, which would let perApp members stop the global one). `patterns`: systemctl's.
refuseUnderGlobal =
pkgs: patterns:
"+${pkgs.writeShellScript "proxy-suite-per-app" ''
set -uo pipefail
(( $# )) || exit 0
active=$(${cfg.host.systemctl}${managerFlag} list-units --plain --no-legend --state=active,activating,reloading "$@" \
| ${pkgs.gawk}/bin/awk 'NR == 1 { print $1 }')
if [[ -n $active ]]; then
echo "proxy-suite: $active carries this traffic already: per-app routing stays down" >&2
exit 1
fi
''} ${lib.concatStringsSep " " patterns}";
# Cloud metadata is no destination for proxy-suite's daemons (check_server only checks
# literal addresses); lookups pass, GCP's resolver being one. "-": no nf_tables, no guard.
daemonMetadataGuard =
pkgs:
if cfg.host.privileged then
"-+${pkgs.nftables}/bin/nft -f ${pkgs.writeText "proxy-suite-routing" ''
table inet proxy_suite_daemon_guard
delete table inet proxy_suite_daemon_guard
table inet proxy_suite_daemon_guard {
chain output {
type filter hook output priority filter; policy accept;
${lib.optionalString (hopPorts != [ ]) ''
# The hops: new connections only (no reply carries their port as its
# destination), from proxy-suite-daemon or root alone.
oifname "lo" tcp dport { ${
lib.concatMapStringsSep ", " toString hopPorts
} } ct state new meta skuid != { 0, "proxy-suite-daemon" } reject with tcp reset
''}
meta skuid ${constants.ownTrafficUsersNft} ip daddr { ${lib.concatStringsSep ", " constants.cloudMetadata.ipv4} } th dport != 53 reject with icmpx admin-prohibited
meta skuid ${constants.ownTrafficUsersNft} ip6 daddr { ${lib.concatStringsSep ", " constants.cloudMetadata.ipv6} } th dport != 53 reject with icmpx admin-prohibited
}
}
''}"
else
null;
# The login of the loopback hops that take one: drawn once per boot by whatever starts
# first, so a restarted tunnel keeps the one the backend dials with.
hopUser = "hop";
hopLoginFile = "${runtimeDir}/proxy-suite-hop-login";
ensureHopLogin =
pkgs:
pkgs.writeShellScript "proxy-suite-hop-login" ''
set -euo pipefail
f=${lib.escapeShellArg "${runtimeDir}/proxy-suite-hop-login"}
[ -s "$f" ] && exit 0
${pkgs.coreutils}/bin/mkdir -p "$(${pkgs.coreutils}/bin/dirname "$f")"
umask 077
tmp=$(${pkgs.coreutils}/bin/mktemp "$f.XXXXXX")
${pkgs.coreutils}/bin/od -An -tx1 -N16 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n' > "$tmp"
${lib.optionalString cfg.host.privileged ''
${pkgs.coreutils}/bin/chgrp proxy-suite-daemon "$tmp"
${pkgs.coreutils}/bin/chmod 0640 "$tmp"
''}
# A hard link fails where the name is taken: the first to get there wins, the rest
# read what it drew.
${pkgs.coreutils}/bin/ln "$tmp" "$f" 2>/dev/null || true
${pkgs.coreutils}/bin/rm -f "$tmp"
'';
# One at a time: a unit this host does not have would fail the rest of one call.
stopPerAppUnits =
pkgs: patterns:
"-+${pkgs.writeShellScript "proxy-suite-per-app" ''
for unit in "$@"; do
${cfg.host.systemctl}${managerFlag} stop -- "$unit" 2>/dev/null || true
done
''} ${lib.concatStringsSep " " patterns}";
# The same for a unit that needs no root at all; "+" ExecStartPre/ExecStopPost
# commands still run privileged.
unprivilegedServiceConfig =
@@ -638,13 +830,48 @@ let
RestrictSUIDSGID = true;
LockPersonality = true;
};
# A direct fetch's lookups past the kill switch, which rejects resolved's and nscd's own
# queries with no tunnel up: glibc asks resolved's upstreams itself, if it lists any.
ownLookups =
pkgs:
pkgs.writeShellScript "proxy-suite-own-lookups" ''
if ${pkgs.gnugrep}/bin/grep -qs '^nameserver' ${resolvedUpstreams}; then
if [ -S /run/nscd/socket ]; then ${pkgs.util-linux}/bin/mount --bind /dev/null /run/nscd/socket || true; fi
${pkgs.util-linux}/bin/mount --bind ${resolvedUpstreams} /etc/resolv.conf || true
fi
exec "$@"
'';
killSwitchOwnLookups =
pkgs:
let
copy = "${runtimeDir}/proxy-suite-own-lookups.conf";
in
lib.optionalAttrs killSwitchEnabled {
ExecStartPre = [
"+${pkgs.writeShellScript "proxy-suite-own-lookups" ''
if ${pkgs.gnugrep}/bin/grep -qs '^nameserver' ${resolvedUpstreams}; then
${pkgs.coreutils}/bin/install -m 0644 ${resolvedUpstreams} ${copy}.$$ && ${pkgs.coreutils}/bin/mv -f ${copy}.$$ ${copy}
else
${pkgs.coreutils}/bin/rm -f ${copy}
fi
''}"
];
BindReadOnlyPaths = [ "-${copy}:/etc/resolv.conf" ];
InaccessiblePaths = [ "-/run/nscd" ];
};
# For a unit that stays root but works in a directory the userControl group writes to:
# the file system read-only but for its own State-, Runtime- and private Tmp
# directories, so a symlink the group plants there leads root's writes nowhere else.
# (No ProtectKernelModules: preStarts modprobe.)
rootInSharedDirConfig = lib.optionalAttrs cfg.host.privileged {
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
PrivateDevices = true;
ProtectKernelTunables = true;
ProtectKernelLogs = true;
ProtectControlGroups = true;
ProtectClock = true;
};
# POSIX ACLs for the groups in userControl.groups, which cannot own a file the way
# userControl.group does. Shell text, for root.
@@ -700,7 +927,12 @@ let
zapret2 = 300;
};
# Root's alone to write: state.json, and rules/ for sing-box. The autoProxy scope's
# group reads it; what members ask of the prober goes to the spool instead.
autoProxyStateDir = "${stateDir}/autoproxy";
# `proxy-ctl proxy auto learn|forget|relearn|clear`: a file per request, in a sticky
# directory, so no member takes away or rewrites another's. Root reads and removes them.
autoProxySpoolDir = "${stateDir}/autoproxy-requests";
# Runtime outbound control. The spool dirs hold one proxy URL per file and are
# group-writable when userControl is on, so proxy-ctl edits them without sudo;
@@ -710,6 +942,8 @@ let
runtimeSubscriptionsDir = "${stateDir}/subscriptions.d";
# inbounds.runtime: users/<name>.json and listeners/<tag>.json (scripts/inbound_runtime.py).
runtimeInboundsDir = "${stateDir}/inbounds.d";
# Its lock, made by root outside the spool, where no member can swap it.
runtimeInboundsLock = "${runtimeDir}/proxy-suite-inbounds-runtime.lock";
# Per-app profiles added with `proxy-ctl apps add`: <name>.json, next to the declared ones.
runtimeAppsDir = "${stateDir}/apps.d";
# Shell function for the scripts that read those spools as root. $1 a file: in a spool,
@@ -800,6 +1034,12 @@ let
ipv6 = "fd66:21::${lib.toLower (lib.toHexString (slot + 2))}";
};
perAppTunClashApiPort = 19180;
# The DNS forwarders of per-app TUN and TProxy apps (proxy-suite-per-app-<route>-dns): the
# route's at the base, pin slot n's at base + 1 + n; they ask perAppDnsUpstream with its mark.
perAppTproxyDnsBasePort = 19200;
perAppTunDnsBasePort = 19220;
# TEST-NET-1: no real resolver, and in none of the ranges the routes leave alone.
perAppDnsUpstream = "192.0.2.53";
# sing-box's fake IP caches, one per TUN config; the start script hands it to the backend.
fakeIpCacheDir = "${stateDir}/fakeip";
# Downloaded proxy.routing.ruleSets, one file each, written by the service user.
@@ -878,6 +1118,7 @@ in
globalTproxy
tproxyLanSysctl
killSwitchEnabled
killSwitchDirectFallbacks
ruleSets
ruleSetsEnabled
perAppRoutingTun
@@ -949,6 +1190,10 @@ in
proxyInboundsServerSource
proxyInboundsSelfSources
proxyInboundsGuardPrivate
proxyInboundsLoopback
hopPorts
proxyInboundsHostPorts
proxyInboundsHostClosedPorts
proxyInboundsGuardStrategy
proxyInboundViaTags
proxyInboundViaOutbounds
+15 -9
View File
@@ -27,14 +27,19 @@ rec {
};
# One system user per daemon, each in a group of its own, plus the userControl group.
systemUsersAndGroups = cfg: {
users.users = lib.genAttrs cfg.internal.systemUsers (name: {
isSystemUser = true;
group = name;
description = "proxy-suite daemons";
});
users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { });
};
systemUsersAndGroups =
cfg:
let
users = lib.unique cfg.internal.systemUsers;
in
{
users.users = lib.genAttrs users (name: {
isSystemUser = true;
group = name;
description = "proxy-suite daemons";
});
users.groups = lib.genAttrs (users ++ cfg.internal.groups) (_: { });
};
firewallPortForward = internal: {
networking.firewall = {
@@ -52,11 +57,12 @@ rec {
host,
internal,
hostPath ? null,
withSystemd ? true,
}:
let
units = import ./user-units.nix (
{
inherit lib pkgs;
inherit lib pkgs withSystemd;
inherit (host) runtimeDir;
stateDir = builtins.dirOf host.stateDir;
}
@@ -23,6 +23,7 @@ let
internal
;
hostPath = "${home}/.nix-profile/bin";
withSystemd = false;
};
supervisorDir = "${host.runtimeDir}/proxy-suite-supervisor";
@@ -76,6 +77,11 @@ in
firewallPackage = null;
resolvconfPackage = null;
};
# A phone's storage is tight: proxy-ctl falls back to less and plain curl.
services.proxy-suite.tools = {
lnav.enable = lib.mkDefault false;
curlImpersonate.enable = lib.mkDefault false;
};
# An app may not join netlink's route groups: without this sing-box fails to start.
services.proxy-suite.proxy.singBox.package = lib.mkDefault (
import ../../../pkgs/sing-box-rootless-netlink.nix { inherit (proxySuiteUpstream) sing-box; }
+59
View File
@@ -3,6 +3,7 @@
config,
options,
lib,
pkgs,
...
}:
@@ -42,6 +43,11 @@ in
) ([ firewall ] ++ lib.attrValues firewall.interfaces)
);
resolvconfPackage = config.networking.resolvconf.package;
# ntpd-rs runs as a dynamic user, which has no name until it starts.
timeSyncUsers =
lib.optional config.services.timesyncd.enable "systemd-timesync"
++ lib.optional config.services.chrony.enable "chrony"
++ lib.optional (config.services.ntp.enable || config.services.openntpd.enable) "ntp";
};
# NixOS's place for helper functions; set even while disabled, so a config can
# refer to it unconditionally.
@@ -57,8 +63,40 @@ in
security.polkit.enable = lib.mkIf cfg.internal.polkit.enable true;
security.polkit.extraConfig = forwardWith lib.mkAfter internal.polkit.rules;
# polkitd reads actions from the system profile's share/polkit-1/actions.
environment.systemPackages = lib.mkIf (cfg.internal.polkit.actions != { }) [
(pkgs.linkFarm "proxy-suite-polkit-actions" (
lib.mapAttrsToList (name: path: {
name = "share/polkit-1/actions/${name}";
inherit path;
}) cfg.internal.polkit.actions
))
];
networking.nftables.enable = lib.mkIf cfg.internal.nftables (lib.mkDefault true);
# proxy-suite's tables that are up, put back in the firewall's own load, whose flush would
# otherwise drop them (constants.persistedNftDir). An empty glob is no error.
networking.nftables.ruleset = lib.mkIf config.networking.nftables.enable (
lib.mkAfter ''
include "${cfg.host.runtimeDir}/proxy-suite-nft/*.nft"
''
);
# A persisted table that no longer loads (a user it names is gone, its store path
# collected) would fail the whole load: dropped until its unit writes it again.
systemd.services.nftables.serviceConfig = lib.mkIf config.networking.nftables.enable (
let
prune = pkgs.writeShellScript "proxy-suite-nft-prune" ''
for f in ${cfg.host.runtimeDir}/proxy-suite-nft/*.nft; do
[ -e "$f" ] || continue
${pkgs.nftables}/bin/nft -c -f "$f" > /dev/null 2>&1 || ${pkgs.coreutils}/bin/rm -f -- "$f"
done
'';
in
{
ExecStart = lib.mkBefore [ prune ];
ExecReload = lib.mkBefore [ prune ];
}
);
networking.nftables.tables = lib.mapAttrs (_: content: {
family = "inet";
inherit content;
@@ -73,6 +111,13 @@ in
trustedInterfaces = forward internal.firewall.trustedInterfaces;
};
# networkd drops foreign ip rules and unreachable routes (TProxy's and AmneziaWG's IPv6
# refusal) in every table whenever it reconfigures a link.
systemd.network.config.networkConfig = lib.mkIf config.systemd.network.enable {
ManageForeignRoutingPolicyRules = lib.mkDefault false;
ManageForeignRoutes = lib.mkDefault false;
};
boot.extraModulePackages = forward internal.kernelModulePackages;
boot.kernel.sysctl = lib.mapAttrs (_: lib.mkDefault) cfg.internal.sysctl;
@@ -88,6 +133,20 @@ in
|| config.networking.nftables.enable;
message = "proxy-suite: proxy.tproxy.lanInterfaces needs the nftables firewall (networking.nftables.enable); the iptables one drops the gateway clients' diverted traffic";
}
# The kill switch lets that user's traffic past, all of it: a login user's browser
# and apps too, whenever no tunnel is up.
(
let
user = cfg.sshProxy.serviceUser;
declared = config.users.users.${user} or null;
in
{
assertion =
!(cfg.sshProxy.enable && user != null && user != "proxy-suite-daemon" && declared != null)
|| !declared.isNormalUser;
message = "proxy-suite: sshProxy.serviceUser = \"${toString user}\" is a login user, whose traffic would all get past the kill switch; use a system user of its own (isSystemUser = true), or the default";
}
)
];
}
]
@@ -97,6 +97,11 @@ in
(lib.mkIf cfg.internal.polkit.enable {
"polkit-1/rules.d/50-proxy-suite.rules".text = cfg.internal.polkit.rules;
})
# Read from /etc by polkit 126 and later. An older one never finds the action, and
# its pkexec asks for the password every time instead.
(lib.mapAttrs' (
name: path: lib.nameValuePair "polkit-1/actions/${name}" { source = path; }
) cfg.internal.polkit.actions)
];
}
+11 -7
View File
@@ -9,6 +9,8 @@
runtimeDir,
stateDir,
hostPath ? null,
# Off under proxy-suitectl: the scripts call it by path, and nothing needs systemd's tools.
withSystemd ? true,
}:
let
@@ -71,13 +73,15 @@ let
iniSection = section: lib.mapAttrs (_: iniValue) (lib.filterAttrs (_: v: v != null) section);
# As NixOS's service `path` default.
defaultPath = with pkgs; [
coreutils
findutils
gnugrep
gnused
systemd
];
defaultPath =
with pkgs;
[
coreutils
findutils
gnugrep
gnused
]
++ lib.optional withSystemd systemd;
# As NixOS: "@" is not allowed in a store path name.
jobScript =
+169 -26
View File
@@ -8,6 +8,7 @@
let
inherit (import ./derived.nix { inherit lib cfg; })
constants
killSwitchEnabled
awgGlobalProfiles
awgGlobalAvailable
awgRuntimeGlobal
@@ -32,9 +33,9 @@ let
meta mark { ${lib.concatMapStringsSep ", " toString perAppViaMarks} } return
'';
# Shared across all three nftables rule files that do IP routing.
# Shared across the rule files; redefine, as the firewall's ruleset includes several at once.
reservedIpBlock = ''
define RESERVED_IP = {
redefine RESERVED_IP = {
10.0.0.0/8,
100.64.0.0/10,
127.0.0.0/8,
@@ -45,7 +46,7 @@ let
240.0.0.0/4,
255.255.255.255/32
}
define RESERVED_IP6 = {
redefine RESERVED_IP6 = {
::/128,
::1/128,
::ffff:0:0/96,
@@ -86,7 +87,16 @@ let
# Devices using this host as their gateway, past the destinations nobody diverts.
tproxyLanLines = lib.optionalString (globalTproxy.lanInterfaces != [ ]) (
mkTproxyLines "iifname ${lanInterfaceSet} " " meta mark set ${toString globalTproxy.fwmark}"
+ tproxyIPv6RefuseLine "iifname ${lanInterfaceSet} "
);
# Without proxy.ipv6 nothing takes IPv6: marked all the same, it meets the unreachable
# route mkTproxyRoutingUp puts in the table, and apps fall back to IPv4; on-link prefixes
# still go by the main table.
tproxyIPv6RefuseLine =
prefix:
lib.optionalString (!proxyCfg.ipv6) ''
${prefix}meta nfproto ipv6 meta mark set ${toString globalTproxy.fwmark}
'';
perAppTproxyLocalSubnetLines = mkLocalSubnetLines perAppTproxy.localSubnets;
# Without ipv6, IPv6 packets are left alone, as if the table were still `ip`.
@@ -94,11 +104,27 @@ let
lib.optionalString (!proxyCfg.ipv6) "meta nfproto ipv4 "
}meta l4proto { tcp, udp }";
# Both listeners share the port; `tproxy ip`/`tproxy ip6` only match their own family.
mkTproxyLinesTo = port: prefix: suffix: ''
${prefix}meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:${toString port}${suffix}
${lib.optionalString proxyCfg.ipv6 "${prefix}meta l4proto { tcp, udp } tproxy ip6 to [::1]:${toString port}${suffix}"}
# `mark` before the tproxy: with no listener tproxy ends the rule, and an unmarked gateway
# client's packet would be forwarded out direct.
mkTproxyLinesTo = port: prefix: mark: ''
${prefix}meta nfproto ipv4 meta l4proto { tcp, udp }${mark} tproxy ip to 127.0.0.1:${toString port}
${lib.optionalString proxyCfg.ipv6 "${prefix}meta nfproto ipv6 meta l4proto { tcp, udp }${mark} tproxy ip6 to [::1]:${toString port}"}
'';
mkTproxyLines = mkTproxyLinesTo globalTproxy.port;
# The families a TProxy mark carries into the proxy.
tproxyMarkedFamilies = lib.optionalString (!proxyCfg.ipv6) "meta nfproto ipv4 ";
# A marked packet leaving by another interface: its ip rule is gone (`ip rule flush`, a
# VPN tool) and the main table sends it out the uplink, past the kill switch, which lets
# marked packets by. `match`: TProxy without proxy.ipv6 sends on-link IPv6 out marked.
mkMisroutedGuard = mark: interfaces: match: ''
chain misrouted {
type filter hook postrouting priority filter; policy accept;
${match}meta mark ${toString mark} oifname != { ${
lib.concatMapStringsSep ", " (i: ''"${i}"'') interfaces
} } drop
}
'';
nftablesRulesFile = pkgs.writeText "proxy-suite-routing" ''
${reservedIpBlock}
@@ -112,12 +138,11 @@ let
fib daddr type local return
${tproxyLocalSubnetLines}
${tproxyLanLines}
# Packets re-entering via loopback after output marking should not
# be skipped just because the host has an RFC1918 source address.
iifname != "lo" ip saddr $RESERVED_IP return
iifname != "lo" ip6 saddr $RESERVED_IP6 return
${mkTproxyLines "" " meta mark set ${toString globalTproxy.fwmark}"}
# Past lanInterfaces, only what the output chain below marked: a neighbour
# routing through this host is never handed the proxy's exits.
${mkTproxyLines "meta mark ${toString globalTproxy.fwmark} " ""}
}
${killSwitchForwardTag}
chain output {
type route hook output priority mangle; policy accept;
${reservedLines}
@@ -126,12 +151,43 @@ let
# Replies to connections from outside, and proxy-suite's own daemons (the
# inbound XRay dials unmarked, lacking CAP_NET_ADMIN), leave as they are.
ct direction reply return
meta skuid "${serviceUser}" return
meta skuid ${constants.ownTrafficUsersNft} return
${tgWsProxyBypassMarkLine}${perAppViaMarkLine}${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"}${lib.optionalString perAppTproxy.enable " meta mark ${toString perAppTproxy.fwmark} return\n"} ${tproxyProtocols} meta mark set ${toString globalTproxy.fwmark}
${tproxyIPv6RefuseLine ""}
}
${mkMisroutedGuard globalTproxy.fwmark [ "lo" ] tproxyMarkedFamilies}
}
'';
# A marked app's lookup of a loopback resolver would be answered outside the route: the
# forwarder on `dnsPort` asks again through it. `everywhere`: every lookup (TProxy's case).
mkDnsRedirect =
{
mark,
dnsPort,
everywhere ? false,
}:
let
lookup = "meta mark ${toString mark} meta l4proto { tcp, udp } th dport 53";
to = "redirect to :${toString dnsPort}";
in
if everywhere then
''
chain dns_redirect {
type nat hook output priority dstnat; policy accept;
${lookup} ip daddr != ${constants.perAppDnsUpstream} ${to}
${lookup} meta nfproto ipv6 ${to}
}
''
else
''
chain dns_redirect {
type nat hook output priority dstnat; policy accept;
${lookup} ip daddr 127.0.0.0/8 ${to}
${lookup} ip6 daddr ::1 ${to}
}
'';
# Per-app TProxy, and a pin slot of it (perAppRouting.via): `mark` on the app's packets, which
# the backend takes on `port`.
mkPerAppTproxyRules =
@@ -139,10 +195,15 @@ let
table,
mark,
port,
dnsPort,
}:
''
${reservedIpBlock}
table inet ${table} {
# The per-user cgroup mark rules are added here at runtime (user-rules.nix).
# Defined first: a jump only resolves to a chain nft has already read.
chain app_mark {
}
chain prerouting {
type filter hook prerouting priority mangle; policy accept;
${reservedLines}
@@ -160,13 +221,23 @@ let
chain output {
type route hook output priority mangle; policy accept;
${reservedLines}
${perAppTproxyLocalSubnetLines}
meta mark ${toString globalTproxy.proxyMark} return
ct direction reply return
${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"} ct mark ${toString mark} meta mark set ${toString mark}
meta mark ${toString mark} return
# The DNS forwarder's own queries carry the mark on the socket alone: the
# connection takes it too, for prerouting to restore.
meta mark ${toString mark} ct mark set ${toString mark} return
# A lookup goes through the route wherever its resolver is (dns_redirect).
meta l4proto { tcp, udp } th dport 53 goto app_mark
${reservedLines}
${perAppTproxyLocalSubnetLines}
goto app_mark
}
${mkDnsRedirect {
inherit mark dnsPort;
everywhere = true;
}}
${mkMisroutedGuard mark [ "lo" ] tproxyMarkedFamilies}
}
'';
@@ -174,6 +245,7 @@ let
table = "proxy_suite_per_app_tproxy";
mark = perAppTproxy.fwmark;
inherit (globalTproxy) port;
dnsPort = constants.perAppTproxyDnsBasePort;
});
perAppPinTproxyRulesFiles = lib.genList (
slot:
@@ -181,6 +253,7 @@ let
table = "proxy_suite_per_app_via_tproxy_${toString slot}";
mark = constants.perAppPinTproxyFwmarkBase + slot;
port = constants.perAppPinTproxyPortBase + slot;
dnsPort = constants.perAppTproxyDnsBasePort + 1 + slot;
})
) (if perAppPinTproxy then perAppPinSlots else 0);
@@ -196,31 +269,79 @@ let
++ lib.optional tgWsProxyBypassEnabled tgWsProxyCfg.fwmark
++ lib.optional awgGlobalAvailable constants.awgGlobalFwmark
++ perAppViaMarks
++ lib.optionals perAppPinTproxy (
lib.genList (slot: constants.perAppPinTproxyFwmarkBase + slot) perAppPinSlots
)
++ killSwitchPinTproxyMarks
++ lib.optionals perAppPinTun (
lib.genList (slot: constants.perAppPinTunFwmarkBase + slot) perAppPinSlots
)
# zapret's fakes and split segments carry its desync marks; rejected, split connections stall.
++ lib.optionals cfg.zapret.enable [
1073741824 # 0x40000000, the global instance's (zapret2's, and zapret v1's default)
536870912 # 0x20000000
]
++ lib.optionals zapretApp.enable [
134217728 # 0x8000000, the per-app instance's (zapret/packages.nix, zapret2.nix)
67108864 # 0x4000000
];
killSwitchPinTproxyMarks = lib.optionals perAppPinTproxy (
lib.genList (slot: constants.perAppPinTproxyFwmarkBase + slot) perAppPinSlots
);
# TProxy's marks carry only the families it takes into the proxy; without proxy.ipv6 a
# marked IPv6 packet leaving at all is on-link or lost its ip rule.
killSwitchTproxyMarks = [
globalTproxy.fwmark
]
++ lib.optional perAppTproxy.enable perAppTproxy.fwmark
++ killSwitchPinTproxyMarks;
killSwitchMarkLines =
let
set = marks: "{ ${lib.concatMapStringsSep ", " toString (lib.unique marks)} }";
in
if proxyCfg.ipv6 then
"meta mark ${set killSwitchMarks} accept"
else
''
meta mark ${set (lib.subtractLists killSwitchTproxyMarks killSwitchMarks)} accept
meta nfproto ipv4 meta mark ${set killSwitchTproxyMarks} accept
'';
awgGlobalInterfaces =
lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles
++ lib.optional awgRuntimeGlobal cfg.amneziaWg.runtime.interfaceName;
globalTunEnabled = proxyCfg.enable && proxyCfg.tun.enable;
# Forwarded traffic (containers, VMs) follows the routes TUN and a global AmneziaWG profile
# take over, and leaves by the uplink once they go: held to the LAN until one is back.
# TProxy diverts none of it, so while TProxy is up (its table tags it) it passes.
killSwitchForward = globalTunEnabled || awgGlobalAvailable;
killSwitchForwardTag = lib.optionalString (killSwitchEnabled && killSwitchForward) ''
chain forward {
type filter hook forward priority mangle; policy accept;
${
lib.optionalString (globalTproxy.lanInterfaces != [ ]) "iifname != ${lanInterfaceSet} "
}meta mark set meta mark or ${toString constants.killSwitchForwardMark}
}
'';
killSwitchTunnelInterfaces =
lib.optional globalTunEnabled proxyCfg.tun.interface
++ lib.optionals awgGlobalAvailable awgGlobalInterfaces;
killSwitchAllowLines = ''
ip daddr $RESERVED_IP accept
ip6 daddr $RESERVED_IP6 accept
${lib.concatMapStrings (cidr: ''
${ipFamily cidr} daddr ${cidr} accept
'') globalTproxy.localSubnets}
'') cfg.killSwitch.allowedSubnets}
ct direction reply accept
'';
killSwitchRulesFile = pkgs.writeText "proxy-suite-routing" ''
${reservedIpBlock}
table inet proxy_suite_killswitch {
# The time daemons' uids, added by the up script: nft refuses a rule naming a user
# that does not exist.
set time_sync_uids {
type uid
}
chain output {
type filter hook output priority filter; policy accept;
oifname "lo" accept
meta skuid "${serviceUser}" accept
meta skuid ${constants.ownTrafficUsersNft} accept
${lib.optionalString globalTunEnabled ''
oifname "${proxyCfg.tun.interface}" accept
# sing-box's auto_redirect hands DNS to the TUN by rewriting it to the TUN's peer,
@@ -235,20 +356,34 @@ let
${lib.optionalString (
cfg.sshProxy.enable && sshProxyUser != null && sshProxyUser != serviceUser
) ''meta skuid "${sshProxyUser}" accept''}
meta mark { ${lib.concatMapStringsSep ", " toString (lib.unique killSwitchMarks)} } accept
${killSwitchMarkLines}
# A lookup the proxy did not take would name every site to the LAN resolver.
meta l4proto { tcp, udp } th dport 53 reject with icmpx admin-prohibited
${killSwitchAllowLines}
# DHCP keeps the uplink, NTP the clock that TLS depends on.
udp dport { 67, 68, 123 } accept
# DHCP keeps the uplink, NTP the clock TLS needs: from privileged ports or time daemons
# only, so no app's port-123 request learns the uplink address.
meta nfproto ipv4 udp sport 68 udp dport 67 accept
meta nfproto ipv6 udp sport 546 udp dport 547 accept
udp sport 123 udp dport 123 accept
meta skuid @time_sync_uids udp dport 123 accept
reject with icmpx admin-prohibited
}
${lib.optionalString (globalTproxy.lanInterfaces != [ ]) ''
# Gateway clients: what TProxy does not divert is forwarded, to the LAN only.
${lib.optionalString (killSwitchForward || globalTproxy.lanInterfaces != [ ]) ''
# Gateway clients: what TProxy does not divert goes to the LAN only. Containers and VMs
# too while no TUN or AmneziaWG tunnel, nor TProxy, is up.
chain forward {
type filter hook forward priority filter; policy accept;
${lib.optionalString killSwitchForward ''
oifname { ${lib.concatMapStringsSep ", " (i: ''"${i}"'') killSwitchTunnelInterfaces} } accept
${lib.optionalString globalTproxy.enable "meta mark and ${toString constants.killSwitchForwardMark} != 0 accept"}
''}
${killSwitchAllowLines}
iifname ${lanInterfaceSet} reject with icmpx admin-prohibited
${
if killSwitchForward then
"reject with icmpx admin-prohibited"
else
"iifname ${lanInterfaceSet} reject with icmpx admin-prohibited"
}
}
''}
}
@@ -276,6 +411,7 @@ let
{
table,
mark,
dnsPort,
snat ? null,
}:
''
@@ -304,6 +440,11 @@ let
'') perAppTun.localSubnets}
goto app_mark
}
${mkDnsRedirect { inherit mark dnsPort; }}
${mkMisroutedGuard mark [
"lo"
perAppTun.interface
] ""}
${lib.optionalString (snat != null) ''
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
@@ -317,12 +458,14 @@ let
perAppTunChainFile = pkgs.writeText "proxy-suite-routing" (mkPerAppTunChain {
table = "proxy_suite_per_app_tun";
mark = perAppTun.fwmark;
dnsPort = constants.perAppTunDnsBasePort;
});
perAppPinTunChainFiles = lib.genList (
slot:
pkgs.writeText "proxy-suite-routing" (mkPerAppTunChain {
table = "proxy_suite_per_app_via_tun_${toString slot}";
mark = constants.perAppPinTunFwmarkBase + slot;
dnsPort = constants.perAppTunDnsBasePort + 1 + slot;
snat = constants.perAppPinTunSource slot;
})
) (if perAppPinTun then perAppPinSlots else 0);
+1
View File
@@ -21,6 +21,7 @@
./geodata.nix
./gui.nix
./tui.nix
./tools.nix
./user-control.nix
./kill-switch.nix
./host.nix
+4
View File
@@ -46,6 +46,8 @@ in
# UDP ports the host's firewall opens, as "port" or "from-to".
openUdpPorts = internalOption (types.listOf types.str) [ ];
resolvconfPackage = internalOption (types.nullOr types.package) null;
# The users the host's enabled time daemons send NTP as; null where the host cannot say.
timeSyncUsers = internalOption (types.nullOr (types.listOf types.str)) null;
};
options.services.proxy-suite.internal = {
@@ -64,6 +66,8 @@ in
enable = internalOption types.bool false;
pkexecWrapper = internalOption types.bool false;
rules = internalOption types.lines "";
# Action files by name ("<id>.policy"), for the polkit daemon to read.
actions = internalOption (types.attrsOf types.path) { };
};
nftables = internalOption types.bool false;
# nftables tables by name, family inet (NixOS only): NAT the firewall option cannot express.
+26 -3
View File
@@ -61,11 +61,26 @@ in
Ports of this host's other services that clients reach through the tunnel on
`serverAddress` and `serverAliases`, such as mail, beside the listeners' own. Direct
like those: a connection to this host from itself skips its firewall, so list only
what the firewall already opens to the internet. TCP and UDP alike.
what the firewall already opens to the internet. TCP and UDP alike. Any other port on
any address of this host is refused where the inbounds dial "direct" themselves; the
addresses are read as the inbounds start, so restart them after one changes (DHCP).
Without `routing.serverSource` these connections come from this host's own address,
which its services may trust: a mail server that relays for its own host (Postfix's
default `mynetworks`) relays for every inbound user then. Set `serverSource`, or keep
such services from trusting this host's own addresses.
'';
example = literalExpression "config.networking.firewall.allowedTCPPorts";
};
accessLog = mkOption {
type = types.bool;
default = false;
description = ''
Log every connection, with the user, their address and the site, to the journal of
proxy-suite-inbounds: who went where, for anyone who can read the journal. On with
`proxy.autoProxy` whatever this says, which learns from those lines.
'';
};
openFirewall = bool true "Open the firewall for every listener not on loopback.";
shareLinks = bool true "Generate client share links for `proxy-ctl inbounds link`. Readable by root, and by `userControl.group` with the secrets scope.";
@@ -111,7 +126,12 @@ in
proxy = t.routingFields "that clients always reach through the local proxy, whatever the listener's `via`";
blockRu = bool true ''Block Russian destinations (geosite "category-ru", geoip "ru").'';
blockPrivate = bool true "Block private and loopback addresses, so clients cannot reach this host's LAN or local services.";
blockPrivate = bool true ''
Block private and loopback addresses, so clients cannot reach this host's LAN or local
services. Off, the LAN is open but this host is not. Either way, this host's own
addresses (loopback, and its public ones as its interfaces carry them at start) are
reachable only on the listener ports and `serverPorts`, whichever `via` a client takes.
'';
zapretDirect = bool true "Send zapret hostlist sites direct, so this host's zapret unblocks them. Only for the default `via`. With a direct listener or the XRay backend, only by IP: XRay matches names by what a client puts in its handshake, whatever address it connects to.";
@@ -229,7 +249,10 @@ in
default = [ ];
description = ''
`dest` values a runtime listener's fallbacks may use, such as a decoy site. A
fallback to a `listener` must name another runtime listener.
fallback to a `listener` must name another runtime listener. A runtime listener's
`reality.dest` may be any public site on port 443; one on another port, on this host
or on a private network must be listed here. Its `hysteria.masquerade` must be a
public http(s) site, on port 80 or 443 unless its `host:port` is listed here.
'';
example = [ "127.0.0.1:8080" ];
};
+70 -8
View File
@@ -1,11 +1,73 @@
{ lib, ... }:
{ config, lib, ... }:
let
inherit (import ./lib.nix { inherit lib; }) addressOrCidrType;
hostTimeSyncUsers = config.services.proxy-suite.host.timeSyncUsers;
in
{
options.services.proxy-suite.killSwitch.enable = lib.mkEnableOption "the kill switch" // {
description = ''
Block outgoing traffic that bypasses the active global tunnel (TUN, TProxy or a global
AmneziaWG profile), including while it restarts or after it fails. LAN, DHCP and NTP stay
open; `proxy.tproxy.lanInterfaces` devices keep the LAN but lose the internet. Only turning
the tunnel off, or `proxy-ctl killswitch off`, lifts it.
'';
options.services.proxy-suite.killSwitch = {
enable = lib.mkEnableOption "the kill switch" // {
description = ''
Block outgoing traffic that bypasses the active global tunnel (TUN, TProxy or a global
AmneziaWG profile) from boot until the tunnel is up, while it restarts and after it
fails. LAN, DHCP and the time daemons' NTP stay open. Forwarded traffic TProxy does not
divert reaches the LAN only from `proxy.tproxy.lanInterfaces`. With TUN or a global
AmneziaWG profile configured, containers' and VMs' traffic is held to the LAN too while
neither that tunnel nor TProxy is up. Only turning the tunnel off with `proxy-ctl`, or
`proxy-ctl killswitch off`, lifts it, until the next boot or tunnel start.
'';
};
directFallbacks = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether, with the kill switch on, a subscription that cannot be fetched through the
tunnel is fetched once more directly, and WARP registers directly when the local proxy
cannot carry it. Either shows that server this host's own address. Off, both go through
the tunnel or not at all: a cold start with nothing cached then has no outbounds from
that subscription, and a WARP device that is itself the tunnel cannot register.
'';
};
allowedSubnets = lib.mkOption {
type = lib.types.listOf addressOrCidrType;
default = config.services.proxy-suite.proxy.tproxy.localSubnets;
defaultText = lib.literalExpression "config.services.proxy-suite.proxy.tproxy.localSubnets";
description = ''
Networks the kill switch leaves open besides the private and reserved ranges, such as
a routed IPv6 prefix on a VM bridge, whichever global mode is on. The default keeps
what TProxy leaves out reachable; set it to open a network without also taking it out
of TProxy.
'';
example = [
"192.168.0.0/16"
"2001:db8:1::/64"
];
};
timeSyncUsers = lib.mkOption {
type = lib.types.listOf lib.types.str;
default =
if hostTimeSyncUsers != null then
hostTimeSyncUsers
else
[
"systemd-timesync"
"chrony"
"_chrony"
"ntp"
"ntpsec"
];
defaultText = lib.literalMD ''
the users of the enabled timesyncd, chrony, ntp and openntpd on NixOS; elsewhere
`[ "systemd-timesync" "chrony" "_chrony" "ntp" "ntpsec" ]`
'';
description = ''
Users that may send NTP (UDP port 123) past the kill switch. Users that do not exist
are skipped when it starts. A daemon sending from port 123 itself, as ntpd does, needs
no entry.
'';
example = [ "chrony" ];
};
};
}
+23
View File
@@ -2,8 +2,31 @@
{ lib }:
let
inherit (lib) mkOption types;
octet = "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])";
ipv4 = "(${octet}\\.){3}${octet}";
ipv4Prefix = "/(3[0-2]|[12]?[0-9])";
# Loose on the groups (nft and ip reject a malformed one), strict on the characters.
ipv6 = "[0-9A-Fa-f]{0,4}(:[0-9A-Fa-f]{0,4}){2,7}(:${ipv4})?";
ipv6Prefix = "/(12[0-8]|1[01][0-9]|[1-9]?[0-9])";
# A readable name in docs and errors in place of the pattern.
matching =
description: pattern:
types.strMatching pattern
// {
inherit description;
};
in
{
# Interface names, addresses and CIDRs go into nft rules and scripts as they are: catch
# typos early. An interface name is the kernel's (15 bytes at most), no leading "." or "-".
interfaceType = matching "network interface name" "[A-Za-z0-9_][A-Za-z0-9_.+-]{0,14}";
ipv4CidrType = matching "IPv4 CIDR" "${ipv4}${ipv4Prefix}";
ipv6CidrType = matching "IPv6 CIDR" "${ipv6}${ipv6Prefix}";
addressOrCidrType = matching "IPv4 or IPv6 address or CIDR" "(${ipv4}(${ipv4Prefix})?|${ipv6}(${ipv6Prefix})?)";
# A listen address: an IP or a host name.
hostType = matching "IP address or host name" "[A-Za-z0-9._:-]+";
list =
description: example:
mkOption {
@@ -3,11 +3,16 @@
let
inherit (lib) mkEnableOption mkOption types;
t = import ./types.nix { inherit lib; };
inherit (import ./lib.nix { inherit lib; }) int;
inherit (import ./lib.nix { inherit lib; })
int
addressOrCidrType
interfaceType
ipv4CidrType
;
localSubnets =
description:
mkOption {
type = types.listOf types.str;
type = types.listOf addressOrCidrType;
default = [ "192.168.0.0/16" ];
inherit description;
example = [
@@ -64,15 +69,15 @@ in
localSubnets = localSubnets "Subnets that skip the proxy (DNS still goes through it).";
interface = mkOption {
type = types.str;
type = interfaceType;
default = "psperapptun0";
description = "Interface name.";
};
address = mkOption {
type = types.str;
type = ipv4CidrType;
default = "172.20.0.1/30";
description = "Interface address (CIDR).";
description = "Interface IPv4 address (CIDR).";
};
mtu = int 1400 "Interface MTU.";
@@ -41,6 +41,35 @@ in
];
};
runtimeSubscriptions = {
allowHttp = mkOption {
type = types.bool;
default = false;
description = ''
Let subscriptions added at runtime (`proxy-ctl proxy subs add`) be fetched over plain
http. Anyone on the way can then add entries of their own.
'';
};
allowInsecure = mkOption {
type = types.bool;
default = false;
description = ''
Keep entries of subscriptions added at runtime that turn certificate checks off, as
`subscriptions.*.allowInsecure` does for a declared one. Anyone on the way can then
stand in for those servers.
'';
};
allowPrivateServers = mkOption {
type = types.bool;
default = false;
description = ''
Keep entries of subscriptions added at runtime whose server is a private address, as
`subscriptions.*.allowPrivateServers` does for a declared one. Whoever can add a
subscription then picks servers on your network.
'';
};
};
subscriptionUpdateInterval = mkOption {
type = types.str;
default = "1d";
@@ -72,8 +72,8 @@ in
types.submodule {
options = {
url = mkOption {
type = types.strMatching "https?://.+";
description = "URL of the sing-box rule set.";
type = types.strMatching "https://.+";
description = "URL of the sing-box rule set (https only).";
example = "https://example.com/antifilter.srs";
};
format = mkOption {
+3 -2
View File
@@ -2,6 +2,7 @@
let
inherit (lib) mkEnableOption mkOption types;
inherit (import ./lib.nix { inherit lib; }) addressOrCidrType interfaceType;
in
{
options.services.proxy-suite.proxy.tproxy = {
@@ -32,7 +33,7 @@ in
};
localSubnets = mkOption {
type = types.listOf types.str;
type = types.listOf addressOrCidrType;
default = [ "192.168.0.0/16" ];
description = "Subnets that skip the proxy, such as your LAN and VM bridges (DNS still goes through it). IPv6 works too.";
example = [
@@ -43,7 +44,7 @@ in
};
lanInterfaces = mkOption {
type = types.listOf types.str;
type = types.listOf interfaceType;
default = [ ];
description = ''
LAN interfaces whose devices use this host as their gateway. Their TCP and UDP goes through the
+4 -3
View File
@@ -2,21 +2,22 @@
let
inherit (lib) mkEnableOption mkOption types;
inherit (import ./lib.nix { inherit lib; }) interfaceType ipv4CidrType;
in
{
options.services.proxy-suite.proxy.tun = {
enable = mkEnableOption "global TUN mode";
interface = mkOption {
type = types.str;
type = interfaceType;
default = "singtun0";
description = "TUN interface name.";
};
address = mkOption {
type = types.str;
type = ipv4CidrType;
default = "172.19.0.1/30";
description = "TUN interface address (CIDR).";
description = "TUN interface IPv4 address (CIDR).";
};
mtu = mkOption {
+12 -5
View File
@@ -13,6 +13,7 @@ let
mkOption
types
;
inherit (import ./lib.nix { inherit lib; }) hostType;
in
{
options.services.proxy-suite.proxy = {
@@ -51,15 +52,17 @@ in
default = config.services.proxy-suite.host.enableIPv6;
defaultText = literalExpression "config.networking.enableIPv6";
description = ''
Route IPv6 through TUN and TProxy too. When off, TProxy ignores IPv6 and the TUNs block
it, so apps fall back to IPv4. If the uplink has no IPv6, also set
`proxy.dns.strategy = "ipv4_only"`, or direct IPv6 connections hang instead of falling back.
Route IPv6 through TUN and TProxy too. When off, TProxy refuses IPv6 past the LAN and
on-link prefixes and the TUNs block it, so apps fall back to IPv4. If the uplink has no
IPv6, also set `proxy.dns.strategy = "ipv4_only"`, or direct IPv6 connections hang
instead of falling back.
'';
};
listener = {
address = mkOption {
type = types.str;
# Also a line of proxychains' config.
type = hostType;
default = "127.0.0.1";
description = ''Address of the local SOCKS5/HTTP proxy. Use "0.0.0.0" only to expose it to the network.'';
};
@@ -116,7 +119,11 @@ in
probesPerRun = mkOption {
type = types.ints.positive;
default = 200;
description = "Maximum destinations probed per run. The rest wait for the next run, most-used first.";
description = ''
Maximum destinations probed per run: of those asked for with `proxy-ctl proxy auto
learn`, and again of those queued from traffic. The rest wait for the next run, the
queued ones most-used first. A run also ends after two hours, its probes kept.
'';
};
maxExits = mkOption {
+21 -9
View File
@@ -48,13 +48,13 @@ in
type = types.listOf types.str;
default = [ ];
description = ''
Accepted host keys, for sing-box. List every key `ssh-keyscan` prints, since the key type
is negotiated.
Accepted host keys, for sing-box, and for OpenSSH without `knownHostsFile`. List every
key `ssh-keyscan` prints, since the key type is negotiated.
'';
example = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..." ];
};
hostKeyFile = path "Known-hosts file to read host keys from (sing-box). Takes priority over `hostKey`." "/root/.ssh/known_hosts";
hostKeyFile = path "Known-hosts file to read host keys from (sing-box, and OpenSSH without `knownHostsFile`). Takes priority over `hostKey`." "/root/.ssh/known_hosts";
# The rest only apply to the OpenSSH unit (XRay, or asOutbound = false).
knownHostsFile = path "Known-hosts file for OpenSSH." "/run/secrets/proxy-suite-ssh-known-hosts";
@@ -65,9 +65,13 @@ in
"accept-new"
"no"
];
default = "accept-new";
description = "OpenSSH host key policy.";
example = "yes";
default = "yes";
description = ''
OpenSSH host key policy. "yes" needs the server's keys: `knownHostsFile`, or else
`hostKeyFile` or `hostKey`. "accept-new" takes whatever key the first connection
meets, which anyone on the way can answer then.
'';
example = "accept-new";
};
# The local SOCKS5 listener the OpenSSH unit opens.
@@ -81,14 +85,22 @@ in
port = mkOption {
type = types.port;
default = 1091;
description = "Port of the OpenSSH SOCKS5 listener.";
description = ''
Port of the OpenSSH SOCKS5 listener. It takes no login: where it is the XRay backend's
hop (`asOutbound`) on a host with root, only proxy-suite's daemons and root may
connect to it. A standalone tunnel stays open to every local user.
'';
};
};
serviceUser = mkOption {
type = token;
# A user name as nft and systemd take one.
type = types.nullOr (types.strMatching "[a-z_][a-z0-9_-]*[$]?");
default = "proxy-suite-daemon";
description = "User that runs OpenSSH. The default is sandboxed; `null` runs it as root.";
description = ''
User that runs OpenSSH. The default is sandboxed; `null` runs it as root. Another user's
traffic gets past the kill switch, all of it: never a login user's.
'';
example = "proxy";
};
+29
View File
@@ -0,0 +1,29 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
in
{
# Heavy helpers proxy-ctl can do without; nix-on-droid leaves them out by default.
options.services.proxy-suite.tools = {
lnav.enable = mkOption {
type = types.bool;
default = true;
defaultText = lib.literalMD "`true`, `false` on nix-on-droid";
description = ''
Follow `proxy-ctl logs` in lnav. Without it they follow in less.
'';
};
curlImpersonate.enable = mkOption {
type = types.bool;
default = true;
defaultText = lib.literalMD "`true`, `false` on nix-on-droid";
description = ''
Probe with curl-impersonate (`proxy-ctl proxy auto probe`, and autoProxy), which
presents a browser's TLS fingerprint. Without it probes use plain curl, which some
bot protection refuses, so a working exit can be judged blocked.
'';
};
};
}
+7 -2
View File
@@ -73,12 +73,17 @@ in
socksPort = mkOption {
type = types.port;
default = 18530;
description = "Loopback SOCKS port of Tor.";
description = ''
Loopback SOCKS port of Tor. Tor takes no login on it, so with `asOutbound` on a host with
root only proxy-suite's daemons and root may connect to it; other users reach Tor
through the proxy's own listener.
'';
};
bridges = {
lines = mkOption {
type = types.listOf types.str;
# One torrc line each: a newline would add directives of its own.
type = types.listOf (types.strMatching "[^\n]*");
default = [ ];
description = ''
Bridge lines from https://bridges.torproject.org, without the leading "Bridge". Setting
@@ -3,7 +3,7 @@
let
inherit (lib) mkOption types;
inherit (import ./amnezia-wg.nix { inherit lib; }) obfuscationType;
inherit (import ../lib.nix { inherit lib; }) nullStr;
inherit (import ../lib.nix { inherit lib; }) nullStr ipv6CidrType;
# One inbound user, in `inbounds.users` under their name (shown in share links, subscriptions
# and stats); listeners name the ones they accept.
@@ -73,10 +73,14 @@ let
'';
};
subnet6 = nullStr ''
Tunnel IPv6 subnet (ULA). `null`: IPv4 only. With `mode = "lan"` it turns on IPv6
forwarding, which stops this host from configuring itself from router advertisements.
'' "fd66:66::/64";
subnet6 =
nullStr ''
Tunnel IPv6 subnet (ULA). `null`: IPv4 only. With `mode = "lan"` it turns on IPv6
forwarding, which stops this host from configuring itself from router advertisements.
'' "fd66:66::/64"
// {
type = types.nullOr ipv6CidrType;
};
privateKeyFile = nullStr "File with the server private key, instead of a generated one." "/run/secrets/awg-server-key";
@@ -35,6 +35,29 @@ let
url = nullStr "Subscription URL. Ends up in the Nix store; prefer `urlFile`." "https://example.com/sub/token123";
urlFile = nullStr "File with the subscription URL." "/run/secrets/proxy-subscription-url";
detour = detourOption "every entry of this subscription";
allowPrivateServers = mkOption {
type = types.bool;
default = false;
description = ''
Keep entries whose server is a private address (10.0.0.0/8, 172.16.0.0/12,
192.168.0.0/16, 100.64.0.0/10, fc00::/7), such as a subscription served on your own
network. Entries pointing at this host (loopback, "localhost", unspecified) or at a
link-local or multicast address are dropped either way: whoever serves the list picks
the servers, and the fastest wins. Only literal addresses (and "localhost") are
checked. For subscriptions added at runtime, see
`proxy.runtimeSubscriptions.allowPrivateServers`.
'';
};
allowInsecure = mkOption {
type = types.bool;
default = false;
description = ''
Keep entries that turn certificate checks off (`insecure=1`, for hysteria2 and
AnyTLS on sing-box), as for a provider with self-signed certificates. Anyone on the
way can then stand in for those servers. Dropped otherwise. For subscriptions added
at runtime, see `proxy.runtimeSubscriptions.allowInsecure`.
'';
};
};
};
+13 -1
View File
@@ -77,7 +77,19 @@ let
};
nfqwsArgs = mkOption {
type = types.listOf types.str;
# They go into zapret's config inside double quotes, which its init script sources.
type = types.listOf (
types.addCheck types.str (
arg:
!builtins.any (c: lib.hasInfix c arg) [
"\""
"$"
"`"
"\\"
"\n"
]
)
);
default = [ ];
description = "Raw nfqws arguments; `--hostlist` and `--new` are added. Cannot be used with `configName`.";
example = [ "--filter-tcp=443 --dpi-desync=fake,multisplit" ];
+4 -2
View File
@@ -3,7 +3,7 @@
let
inherit (lib) mkEnableOption mkOption types;
t = import ./types.nix { inherit lib; };
inherit (import ./lib.nix { inherit lib; }) list bool;
inherit (import ./lib.nix { inherit lib; }) list bool addressOrCidrType;
in
{
options.services.proxy-suite.zapret = {
@@ -44,7 +44,9 @@ in
# Shared by both engines: a netfilter-level bypass, not an engine-specific concept.
cidrExemption = {
enable = mkEnableOption "skipping zapret for some subnets, such as NATed VMs it would break";
cidrs = list "Subnets zapret skips." [ "192.168.123.0/24" ];
cidrs = list "Subnets zapret skips." [ "192.168.123.0/24" ] // {
type = types.listOf addressOrCidrType;
};
};
zapret-discord-youtube = {
+4 -3
View File
@@ -38,7 +38,7 @@ in
};
blobs = mkOption {
type = types.attrsOf types.str;
type = types.attrsOf (types.strMatching "[^[:space:]]+");
default = { };
description = "Extra fake payloads by name (blob=<name>): a file in zapret2's files/fake, or an absolute path.";
example = {
@@ -47,14 +47,15 @@ in
};
domains = mkOption {
type = types.listOf types.str;
# Each becomes one nfqws2 argument: whitespace would make more.
type = types.listOf (types.strMatching "[^[:space:]]+");
default = [ ];
description = "Domains always treated as blocked. At runtime: `proxy-ctl zapret auto add`.";
example = [ "rutracker.org" ];
};
excludeDomains = mkOption {
type = types.listOf types.str;
type = types.listOf (types.strMatching "[^[:space:]]+");
default = [ ];
description = "Domains never touched or learned. At runtime: `proxy-ctl zapret auto exclude`.";
example = [ "bank.example.com" ];
+3 -2
View File
@@ -80,7 +80,8 @@ let
onionOutbound
;
inherit (cfg) geodata;
inherit (derived) ruleSets;
inherit (derived) ruleSets proxyInboundsLoopback;
hopPorts = lib.optionals cfg.host.privileged derived.hopPorts;
};
inherit (singBoxRules)
geositeRuleSets
@@ -101,7 +102,7 @@ let
customRuleCategory
onionOutbound
;
inherit (derived) selectionMode;
inherit (derived) selectionMode proxyInboundsLoopback;
};
inherit (xrayRules) xrayRoutingRules xrayRouteModeRules;
+116 -40
View File
@@ -9,7 +9,8 @@
proxyInboundsSelfSources,
proxyInboundsRuntimeEnabled,
proxyInboundsRuntimeVias,
proxyInboundRuntimePorts,
proxyInboundsHostPorts,
proxyInboundsLoopback,
zapretDirectRules,
}:
@@ -34,17 +35,24 @@ let
# A blocked listener stays blocked: neither serverAddress nor the proxy exceptions open it.
exceptionInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via != "block") proxyInbounds);
# Only Tor reaches .onion: to the local proxy, whose own rule sends it there. First, so no
# IP rule before it has XRay look the name up, which would leak it to a resolver.
onionRule = lib.optional proxyInboundsRouteOnion (forException {
type = "field";
ruleTag = "inbound-tor-onion";
domain = [ "domain:onion" ];
inboundTag = map (ib: ib.tag) (
builtins.filter (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds
);
outboundTag = "proxy";
});
# .onion goes to the local proxy, which hands it to Tor; first, so no IP rule looks it up.
# An address with an .onion SNI keeps its listener's via (mkSniffGuard).
onionListeners = builtins.filter (
ib: ib.via != "block" && ib.listener.type != "amneziawg"
) proxyInbounds;
onionRule =
lib.optionals (proxyInboundsRouteOnion && proxyInboundsResolveInSingBox) (
mkSniffGuard "inbound-tor-onion-sniffed" [ "domain:onion" ] onionListeners runtimeOpenVias { }
)
++ lib.optional proxyInboundsRouteOnion (forException {
type = "field";
ruleTag = "inbound-tor-onion";
domain = [ "domain:onion" ];
inboundTag = map (ib: ib.tag) (
builtins.filter (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds
);
outboundTag = "proxy";
});
blockPrivateRule = lib.optional proxyInboundsCfg.routing.blockPrivate {
type = "field";
@@ -70,30 +78,37 @@ let
# Only the ports clients dial there, and the ones listed as public: the rest of this host
# (wildcard services the firewall keeps from the internet) must not be reachable through it.
serverAddressPorts = lib.unique (
map (ib: if ib.listener.sharePort != null then ib.listener.sharePort else ib.listener.port) (
# AmneziaWG is UDP to the interface, never relayed through XRay.
builtins.filter (ib: ib.listener.type != "amneziawg") proxyInbounds
)
++ lib.optionals proxyInboundsCfg.subscriptions.enable [
80
443
]
++ proxyInboundsCfg.serverPorts
++ proxyInboundRuntimePorts
);
# An allow toward "direct" only: hostFenceRules below refuse the rest there.
serverAddressPorts = proxyInboundsHostPorts;
# XRay routes a UDP session by its first packet, so no exception leads to plain "direct"
# over UDP: IP rules go to outbounds whose finalRules allow only those addresses, name rules
# are held to TCP.
exceptionTarget =
field: ipOutbound:
if field == "ip" then
{ outboundTag = ipOutbound; }
else
{
outboundTag = "direct";
network = "tcp";
};
# Names and IPs in rules of their own: XRay ANDs the fields of one rule.
mkServerAddressRule =
ruleTag: field: items:
lib.optional (items != [ ] && any exceptionInboundTags) (forException {
type = "field";
inherit ruleTag;
${field} = items;
inboundTag = exceptionInboundTags;
port = serverPortList;
outboundTag = "direct";
});
lib.optional (items != [ ] && any exceptionInboundTags) (
forException (
{
type = "field";
inherit ruleTag;
${field} = items;
inboundTag = exceptionInboundTags;
port = serverPortList;
}
// exceptionTarget field "direct-server"
)
);
# Sniffing is routeOnly (proxy_inbound.py): a name rule also matches a connection to an IP
# whose TLS SNI or HTTP Host carries that name, and "direct" then dials the IP, from this
@@ -249,13 +264,17 @@ let
mkZapretRule =
ruleTag: field: items:
lib.optional (zapretDirectEnabled && items != [ ]) (forDefault {
type = "field";
inherit ruleTag;
${field} = items;
inboundTag = defaultInboundTags;
outboundTag = "direct";
});
lib.optional (zapretDirectEnabled && items != [ ]) (
forDefault (
{
type = "field";
inherit ruleTag;
${field} = items;
inboundTag = defaultInboundTags;
}
// exceptionTarget field "direct-zapret"
)
);
zapretDomains = map (domain: "domain:${domain}") zapretDirectRules.domains;
# Under IPOnDemand the guard would take every zapret name too: the domain rule stays off.
@@ -314,9 +333,66 @@ let
ip = [ "geoip:private" ];
}
];
# The "direct" outbound's fence around this host, whose own addresses it reaches past the
# firewall: only the ports above. The start script adds its interfaces' addresses.
hostAddresses =
proxyInboundsLoopback
++ lib.filter (range: range != null) [
proxyInboundsCfg.routing.serverSource.ipv4
proxyInboundsCfg.routing.serverSource.ipv6
]
++ serverIps;
hostFenceRules =
lib.optional (serverAddressPorts != [ ]) {
action = "allow";
ip = hostAddresses;
port = serverPortList;
_hostAddresses = true;
}
++ [
{
action = "block";
ip = hostAddresses;
_hostAddresses = true;
}
];
in
{
inherit xrayInboundRules selfFinalRules;
inherit xrayInboundRules selfFinalRules hostFenceRules;
# The names whose rules send a connection past its listener's via (this host, zapret's
# sites, .onion): matched only on the address the client asked for, never a sniffed name.
sniffDomainsExcluded = lib.unique (
serverNameDomains
++ lib.optionals zapretDirectEnabled zapretDomains
++ lib.optional (onionListeners != [ ]) "domain:onion"
);
# The outbounds the IP exceptions above lead to: each dials its own addresses alone. The
# start script puts "direct"'s fence around this host ahead of their rules.
exceptionOutbounds =
lib.optional (serverIps != [ ] && serverAddressPorts != [ ] && any exceptionInboundTags) {
protocol = "freedom";
tag = "direct-server";
settings.finalRules = [
{
action = "allow";
ip = serverIps;
port = serverPortList;
}
{ action = "block"; }
];
}
++ lib.optional (zapretDirectEnabled && zapretDirectRules.ips != [ ]) {
protocol = "freedom";
tag = "direct-zapret";
settings.finalRules = [
{
action = "allow";
ip = zapretDirectRules.ips;
}
{ action = "block"; }
];
};
# Names of this host sent direct with no guard (IPOnDemand, and no IP aliases): a warning.
unguardedServerNames = lib.optionals (!serverNameGuarded) serverNames;
}
+12 -1
View File
@@ -9,6 +9,8 @@
onionOutbound,
geodata,
ruleSets,
proxyInboundsLoopback,
hopPorts,
}:
let
@@ -85,6 +87,13 @@ let
++ lib.optional (onionOutbound != null) {
domain_suffix = [ "onion" ];
outbound = onionOutbound;
}
# A client asking for 127.0.0.1:<hop> (mixed-in's local users) would have the daemon dial
# the loopback hops the nft guard keeps from them.
++ lib.optional (hopPorts != [ ]) {
ip_cidr = proxyInboundsLoopback;
port = hopPorts;
action = "reject";
};
customRouteRules = map (rule: {
@@ -135,13 +144,15 @@ let
(mkRulesetRule "proxy" (map remoteTag r.proxy.ruleSets))
];
# Block ahead of the direct lists (category-ru's ad domains are in category-ads-all too);
# the user's own proxy lists still come first.
singBoxRoutingRules =
commonRules
++ lib.concatMap (item: item.entries) customRouteRules
++ proxyPrimaryRules
++ blockRules
++ directRules
++ safetyDirectRules
++ blockRules
++ proxyGeoRules;
# DNS follows the routing: a name that goes through the proxy is looked up through it, so
+31 -6
View File
@@ -8,6 +8,7 @@
customRuleCategory,
onionOutbound,
selectionMode,
proxyInboundsLoopback,
}:
let
@@ -117,19 +118,43 @@ let
(xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips)
];
# Kept by every route mode, like sing-box's common rules.
xrayCommonRules = lib.optional (onionOutbound != null) (
mkXrayRule "tor-onion" { domain = [ "domain:onion" ]; } onionOutbound
);
# Sniffing (and the TUN's fake DNS) puts a name in place of where a client connected: a
# TProxy LAN client's "Host: 127.0.0.1:2375", or a container's lvh.me through the TUN, must
# not reach this host's loopback. Names resolved only at the dial are the direct
# outbound's finalRules' (config-templates/xray.nix). No "::ffff:127.0.0.0/104": XRay
# refuses its whole config over it.
xrayTransparentInbounds = [
"tproxy-in"
"tproxy-in6"
"tun-in"
];
xrayLoopbackGuardRules = [
(mkXrayRule "guard-loopback-ip" {
inboundTag = xrayTransparentInbounds;
ip = proxyInboundsLoopback;
} "block")
(mkXrayRule "guard-loopback-domain" {
inboundTag = xrayTransparentInbounds;
domain = [ "domain:localhost" ];
} "block")
];
# Kept by every route mode, like sing-box's common rules.
xrayCommonRules =
xrayLoopbackGuardRules
++ lib.optional (onionOutbound != null) (
mkXrayRule "tor-onion" { domain = [ "domain:onion" ]; } onionOutbound
);
# Block ahead of the direct lists, as sing-box has it (rules/sing-box.nix).
xrayRoutingRules =
xrayCommonRules
++ lib.concatMap (item: item.entries) xrayCustomRouteRules
++ xrayProxyPrimaryRules
++ xrayBlockRules
++ xrayDirectRules
++ xraySafetyDirectRules
++ xrayProxyGeoRules
++ xrayBlockRules;
++ xrayProxyGeoRules;
xrayRouteModeRules = {
common = xrayCommonRules;
@@ -12,7 +12,8 @@ failed=0
# DNS rules read.
fetch() {
local name=$1 url=$2 path=$3 dns=$4 format=$5 detour=$6 tmp dnsTmp
local args=(--fail --silent --show-error --location --max-time 120 --max-filesize 64M)
# --proto-redir: a redirect to http would let the path pick the rules.
local args=(--fail --silent --show-error --location --proto-redir =https --max-time 120 --max-filesize 64M)
[ "$detour" = proxy ] && args+=("${proxy[@]}")
tmp=$(@coreutils@/bin/mktemp "$path.XXXXXX") || { failed=1; return; }
dnsTmp=$(@coreutils@/bin/mktemp "$dns.XXXXXX") || { rm -f "$tmp"; failed=1; return; }
+13 -7
View File
@@ -83,13 +83,19 @@ in
"proxy-suite-socks.service"
];
wants = [ "network-online.target" ];
serviceConfig = unprivilegedServiceConfig [ ] // {
Type = "oneshot";
ExecStart = fetchScript;
StateDirectory = "proxy-suite/rulesets";
StateDirectoryMode = "0755";
LoadCredential = lib.optional withProxyAuth "proxy-password:${passwordSource}";
};
serviceConfig =
unprivilegedServiceConfig [ ]
# Through the proxy curl looks nothing up itself (socks5h).
// lib.optionalAttrs (lib.any (rs: rs.detour == "direct") ruleSets) (
derived.constants.killSwitchOwnLookups pkgs
)
// {
Type = "oneshot";
ExecStart = fetchScript;
StateDirectory = "proxy-suite/rulesets";
StateDirectoryMode = "0755";
LoadCredential = lib.optional withProxyAuth "proxy-password:${passwordSource}";
};
};
timers.proxy-suite-rulesets = {
@@ -300,6 +300,17 @@ let
(!derived.sshProxyNativeOutbound || cfg.sshProxy.hostKey != [ ] || cfg.sshProxy.hostKeyFile != null)
"proxy-suite: sshProxy.hostKey or sshProxy.hostKeyFile is required when sshProxy.asOutbound = true with a SingBox or hybrid backend, because SingBox verifies host keys by value and an empty list accepts any key. Point hostKeyFile at a known-hosts file, or list every key from `ssh-keyscan -p <server.port> <server.host>` in hostKey -- the host key algorithm is negotiated, so a single pinned key fails the handshake when the server picks another algorithm."
)
# OpenSSH's own: with "yes" and no key known, it would refuse every connection.
(mkAssertion
(
!(cfg.sshProxy.enable && derived.sshProxyUnitEnabled)
|| cfg.sshProxy.strictHostKeyChecking != "yes"
|| cfg.sshProxy.knownHostsFile != null
|| cfg.sshProxy.hostKeyFile != null
|| cfg.sshProxy.hostKey != [ ]
)
"proxy-suite: sshProxy needs the server's host keys (knownHostsFile, hostKeyFile or hostKey, from `ssh-keyscan -p <server.port> <server.host>`), or strictHostKeyChecking = \"accept-new\" to trust whatever key the first connection meets"
)
(mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ])
"proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}"
)
@@ -589,6 +600,17 @@ let
(requireEnabled proxyInboundsEnabled (proxyInbounds != [ ] || derived.proxyInboundsRuntimeEnabled)
"proxy-suite: inbounds.enable requires at least one entry in inbounds.listeners, or inbounds.runtime.enable"
)
# Each range is sized for any sane config, not for every one: a second listener on a
# port fails its unit, and whatever routes to it goes nowhere.
(uniqueValues true reservedLoopbackPorts
"proxy-suite: two of proxy-suite's own loopback listeners share a port (${
lib.concatMapStringsSep ", " toString (
lib.unique (
builtins.filter (port: lib.count (p: p == port) reservedLoopbackPorts > 1) reservedLoopbackPorts
)
)
}): too many AmneziaWG outbounds, AmneziaWG listeners or whitelistBypass joiners for their ranges"
)
# Runtime listeners bind only there: clear of what is bound here already.
(mkAssertion
(
@@ -1042,6 +1064,31 @@ let
)
"proxy-suite: AmneziaWG inbounds listeners route with table ${toString derived.constants.awgInboundRouteTable}, which proxy.tproxy.routeTable or a perAppRouting routeTable also uses"
)
# The tables proxy-suite numbers itself, which an option must not name too: each start
# flushes and refills its own.
(
let
c = derived.constants;
slots = base: n: lib.genList (i: base + i) n;
internal =
map (ob: ob.routeTable) derived.awgInterfaceOutbounds
++ lib.optionals derived.awgRuntimeIfaceOutbounds (
slots c.awgRuntimeIfaceTableBase c.awgRuntimeIfaceSlots
)
++ lib.optionals derived.perAppPinTproxy (slots c.perAppPinTproxyTableBase derived.perAppPinSlots)
++ lib.optionals derived.perAppPinTun (slots c.perAppPinTunTableBase derived.perAppPinSlots)
++ lib.optionals derived.perAppViaProfiles (slots c.awgAppTableBase c.awgAppSlots);
named =
lib.optional globalTproxy.enable globalTproxy.routeTable
++ lib.optional perAppRoutingTun.enable perAppRoutingTun.routeTable
++ lib.optional perAppRoutingTproxy.enable perAppRoutingTproxy.routeTable;
taken = builtins.filter (t: builtins.elem t internal) named;
in
mkAssertion (taken == [ ])
"proxy-suite: route table ${
lib.concatMapStringsSep ", " toString taken
} (proxy.tproxy.routeTable or a perAppRouting routeTable) is one proxy-suite uses itself: AmneziaWG interface outbounds take ${toString c.awgOutboundRouteTableBase} up, runtime ones ${toString c.awgRuntimeIfaceTableBase} up, pin slots ${toString c.perAppPinTproxyTableBase} and ${toString c.perAppPinTunTableBase} up, apps through AmneziaWG profiles ${toString c.awgAppTableBase} up"
)
]
++ lib.concatMap (
ib:
@@ -1240,6 +1287,16 @@ let
) derived.torOnionInbounds;
whitelistBypassCfg = cfg.whitelistBypass;
whitelistBypassAssertions = [
# They become unit names, outbound tags and file names, spliced into the units' scripts.
(mkAssertion
(
!whitelistBypassCfg.enable
|| lib.all (name: builtins.match "[A-Za-z0-9][A-Za-z0-9._-]*" name != null) (
builtins.attrNames whitelistBypassCfg.joiners ++ builtins.attrNames whitelistBypassCfg.creators
)
)
"proxy-suite: whitelistBypass.joiners and .creators names must be letters, digits, '.', '_' and '-', starting with a letter or digit"
)
(requireEnabled (
derived.whitelistBypassJoiners != [ ]
) proxyEnabled "proxy-suite: whitelistBypass.joiners requires proxy.enable = true")
@@ -1319,8 +1376,15 @@ let
"proxy-suite: tor.socksPort ${toString torCfg.socksPort} collides with another proxy-suite listener"
)
];
# zapret2.blobs' names go into nfqws2's argv as --blob=<name>:@<file>.
blobNameAssertions = map (
name:
mkAssertion (builtins.match "[A-Za-z0-9._-]+" name != null)
"proxy-suite: zapret.zapret2.blobs name '${name}' must be letters, digits, dot, dash and underscore"
) (builtins.attrNames cfg.zapret.zapret2.blobs);
in
rootlessAssertions
++ blobNameAssertions
++ featureAssertions
++ torAssertions
++ whitelistBypassAssertions
+37 -4
View File
@@ -68,6 +68,10 @@ rec {
ExecStart = execStart;
Restart = "on-failure";
RestartSec = 5;
# Backing off to two minutes: a unit that cannot come up would refetch what it lacks
# every 5 s for good.
RestartSteps = 5;
RestartMaxDelaySec = 120;
RuntimeDirectory = runtimeDirectory;
}
// lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; }
@@ -128,11 +132,13 @@ rec {
execStart,
execStop,
}:
mkOneshotService {
# Requires=: holds the shared backend up (StopWhenUnneeded=) and restarts this with it,
# its crash included. Restarted by a switch, not stopped and started: a stop drops the hold.
lib.recursiveUpdate (mkOneshotService {
inherit description execStart execStop;
requires = [ "${backendService}.service" ];
after = [ "${backendService}.service" ];
};
}) { serviceConfig."X-StopIfChanged" = false; };
mkAnchorService =
sliceName: description:
@@ -201,6 +207,19 @@ rec {
${nft} delete table ${family} ${table} 2>/dev/null || true
'';
# A table's rules file swapped in whole, in one transaction: for a reload after the
# firewall flushed the ruleset, where a delete-then-load would leave a gap.
mkNftReplaceTable =
{
nft,
family,
table,
file,
}:
''
{ printf '%s\n' "table ${family} ${table}" "delete table ${family} ${table}"; cat ${file}; } | ${nft} -f -
'';
mkIpRuleDeleteByFwmark =
{
ip,
@@ -275,11 +294,15 @@ rec {
;
}}
${mkIpLocalDefaultRouteDelete { inherit ip family table; }}
${ip} ${family} route del unreachable default table ${toString table} 2>/dev/null || true
'')
[
"-4"
"-6"
];
]
+ ''
while ${ip} -6 rule del fwmark ${toString fwmark} table main suppress_prefixlength 0 2>/dev/null; do :; done
'';
mkTproxyRoutingUp =
{
@@ -291,7 +314,17 @@ rec {
lib.concatMapStrings (family: ''
${ip} ${family} route replace local default dev lo table ${toString table}
${ip} ${family} rule add fwmark ${toString fwmark} table ${toString table}
'') ([ "-4" ] ++ lib.optional ipv6 "-6");
'') ([ "-4" ] ++ lib.optional ipv6 "-6")
# Without proxy.ipv6, marked IPv6 would leave directly: unreachable instead, so apps fall
# back to IPv4. Not where the kernel has no IPv6 at all. On-link IPv6 still goes by main
# (suppress_prefixlength 0: any route but its default); added last, it is looked at first.
+ lib.optionalString (!ipv6) ''
if [ -e /proc/net/if_inet6 ]; then
${ip} -6 route replace unreachable default table ${toString table}
${ip} -6 rule add fwmark ${toString fwmark} table ${toString table}
${ip} -6 rule add fwmark ${toString fwmark} table main suppress_prefixlength 0
fi
'';
mkIpLinkDelete =
{
+4
View File
@@ -113,6 +113,10 @@ let
ip
nft
;
# NixOS's firewall loads the tables in constants.persistedNftDir itself (hosts/nixos.nix).
firewallIncludesTables = cfg.host.privileged && cfg.host.kind == "nixos";
# Fetches subscriptions through the tunnel (subscriptions.nix): no daemon, never exempt.
subscriptionFetchUser = "proxy-suite-fetch";
# Filled in below; lazily, so the sub-modules can read each other's results.
inherit scripts perAppRouting;
};
+13 -2
View File
@@ -60,6 +60,9 @@ in
proxychainsConfigFile
amneziaWgProfileNamesFile
;
withSystemd = constants.serviceManager != "supervisor";
withLnav = cfg.tools.lnav.enable;
withCurlImpersonate = cfg.tools.curlImpersonate.enable;
env = {
CLASH_API = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
SELECTION = selectionMode;
@@ -134,7 +137,6 @@ in
INBOUNDS_ENABLED = flag proxyInboundsEnabled;
INBOUNDS_LINKS_FILE = proxyInboundsLinksFile;
INBOUNDS_STATS_FILE = constants.inboundStatsFile;
INBOUNDS_XRAY = proxyInboundsXray;
INBOUNDS_API = "unix://${constants.inboundStatsApiSocket}";
INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile;
INBOUNDS_SUB_BASE_URL =
@@ -153,19 +155,28 @@ in
OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile;
RUNTIME_OUTBOUNDS_DIR = constants.runtimeOutboundsDir;
RUNTIME_SUBS_DIR = constants.runtimeSubscriptionsDir;
RUNTIME_SUBS_ALLOW_HTTP = flag proxyCfg.runtimeSubscriptions.allowHttp;
USER_CONTROL_GROUP = userControlCfg.group;
# {group: [scopes]}: what proxy-suite-clash-api lets each group's members ask.
USER_CONTROL_GROUPS = builtins.toJSON ctx.clashBrokerGroups;
LOCAL_PROXY_URL = "http://${localProxy.hostPart}:${toString proxyCfg.listener.port}";
AUTOPROXY_ENABLED = flag proxyCfg.autoProxy.enable;
AUTOPROXY_STATE_DIR = constants.autoProxyStateDir;
AUTOPROXY_SPOOL_DIR = constants.autoProxySpoolDir;
TOR_CONTROL_SOCKET = constants.torControlSocket;
SING_BOX = "${singBoxCfg.package}/bin/sing-box";
STATE_DIR = constants.stateDir;
RUNTIME_DIR = constants.runtimeDir;
SERVICE_MANAGER = constants.serviceManager;
PRIVILEGED = flag constants.privileged;
}
# Only the engines this host runs, so the other stays out of the closure; unset,
# proxy_ctl.py looks on PATH and skips what it cannot run.
// lib.optionalAttrs ctx.singBoxEnabled {
SING_BOX = "${singBoxCfg.package}/bin/sing-box";
}
// lib.optionalAttrs proxyInboundsEnabled {
INBOUNDS_XRAY = proxyInboundsXray;
}
// lib.optionalAttrs ctx.clashBrokerEnabled {
CLASH_BROKER = constants.clashBrokerSocket;
}
+99 -25
View File
@@ -102,6 +102,10 @@ let
++ lib.optional cfg.whitelistBypass.enable {
path = "${constants.stateDir}/whitelist-bypass";
scope = "whitelistBypass";
}
++ lib.optional cfg.proxy.autoProxy.enable {
path = constants.autoProxySpoolDir;
scope = "autoProxy";
};
serviceUnits = import ./units.nix {
@@ -122,7 +126,12 @@ let
import ../autoproxy.nix {
inherit lib pkgs cfg;
inherit (control) proxyCtl;
inherit (constants) autoProxyStateDir runtimeDir journalctl;
inherit (constants)
autoProxyStateDir
autoProxySpoolDir
runtimeDir
journalctl
;
inherit userControlAllows;
}
);
@@ -140,8 +149,17 @@ let
# health/ takes hints from watchdogs; groups-state.json is for the front ends.
RuntimeDirectory = "proxy-suite-outbound-groups";
RuntimeDirectoryMode = "0755";
}
// lib.optionalAttrs cfg.host.privileged {
# health/ is the watchdogs' (root's and the service user's) to write to, not every
# local user's. Made here, with the capabilities the watcher lacks.
ExecStartPre = "+${pkgs.coreutils}/bin/install -d -m 1730 -o root -g ${constants.serviceUser} ${constants.runtimeDir}/proxy-suite-outbound-groups/health";
}
// {
NoNewPrivileges = true;
PrivateTmp = true;
# Root without capabilities still owns the disks' device nodes.
PrivateDevices = true;
ProtectSystem = "strict";
ProtectHome = true;
ProtectClock = true;
@@ -176,6 +194,8 @@ let
CapabilityBoundingSet = [ "" ];
NoNewPrivileges = true;
PrivateTmp = true;
# Root without capabilities still owns the disks' device nodes.
PrivateDevices = true;
ProtectSystem = "strict";
ProtectHome = true;
ProtectClock = true;
@@ -242,8 +262,10 @@ lib.mkMerge [
services.proxy-suite.internal = {
# The GUI's pkexec needs its setuid wrapper.
polkit.pkexecWrapper = lib.mkIf (cfg.enable && cfg.gui.enable) true;
# See constants.serviceUser.
systemUsers = [ constants.serviceUser ];
# See constants.serviceUser; and the subscription fetcher's (subscriptions.nix).
systemUsers =
constants.ownTrafficUsers
++ lib.optional (constants.privileged && proxyEnabled) context.ctx.subscriptionFetchUser;
packages = [
control.proxyCtl
@@ -289,13 +311,17 @@ lib.mkMerge [
# carry a mark whose table has no route back. Only those: the LAN is not trusted.
(lib.mkIf (tproxyLanSysctl != { }) (
let
rules = lib.concatMapStrings (interface: ''
iifname "${interface}" meta mark ${toString globalTproxy.fwmark} accept
'') globalTproxy.lanInterfaces;
rules =
extra:
lib.concatMapStrings (interface: ''
iifname "${interface}" meta mark ${toString globalTproxy.fwmark}${extra} accept
'') globalTproxy.lanInterfaces;
in
{
extraInputRules = rules;
extraReversePathFilterRules = rules;
# Into the backend's transparent socket alone: while it restarts, the mark would
# otherwise let a gateway client into any of this host's own listeners.
extraInputRules = rules " socket transparent 1";
extraReversePathFilterRules = rules "";
}
))
];
@@ -306,18 +332,12 @@ lib.mkMerge [
);
polkit.enable = lib.mkIf (cfg.enable && (userControlEnabled || cfg.gui.enable)) true;
# The GUI's "Retry as Root" and root toggle run proxy-ctl through pkexec: one
# admin password then covers the next few minutes, as sudo's does in the TUI.
# The GUI's "Retry as Root" runs proxy-ctl through pkexec (polkit.nix), by the path
# proxy_model.elevated uses.
polkit.actions = lib.mkIf (cfg.enable && cfg.gui.enable) {
"${polkit.proxyCtlActionId}.policy" = polkit.mkProxyCtlAction "${control.proxyCtl}/bin/proxy-ctl";
};
polkit.rules = lib.mkMerge [
(lib.mkIf (cfg.enable && cfg.gui.enable) ''
polkit.addRule(function(action, subject) {
if (action.id === "org.freedesktop.policykit.exec" &&
action.lookup("program") === "${control.proxyCtl}/bin/proxy-ctl") {
return polkit.Result.AUTH_ADMIN_KEEP;
}
return null;
});
'')
(lib.mkIf (cfg.enable && userControlEnabled) ''
polkit.addRule(function(action, subject) {
if (!(${polkit.userControlPolkitMember})) {
@@ -356,6 +376,18 @@ lib.mkMerge [
"${constants.runtimeInboundsDir}/listeners"
]
))
# inbound_runtime.py's lock, outside the spool the members write to; it opens it
# read-only and never makes it, so it must be here first.
(lib.mkIf (cfg.enable && derived.proxyInboundsRuntimeEnabled && constants.privileged) (
[
"f ${constants.runtimeInboundsLock} 0640 root ${
if userControlAllows "inbounds" then userControlCfg.group else "root"
} -"
]
++ map (g: "a+ ${constants.runtimeInboundsLock} - - - - g:${g}:r") (
derived.userControlExtraGroupsFor "inbounds"
)
))
# Per-app profiles added at runtime: read by everyone who runs apps, written with the
# perApp scope.
(lib.mkIf (cfg.enable && cfg.perAppRouting.enable) [
@@ -436,6 +468,33 @@ lib.mkMerge [
"proxy-suite: no outbounds or subscriptions are declared; the proxy will not start"
+ " until one is added with `proxy-ctl proxy outbounds add`"
)
# On Android every app reaches loopback: one that finds the proxy there learns its exit,
# or tells whoever asks that this phone runs one.
++ lib.optional (cfg.host.kind == "nix-on-droid" && proxyEnabled && !localProxyAuthEnabled) (
"proxy-suite: proxy.listener takes no login, and on Android every app can use it;"
+ " set proxy.listener.auth"
)
# Tor's SOCKS port and OpenSSH's -D take no login: without the nftables guard
# (constants.daemonMetadataGuard), every local user reaches those exits.
++
lib.optional
(
!constants.privileged
&& (
derived.torOutboundEnabled || (derived.sshProxyOutboundEnabled && !derived.sshProxyNativeOutbound)
)
)
(
"proxy-suite: without root, nothing keeps other local users (on Android, other apps) off"
+ " the loopback SOCKS ports of ${
lib.concatStringsSep " and " (
lib.optional derived.torOutboundEnabled "Tor (tor.socksPort)"
++ lib.optional (
derived.sshProxyOutboundEnabled && !derived.sshProxyNativeOutbound
) "the OpenSSH tunnel (sshProxy.listener.port)"
)
}: neither takes a login. sing-box dials SSH natively, with no listener"
)
++
lib.optional
(
@@ -452,15 +511,30 @@ lib.mkMerge [
+ " anyone who reaches the port uses your outbounds; set listener.auth, or keep it off the"
+ " firewall's allowed ports"
)
# The prober and proxy-ctl's outbound test dial these without credentials.
# OpenSSH's -D takes no login at all.
++
lib.optional
(proxyEnabled && localProxyAuthEnabled && proxyCfg.autoProxy.enable && !pureXrayEnabled)
(
"proxy-suite: proxy.listener.auth does not cover autoProxy's loopback listeners"
+ " (ports ${toString proxyCfg.autoProxy.probeBasePort}-${
toString (proxyCfg.autoProxy.probeBasePort + proxyCfg.autoProxy.maxExits - 1)
} and ${toString constants.outboundTestPort}): every local user reaches your exits through them"
cfg.sshProxy.enable
&& !(
lib.hasPrefix "127." cfg.sshProxy.listener.address
|| cfg.sshProxy.listener.address == "::1"
|| cfg.sshProxy.listener.address == "localhost"
)
)
(
"proxy-suite: sshProxy.listener.address is ${cfg.sshProxy.listener.address}: its SOCKS port takes"
+ " no login, so anyone who reaches it uses the SSH server; keep it on loopback, or off the"
+ " firewall's allowed ports"
)
++
lib.optional
(
cfg.warp.enable && cfg.warp.generatorUrl != null && !lib.hasPrefix "https://" cfg.warp.generatorUrl
)
(
"proxy-suite: warp.generatorUrl is not https://: anyone on the way can hand back a profile"
+ " of their own, and the WARP traffic goes to them"
)
# rules/proxy-inbounds.nix guards the names of this host only where XRay leaves names
# unresolved, or where IP aliases catch a name that resolves here first.
@@ -34,6 +34,7 @@ let
findBin
headBin
;
inherit (ctx.constants) systemctl;
}
// slices
);
@@ -73,7 +73,6 @@ let
family = "-6";
table = perAppRoutingTun.routeTable;
}}
${nft} -f ${perAppTunChainFile}
${perAppTunWaitForInterface}
# The backend may not have brought the link up yet, and routes via a down link fail
# with "Device for nexthop is not up".
@@ -84,7 +83,8 @@ let
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable}
# No uplink src, as in xrayTunUpScript: it goes stale when the uplink address changes.
${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
# Cleared above, so it goes in; if it did not, marked apps would leave by the main table.
${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
${
if ipv6 then
''
@@ -100,6 +100,8 @@ let
''
}
${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
# The marking last, once its routes are in (as tproxyUpScript).
${nft} -f ${perAppTunChainFile}
'';
perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app" ''
@@ -140,6 +142,27 @@ let
${builders.flushResolvedCaches}
'';
# After a firewall reload that flushed the ruleset: the marking alone (the routes stay).
# The users' rules go back in with their own units' reload, ordered after this one.
perAppTunReloadScript = pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${builders.mkNftReplaceTable {
inherit nft;
family = "inet";
table = "proxy_suite_per_app_tun";
file = perAppTunChainFile;
}}
'';
perAppTproxyReloadScript = pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${builders.mkNftReplaceTable {
inherit nft;
family = "inet";
table = "proxy_suite_per_app_tproxy";
file = perAppTproxyRulesFile;
}}
'';
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
@@ -154,13 +177,14 @@ let
table = perAppRoutingTproxy.routeTable;
}}
${nft} -f ${perAppTproxyRulesFile}
# The route first, then the marking (as tproxyUpScript).
${builders.mkTproxyRoutingUp {
inherit ip;
inherit ipv6;
fwmark = perAppRoutingTproxy.fwmark;
table = perAppRoutingTproxy.routeTable;
}}
${nft} -f ${perAppTproxyRulesFile}
'';
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app" ''
@@ -181,8 +205,10 @@ in
{
inherit
perAppTunUpScript
perAppTunReloadScript
perAppTunDownScript
perAppTproxyUpScript
perAppTproxyReloadScript
perAppTproxyDownScript
;
}
@@ -13,9 +13,83 @@
grepBin,
findBin,
headBin,
systemctl,
}:
let
# The hold: what a per-app slice sends unmarked is turned away, in a table no backend
# touches, so a backend restart or crash holds the apps rather than letting them out
# directly. It goes with the user's unit, not its restart, and mirrors the route's exceptions.
holdTable = "proxy_suite_per_app_hold";
# nftables.nix's RESERVED_IP and RESERVED_IP6, which the TUN and TProxy chains leave alone.
reserved4 = [
"10.0.0.0/8"
"100.64.0.0/10"
"127.0.0.0/8"
"169.254.0.0/16"
"172.16.0.0/12"
"192.0.0.0/24"
"224.0.0.0/4"
"240.0.0.0/4"
"255.255.255.255/32"
];
reserved6 = [
"::/128"
"::1/128"
"::ffff:0:0/96"
"fc00::/7"
"fe80::/10"
"ff00::/8"
];
nftSet = items: "{ ${lib.concatStringsSep ", " items} }";
# As shell words in double quotes, printed one per line: a mark of "$mark" is the shell's.
# Every route marks lookups wherever the resolver is, loopback's too. `allow`: what goes
# unmarked, in either family.
mkHoldBodies =
{
# The marks the route's packets carry, as shell text (a number, or "$mark").
marks,
allow,
}:
let
# Not merely "no mark": since Linux 5.17 CAP_NET_RAW sets one (ping -m), so a held app
# could mark its way out. A kernel AmneziaWG interface's own encapsulated packets keep
# the app's socket with the interface's FwMark: the via route lists that mark too.
unmarked = "meta mark != { ${lib.concatStringsSep ", " marks} }";
reject = "reject with icmpx admin-prohibited";
allow4 = builtins.filter (cidr: !lib.hasInfix ":" cidr) allow;
allow6 = builtins.filter (lib.hasInfix ":") allow;
bodies = [
"${unmarked} meta l4proto { tcp, udp } th dport 53 ${reject}"
"${unmarked} ct direction != reply ip daddr != ${nftSet allow4} ${reject}"
"${unmarked} ct direction != reply ip6 daddr != ${nftSet allow6} ${reject}"
];
in
"printf '%s\\n' ${lib.concatMapStringsSep " " (body: "\"${body}\"") bodies}";
tunHold =
mark:
mkHoldBodies {
marks = [ mark ];
allow = reserved4 ++ reserved6 ++ perAppRoutingTun.localSubnets;
};
tproxyHold =
mark:
mkHoldBodies {
marks = [ mark ];
allow = reserved4 ++ reserved6 ++ perAppRoutingTproxy.localSubnets;
};
# Deletes the rules of one comment from a chain, if the table is there.
dropRulesByComment = table: chain: comment: ''
handles=$(${nft} -a list chain ${table} ${chain} 2>/dev/null \
| ${grepBin} -F "comment \"${comment}\"" \
| ${awk} '{ print $NF }' || true)
if [ -n "$handles" ]; then
while IFS= read -r handle; do
[ -n "$handle" ] || continue
${nft} delete rule ${table} ${chain} handle "$handle" || true
done <<< "$handles"
fi
'';
# `prelude` runs first and may set what the rest reads: a template whose instance carries
# more than the uid turns its $1 into the uid and sets the shell variables that `nftTable`,
# `markRule` and `sliceNameArg` (the slice's name, as shell text) then name.
@@ -30,6 +104,8 @@ let
sliceLabel,
markRule,
prelude ? "",
# Shell text printing the hold's rule bodies (mkHoldBodies); null: no hold.
hold ? null,
}:
pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
@@ -58,6 +134,22 @@ let
fi
cgroup_path=''${cgroup_dir#/sys/fs/cgroup/}
cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }')
${lib.optionalString (hold != null) ''
# The hold first: from here on, nothing of the app leaves unmarked.
hold_comment="$rule_comment_prefix-hold"
${dropRulesByComment "inet ${holdTable}" "output" "$hold_comment"}
{
printf '%s\n' "add table inet ${holdTable}" \
"add chain inet ${holdTable} output { type filter hook output priority filter; policy accept; }"
# In a subshell: `hold` may be a case statement over several lines.
(
${hold}
) | while IFS= read -r body; do
printf 'add rule inet ${holdTable} output socket cgroupv2 level %s "%s" %s comment "%s"\n' \
"$cgroup_level" "$cgroup_path" "$body" "$hold_comment"
done
} | ${nft} -f -
''}
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
| ${grepBin} -F "comment \"$rule_comment_prefix-mark\"" \
@@ -81,12 +173,24 @@ let
nftTable,
nftChain,
prelude ? "",
# Whether the start put a hold in (mkUserRuleStart).
hold ? false,
# The unit this runs in, as shell text.
unitName ? ''"proxy-suite-${name}-user@$uid.service"'',
}:
pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${prelude}
uid="$1"
rule_comment_prefix="proxy-suite-${name}-user-$uid"
${lib.optionalString hold ''
# Its restart (the backend's restart or crash, through Requires=, or a switch) keeps the
# hold, a job of that type until the stop half is done: the app waits for its marking.
if ! ${systemctl} list-jobs --no-legend ${unitName} \
| ${awk} '$3 == "restart" { found = 1 } END { exit !found }'; then
${dropRulesByComment "inet ${holdTable}" "output" "$rule_comment_prefix-hold"}
fi
''}
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
| ${grepBin} -F "comment \"$rule_comment_prefix-mark\"" \
| ${awk} '{ print $NF }' || true)
@@ -107,28 +211,32 @@ let
sliceName = perAppTunSliceName;
sliceLabel = "app TUN";
markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}";
hold = tunHold (toString perAppRoutingTun.fwmark);
};
perAppTunUserRuleStop = mkUserRuleStop {
name = "per-app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tun";
nftChain = "app_mark";
hold = true;
};
perAppTproxyUserRuleStart = mkUserRuleStart {
name = "per-app-tproxy";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tproxy";
nftChain = "output";
nftChain = "app_mark";
sliceName = perAppTproxySliceName;
sliceLabel = "app TProxy";
markRule = "meta mark set ${toString perAppRoutingTproxy.fwmark} ct mark set ${toString perAppRoutingTproxy.fwmark}";
hold = tproxyHold (toString perAppRoutingTproxy.fwmark);
};
perAppTproxyUserRuleStop = mkUserRuleStop {
name = "per-app-tproxy";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tproxy";
nftChain = "output";
nftChain = "app_mark";
hold = true;
};
perAppZapretUserRuleStart = mkUserRuleStart {
@@ -148,7 +256,13 @@ let
};
in
{
inherit mkUserRuleStart mkUserRuleStop;
inherit
mkUserRuleStart
mkUserRuleStop
mkHoldBodies
tunHold
tproxyHold
;
inherit
perAppTunUserRuleStart
perAppTunUserRuleStop
@@ -27,6 +27,7 @@ let
ip
nft
jq
awk
;
inherit (constants)
awgPerAppRulePriority
@@ -91,7 +92,7 @@ let
if perAppViaProfiles then
''
slot=$(${pkgs.coreutils}/bin/head -n 1 "/run/proxy-suite-awg-app-$tag/slot" 2>/dev/null || true)
if [[ ! $slot =~ ^[0-9]+$ ]] || (( slot >= ${toString constants.awgAppSlots} )); then
if [[ ! $slot =~ ^(0|[1-9][0-9]{0,2})$ ]] || (( slot >= ${toString constants.awgAppSlots} )); then
echo "proxy-suite: AmneziaWG profile '$tag' is not up for apps (proxy-suite-awg-app@$tag)" >&2
exit 1
fi
@@ -112,9 +113,16 @@ let
}
elif ! entry=$(${jq} -ce --arg t "$tag" '.[$t] // empty' ${perAppViaFile}); then
${lib.optionalString perAppViaRuntime ''
# One added at runtime: its slot in the spool, which is group-writable (O_NOFOLLOW).
slot=$(${pkgs.coreutils}/bin/dd if="${runtimeOutboundsDir}/$tag.iface" iflag=nofollow,nonblock status=none 2>/dev/null | ${pkgs.coreutils}/bin/head -n 1 || true)
if [[ $slot =~ ^[0-9]+$ ]] && (( slot < ${toString awgRuntimeIfaceSlots} )); then
# One added at runtime: the slot its interface runs in, as proxy-suite-awg-if@ keeps it;
# else the spool's, which is group-writable (O_NOFOLLOW), and names the slot it gets
# next, not the one a tag removed and added again still runs in.
slot_file="/run/proxy-suite-awg-if-$tag/slot"
if [[ -s $slot_file && ! -L $slot_file ]]; then
slot=$(${pkgs.coreutils}/bin/head -n 1 "$slot_file")
else
slot=$(${pkgs.coreutils}/bin/dd if="${runtimeOutboundsDir}/$tag.iface" iflag=nofollow,nonblock status=none 2>/dev/null | ${pkgs.coreutils}/bin/head -n 1 || true)
fi
if [[ $slot =~ ^(0|[1-9][0-9]{0,2})$ ]] && (( slot < ${toString awgRuntimeIfaceSlots} )); then
entry=$(${jq} -nc --arg t "$tag" --argjson s "$slot" --argjson fallback ${lib.escapeShellArg (builtins.toJSON fallbackDns)} '{
interface: ("${awgRuntimeIfacePrefix}" + ($s | tostring)),
table: (${toString awgRuntimeIfaceTableBase} + $s),
@@ -217,6 +225,12 @@ let
type nat hook postrouting priority srcnat; policy accept;
oifname "$interface" meta mark $mark masquerade
}
# The app's packets out of any other interface: the ip rules are gone (networkd
# drops rules it did not make), and the main table took them to the uplink.
chain misrouted {
type filter hook postrouting priority filter; policy accept;
meta mark $mark oifname != { "lo", "$interface" } drop
}
}
EOF
@@ -237,9 +251,15 @@ let
exec ${python3} ${proxySuiteScriptsDir}/per_app_dns.py --port "$dns_port" --mark "$mark" "''${servers[@]}"
'';
# A failure keeps the marking and the unreachable rule, so the apps are turned away rather
# than sent out directly until the restart; viaUp clears it. A stop takes it all down.
viaDown = pkgs.writeShellScript "proxy-suite-per-app" ''
set -uo pipefail
${resolveInstance}
if [[ ''${SERVICE_RESULT:-success} != success ]]; then
echo "proxy-suite: per-app via $1 failed ($SERVICE_RESULT): its apps are held until it is back" >&2
exit 0
fi
${nft} delete table inet "$nft_table" 2>/dev/null || true
${rulesDown}
'';
@@ -279,7 +299,33 @@ let
slice_name="proxy-suite-per-app-via-$key.slice"
set -- "''${instance%%-*}"
'';
viaUserStart = userRules.mkUserRuleStart {
# The hold (user-rules.nix), by what the key runs via: an AmneziaWG interface takes the
# private ranges too (as viaUp's chain does), a pin slot what its route's backend takes.
viaHold = ''
case "$key" in
awg-* | app-*)
${userRules.mkHoldBodies {
marks = [
"$mark"
(toString cfg.proxy.tproxy.proxyMark)
];
allow = [
"127.0.0.0/8"
"169.254.0.0/16"
"224.0.0.0/4"
"255.255.255.255/32"
"::1/128"
"fe80::/10"
"ff00::/8"
]
++ perAppRoutingCfg.via.localSubnets;
}}
;;
tproxy-*) ${userRules.tproxyHold "$mark"} ;;
tun-*) ${userRules.tunHold "$mark"} ;;
esac
'';
viaUserRule = userRules.mkUserRuleStart {
name = "per-app-via-$key";
nftFamily = "inet";
nftTable = "$nft_table";
@@ -288,6 +334,7 @@ let
sliceLabel = "app via";
markRule = "meta mark set $mark ct mark set $mark";
prelude = userPrelude;
hold = viaHold;
};
viaUserStop = userRules.mkUserRuleStop {
name = "per-app-via-$key";
@@ -295,7 +342,88 @@ let
nftTable = "$nft_table";
nftChain = "$nft_chain";
prelude = userPrelude;
hold = true;
unitName = ''"proxy-suite-per-app-via-user@$instance.service"'';
};
# $1, a user unit's instance <uid>-<key>, to $key and $via_unit, the unit whose table
# the key's user rules go in.
viaUserKey = ''
instance=''${1:-}
if [[ ! $instance =~ ^[0-9]+-((awg|app|tproxy|tun)-[0-9a-f]+)$ ]]; then
echo "proxy-suite: '$instance' is not <uid>-<per-app via instance>" >&2
exit 1
fi
key=''${BASH_REMATCH[1]}
case "$key" in
awg-* | app-*) via_unit="proxy-suite-per-app-via@$key.service" ;;
*) via_unit="proxy-suite-per-app-via-''${key%%-*}@''${key#*-}.service" ;;
esac
'';
# Held while a user's rule goes in, and while the last user's unit takes the via unit
# down: no rule lands in a table on its way out, to leave its app unmarked.
viaUsersLock = ''
${pkgs.coreutils}/bin/mkdir -p ${pinDir}
exec 8>>"${pinDir}/users-$key.lock"
${flock} 8
'';
viaUserStart = pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${viaUserKey}
${viaUsersLock}
# proxy-ctl starts it first; one on its way down takes the table with it.
if [[ $(${constants.systemctl} show --property=ActiveState --value "$via_unit") != active ]]; then
echo "proxy-suite: $via_unit is not up" >&2
exit 1
fi
${viaUserRule} "$1"
'';
# ExecStopPost of a user's unit: with no other user's left, the via unit goes, and the
# global profile it ran through. perApp members may only start those (polkit.nix):
# stopping one under another user's apps would send them out unmarked.
viaRetire = pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${viaUserKey}
# Its own restart (a job of that type until the stop half is done) comes straight back.
if ${constants.systemctl} list-jobs --no-legend "proxy-suite-per-app-via-user@$1.service" \
| ${awk} '$3 == "restart" { found = 1 } END { exit !found }'; then
exit 0
fi
${viaUsersLock}
others=$(${constants.systemctl} list-units --plain --no-legend --state=active,activating,reloading \
"proxy-suite-per-app-via-user@*-$key.service" \
| ${awk} -v self="proxy-suite-per-app-via-user@$1.service" '$1 != self')
[[ -z $others ]] || exit 0
was=$(${constants.systemctl} show --property=ActiveState --value "$via_unit" || true)
${constants.systemctl} stop "$via_unit"
# A failed one kept its rules to hold its apps (viaDown), and a stop runs nothing more for
# it: with no app left, they go here.
if [[ $was == failed && ( $key == awg-* || $key == app-* ) ]]; then
SERVICE_RESULT=success ${viaDown} "$key" || true
${constants.systemctl} reset-failed "$via_unit" 2>/dev/null || true
fi
${lib.optionalString perAppViaProfiles ''
# After the via unit: its stop reads the profile's slot.
if [[ $key == app-* ]]; then
set -- "''${key#app-}"
${decodeTag}
${constants.systemctl} stop "proxy-suite-awg-app@$tag.service"
fi
''}
'';
# ExecStartPost of the via units, $1 the key. Their table starts empty, also on a restart
# (Restart=, or that of the backend a pin is part of), under users' units that stay
# active: their rules go back in here, or their apps would go out unmarked.
viaReapply = pkgs.writeShellScript "proxy-suite-per-app" ''
set -uo pipefail
${constants.systemctl} list-units --plain --no-legend --state=active \
"proxy-suite-per-app-via-user@*-''${1:-}.service" \
| while read -r unit _; do
instance=''${unit#proxy-suite-per-app-via-user@}
${viaUserRule} "''${instance%.service}" \
|| echo "proxy-suite: the rule of $unit did not go back in" >&2
done
'';
# The pin slots, of per-app TProxy and of per-app TUN.
pinRouteNames = lib.optional perAppPinTproxy "tproxy" ++ lib.optional perAppPinTun "tun";
pinDir = "${constants.runtimeDir}/proxy-suite-per-app-via";
@@ -308,7 +436,7 @@ let
tableBase = constants.perAppPinTproxyTableBase;
nftFiles = perAppPinTproxyRulesFiles;
# Where the user rule units add their cgroup rules, as for the per-app TProxy's own.
nftChain = "output";
nftChain = "app_mark";
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
secretFile = "${constants.runtimeDir}/proxy-suite-socks/clash-secret";
backend = "proxy-suite-socks.service";
@@ -458,6 +586,26 @@ let
set -euo pipefail
${decodeTag}
${pinSlot route true}
if [[ -z $slot ]]; then
# Every slot taken: one that nothing has run through for a minute (no user's marking
# unit for it), as a perApp member could leave behind by starting the unit alone, is
# taken back. The minute spares one proxy-ctl has just started for its app.
for (( n = 0; n < ${toString perAppPinSlots}; n++ )); do
slot_file="${pinDir}/${route}-$n"
[[ -f $slot_file ]] || continue
other=$(< "$slot_file")
[[ $other =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || continue
(( $(${pkgs.coreutils}/bin/date +%s) - $(${pkgs.coreutils}/bin/stat -c %Y "$slot_file") >= 60 )) || continue
other_hex=$(printf '%s' "$other" | ${pkgs.coreutils}/bin/od -An -tx1 | ${pkgs.coreutils}/bin/tr -d ' \n')
if [[ -z $(${constants.systemctl} list-units --plain --no-legend --state=active,activating,reloading \
"proxy-suite-per-app-via-user@*-${route}-$other_hex.service") ]]; then
echo "proxy-suite: taking back ${route} pin slot $n from '$other': nothing runs through it" >&2
${constants.systemctl} stop "proxy-suite-per-app-via-${route}@$other_hex.service" || true
break
fi
done
${pinSlot route true}
fi
if [[ -z $slot ]]; then
echo "proxy-suite: all ${toString perAppPinSlots} ${route} pin slots are taken (perAppRouting.via.pinSlots)" >&2
exit 1
@@ -472,8 +620,10 @@ let
trap release ERR
files=(${lib.concatMapStringsSep " " toString r.nftFiles})
${nft} delete table inet "$nft_table" 2>/dev/null || true
${nft} -f "''${files[$slot]}"
# The route first, then the marking: a packet marked before its route is in would
# leave by the main table, and the kill switch lets the mark through.
${r.routingUp}
${nft} -f "''${files[$slot]}"
# A backend that restarts restarts this too (PartOf), which switches it again.
select_pin "$tag" 60
'';
@@ -505,8 +655,11 @@ in
viaUp
viaDns
viaDown
viaUserRule
viaUserStart
viaUserStop
viaRetire
viaReapply
pinRoutes
pinUp
pinDown
@@ -3,6 +3,8 @@ if (typeof unit !== "string" || @verbs@.indexOf(verb) === -1) {
return null;
}
var known = @units@.indexOf(unit) !== -1;
// One of the subject's own per-app marking units, rather than one every user shares.
var own = false;
var templates = @templates@;
for (var i = 0; !known && i < templates.length; i++) {
var template = templates[i];
@@ -25,6 +27,7 @@ for (var i = 0; !known && i < templates.length; i++) {
if (owner !== uid) {
return null;
}
own = true;
}
known = true;
}
@@ -40,6 +43,9 @@ for (var prefix in scopeByUnitPrefix) {
break;
}
}
if (scope === "perApp" && !own && @sharedVerbs@.indexOf(verb) === -1) {
return null;
}
// Any of the subject's groups that holds the scope.
var groupScopes = @groupScopes@;
for (var group in groupScopes) {
+45 -1
View File
@@ -1,5 +1,5 @@
# Polkit rule body granting userControl group members passwordless control over the
# units of their scopes.
# units of their scopes; and the GUI's pkexec action for proxy-ctl.
#
# Only units this module declares, by their full names: systemd asks the same
# manage-units question with the same unit name for a transient unit
@@ -30,6 +30,10 @@ let
# A global profile brought up for `apps run --via`, by proxy-ctl as the app starts.
"proxy-suite-awg-app@" = "perApp";
"proxy-suite-awg-if@" = "outbounds";
# Their watchdogs, which pull them in (Wants=, BindsTo=): the same scope, or "services"
# would start what it does not hold.
"proxy-suite-awg-app-watchdog@" = "perApp";
"proxy-suite-awg-if-watchdog@" = "outbounds";
"proxy-suite-awg-runtime-sync." = "outbounds";
"proxy-suite-autoproxy-learn." = "autoProxy";
"proxy-suite-zapret2-cutoff." = "zapret";
@@ -50,10 +54,18 @@ let
"reload-or-try-restart"
"reset-failed"
];
# perApp units every user's apps share: start only, as a stop or restart would send the
# other users' apps out unmarked. They go once idle on their own.
sharedVerbs = [
"start"
"reset-failed"
];
proxyCtlActionId = "io.github.FUFSoB.ProxySuite.proxy-ctl";
in
{
userControlPolkitRules = fillTemplate ./polkit-rules.template.js {
verbs = builtins.toJSON verbs;
sharedVerbs = builtins.toJSON sharedVerbs;
units = builtins.toJSON units;
templates = builtins.toJSON templates;
coreutils = pkgs.coreutils;
@@ -64,4 +76,36 @@ in
userControlPolkitMember = lib.concatMapStringsSep " || " (
group: "subject.isInGroup(${builtins.toJSON group})"
) (builtins.attrNames userControlGroupScopes);
inherit proxyCtlActionId;
# pkexec's action for proxy-ctl, by its path after realpath. The password every time: a
# kept grant covers the whole session, and proxy-ctl as root runs commands (`apps run`).
mkProxyCtlAction =
program:
pkgs.writeTextFile {
name = "proxy-suite-polkit-action";
# polkitd skips a file it cannot parse, and pkexec then falls back to its generic action.
checkPhase = ''
${pkgs.libxml2.bin}/bin/xmllint --noout --nonet \
--dtdvalid ${pkgs.polkit.out}/share/polkit-1/policyconfig-1.dtd "$target"
'';
text = ''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>
<vendor>proxy-suite</vendor>
<action id="${proxyCtlActionId}">
<description>Run proxy-ctl as root</description>
<message>Authentication is required to change proxy-suite as root</message>
<defaults>
<allow_any>auth_admin</allow_any>
<allow_inactive>auth_admin</allow_inactive>
<allow_active>auth_admin</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.exec.path">${program}</annotate>
</action>
</policyconfig>
'';
};
}
@@ -31,6 +31,10 @@ let
builders
constants
;
# A value in a shell comment, on that one line: a newline in a tag (types.str) would end
# the comment and run the rest as root.
oneLine = value: builtins.replaceStrings [ "\n" "\r" ] [ " " " " ] (toString value);
runtimeDir = "${constants.runtimeDir}/proxy-suite-inbounds";
linksFile = "${runtimeDir}/links.json";
subscriptionsFile = "${runtimeDir}/subscriptions.json";
@@ -126,7 +130,7 @@ let
in
if urlSource == null then
''
# via outbound: ${ob.tag} (static xray json)
# via outbound: ${oneLine ob.tag} (static xray json)
OB_JSON=$(cat ${
pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON (ob.xrayJson // { inherit (ob) tag; }))
})
@@ -135,7 +139,7 @@ let
''
else
''
# via outbound: ${ob.tag}
# via outbound: ${oneLine ob.tag}
URL=$(cat ${lib.escapeShellArg urlSource})
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \
--backend xray --tag ${lib.escapeShellArg ob.tag})
@@ -165,9 +169,12 @@ let
printf '%s' "$body" > "$SUB_DIR.new/$token"
done
chmod -R u=rwX,g=rX,o= "$SUB_DIR.new"
# Traverse-only for the group: the web server opens a token by name but can never
# list them all (autoindex, a stray directory listing).
chmod 0710 "$SUB_DIR.new"
${constants.ifPrivileged ''
${pkgs.coreutils}/bin/chgrp -R ${lib.escapeShellArg subsCfg.group} "$SUB_DIR.new" ||
echo "proxy-suite: group ${subsCfg.group} cannot be given the subscriptions; they stay root-only" >&2''}
echo "proxy-suite: group "${lib.escapeShellArg subsCfg.group}" cannot be given the subscriptions; they stay root-only" >&2''}
rm -rf "$SUB_DIR"
mv "$SUB_DIR.new" "$SUB_DIR"
${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}"
@@ -194,11 +201,19 @@ let
INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED")
# Every address this host has now, for the direct outbound's fence (rules/proxy-inbounds.nix):
# one it gains later is fenced from the next start. Where netlink is closed (Android), the
# fence keeps what the configuration knows.
if ! HOST_ADDRESSES=$(${ip} -j addr show | ${jq} -c '[.[].addr_info[]?.local | strings] | unique'); then
echo "proxy-suite: cannot list this host's addresses; direct reaches any port of those not configured" >&2
HOST_ADDRESSES='[]'
fi
OUTBOUNDS_JSON='[]'
${viaOutboundsBlock}
${lib.optionalString needsLocalProxyAuth ''
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
LOCAL_PROXY_PASSWORD="$(cat ${lib.escapeShellArg localProxyAuthPasswordSource})"
''}
# With inbounds.runtime, the routing rules are build-inbound.py's: the template's with the
@@ -216,8 +231,19 @@ let
} \
--argjson runtime ${if proxyInboundsRuntimeEnabled then "true" else "false"} \
--slurpfile rendered <(printf '%s' "$RENDERED") \
--argjson host_addresses "$HOST_ADDRESSES" \
'.inbounds += $ibs[0]
| (.outbounds[] | select(.tag == "direct") | .settings.finalRules[] | select(._hostAddresses))
|= (.ip += ($host_addresses - .ip) | del(._hostAddresses))
| .outbounds = $obs[0] + .outbounds
# A via outbound that is freedom too (xrayJson, say, for its fragment settings)
# dials from this host as "direct" does: the same fence, ahead of its own rules;
# all of it but the closing allow of "direct", which would end them.
| ([.outbounds[] | select(.tag == "direct") | .settings.finalRules // []] | first // []) as $fence
| (.outbounds[] | select(.protocol == "freedom" and .tag != "direct"
and ((.tag // "") | startswith("direct-self") | not)))
|= (.settings = ((.settings // {})
| .finalRules = (($fence | map(select(. != {action: "allow"}))) + (.finalRules // []))))
| if $runtime then
.routing.rules = $rendered[0].rules
| .outbounds += $rendered[0].selfOutbounds
@@ -262,7 +288,8 @@ let
else
''
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp"''}
chmod 640 "$RUNTIME_DIR/config.json.tmp"
# Without root the group is the user's own primary one, which may be shared.
chmod ${if constants.privileged then "640" else "600"} "$RUNTIME_DIR/config.json.tmp"
''
}
${constants.grantFileAcl pkgs ''"$RUNTIME_DIR/config.json.tmp"''
@@ -271,26 +298,17 @@ let
}
mv "$RUNTIME_DIR/config.json.tmp" "$RUNTIME_DIR/config.json"
# The stats API's socket takes this setgid directory's group: XRay cannot chown it.
# The stats API's socket: the daemon's and root's alone. Whoever reaches it can reset the
# counters, wiping per-user traffic before the collector adds it up; the stats scope
# reads the collector's file instead.
API_DIR=$(dirname ${lib.escapeShellArg constants.inboundStatsApiSocket})
rm -rf "$API_DIR"
${
if !constants.privileged then
''mkdir -m 0700 "$API_DIR"''
else if userControlAllows "stats" then
''
install -d -m 2750 -o ${constants.serviceUser} -g ${lib.escapeShellArg userControlCfg.group} "$API_DIR" ||
install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"''
else
''install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"''
''install -d -m 0700 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"''
}
# userControl.groups with the stats scope: into the directory, and onto the socket XRay
# makes in it as its own group is (a default entry; the socket's mode caps it).
${lib.optionalString (constants.privileged && userControlExtraGroupsFor "stats" != [ ]) ''
${pkgs.acl}/bin/setfacl -m ${
lib.concatMapStringsSep "," (g: "g:${g}:rx,d:g:${g}:rwx") (userControlExtraGroupsFor "stats")
} -- "$API_DIR"
''}
${writeLinksBlock}
${writeSubscriptionsBlock}
@@ -300,7 +318,8 @@ let
'';
# Adds XRay's counters to the daily totals, read and reset in one call, and notes who
# is online. Run by a timer, and by the inbounds' ExecStop, so a restart loses nothing.
# is online: .online, for `proxy-ctl inbounds online` without the API. Run by a timer,
# and by the inbounds' ExecStop, so a restart loses nothing.
collectInboundStats = pkgs.writeShellScript "proxy-suite-inbounds" ''
set -euo pipefail
file=${lib.escapeShellArg constants.inboundStatsFile}
@@ -326,18 +345,22 @@ let
}
[ -s "$file" ] || echo '{}' > "$file"
tmp=$(${pkgs.coreutils}/bin/mktemp "$file.XXXXXX")
${jq} --argjson q "$reading" --argjson online "$online" --argjson awg "$awg" \
# Slurped, not --argjson: one argument holds at most 128 KiB, which a few hundred users'
# counters outgrow, and the reading above already reset them.
${jq} --slurpfile q_ <(printf '%s' "$reading") --slurpfile online_ <(printf '%s' "$online") \
--slurpfile awg_ <(printf '%s' "$awg") \
--arg day "$(${pkgs.coreutils}/bin/date +%F)" \
--argjson now "$(${pkgs.coreutils}/bin/date +%s)" \
-f ${
"\$q_[0] as \$q | \$online_[0] as \$online | \$awg_[0] as \$awg | $(< ${
builtins.path {
name = "proxy-suite-inbounds";
path = ../inbound-stats-add.jq;
}
} "$file" > "$tmp"
})
| .online = (\$online.users // [])" "$file" > "$tmp"
${lib.optionalString (userControlAllows "stats") ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$tmp" ||
echo "proxy-suite: group ${userControlCfg.group} cannot read the stats; they stay root-only" >&2
echo "proxy-suite: group "${lib.escapeShellArg userControlCfg.group}" cannot read the stats; they stay root-only" >&2
''}
chmod ${if userControlAllows "stats" then "640" else "600"} "$tmp"
${constants.grantFileAcl pkgs ''"$tmp"'' (userControlExtraGroupsFor "stats") "r"}
+108 -17
View File
@@ -15,6 +15,7 @@ let
tproxyLanSysctl
perAppRoutingTun
proxyCfg
cfg
;
inherit (proxyCfg) ipv6;
inherit (constants)
@@ -47,6 +48,23 @@ let
"-6"
];
# A table, as NixOS's firewall includes it (constants.persistedNftDir): written aside and
# renamed, never half there. `lines`: its rules, as shell words printed one per line.
persistedNftDir = ctx.constants.persistedNftDir;
persistTable =
table: lines:
lib.optionalString ctx.firewallIncludesTables ''
${pkgs.coreutils}/bin/install -d -m 0700 ${persistedNftDir}
(
umask 077
printf '%s\n' "add table inet ${table}" "delete table inet ${table}" ${lines} \
> ${persistedNftDir}/${table}.nft.tmp
) && mv -f ${persistedNftDir}/${table}.nft.tmp ${persistedNftDir}/${table}.nft
'';
# Before the table goes: a firewall reload in between would bring it back.
unpersistTable =
table: lib.optionalString ctx.firewallIncludesTables "rm -f ${persistedNftDir}/${table}.nft";
# Replies to connections from outside (sshd, a game server, anything listening) take
# proxyMark, so the fwmark rule sends them back out the way they came instead of into
# the TUN, where nothing expects them. Locally started connections stay "original".
@@ -72,18 +90,30 @@ let
in
{
# One nft transaction swaps the old table for the new: traffic never sees neither. Also the
# unit's reload, which a switch runs instead of a restart (units.nix).
# unit's reload, which a switch runs instead of a restart (units.nix). The time daemons'
# users are looked up here rather than named in the rules: a missing one would fail them all.
killSwitchUpScript = pkgs.writeShellScript "proxy-suite-routing" ''
set -euo pipefail
${nft} -f - <<'EOF'
uids=()
for user in ${lib.escapeShellArgs cfg.killSwitch.timeSyncUsers}; do
uid=$(${pkgs.coreutils}/bin/id -u -- "$user" 2>/dev/null) && uids+=("$uid")
done
time_sync=
if (( ''${#uids[@]} )); then
time_sync="add element inet proxy_suite_killswitch time_sync_uids { $(IFS=,; echo "''${uids[*]}") }"
fi
${nft} -f - <<EOF
add table inet proxy_suite_killswitch
delete table inet proxy_suite_killswitch
include "${killSwitchRulesFile}"
$time_sync
EOF
${persistTable "proxy_suite_killswitch" '''include "${killSwitchRulesFile}"' ''${time_sync:+"$time_sync"}''}
'';
killSwitchDownScript = pkgs.writeShellScript "proxy-suite-routing" ''
set +e
${unpersistTable "proxy_suite_killswitch"}
${deleteKillSwitchTable}
'';
@@ -95,6 +125,10 @@ in
tun6_route_prefix=${lib.escapeShellArg globalTunIPv6RoutePrefix}
tun_addr=""
tun_route_prefix=""
# A kernel booted with ipv6.disable=1 refuses every -6 command: the TUN still comes up.
families=(-4)
if [ -e /proc/net/if_inet6 ]; then families+=(-6); fi
has_ipv6() { [ "''${#families[@]}" = 2 ]; }
${builders.cidrNetworkFunction}
@@ -113,6 +147,7 @@ in
${deleteXrayTunRules}
${deleteXrayTunReplyTable}
${nft} -f ${xrayTunReplyRules}
${persistTable xrayTunReplyTable "'include \"${xrayTunReplyRules}\"'"}
# XRay may not have brought the link up yet, and routes via a down link fail with
# "Device for nexthop is not up".
@@ -121,30 +156,59 @@ in
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface}
${lib.optionalString ipv6 ''${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface}''}
${lib.optionalString ipv6 ''has_ipv6 && ${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface}''}
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex}
# No uplink src: it goes stale when the uplink address changes, and XRay's own sockets
# (routed by uid and mark, not bound to an interface) pick theirs from main.
${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${lib.optionalString ipv6 ''
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
''}
${
if ipv6 then
''
if has_ipv6; then
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
fi
''
else
''
# No IPv6 in the TUN: unreachable, as sing-box's strict_route and the per-app TUN
# have it, so apps fall back to IPv4. Without, the rules below would find nothing
# in this table and go on to main: every IPv6 connection straight out the uplink.
${ip} -6 route replace unreachable default table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
''
}
${lib.optionalString perAppRoutingTun.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
for family in "''${families[@]}"; do
${ip} "$family" rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
done
''}
service_uid=$(${pkgs.coreutils}/bin/id -u ${constants.serviceUser})
${ip} -4 rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main
${ip} -6 rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main
for family in -4 -6; do
for service_user in ${lib.escapeShellArgs constants.ownTrafficUsers}; do
service_uid=$(${pkgs.coreutils}/bin/id -u "$service_user")
for family in "''${families[@]}"; do
${ip} "$family" rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main
done
done
for family in "''${families[@]}"; do
${ip} "$family" rule add pref ${toString xrayTunMarkBypassRulePriority} fwmark ${toString globalTproxy.proxyMark} lookup main
${ip} "$family" rule add pref ${toString xrayTunDnsRulePriority} ipproto udp dport 53 table ${toString tunAutoRouteTableIndex}
${ip} "$family" rule add pref ${toString xrayTunDnsRulePriority} ipproto tcp dport 53 table ${toString tunAutoRouteTableIndex}
${ip} "$family" rule add pref ${toString xrayTunMainRulePriority} lookup main suppress_prefixlength 0
done
${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
for family in "''${families[@]}"; do
${ip} "$family" rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
done
'';
# The reply marking, after a firewall reload that flushed the ruleset: without it, replies
# to connections from outside (sshd among them) are routed into the TUN until it restarts.
xrayTunReloadScript = pkgs.writeShellScript "proxy-suite-routing" ''
set -euo pipefail
${builders.mkNftReplaceTable {
inherit nft;
family = "inet";
table = xrayTunReplyTable;
file = xrayTunReplyRules;
}}
'';
tproxyUpScript = pkgs.writeShellScript "proxy-suite-routing" ''
@@ -164,24 +228,50 @@ in
table = globalTproxy.routeTable;
}}
${nft} -f ${nftablesRulesFile}
# Set on NixOS already; system-manager hosts only get them here.
# Set on NixOS already; system-manager hosts only get them here. Left on at the stop:
# by then something else (Docker, libvirt) may rely on forwarding too.
${lib.concatStrings (
lib.mapAttrsToList (name: value: ''
${pkgs.procps}/bin/sysctl -q -w ${name}=${toString value}
'') tproxyLanSysctl
)}
# The route first, then the marking: a packet marked before its rule exists would leave
# by the main table, and the kill switch lets the mark through.
${builders.mkTproxyRoutingUp {
inherit ip;
inherit ipv6;
fwmark = globalTproxy.fwmark;
table = globalTproxy.routeTable;
}}
${nft} -f ${nftablesRulesFile}
${persistTable "singbox" "'include \"${nftablesRulesFile}\"'"}
'';
# After a firewall reload that flushed the ruleset (NixOS's flushRuleset, a distribution's
# `flush ruleset` config): the marking alone, swapped in whole in one transaction. The
# policy routing is no nftables state, and stays.
tproxyReloadScript = pkgs.writeShellScript "proxy-suite-routing" ''
set -euo pipefail
${builders.mkNftReplaceTable {
inherit nft;
family = "inet";
table = "singbox";
file = nftablesRulesFile;
}}
'';
# The daemon guard (constants.daemonMetadataGuard) as loaded: a static table, so its
# listing loads again as it is.
persistDaemonGuardScript = pkgs.writeShellScript "proxy-suite-routing" ''
set -euo pipefail
rules=$(${nft} -s list table inet proxy_suite_daemon_guard) || exit 0
${persistTable "proxy_suite_daemon_guard" ''"$rules"''}
'';
tproxyDownScript = pkgs.writeShellScript "proxy-suite-routing" ''
set +e
${unpersistTable "singbox"}
${builders.mkNftDeleteTable {
inherit nft;
family = "inet";
@@ -216,6 +306,7 @@ in
table = tunAutoRouteTableIndex;
}}
${deleteXrayTunRules}
${unpersistTable xrayTunReplyTable}
${deleteXrayTunReplyTable}
${builders.mkIpRouteFlushTable {
inherit ip;
@@ -1,10 +1,16 @@
# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved.
# inbounds.routing.blockPrivate (or, without it, this host's loopback), enforced here because
# the listener passes names unresolved.
# Just before the first direct rule (or last, for a direct final), so names that the
# proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local
# mixed-in clients lose names that resolve private. Rules for other inbounds do not count:
# autoProxy's direct probe pin would put the guard first, resolving every name, .onion too.
# This host's own addresses too, its public one among them, on every port but those its
# clients may reach there (inbounds.serverPorts and the like): dialed from here, a service the
# firewall keeps from the internet would answer (the start script lists them).
| [{inbound: ["mixed-in"], action: "resolve"@resolveStrategy@},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard
{inbound: ["mixed-in"]@rejectMatch@, action: "reject"}]
+ (($ARGS.named.host_addresses // []) as $own
| if $own == [] or @hostPortsAllOpen@ then [] else [{inbound: ["mixed-in"], ip_cidr: $own@hostPortMatch@, action: "reject"}] end) as $guard
| (.route.rules
| map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null)
| index(true)) as $first_direct
@@ -4,7 +4,11 @@ def sing_box_preserved_rules:
and (((.inbound? // []) | index("xray-dns-in")) != null))];
# perAppRouting.via's pin rules, which no route mode replaces.
def is_pin: ((.outbound? // "") | type) == "string" and ((.outbound? // "") | startswith("proxy-suite-pin-"));
([.route.rules[]? | select(is_pin)]) as $pin_rules
# Slurped (lists of one), not arguments: they grow with the outbounds and rules.
$route_rules[0] as $route_rules | $probe_inbounds[0] as $probe_inbounds
| $probe_pin_rules[0] as $probe_pin_rules | $autoproxy_rule_sets[0] as $autoproxy_rule_sets
| $autoproxy_rules[0] as $autoproxy_rules
| ([.route.rules[]? | select(is_pin)]) as $pin_rules
| .outbounds = ($obs[0] + .outbounds)
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
@@ -30,6 +34,13 @@ def is_pin: ((.outbound? // "") | type) == "string" and ((.outbound? // "") | st
else . end
| .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets)
| .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules)
# What autoProxy sends through an exit is looked up through the proxy too, as every other
# proxied name is (proxy.dns.remote): not by the local resolver, in the clear, for a
# destination learned blocked. Its own rule-sets alone, which hold names only.
| .dns.rules = ((.dns.rules // []) + [$autoproxy_rules[]
| select((.outbound? // "direct") != "direct"
and ((.rule_set? // []) | all(startswith("autoproxy-"))) and ((.rule_set? // []) | length > 0))
| {rule_set, server: "remote"}])
# Pins after the common hijack-dns and sniff rules, so a pinned app's lookups are answered
# as any other's, and before every rule that picks an outbound.
| .route.rules |= [.[] | select(is_pin | not)]
@@ -13,7 +13,8 @@ def xray_rewrite_proxy_rule($single_tag):
end;
def xray_preserved_rules:
[.routing.rules[]
| select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote")];
| select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote"
or . == "inbounds-private-guard" or . == "inbounds-host-guard")];
def xray_final_rule($tag; $single_tag):
if $tag == "proxy" and "@selectionMode@" == "urltest" then
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
@@ -42,7 +43,9 @@ def xray_pin_server_names:
else .dns.servers += [.dns.servers[] | select((.tag? // "") == "local")
| . + {domains: ($names | map("full:" + .)), skipFallback: true}]
end;
.outbounds = ($obs[0] + .outbounds)
# Slurped (a list of one), not an argument: it grows with the rules.
$route_rules[0] as $route_rules
| .outbounds = ($obs[0] + .outbounds)
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
| if $auth_enabled then
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
@@ -65,11 +68,25 @@ def xray_pin_server_names:
# too: name the rest instead. Disabling is a runtime decision, so always.
# ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop";
# rename one of them if that matters.
| if $ARGS.named.xray_selectable == null then . else
($ARGS.named.xray_selectable | map("proxy-suite-ob-" + .)) as $candidates
# Slurped (a list of one), not an argument: every tag of a large subscription.
| ($ARGS.named.xray_selectable // [null])[0] as $selectable
| if $selectable == null then . else
($selectable | map("proxy-suite-ob-" + .)) as $candidates
| if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end
| if .observatory then .observatory.subjectSelector = $candidates else . end
end
# This host's own addresses, on every port but those its inbounds' clients may reach there,
# just after the inbounds' guard: dialed from here, its public one would reach a service
# the firewall keeps from the internet (the start script lists them).
| ($ARGS.named.host_addresses // []) as $own
| (.routing.rules | map((.ruleTag? // "") == "inbounds-private-guard") | index(true)) as $at
| if $own == [] or $at == null or "@hostClosedPorts@" == "" then . else
.routing.rules |= [.[] | select((.ruleTag? // "") != "inbounds-host-guard")]
| .routing.rules = .routing.rules[:$at + 1]
+ [{type: "field", ruleTag: "inbounds-host-guard", inboundTag: ["mixed-in"], ip: $own,
port: "@hostClosedPorts@", outboundTag: "block"}]
+ .routing.rules[$at + 1:]
end
| if $xray_single_proxy_tag == "" then
.
else
@@ -4,17 +4,31 @@
selectionMode,
proxyInboundsGuardPrivate,
proxyInboundsGuardStrategy ? null,
# inbounds.routing.blockPrivate: the guard rejects the private ranges, else loopback alone.
proxyInboundsBlockPrivate ? true,
proxyInboundsLoopback ? [ ],
# The ports of this host's own addresses its inbounds' clients may not reach, as ranges.
proxyInboundsHostClosedPorts ? [ ],
userDnsRules ? [ ],
# proxy.dns.remote as a sing-box server, for the AmneziaWG interfaces added at runtime; null
# when there are none.
awgRuntimeDnsServer ? null,
# proxy.listener on an address other machines reach (0.0.0.0, a LAN address).
listenerExposed ? false,
}:
let
fillTemplate = import ../../lib/fill-template.nix;
# XRay's port list: "80,1000-2000".
closedPorts = map (
r: if r.from == r.to then toString r.from else "${toString r.from}-${toString r.to}"
) proxyInboundsHostClosedPorts;
in
if pureXrayEnabled then
(fillTemplate ./backend-filter-xray.template.jq { inherit selectionMode; })
(fillTemplate ./backend-filter-xray.template.jq {
inherit selectionMode;
hostClosedPorts = lib.concatStringsSep "," closedPorts;
})
else
(fillTemplate ./backend-filter-sing-box.template.jq {
userDnsRuleCount = toString (builtins.length userDnsRules);
@@ -33,8 +47,45 @@ else
+ (if .routing_mark then {routing_mark} else {} end)
]
''
# A listener others reach, without the inbounds' guard: a LAN client could CONNECT to
# 127.0.0.1 (or a name resolving there), which the private-ranges rule sends direct, dialed
# from here: this host's loopback-only services. This host's own clients may still, and
# their names stay unresolved for the proxy.
+ lib.optionalString (listenerExposed && !proxyInboundsGuardPrivate) ''
| {source_ip_cidr: ["127.0.0.0/8", "::1/128"], invert: true} as $remote
| [{type: "logical", mode: "and", rules: [{inbound: ["mixed-in"]}, $remote],
action: "resolve", server: "local"},
{type: "logical", mode: "and",
rules: [{inbound: ["mixed-in"], ip_cidr: ${builtins.toJSON proxyInboundsLoopback}}, $remote],
action: "reject"}] as $guard
| (.route.rules
| map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null)
| index(true)) as $first_direct
| if $first_direct != null then
.route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:]
elif (.route.final // "direct") == "direct" then
.route.rules += $guard
else . end
''
# No sniffing on mixed-in, where the inbounds' clients arrive: an SNI the rules send direct
# would take their connection direct to any address. Their names still route as names.
+ lib.optionalString proxyInboundsGuardPrivate ''
| (.route.rules[]? | select(.action? == "sniff" and (has("inbound") | not)))
|= . + {inbound: ["mixed-in"], invert: true}
''
+ lib.optionalString proxyInboundsGuardPrivate (
fillTemplate ./backend-filter-private-guard.template.jq {
rejectMatch =
if proxyInboundsBlockPrivate then
", ip_is_private: true"
else
", ip_cidr: ${builtins.toJSON proxyInboundsLoopback}";
# sing-box's port_range is always from:to.
hostPortMatch = ", port_range: ${
builtins.toJSON (map (r: "${toString r.from}:${toString r.to}") proxyInboundsHostClosedPorts)
}";
# Then there is nothing to reject: no rule, as an empty port_range would match any port.
hostPortsAllOpen = lib.boolToString (proxyInboundsHostClosedPorts == [ ]);
resolveStrategy = lib.optionalString (
proxyInboundsGuardStrategy != null
) ", strategy: \"${proxyInboundsGuardStrategy}\"";
@@ -55,7 +55,9 @@ _proxy_suite_write_xray_sidecar_config() {
if [ "$(@jq@ 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
return 0
fi
@jq@ -n \
# umask: the file holds every XRay outbound's credentials until the start script's
# chmod, in a runtime directory others can list.
(umask 077 && @jq@ -n \
--arg loglevel "$XRAY_LOGLEVEL" \
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
--argjson port "$XRAY_SIDECAR_PORT" \
@@ -92,5 +94,5 @@ _proxy_suite_write_xray_sidecar_config() {
domainStrategy: "AsIs",
rules: ($route_rules[0] + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
}
}' > "$RUNTIME_DIR/xray-sidecar.json"
}' > "$RUNTIME_DIR/xray-sidecar.json")
}
@@ -27,9 +27,17 @@
mkSubscriptionBlock,
mkSubscriptionLoadHelperBlock,
runtimeSubscriptionsBlock,
laterTags ? [ ],
# The backends, to check a runtime JSON outbound with before it joins the config.
singBoxBin ? null,
xrayBin ? null,
}:
let
# A value in a shell comment, on that one line: a newline in a tag (types.str) would end
# the comment and run the rest as root.
oneLine = value: builtins.replaceStrings [ "\n" "\r" ] [ " " " " ] (toString value);
sshProxyTag = "ssh-proxy";
torOutboundEnabled = torCfg != null && torCfg.enable && torCfg.asOutbound;
groupsJq = builtins.path {
@@ -41,12 +49,13 @@ let
# The keys of an outbound that point the backend at a local file or program, comma-joined;
# a sing-box tor outbound as "type: tor". proxy_url_parsers.local_file_keys and proxy-ctl's
# _local_file_keys apply the same rule.
# _local_file_keys apply the same rule. A non-ASCII key counts as well: Go's JSON
# decoding matches field names under Unicode case folding ("maſterKeyLog" is masterKeyLog).
localFileKeysJq = ''
[(if .type == "tor" then "type: tor" else empty end),
(.. | objects | keys[] | ascii_downcase
| select(endswith("file") or (endswith("path") and . != "path") or endswith("directory")
or IN("masterkeylog", "torrc", "extra_args")))]
| select((explode | any(. > 127)) or endswith("file") or (endswith("path") and . != "path")
or endswith("directory") or IN("masterkeylog", "torrc", "extra_args")))]
| unique | join(", ")
'';
@@ -91,16 +100,24 @@ let
case "$pref" in
xray)
ob=$(_proxy_suite_parse_xray_url "$tag" "$url") || return 1
_proxy_suite_check_url_outbound xray "$ob" "$tag" "$source" || return 1
_proxy_suite_add_xray_sidecar_ob "$ob" "$tag"
;;
sing-box)
ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url") || return 1
_proxy_suite_check_url_outbound sing-box "$ob" "$tag" "$source" || return 1
_proxy_suite_add_sing_box_ob "$ob"
;;
*)
if ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url" 2>"$RUNTIME_DIR/sing-box-parser.err"); then
# Created 0600 first: the parser's error can quote the link's id or password,
# and the runtime directory is world-listable.
(umask 077 && : > "$RUNTIME_DIR/sing-box-parser.err")
# One sing-box parses but refuses still gets XRay's turn.
if ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url" 2>"$RUNTIME_DIR/sing-box-parser.err") &&
_proxy_suite_check_url_outbound sing-box "$ob" "$tag" "$source" 2>/dev/null; then
_proxy_suite_add_sing_box_ob "$ob"
elif ob=$(_proxy_suite_parse_xray_url "$tag" "$url"); then
_proxy_suite_check_url_outbound xray "$ob" "$tag" "$source" || return 1
_proxy_suite_add_xray_sidecar_ob "$ob" "$tag"
else
echo "proxy-suite: outbound '$tag' cannot be parsed by SingBox or XRay" >&2
@@ -115,6 +132,9 @@ let
else
''
ob=$(_proxy_suite_parse_url "$tag" "$url") || return 1
_proxy_suite_check_url_outbound ${
if pureXrayEnabled then "xray" else "sing-box"
} "$ob" "$tag" "$source" || return 1
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON")
'';
# Raw JSON gets the tag and the routing mark a Nix-declared one gets (rawOutboundJson).
@@ -166,14 +186,17 @@ let
"" | *[!0-9]*) return 1 ;;
esac
[ "$2" -ge 1 ] && [ "$2" -le 65535 ] || return 1
ob=$(${jq} -nc --arg t "$1" --argjson p "$2" ${
lib.escapeShellArg (
if pureXrayEnabled then
''{protocol: "socks", tag: $t, settings: {address: "127.0.0.1", port: $p}}''
else
''{type: "socks", tag: $t, server: "127.0.0.1", server_port: $p}''
)
}) || return 1
# The tunnel's listener takes the hop login (constants.ensureHopLogin).
${constants.ensureHopLogin pkgs}
ob=$(${jq} -nc --arg t "$1" --argjson p "$2" --arg u ${constants.hopUser} \
--rawfile pw ${lib.escapeShellArg constants.hopLoginFile} ${
lib.escapeShellArg (
if pureXrayEnabled then
''{protocol: "socks", tag: $t, settings: {address: "127.0.0.1", port: $p, user: $u, pass: ($pw | rtrimstr("\n"))}}''
else
''{type: "socks", tag: $t, server: "127.0.0.1", server_port: $p, username: $u, password: ($pw | rtrimstr("\n"))}''
)
}) || return 1
${
if hybridEnabled then
''_proxy_suite_add_sing_box_ob "$ob"''
@@ -219,19 +242,25 @@ let
# written before links existed: those entries share as JSON until the next update).
_proxy_suite_record_subscription_share() {
SUBSCRIPTION_URLS_JSON=$(${jq} --arg t "$1" --rawfile u <(_proxy_suite_read_source "$2") '.[$t] = ($u | rtrimstr("\n"))' <<< "$SUBSCRIPTION_URLS_JSON")
# Only the entries merged (_proxy_suite_record_outbound_source ran first): one left
# out for a taken tag would otherwise put its link on that tag's outbound.
if [ -s "$3" ]; then
OUTBOUND_URLS_JSON=$(${jq} --slurpfile l "$3" '. + $l[0]' <<< "$OUTBOUND_URLS_JSON") || true
OUTBOUND_URLS_JSON=$(${jq} --slurpfile l "$3" --arg s "sub:$1" \
--slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \
'. + ($l[0] | with_entries(select($sources[0][.key] == $s)))' <<< "$OUTBOUND_URLS_JSON") || true
fi
}
# $1 source label, $2 array length before the add, $3 after. Subscriptions
# append an unknown number of outbounds, so they label them by range.
# Here and below, whatever grows with the outbounds goes to jq through a file, not
# --argjson: a big subscription outgrows the kernel's 128 KiB limit on one argument.
_proxy_suite_record_outbound_source() {
[ "$3" -gt "$2" ] || return 0
OUTBOUND_SOURCES_JSON=$(${jq} \
--argjson sources "$OUTBOUND_SOURCES_JSON" --arg s "$1" \
--slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") --arg s "$1" \
--argjson b "$2" --argjson a "$3" \
'reduce .[$b:$a][].tag as $t ($sources; .[$t] = $s)' <<< "$OUTBOUNDS_JSON")
'reduce .[$b:$a][].tag as $t ($sources[0]; .[$t] = $s)' <<< "$OUTBOUNDS_JSON")
}
${
@@ -256,6 +285,15 @@ let
}
''
}
# $1 kind, $2 the outbound parsed from a URL, $3 tag, $4 source label: a runtime one
# through the backend's own check, as for runtime JSON.
_proxy_suite_check_url_outbound() {
[ "$4" = runtime ] || return 0
_proxy_suite_check_json_outbound "$1" "$2" && return 0
echo "proxy-suite: runtime outbound '$3' is not one the backend takes" >&2
return 1
}
# $1 tag, $2 URL, $3 source label, $4 backend preference (auto|sing-box|xray).
# Returns non-zero when the URL cannot be parsed; the caller decides whether
# that is fatal.
@@ -266,6 +304,28 @@ let
OUTBOUND_URLS_JSON=$(${jq} --arg t "$tag" --rawfile u <(printf '%s' "$url") '.[$t] = $u' <<< "$OUTBOUND_URLS_JSON")
}
# $1 kind, $2 the outbound: whether its backend takes it, as one it refuses would fail
# the whole start. Alone (its references dropped), as the service user, from stdin.
_proxy_suite_check_json_outbound() {
local kind="$1" ob="$2" as=()
[ "$(${pkgs.coreutils}/bin/id -u)" = 0 ] && as=(${constants.runAsServiceUser pkgs [ ]})
case "$kind" in
${lib.optionalString (singBoxBin != null) ''
sing-box)
${jq} -c '{outbounds: [del(.detour, .domain_resolver) | select(.type != "selector" and .type != "urltest")]}' <<< "$ob" \
| "''${as[@]}" ${singBoxBin} check -c /dev/stdin >/dev/null 2>&1
;;
''}
${lib.optionalString (xrayBin != null) ''
xray)
${jq} -c '{outbounds: [del(.proxySettings) | del(.streamSettings.sockopt.dialerProxy)]}' <<< "$ob" \
| "''${as[@]}" ${xrayBin} run -test -format json -c stdin: >/dev/null 2>&1
;;
''}
*) return 0 ;;
esac
}
# $1 tag, $2 file holding one sing-box or XRay outbound, $3 source label.
_proxy_suite_add_json_outbound() {
local tag="$1" source="$3" ob kind unsafe
@@ -282,6 +342,10 @@ let
fi
fi
kind=$(${jq} -r 'if has("protocol") then "xray" elif has("type") then "sing-box" else "" end' <<< "$ob")
if [ "$source" = runtime ] && ! _proxy_suite_check_json_outbound "$kind" "$ob"; then
echo "proxy-suite: runtime outbound '$tag' is not one the backend takes (a field misspelt, or one it no longer has)" >&2
return 1
fi
${jsonAddBlock}
_proxy_suite_record_tag_source "$tag" "$source"
}
@@ -297,8 +361,16 @@ let
[ -f "$f" ] && [ ! -L "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.*}"
# A tab or newline in a name would split the line into entries of its own.
if [[ ! $tag =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then
echo "proxy-suite: warning: ignoring a runtime outbound whose name is not a valid tag" >&2
continue
fi
case "$tag" in
proxy | direct | block${lib.optionalString torOutboundEnabled " | tor"})
# proxy-suite-*: the test selector and the pin selectors the start script adds;
# priority.json is the priority overrides, not an outbound.
proxy | direct | block | priority | proxy-suite-*${lib.optionalString torOutboundEnabled " | tor"})
[ "$f" = "${runtimeOutboundsDir}/priority.json" ] && continue
echo "proxy-suite: warning: ignoring runtime outbound '$tag': reserved name" >&2
continue
;;
@@ -316,7 +388,7 @@ let
jsonFile = pkgs.writeText "proxy-suite-core" outboundJson;
in
''
# outbound: ${tag} (static ${backend} json)
# outbound: ${oneLine tag} (static ${backend} json)
OB_JSON=$(cat "${jsonFile}")
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON")
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
@@ -326,8 +398,8 @@ let
urlSource = if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-core" ob.url;
in
''
# outbound: ${tag}
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static || exit 1
# outbound: ${oneLine tag}
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat ${lib.escapeShellArg urlSource})" static || exit 1
'';
singBoxRawOutboundJson =
@@ -347,7 +419,7 @@ let
jsonFile = pkgs.writeText "proxy-suite-core" outboundJson;
in
''
# outbound: ${tag} (hybrid XRay json sidecar)
# outbound: ${oneLine tag} (hybrid XRay json sidecar)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
@@ -358,7 +430,7 @@ let
jsonFile = pkgs.writeText "proxy-suite-core" outboundJson;
in
''
# outbound: ${tag} (hybrid SingBox json)
# outbound: ${oneLine tag} (hybrid SingBox json)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_sing_box_ob "$OB_JSON"
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
@@ -368,8 +440,8 @@ let
urlSource = if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-core" ob.url;
in
''
# outbound: ${tag} (hybrid ${ob.backend})
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static ${ob.backend} || exit 1
# outbound: ${oneLine tag} (hybrid ${ob.backend})
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat ${lib.escapeShellArg urlSource})" static ${ob.backend} || exit 1
'';
mkSshProxyOutboundBlock =
@@ -420,7 +492,7 @@ let
-f ${lib.escapeShellArg sshProxyCfg.hostKeyFile} \
| ${jq} -R -s '[splits("\n")] | map(select(length > 0 and (startswith("#") | not))) | map(sub("^\\S+\\s+"; ""))')
if [ "$(${jq} 'length' <<< "$SSH_HOST_KEYS")" -eq 0 ]; then
echo "proxy-suite: no host keys for ${knownHostsTarget} in ${sshProxyCfg.hostKeyFile}" >&2
echo "proxy-suite: no host keys for "${lib.escapeShellArg knownHostsTarget}" in "${lib.escapeShellArg sshProxyCfg.hostKeyFile} >&2
exit 1
fi
OB_JSON=$(${jq} --argjson hk "$SSH_HOST_KEYS" '.host_key = $hk' <<< "$OB_JSON")
@@ -433,7 +505,9 @@ let
# sing-box opens the key as ${constants.serviceUser}, which cannot read a key in a
# home directory: it gets a copy only root and its group can read.
SSH_IDENTITY="$RUNTIME_DIR/ssh-identity"
install -m 0640 ${constants.ifPrivileged "-g ${constants.serviceUser} "}${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY"
install -m ${
if constants.privileged then "0640" else "0600"
} ${constants.ifPrivileged "-g ${constants.serviceUser} "}${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY"
OB_JSON=$(${jq} --arg key "$SSH_IDENTITY" '.private_key_path = $key' <<< "$OB_JSON")
''}
${hostKeyFileBlock}
@@ -448,7 +522,7 @@ let
# Outbounds whose JSON is known at build time: every backend takes it as is.
mkFixedOutboundBlock = comment: source: outbound: ''
# outbound: ${outbound.tag} (${comment})
# outbound: ${oneLine outbound.tag} (${comment})
OB_JSON=${lib.escapeShellArg (builtins.toJSON outbound)}
${
if hybridEnabled then
@@ -459,28 +533,52 @@ let
_proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source}
'';
# As mkFixedOutboundBlock, with the hop login added at start: it is drawn per boot, and
# the password reaches jq from its file, never argv.
mkHopOutboundBlock = comment: source: outbound: ''
# outbound: ${oneLine outbound.tag} (${comment})
${constants.ensureHopLogin pkgs}
OB_JSON=$(${jq} -c --arg u ${constants.hopUser} --rawfile pw ${lib.escapeShellArg constants.hopLoginFile} ${
lib.escapeShellArg (
if pureXrayEnabled then
''.settings += {user: $u, pass: ($pw | rtrimstr("\n"))}''
else
''. + {username: $u, password: ($pw | rtrimstr("\n"))}''
)
} <<< ${lib.escapeShellArg (builtins.toJSON outbound)})
${
if hybridEnabled then
''_proxy_suite_add_sing_box_ob "$OB_JSON"''
else
''OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON")''
}
_proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source}
'';
# WARP and "singBox" or "userspace" AmneziaWG profiles run in a tunnel unit, which restarts them when the
# handshake stops being answered. Every backend reaches it as a loopback SOCKS hop.
# Every hop but Tor's takes the hop login (constants.ensureHopLogin); Tor has none to take.
mkTunnelOutboundBlock =
unit: source: tag: port:
mkFixedOutboundBlock "SOCKS hop to ${unit}" source (
if pureXrayEnabled then
{
protocol = "socks";
inherit tag;
settings = {
address = "127.0.0.1";
inherit port;
};
}
else
{
type = "socks";
inherit tag;
server = "127.0.0.1";
server_port = port;
}
);
(if source == "tor" then mkFixedOutboundBlock else mkHopOutboundBlock) "SOCKS hop to ${unit}" source
(
if pureXrayEnabled then
{
protocol = "socks";
inherit tag;
settings = {
address = "127.0.0.1";
inherit port;
};
}
else
{
type = "socks";
inherit tag;
server = "127.0.0.1";
server_port = port;
}
);
# An "interface" AmneziaWG profile: the outbound binds to the interface, which has no routes.
# sing-box resolves its destinations through it too; XRay resolves as usual.
@@ -532,11 +630,31 @@ let
mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock;
# Tags a runtime outbound may not take: the outbounds added after it, the groups (declared
# and runtime), and the backend template's own. Those already in (declared, subscriptions,
# an earlier runtime one under another extension) are checked as it comes.
runtimeTakenTags = laterTags ++ lib.optional pureXrayEnabled "dns-out";
runtimeOutboundsBlock = ''
# outbounds added at runtime, and the hop each one chains through (<tag>.detour)
RUNTIME_DETOURS_JSON='{}'
RUNTIME_TAKEN_JSON=$(
for f in "${runtimeOutboundsDir}"/*.group; do
[ -e "$f" ] || continue
f="''${f##*/}"
printf '%s\n' "''${f%.group}"
done | ${jq} -R . | ${jq} -cs --argjson fixed ${lib.escapeShellArg (builtins.toJSON runtimeTakenTags)} '. + $fixed'
)
while IFS=$'\t' read -r RUNTIME_OB_TAG RUNTIME_OB_SRC; do
[ -n "$RUNTIME_OB_TAG" ] || continue
# A duplicate tag fails the backend's start, every outbound with it: this one goes.
if {
printf '%s\n' "''${OUTBOUNDS_JSON:-[]}"
${lib.optionalString hybridEnabled ''printf '%s\n' "''${XRAY_OUTBOUNDS_JSON:-[]}"''}
} | ${jq} -e -s --arg t "$RUNTIME_OB_TAG" --argjson taken "$RUNTIME_TAKEN_JSON" \
'(add | [.[].tag]) + $taken | index([$t]) != null' >/dev/null 2>&1; then
echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG': the tag is taken" >&2
continue
fi
case "$RUNTIME_OB_SRC" in
*.json) _proxy_suite_add_json_outbound "$RUNTIME_OB_TAG" "$RUNTIME_OB_SRC" runtime ;;
# Its tunnel (proxy-suite-awg-tunnel@<tag>) checks the port again before listening.
@@ -581,24 +699,25 @@ let
# unchained; whatever chained through it is checked again.
detourBlock = ''
# outbound chaining
DETOURS_JSON=$(${jq} -c --argjson runtime "$RUNTIME_DETOURS_JSON" '.outbounds = $runtime + .outbounds' \
DETOURS_JSON=$(${jq} -c --slurpfile runtime <(printf '%s' "$RUNTIME_DETOURS_JSON") '.outbounds = $runtime[0] + .outbounds' \
<<< ${lib.escapeShellArg (builtins.toJSON detours)})
while [ "$DETOURS_JSON" != '{"outbounds":{},"subscriptions":{}}' ]; do
# The filter reads $sources as the object itself, so the program unwraps the slurped one.
DETOUR_RESULT=$(${jq} -c --slurpfile xob <(printf '%s' "${
if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"
}") '{outbounds: ., xray: $xob[0]}' <<< "$OUTBOUNDS_JSON" \
| ${jq} -c -f ${
| ${jq} -c -f <(printf '%s' '$sources[0] as $sources | '; cat ${
builtins.path {
name = "proxy-suite-outbound-detours";
path = ../../outbound-detours.jq;
}
} \
}) \
--argjson d "$DETOURS_JSON" \
--argjson sources "$OUTBOUND_SOURCES_JSON" \
--slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \
--arg kind ${detourKind})
DETOUR_DROP=$(${jq} -c --argjson sources "$OUTBOUND_SOURCES_JSON" \
'[.errors[] | select($sources[.tag] == "runtime")] | unique_by(.tag)' <<< "$DETOUR_RESULT")
if ${jq} -e --argjson sources "$OUTBOUND_SOURCES_JSON" 'any(.errors[]; $sources[.tag] != "runtime")' <<< "$DETOUR_RESULT" >/dev/null; then
DETOUR_DROP=$(${jq} -c --slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \
'[.errors[] | select($sources[0][.tag] == "runtime")] | unique_by(.tag)' <<< "$DETOUR_RESULT")
if ${jq} -e --slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") 'any(.errors[]; $sources[0][.tag] != "runtime")' <<< "$DETOUR_RESULT" >/dev/null; then
${jq} -r '.errors[] | "proxy-suite: " + .message' <<< "$DETOUR_RESULT" >&2
exit 1
fi
@@ -638,7 +757,7 @@ let
DISABLED_TAGS_JSON=$(${jq} -c --arg t "''${DISABLED_TAG%.disabled}" '. + [$t]' <<< "$DISABLED_TAGS_JSON")
done
fi
DISABLED_TAGS_JSON=$(${jq} -c --argjson tags "$OUTBOUND_TAGS_JSON" 'map(select(. as $t | $tags | index([$t]))) | unique' <<< "$DISABLED_TAGS_JSON")
DISABLED_TAGS_JSON=$(${jq} -c --slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") 'map(select(. as $t | $tags[0] | index([$t]))) | unique' <<< "$DISABLED_TAGS_JSON")
'';
# proxy.groups and those `proxy-ctl proxy groups add` left as <tag>.group next to the runtime
@@ -671,7 +790,7 @@ let
# As proxy-ctl names them; the spool is group-writable, and a group tagged "proxy"
# would shadow the real selector.
case "$GROUP_NAME" in
proxy | direct | block${lib.optionalString torOutboundEnabled " | tor"} | [!A-Za-z0-9]* | *[!A-Za-z0-9._-]*)
proxy | direct | block | proxy-suite-*${lib.optionalString torOutboundEnabled " | tor"} | [!A-Za-z0-9]* | *[!A-Za-z0-9._-]*)
echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': reserved or invalid name" >&2
continue
;;
@@ -713,12 +832,13 @@ let
while IFS= read -r GROUP_NAME; do
echo "proxy-suite: warning: ignoring group '$GROUP_NAME': an outbound has that tag" >&2
GROUPS_CONFIG_JSON=$(${jq} -c --arg g "$GROUP_NAME" 'del(.[$g])' <<< "$GROUPS_CONFIG_JSON")
done < <(${jq} -r --argjson tags "$OUTBOUND_TAGS_JSON" 'keys[] | select(. as $g | $tags | index([$g]))' <<< "$GROUPS_CONFIG_JSON")
done < <(${jq} -r --slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") 'keys[] | select(. as $g | $tags[0] | index([$g]))' <<< "$GROUPS_CONFIG_JSON")
# A runtime group inside itself is left out, like any runtime outbound that cannot be
# built; only a loop among declared groups fails the start.
while :; do
GROUPS_RESULT=$(${jq} -nc --argjson tags "$OUTBOUND_TAGS_JSON" --argjson sources "''${OUTBOUND_SOURCES_JSON:-{\}}" \
'{tags: $tags, sources: $sources}' \
GROUPS_RESULT=$(${jq} -nc --slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") \
--slurpfile sources <(printf '%s' "''${OUTBOUND_SOURCES_JSON:-{\}}") \
'{tags: $tags[0], sources: $sources[0]}' \
| ${jq} -c -f ${groupsJq} \
--argjson groups "$GROUPS_CONFIG_JSON" \
--argjson priority "$PRIORITY_JSON" \
@@ -741,7 +861,7 @@ let
GROUP_TAGS_JSON=$(${jq} -c '.groups | keys_unsorted' <<< "$GROUPS_RESULT")
GROUPS_INFO_JSON=$(${jq} -c '.groups' <<< "$GROUPS_RESULT")
TOP_TAGS_JSON=$(${jq} -c '.top' <<< "$GROUPS_RESULT")
OUTBOUNDS_JSON=$(${jq} -c --argjson g "$(${jq} -c '.outbounds' <<< "$GROUPS_RESULT")" '. + $g' <<< "$OUTBOUNDS_JSON")
OUTBOUNDS_JSON=$(${jq} -c --slurpfile g <(${jq} -c '.outbounds' <<< "$GROUPS_RESULT") '. + $g[0]' <<< "$OUTBOUNDS_JSON")
'';
pinBlock = ''
@@ -778,19 +898,21 @@ let
# chains through, what selection leaves alone, and what was disabled.
inventoryBlock = ''
${jq} -n \
--argjson tags "$OUTBOUND_TAGS_JSON" \
--argjson sources "$OUTBOUND_SOURCES_JSON" \
--slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") \
--slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \
--arg pinned "$PINNED_OUTBOUND" \
--arg selection ${lib.escapeShellArg selectionMode} \
--slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \
--slurpfile xobs <(printf '%s' "${if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"}") \
--argjson selectable "$SELECTABLE_TAGS_JSON" \
--slurpfile selectable <(printf '%s' "$SELECTABLE_TAGS_JSON") \
--argjson disabled "$DISABLED_TAGS_JSON" \
--argjson groups "$GROUPS_INFO_JSON" \
--argjson top "$TOP_TAGS_JSON" \
--slurpfile groups <(printf '%s' "$GROUPS_INFO_JSON") \
--slurpfile top <(printf '%s' "$TOP_TAGS_JSON") \
--argjson priority "$PRIORITY_JSON" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
'{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection,
'$tags[0] as $tags | $sources[0] as $sources | $selectable[0] as $selectable
| $groups[0] as $groups | $top[0] as $top
| {tags: $tags, sources: $sources, pinned: $pinned, selection: $selection,
detours: ([($xobs[0] + $obs[0])[] | (.detour // .streamSettings.sockopt.dialerProxy?) as $h
| select($h != null) | {key: .tag, value: $h}] | from_entries),
excluded: ($top - $selectable), disabled: $disabled,
@@ -864,17 +986,17 @@ let
if [ -z "$PINNED_OUTBOUND" ] && [ "''${GROUPS_WATCHED:-true}" != true ]; then
# No Clash API here for the watcher to drive: sing-box's own urltest instead.
WRAPPER=$(${jq} -n \
--argjson tags "$SELECTABLE_TAGS_JSON" \
--slurpfile tags <(printf '%s' "$SELECTABLE_TAGS_JSON") \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:"30s",tolerance:$tolerance}')
'{type:"urltest",tag:"proxy",outbounds:$tags[0],url:$url,interval:"30s",tolerance:$tolerance}')
else
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--slurpfile tags <(printf '%s' "$TAGS") \
--arg default "$DEFAULT_TAG" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default,interrupt_exist_connections:true}')
'{type:"selector",tag:"proxy",outbounds:$tags[0],default:$default,interrupt_exist_connections:true}')
fi
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
OUTBOUNDS_JSON=$(${jq} --slurpfile w <(printf '%s' "$WRAPPER") '$w + .' <<< "$OUTBOUNDS_JSON")
''
else if selectionMode == "selector" then
''
@@ -884,10 +1006,10 @@ let
DEFAULT_TAG=$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON")
fi
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--slurpfile tags <(printf '%s' "$TAGS") \
--arg default "$DEFAULT_TAG" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
'{type:"selector",tag:"proxy",outbounds:$tags[0],default:$default}')
OUTBOUNDS_JSON=$(${jq} --slurpfile w <(printf '%s' "$WRAPPER") '$w + .' <<< "$OUTBOUNDS_JSON")
''
else
''
@@ -896,18 +1018,18 @@ let
# A pin beats latency ranking: the same outbounds, behind a selector
# the Clash API can also switch live.
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--slurpfile tags <(printf '%s' "$TAGS") \
--arg default "$PINNED_OUTBOUND" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
'{type:"selector",tag:"proxy",outbounds:$tags[0],default:$default}')
else
WRAPPER=$(${jq} -n \
--argjson tags "$SELECTABLE_TAGS_JSON" \
--slurpfile tags <(printf '%s' "$SELECTABLE_TAGS_JSON") \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
'{type:"urltest",tag:"proxy",outbounds:$tags[0],url:$url,interval:$interval,tolerance:$tolerance}')
fi
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
OUTBOUNDS_JSON=$(${jq} --slurpfile w <(printf '%s' "$WRAPPER") '$w + .' <<< "$OUTBOUNDS_JSON")
'';
# Real exits for autoProxy, taken after the wrapper may have renamed one to
# "proxy".
@@ -2,6 +2,11 @@
SUB_CACHE_DIR="@cacheDir@"
RUNTIME_SUBS_DIR="@runtimeSubscriptionsDir@"
# The caches hold every server's credentials and original link: root and, with the
# "secrets" scope, the userControl groups only, as for the share file.
mkdir -p "$SUB_CACHE_DIR"
@cacheDirAccess@
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && @jq@ -e @validCacheFilter@ "$1" >/dev/null 2>&1
}
@@ -34,34 +39,72 @@ _proxy_suite_drop_invalid_subscription_cache() {
fi
}
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically,
# and next to it <tag>.links: each entry's original URI, for proxy-ctl to share.
# $1 "direct" to fetch as the service user, past the kill switch and outside the tunnel;
# otherwise as an unprivileged user the tunnel and the kill switch take as they take root.
# Root opens the output files either way (the links on fd 3).
_proxy_suite_run_fetcher() {
local how="$1" tag="$2" src="$3" cache_tmp="$4" links_tmp="$5" as=(@tunnelFetch@)
shift 5
[ "$how" = direct ] && as=(@directFetch@)
printf '%s' "$(_proxy_suite_read_source "$src")" \
| PYTHONPATH="@pythonPath@" "${as[@]}" @python3@ @fetchSubscriptionPy@ \
@backendArg@ --tag-prefix "$tag" --links-fd 3 "$@" > "$cache_tmp" 3> "$links_tmp"
}
# A temporary file of its own next to $1: the start scripts share the directory and fetch at
# once. Readable as the caches always were; the directory's mode keeps others out.
_proxy_suite_cache_tmp() {
local tmp
tmp=$(mktemp "$1.XXXXXX") || return 1
chmod 0644 "$tmp"
printf '%s' "$tmp"
}
# $1 tag, $2 file holding the subscription URL, then the fetcher's flags. Writes the cache
# atomically, and <tag>.links for proxy-ctl to share. Through the tunnel; directly past the
# kill switch only with no cache, which has no proxy to fetch through.
_proxy_suite_fetch_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links"
mkdir -p "$SUB_CACHE_DIR"
if printf '%s' "$(_proxy_suite_read_source "$src")" \
| PYTHONPATH="@pythonPath@" @python3@ @fetchSubscriptionPy@ \
@backendArg@ --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then
if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then
mv "$links.tmp" "$links"
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links" cache_tmp links_tmp
# What a fetch killed midway (a stop's timeout) left behind.
@findutils@/bin/find "$SUB_CACHE_DIR" -maxdepth 1 -type f \( -name "$tag.json.??????" -o -name "$tag.links.??????" \) \
-mmin +10 -delete 2>/dev/null || true
cache_tmp=$(_proxy_suite_cache_tmp "$cache") || return 1
links_tmp=$(_proxy_suite_cache_tmp "$links") || { rm -f "$cache_tmp"; return 1; }
if _proxy_suite_run_fetcher tunnel "$tag" "$src" "$cache_tmp" "$links_tmp" "${@:3}" ||
{ @killSwitch@ && ! _proxy_suite_valid_subscription_cache "$cache" &&
echo "proxy-suite: subscription '$tag' not fetched through the tunnel and not cached; fetching it directly, past the kill switch" >&2 &&
_proxy_suite_run_fetcher direct "$tag" "$src" "$cache_tmp" "$links_tmp" "${@:3}"; }; then
if _proxy_suite_commit_subscription_cache "$cache_tmp" "$cache" "$tag"; then
mv "$links_tmp" "$links"
return 0
fi
rm -f "$links.tmp"
rm -f "$links_tmp"
return 1
fi
rm -f "$cache.tmp" "$links.tmp"
rm -f "$cache_tmp" "$links_tmp"
echo "proxy-suite: failed to update subscription '$tag'" >&2
return 1
}
# Every runtime subscription, as "<tag>\t<url file>" lines.
# Every runtime subscription, as "<tag>\t<url file>" lines. Checked again here, as the spool
# is group-writable: a declared subscription's name would take over its cache.
_proxy_suite_runtime_subscriptions() {
local f tag
local f tag declared
[ -d "$RUNTIME_SUBS_DIR" ] || return 0
for f in "$RUNTIME_SUBS_DIR"/*.url; do
[ -f "$f" ] && [ ! -L "$f" ] || continue
tag="${f##*/}"
tag="${tag%.url}"
if [[ ! $tag =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ || $tag == proxy-suite-* ]]; then
echo "proxy-suite: warning: ignoring a runtime subscription whose name is not a valid tag" >&2
continue
fi
for declared in @declaredTags@; do
if [ "$tag" = "$declared" ]; then
echo "proxy-suite: warning: ignoring runtime subscription '$tag': a declared one has that name" >&2
continue 2
fi
done
printf '%s\t%s\n' "$tag" "$f"
done
}
@@ -21,9 +21,17 @@ let
fetchSubscriptionPy
routingMarkJq
;
inherit (constants) stateDir runtimeSubscriptionsDir;
inherit (constants) stateDir runtimeSubscriptionsDir runtimeOutboundsDir;
# Outbounds and groups the start script adds after the subscriptions, which a subscription
# entry must not take the tag of.
laterTagsJson = builtins.toJSON (ctx.effectiveOutboundTags ++ ctx.groupTags);
subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend;
subscriptionBackendArg = "--backend ${subscriptionBackend}";
# Each entry also through its backend's own config check: one it refuses would fail the
# whole start, every other outbound with it.
subscriptionBackendArg =
"--backend ${subscriptionBackend}"
+ lib.optionalString (subscriptionBackend != "xray") " --check-sing-box ${ctx.singBox}"
+ lib.optionalString (subscriptionBackend != "sing-box") " --check-xray ${ctx.xray}";
subscriptionCacheDir = "${stateDir}/subscriptions/${backend}";
mkSubscriptionUrlSource =
@@ -35,16 +43,53 @@ let
readSourceFunction = constants.readSourceFunction pkgs;
cacheDir = subscriptionCacheDir;
inherit runtimeSubscriptionsDir jq;
declaredTags = lib.escapeShellArgs (map (sub: sub.tag) proxyCfg.subscriptions);
validCacheFilter = lib.escapeShellArg (
if hybridEnabled then
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
else
''type == "array"''
);
diffutils = pkgs.diffutils;
inherit (pkgs) diffutils findutils;
# The directory alone, not what is in it (constants.grantDirAcl): the caches are 0644, and
# a recursive pass would trip over another start script's temporary file.
cacheDirAccess =
let
secrets = ctx.userControlAllows "secrets";
extraGroups = ctx.userControlExtraGroupsFor "secrets";
in
lib.optionalString secrets ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg ctx.userControlCfg.group} "$SUB_CACHE_DIR"
''
+ ''
chmod ${if secrets then "0750" else "0700"} "$SUB_CACHE_DIR"
''
+ constants.ifPrivileged (
if extraGroups == [ ] then
''${pkgs.acl}/bin/setfacl -b -- "$SUB_CACHE_DIR"''
else
''${pkgs.acl}/bin/setfacl --set ${
lib.concatStringsSep "," (
[
"u::rwx"
"g::${if secrets then "r-x" else "---"}"
"o::---"
]
++ map (g: "g:${g}:r-x") extraGroups
)
} -- "$SUB_CACHE_DIR"''
);
pythonPath = parserScriptsPythonPath;
inherit python3 fetchSubscriptionPy;
backendArg = subscriptionBackendArg;
killSwitch = lib.boolToString ctx.killSwitchDirectFallbacks;
# Its own user, not exempt from the tunnel or the kill switch: the HTTP client and the
# parser of what any subscription server sends do not run as root.
tunnelFetch = constants.ifPrivileged "${pkgs.util-linux}/bin/setpriv --reuid=${ctx.subscriptionFetchUser} --regid=${ctx.subscriptionFetchUser} --clear-groups --inh-caps=-all --ambient-caps=-all --bounding-set=-all --no-new-privs --";
# Past the kill switch as the service user, resolving names itself (constants.ownLookups).
directFetch = lib.optionalString ctx.killSwitchDirectFallbacks "${pkgs.util-linux}/bin/unshare --mount ${constants.ownLookups pkgs} ${
constants.runAsServiceUser pkgs [ ]
}";
};
# Merging a cache into OUTBOUNDS_JSON needs the routing mark, which differs per
@@ -62,25 +107,54 @@ let
mergeBlock =
if hybridEnabled then
''
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$cache")
SUB_SING_BOX_JSON=$(_proxy_suite_free_tags "$tag" < <(${jq} -c '.singBox' "$cache"))
${markBlock}OUTBOUNDS_JSON=$(${jq} --slurpfile sub <(printf '%s' "$SUB_SING_BOX_JSON") '. + $sub[0]' <<< "$OUTBOUNDS_JSON")
_proxy_suite_add_xray_sidecar_obs "$(${jq} -c '.xray' "$cache")"
_proxy_suite_add_xray_sidecar_obs "$(_proxy_suite_free_tags "$tag" < <(${jq} -c '.xray' "$cache"))"
''
else
''
SUB_JSON=$(cat "$cache")
SUB_JSON=$(_proxy_suite_free_tags "$tag" < "$cache")
${markBlock}OUTBOUNDS_JSON=$(${jq} --slurpfile sub <(printf '%s' "$SUB_JSON") '. + $sub[0]' <<< "$OUTBOUNDS_JSON")
'';
in
''
# $1 tag, $2 file holding the subscription URL. Fetches on a cold cache and
# merges whatever is cached; a subscription that cannot be fetched is a
# stdin: a subscription's outbounds; prints those whose tag is free. A taken one (by any
# other outbound, a group or the suite's own) would fail the backend's start.
_proxy_suite_free_tags() {
local entries taken f name
entries=$(cat)
taken=$(
{
${jq} -r 'map(.tag) | .[]' <<< "$OUTBOUNDS_JSON"
if [ -d ${lib.escapeShellArg runtimeOutboundsDir} ]; then
for f in ${lib.escapeShellArg runtimeOutboundsDir}/*.url ${lib.escapeShellArg runtimeOutboundsDir}/*.json \
${lib.escapeShellArg runtimeOutboundsDir}/*.awg ${lib.escapeShellArg runtimeOutboundsDir}/*.group; do
[ -e "$f" ] || continue
name="''${f##*/}"
printf '%s\n' "''${name%.*}"
done
fi
} | ${jq} -R . | ${jq} -cs --argjson fixed ${lib.escapeShellArg laterTagsJson} '. + $fixed + ["proxy", "direct", "block"] | unique'
)
${jq} -r --arg sub "$1" --slurpfile taken <(printf '%s' "$taken") '
$taken[0] as $taken
| .[] | .tag | select(. as $t | ($taken | index([$t])) != null or startswith("proxy-suite-"))
| "proxy-suite: warning: subscription \($sub) entry \(.) left out: the tag is taken"
' <<< "$entries" >&2
${jq} -c --slurpfile taken <(printf '%s' "$taken") '
$taken[0] as $taken
| map(select(.tag as $t | ($taken | index([$t])) == null and ($t | startswith("proxy-suite-") | not)))
' <<< "$entries"
}
# $1 tag, $2 file holding the subscription URL, then the fetcher's flags. Fetches on a
# cold cache and merges whatever is cached; a subscription that cannot be fetched is a
# warning, never a failed start.
_proxy_suite_load_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" before after
_proxy_suite_drop_invalid_subscription_cache "$cache" "$tag"
if [ ! -f "$cache" ]; then
_proxy_suite_fetch_subscription "$tag" "$src" \
_proxy_suite_fetch_subscription "$tag" "$src" "''${@:3}" \
|| echo "proxy-suite: warning: could not fetch subscription '$tag'" >&2
fi
[ -f "$cache" ] || return 0
@@ -92,21 +166,31 @@ let
}
'';
# A subscription's fetcher flags. Runtime ones take proxy.runtimeSubscriptions', https only
# unless allowHttp: over http anyone on the way could add entries.
mkSubscriptionFetchArgs =
sub:
lib.optionalString sub.allowPrivateServers " --allow-private-servers"
+ lib.optionalString sub.allowInsecure " --allow-insecure";
runtimeCfg = proxyCfg.runtimeSubscriptions;
runtimeFetchArgs =
mkSubscriptionFetchArgs runtimeCfg + lib.optionalString (!runtimeCfg.allowHttp) " --https-only";
mkSubscriptionBlock = sub: _routingMark: ''
# subscription: ${sub.tag}
_proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}
_proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}${mkSubscriptionFetchArgs sub}
'';
runtimeSubscriptionsBlock = ''
# subscriptions added at runtime
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
[ -n "$RUNTIME_SUB_TAG" ] || continue
_proxy_suite_load_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"
_proxy_suite_load_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"${runtimeFetchArgs}
done < <(_proxy_suite_runtime_subscriptions)
'';
mkSubscriptionFetchBlock = sub: ''
if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}; then
if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}${mkSubscriptionFetchArgs sub}; then
echo "Updated subscription: ${sub.tag}"
else
FAILED=1
@@ -116,7 +200,7 @@ let
runtimeSubscriptionsFetchBlock = ''
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
[ -n "$RUNTIME_SUB_TAG" ] || continue
if _proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"; then
if _proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"${runtimeFetchArgs}; then
echo "Updated subscription: $RUNTIME_SUB_TAG"
else
FAILED=1
+12
View File
@@ -148,6 +148,11 @@ let
mkSubscriptionLoadHelperBlock
runtimeSubscriptionsBlock
;
# What the start script adds after the runtime outbounds: one of theirs named like these
# would fail the backend's start, every outbound with it.
laterTags = sctx.effectiveOutboundTags ++ sctx.groupTags;
singBoxBin = if pureXrayEnabled then null else sctx.singBox;
xrayBin = if xrayEnabled then sctx.xray else null;
};
inherit (outboundScripts) mkOutboundScript;
@@ -161,6 +166,13 @@ let
proxyInboundsGuardPrivate
proxyInboundsGuardStrategy
;
proxyInboundsBlockPrivate = proxyInboundsCfg.routing.blockPrivate;
inherit (ctx) proxyInboundsLoopback proxyInboundsHostClosedPorts;
listenerExposed =
let
address = proxyCfg.listener.address;
in
!(lib.hasPrefix "127." address || address == "::1" || address == "localhost");
userDnsRules = proxyCfg.dns.singBox.rules;
awgRuntimeDnsServer =
if ctx.awgRuntimeIfaceOutbounds then
+111 -40
View File
@@ -38,6 +38,7 @@ let
;
inherit (constants)
autoProxyStateDir
autoProxySpoolDir
outboundTestPort
xrayDnsBridgePorts
xraySidecarPorts
@@ -47,22 +48,20 @@ let
inherit pkgs;
inherit (constants) serviceUser ifPrivileged;
};
autoProxyMigrate = import ../autoproxy-migrate.nix { inherit pkgs; };
# Who reads the probe listeners' login (`proxy outbounds test`, `proxy auto probe`).
# Local proxy auth with userControl off keeps its group as before.
probeLoginMainGroup =
(!userControlCfg.enable && localProxyAuthEnabled)
|| userControlAllows "outbounds"
|| userControlAllows "autoProxy";
probeLoginExtraGroups = lib.unique (
ctx.userControlExtraGroupsFor "outbounds" ++ ctx.userControlExtraGroupsFor "autoProxy"
);
runBackend = constants.runAsServiceUser pkgs constants.backendCaps;
userControlGroup = lib.escapeShellArg userControlCfg.group;
chgrp = "${pkgs.coreutils}/bin/chgrp";
routeModeBlacklistTail =
if pureXrayEnabled then
''
+ .proxyGeo
+ .block
''
else
''
+ .block
+ .proxyGeo
'';
# Every route mode is the same four assignments over one jq program on the rule buckets.
routeModeArms = [
{
@@ -73,9 +72,10 @@ let
.common
+ (.custom | map(.entries) | add // [])
+ .proxyPrimary
+ .block
+ .direct
+ .safetyDirect
${routeModeBlacklistTail}
+ .proxyGeo
'';
}
{
@@ -86,9 +86,10 @@ let
.common
+ (.custom | map(.entries) | add // [])
+ .proxyPrimary
+ .block
+ .direct
+ .safetyDirect
${routeModeBlacklistTail}
+ .proxyGeo
'';
}
{
@@ -101,8 +102,9 @@ let
.common
+ (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // [])
+ .proxyPrimary
+ .block
+ .safetyDirect
${routeModeBlacklistTail}
+ .proxyGeo
'';
}
{
@@ -113,8 +115,8 @@ let
rules = ''
.common
+ (.custom | map(select(.category == "block") | .entries) | add // [])
+ .safetyDirect
+ .block
+ .safetyDirect
'';
}
];
@@ -153,6 +155,16 @@ let
'';
writeProxychainsConfigBlock = ''
# proxychains reads its config by words: a password with whitespace in it would come out
# as another field, or another line. None then, and proxy-ctl says why.
case "''${LOCAL_PROXY_PASSWORD:-}" in
*[[:space:]]*)
echo "proxy-suite: listener.auth's password has whitespace, which proxychains cannot take; no proxychains config" >&2
rm -f "${runtimeProxychainsConfig}"
;;
*)
# Private from the start: the chmod below would leave a moment where anyone reads it.
(umask 077 && : > "${runtimeProxychainsConfig}")
{
printf '%s\n' 'strict_chain'
${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"}
@@ -167,12 +179,15 @@ let
"$LOCAL_PROXY_PASSWORD"
} > "${runtimeProxychainsConfig}"
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"''}
chmod 640 "${runtimeProxychainsConfig}"
# Without root the group is the user's own primary one, which may be shared.
chmod ${if constants.privileged then "640" else "600"} "${runtimeProxychainsConfig}"
# It holds the proxy's password: userControl.groups that run apps through proxychains.
${constants.grantFileAcl pkgs ''"${runtimeProxychainsConfig}"''
(ctx.userControlExtraGroupsFor "perApp")
"r"
}
;;
esac
'';
mkStartScript =
@@ -209,7 +224,7 @@ let
${hybridRuntimeHelpersBlock routingMark xraySidecarPort xrayDnsBridgePort}
${subscriptionCacheHelpersBlock}
${lib.optionalString enableLocalProxyAuth ''
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
LOCAL_PROXY_PASSWORD="$(cat ${lib.escapeShellArg localProxyAuthPasswordSource})"
# The umask stays in the subshell: left set, it also narrowed everything
# written below, and autoProxy's state.json is group-readable by design.
(
@@ -238,9 +253,9 @@ let
AUTOPROXY_RULES_JSON='[]'
${lib.optionalString enableAutoProxy ''
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
# 0751: sing-box, running as ${constants.serviceUser}, reaches the rules/ inside;
# 0771 with userControl's autoProxy scope, whose group queues learn requests there.
install -d -m ${if ctx.userControlAnyAllows "autoProxy" then "0771" else "0751"} "$AUTOPROXY_DIR"
# Root's alone, 0751: sing-box, running as ${constants.serviceUser}, reaches the
# rules/ inside. An install from before the spool is made so first.
${autoProxyMigrate} "$AUTOPROXY_DIR" ${lib.escapeShellArg autoProxySpoolDir}
[ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json"
# direct is always exit 0; state is keyed by tag, so shifting indices are
@@ -249,9 +264,9 @@ let
PROBE_EXITS_JSON=$(${jq} -c \
--argjson max ${toString proxyCfg.autoProxy.maxExits} \
--argjson base ${toString proxyCfg.autoProxy.probeBasePort} \
--argjson disabled "''${DISABLED_TAGS_JSON:-[]}" \
--slurpfile disabled <(printf '%s' "''${DISABLED_TAGS_JSON:-[]}") \
--arg dir "$AUTOPROXY_DIR" '
(["direct"] + map(select(. != "direct" and (. as $t | $disabled | index([$t]) | not))))[0:$max]
(["direct"] + map(select(. != "direct" and (. as $t | $disabled[0] | index([$t]) | not))))[0:$max]
| to_entries
| map({i: .key, tag: .value, port: ($base + .key),
rule_set: ("autoproxy-" + (.key | tostring)),
@@ -264,8 +279,19 @@ let
PROBE_INBOUNDS_JSON=$(${jq} -c 'map({type: "mixed", tag: ("probe-in-" + (.i | tostring)),
listen: "127.0.0.1", listen_port: .port})' <<< "$PROBE_EXITS_JSON")
PROBE_PIN_RULES_JSON=$(${jq} -c 'map({inbound: ["probe-in-" + (.i | tostring)],
outbound: .tag})' <<< "$PROBE_EXITS_JSON")
# The hosts probed are ones the inbounds' clients dialed: the direct probe gets their
# fence (inbounds.routing.blockPrivate), resolving as a direct dial would.
PROBE_PIN_RULES_JSON=$(${jq} -c --argjson fence ${
lib.escapeShellArg (
builtins.toJSON (
if ctx.proxyInboundsCfg.routing.blockPrivate then
{ ip_is_private = true; }
else
{ ip_cidr = ctx.proxyInboundsLoopback; }
)
)
} '[{inbound: ["probe-in-0"], action: "resolve", server: "local"}, ({inbound: ["probe-in-0"], action: "reject"} + $fence)]
+ map({inbound: ["probe-in-" + (.i | tostring)], outbound: .tag})' <<< "$PROBE_EXITS_JSON")
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c 'map({type: "local", format: "source",
tag: .rule_set, path: .path})' <<< "$PROBE_EXITS_JSON")
# all-bypass means everything direct; learned exits must not override it.
@@ -280,7 +306,7 @@ let
# hybrid XRay outbound is a sing-box socks hop whose real server is the sidecar's.
# A loopback hop (the WARP tunnel, XRay's SSH listener) has no server worth timing.
ENDPOINTS_TMP="$RUNTIME_DIR/outbound-endpoints.json.tmp"
${jq} -c --slurpfile sidecar <(printf '%s' "''${XRAY_OUTBOUNDS_JSON:-[]}") '
(umask 077 && ${jq} -c --slurpfile sidecar <(printf '%s' "''${XRAY_OUTBOUNDS_JSON:-[]}") '
$sidecar[0] as $sidecar
| def endpoint:
if .server then {server, port: .server_port}
@@ -301,7 +327,7 @@ let
| ($real[.tag] // .) | select(endpoint != null and (endpoint.server | test("^(127\\.|::1$|localhost$)") | not))
| {key: $tag, value: (endpoint + {network: (if udp then "udp" else "tcp" end)})}]
| from_entries
' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP"
' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP")
# Where each proxy server is: not credentials, but not for every local user either.
${
if userControlCfg.enable || localProxyAuthEnabled then
@@ -336,16 +362,18 @@ let
${lib.optionalString (!pureXrayEnabled) ''
# Delay and download: a loopback listener pinned to a selector over every real
# exit, switched one outbound at a time through the Clash API.
OUTBOUNDS_JSON=$(${jq} -c --argjson tags "$EXIT_TAGS_JSON" \
'. + [{type: "selector", tag: "proxy-suite-test", outbounds: $tags}]' <<< "$OUTBOUNDS_JSON")
# Slurped, not --argjson: one argument holds at most 128 KiB, less than the tags
# of a large subscription.
OUTBOUNDS_JSON=$(${jq} -c --slurpfile tags <(printf '%s' "$EXIT_TAGS_JSON") \
'. + [{type: "selector", tag: "proxy-suite-test", outbounds: $tags[0]}]' <<< "$OUTBOUNDS_JSON")
PROBE_INBOUNDS_JSON=$(${jq} -c '. + [{type: "mixed", tag: "proxy-suite-test-in",
listen: "127.0.0.1", listen_port: ${toString outboundTestPort}}]' <<< "$PROBE_INBOUNDS_JSON")
PROBE_PIN_RULES_JSON=$(${jq} -c \
'. + [{inbound: ["proxy-suite-test-in"], outbound: "proxy-suite-test"}]' <<< "$PROBE_PIN_RULES_JSON")
${jq} -n --argjson tags "$EXIT_TAGS_JSON" \
${jq} -n --slurpfile tags <(printf '%s' "$EXIT_TAGS_JSON") \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} '
{port: ${toString outboundTestPort}, selector: "proxy-suite-test", url: $url,
outbounds: ($tags | map({key: ., value: .}) | from_entries)}
outbounds: ($tags[0] | map({key: ., value: .}) | from_entries)}
' > "$RUNTIME_DIR/outbound-test.json"
# Tags and a loopback port only.
chmod 644 "$RUNTIME_DIR/outbound-test.json"
@@ -402,14 +430,25 @@ let
esac
''}
# Every address this host has now, for the inbounds' guard (backend-filter-private-guard):
# dialed from here, a client would reach any port of them past the firewall.
HOST_ADDRESSES_JSON='[]'
${lib.optionalString (ctx.proxyInboundsEnabled && ctx.proxyInboundsNeedLocalProxy) ''
if ! HOST_ADDRESSES_JSON=$(${pkgs.iproute2}/bin/ip -j addr show | ${jq} -c \
'[.[].addr_info[]?.local | strings | if test(":") then . + "/128" else . + "/32" end] | unique'); then
echo "proxy-suite: cannot list this host's addresses; the inbounds' clients reach any port of them" >&2
HOST_ADDRESSES_JSON='[]'
fi
''}
# umask: the file holds credentials until the chmod below; the process
# substitutions keep them out of the argv every local user can read.
(umask 077 && ${jq} \
--slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \
--argjson probe_inbounds "$PROBE_INBOUNDS_JSON" \
--argjson probe_pin_rules "$PROBE_PIN_RULES_JSON" \
--argjson autoproxy_rule_sets "$AUTOPROXY_RULE_SETS_JSON" \
--argjson autoproxy_rules "$AUTOPROXY_RULES_JSON" \
--slurpfile probe_inbounds <(printf '%s' "$PROBE_INBOUNDS_JSON") \
--slurpfile probe_pin_rules <(printf '%s' "$PROBE_PIN_RULES_JSON") \
--slurpfile autoproxy_rule_sets <(printf '%s' "$AUTOPROXY_RULE_SETS_JSON") \
--slurpfile autoproxy_rules <(printf '%s' "$AUTOPROXY_RULES_JSON") \
--argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
--arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
${
@@ -419,24 +458,54 @@ let
"--arg password ''"
} \
--argjson route_enabled "$ROUTE_MODE_ACTIVE" \
--argjson route_rules "$ROUTE_RULES_JSON" \
--slurpfile route_rules <(printf '%s' "$ROUTE_RULES_JSON") \
--arg route_final "$ROUTE_FINAL" \
--arg dns_final "$DNS_FINAL" \
--argjson clear_dns_rules "$CLEAR_DNS_RULES" \
--arg xray_loglevel "$XRAY_LOGLEVEL" \
--arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \
--argjson xray_selectable "$SELECTABLE_TAGS_JSON" \
--slurpfile xray_selectable <(printf '%s' "$SELECTABLE_TAGS_JSON") \
--argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \
--argjson host_addresses "$HOST_ADDRESSES_JSON" \
-f "$BACKEND_JQ_FILTER" \
"${configFile}" > "$RUNTIME_DIR/config.json")
${lib.optionalString excludeServiceUserFromTun ''
# proxy-suite's own daemons (the inbound XRay, replies to its clients included)
# stay out of the TUN; the uid is only known on this host.
SERVICE_UID=$(${pkgs.coreutils}/bin/id -u ${constants.serviceUser})
(umask 077 && ${jq} --argjson uid "$SERVICE_UID" '(.inbounds[] | select(.type == "tun") | .exclude_uid) = [$uid]' \
SERVICE_UIDS=$(for service_user in ${lib.escapeShellArgs constants.ownTrafficUsers}; do
${pkgs.coreutils}/bin/id -u "$service_user"
done | ${jq} -cs .)
(umask 077 && ${jq} --argjson uids "$SERVICE_UIDS" '(.inbounds[] | select(.type == "tun") | .exclude_uid) = $uids' \
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next")
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json"
''}
${lib.optionalString (!pureXrayEnabled) ''
# The probe and test listeners reach any exit past the routing rules and the kill
# switch: a login per start, into jq through its environment (argv is public).
if ${jq} -e '[.inbounds[]? | (.tag // "") | select(startswith("probe-in-") or . == "proxy-suite-test-in")] | length > 0' \
"$RUNTIME_DIR/config.json" >/dev/null; then
PROBE_PASSWORD=$(${pkgs.coreutils}/bin/od -An -tx1 -N16 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n')
(umask 077 && PROBE_PASSWORD="$PROBE_PASSWORD" ${jq} '(.inbounds[]? | select((.tag // "") | startswith("probe-in-") or . == "proxy-suite-test-in"))
+= {users: [{username: "probe", password: $ENV.PROBE_PASSWORD}]}' \
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next")
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json"
(umask 077 && printf 'probe:%s\n' "$PROBE_PASSWORD" > "$RUNTIME_DIR/probe-login.tmp")
unset PROBE_PASSWORD
${
# Only to the groups that test outbounds or probe for autoProxy: to any other the
# login is a way out direct, past the routing rules and the kill switch.
if probeLoginMainGroup then
''
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$RUNTIME_DIR/probe-login.tmp"''}
chmod ${if constants.privileged then "640" else "600"} "$RUNTIME_DIR/probe-login.tmp"
''
else
''chmod 600 "$RUNTIME_DIR/probe-login.tmp"''
}
${constants.grantFileAcl pkgs ''"$RUNTIME_DIR/probe-login.tmp"'' probeLoginExtraGroups "r"}
mv "$RUNTIME_DIR/probe-login.tmp" "$RUNTIME_DIR/probe-login"
fi
''}
# The Clash API lists every connection and switches outbounds. Loopback alone lets
# every local user at it, and every web page too (sing-box allows any origin): a
# secret per start.
@@ -472,7 +541,9 @@ let
else
''
${constants.ifPrivileged ''${chgrp} ${constants.serviceUser} "$backend_config"''}
chmod 640 "$backend_config"
# Without root the group is the user's own primary one, which may be shared
# (users): the owner alone then.
chmod ${if constants.privileged then "640" else "600"} "$backend_config"
''
}
${constants.grantFileAcl pkgs ''"$backend_config"'' (ctx.userControlExtraGroupsFor "secrets") "r"}
+442 -116
View File
@@ -12,7 +12,6 @@ let
globalTun
globalTproxy
killSwitchEnabled
awgGlobalProfiles
perAppRoutingTun
perAppRoutingTproxy
perAppZapretEnabled
@@ -41,7 +40,9 @@ let
inherit (routingScripts)
xrayTunUpScript
xrayTunReloadScript
tproxyUpScript
tproxyReloadScript
tproxyDownScript
killSwitchUpScript
killSwitchDownScript
@@ -74,6 +75,135 @@ let
perAppViaAwg = perAppViaInterfaceOutbounds != [ ] || perAppViaRuntime || ctx.perAppViaProfiles;
# Or any outbound, through a pin slot: either way, the apps' slices and their marking.
perAppViaEnabled = perAppViaAwg || perAppRouting.pinUp != { };
# A per-app backend every user's apps share. perApp members may only start it (polkit.nix):
# it goes once the last user's marking unit that requires it stops, or the last pin of it.
perAppSharedBackend =
unit: restartOnSwitch (lib.recursiveUpdate unit { unitConfig.StopWhenUnneeded = true; });
# A switch restarts it rather than stopping it across activation: a shorter gap, and a
# restart keeps the per-app holds (user-rules.nix). [Service] is where the switch reads it.
restartOnSwitch = unit: lib.recursiveUpdate unit { serviceConfig."X-StopIfChanged" = false; };
# Rules a firewall reload can flush, put back by `reload` (a start of the firewall: by
# proxy-suite-firewall-reapply). After=, or the firewall's flush could come after it.
reloadAfterFirewall =
reload: unit:
lib.recursiveUpdate unit {
after = (unit.after or [ ]) ++ [ "nftables.service" ];
serviceConfig.ExecReload = reload;
unitConfig.ReloadPropagatedFrom = [ "nftables.service" ];
};
# NixOS's firewall loads the static tables itself (constants.persistedNftDir); the per-app
# ones hold cgroup matches, which fail the firewall's whole load once the cgroup is gone.
firewallIncludes = ctx.firewallIncludesTables;
reloadAfterFirewallUnlessIncluded =
reload: if firewallIncludes then lib.id else reloadAfterFirewall reload;
# What proxy-suite-firewall-reapply reloads, as systemctl patterns.
firewallReapplyUnits =
lib.optionals (!firewallIncludes) (
lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service"
++ lib.optional (proxyEnabled || proxyInboundsEnabled) "proxy-suite-daemon-guard.service"
++ lib.optional (proxyEnabled && globalTproxy.enable) "${serviceNames.tproxy}.service"
# Only XRay's TUN has a reload; sing-box's would be restarted.
++ lib.optional (proxyEnabled && globalTun.enable && pureXrayEnabled) "${serviceNames.tun}.service"
)
++ lib.optionals (proxyEnabled && perAppRoutingTun.enable) [
"${serviceNames.perAppTun}.service"
"${serviceNames.perAppTun}-user@*.service"
]
++ lib.optionals (proxyEnabled && perAppRoutingTproxy.enable) [
"${serviceNames.perAppTproxy}.service"
"${serviceNames.perAppTproxy}-user@*.service"
]
++ lib.optional perAppViaAwg "proxy-suite-per-app-via@*.service"
++ map (route: "proxy-suite-per-app-via-${route}@*.service") (
builtins.attrNames perAppRouting.pinUp
);
# A per-app route's DNS forwarder (nftables.nix's dns_redirect), up while the route or one
# of its pin slots is: a listener for the route's own mark, and one for each slot's.
perAppDnsUnit = route: "proxy-suite-per-app-${route}-dns.service";
mkPerAppDnsForwarder =
{
route,
mark,
basePort,
pinMarkBase,
pins,
bind ? [ ],
}:
let
listeners = [
"${toString basePort}:${toString mark}"
]
++ lib.genList (slot: "${toString (basePort + 1 + slot)}:${toString (pinMarkBase + slot)}") (
if pins then ctx.perAppPinSlots else 0
);
in
restartOnSwitch (mkRestartingService {
description = "proxy-suite per-app ${route} DNS forwarder";
execStart = lib.concatStringsSep " " (
[
ctx.python3
"${ctx.proxySuiteScriptsDir}/per_app_dns.py"
]
++ map (l: "--listen ${l}") listeners
++ map (a: "--bind ${a}") bind
++ [ ctx.constants.perAppDnsUpstream ]
);
runtimeDirectory = "proxy-suite-per-app-${route}-dns";
extraServiceConfig = {
# Ready once it listens, so the route's apps' first lookup finds it.
Type = "notify";
NotifyAccess = "main";
RestartSec = 2;
DynamicUser = true;
# SO_MARK on its sockets, and nothing else.
AmbientCapabilities = [ "CAP_NET_ADMIN" ];
CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
PrivateDevices = true;
ProtectClock = true;
ProtectHostname = true;
ProtectKernelLogs = true;
ProtectKernelModules = true;
ProtectKernelTunables = true;
ProtectControlGroups = true;
RestrictNamespaces = true;
RestrictRealtime = true;
LockPersonality = true;
MemoryDenyWriteExecute = true;
SystemCallArchitectures = "native";
RestrictAddressFamilies = [
"AF_UNIX"
"AF_INET"
"AF_INET6"
];
SystemCallFilter = [ "@system-service" ];
# The apps' queries on loopback, sent on to the upstream the backend answers for.
IPAddressAllow = [
"localhost"
ctx.constants.perAppDnsUpstream
];
IPAddressDeny = "any";
};
})
// {
unitConfig.StopWhenUnneeded = true;
};
# The global TUN and TProxy carry every app already: the per-app TProxy backend, its pin
# slots and per-app zapret refuse to start under them, and go when one starts
# (constants.refuseUnderGlobal).
globalModeUnits = [
"${serviceNames.tproxy}.service"
"${serviceNames.tun}.service"
];
perAppUnderGlobalModes = [
"${serviceNames.perAppTproxy}.service"
"proxy-suite-per-app-via-tproxy@*.service"
"proxy-suite-per-app-via-tun@*.service"
"${serviceNames.perAppZapret}.service"
];
# For the root units reading what userControl's group writes (outbounds.d,
# subscriptions.d): the file system read-only but for their own directories, so no
@@ -99,7 +229,9 @@ let
{
enable = proxyEnabled;
name = serviceNames.socks;
value = mkRestartingService {
# No PropagatesStopTo= TProxy: it stops TProxy on a restart too, which should hold the
# traffic meanwhile. `proxy off` stops TProxy itself.
value = restartOnSwitch (mkRestartingService {
description = "${backendDescription} proxy client (SOCKS + TProxy-ready)";
# Only XRay goes through the OpenSSH unit's listener.
after = [
@@ -114,11 +246,18 @@ let
++ lib.optional torOutboundEnabled "proxy-suite-tor.service"
++ map (j: "proxy-suite-wb-joiner-${j.tag}.service") whitelistBypassJoiners;
wantedBy = [ "multi-user.target" ];
# The hop login drawn as root, ahead of the start script, which ProtectSystem keeps
# from writing /run (constants.ensureHopLogin).
execStartPre = lib.filter (x: x != null) [
(ctx.constants.daemonMetadataGuard ctx.pkgs)
"+${ctx.constants.ensureHopLogin ctx.pkgs}"
];
execStart = scripts.startSocks;
runtimeDirectory = serviceNames.socks;
stateDirectory = "proxy-suite";
extraServiceConfig = xrayAssetEnv // spoolReaderSandbox [ ];
};
# The hybrid sidecar's config has no geo rules: only XRay as the backend reads them.
extraServiceConfig = lib.optionalAttrs pureXrayEnabled xrayAssetEnv // spoolReaderSandbox [ ];
});
}
{
enable = proxyInboundsEnabled;
@@ -139,6 +278,7 @@ let
++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service"
++ lib.optional torOnionEnabled "proxy-suite-tor.service";
wantedBy = [ "multi-user.target" ];
execStartPre = ctx.constants.daemonMetadataGuard ctx.pkgs;
execStart = scripts.startInbounds;
# inbounds.routing.serverSource's dummy interface.
execStopPost = scripts.stopInboundsInterface;
@@ -146,9 +286,24 @@ let
# The collector's file.
stateDirectory = "proxy-suite";
# While XRay still runs: what it counted since the last timer run.
extraServiceConfig = xrayAssetEnv // {
ExecStop = scripts.collectInboundStats;
};
extraServiceConfig =
xrayAssetEnv
// {
ExecStop = scripts.collectInboundStats;
}
# Nothing it runs is setuid (setpriv drops to the service user by itself), and no
# other unit shares its temporary files.
// lib.optionalAttrs ctx.constants.privileged {
NoNewPrivileges = true;
PrivateTmp = true;
# Root parses the group-writable inbounds.d: it writes nowhere but its runtime
# and state directories, which systemd leaves writable.
ProtectSystem = "strict";
ProtectKernelTunables = true;
ProtectControlGroups = true;
# The stats API's directory is the daemon's alone now, no setgid one to make.
RestrictSUIDSGID = true;
};
};
}
{
@@ -158,7 +313,11 @@ let
description = "Apply proxy-suite inbound users and listeners added at runtime";
execStart = scripts.reloadInbounds;
stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false;
# Root, over the spool userControl's group writes.
extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ ];
};
}
{
@@ -173,20 +332,22 @@ let
extraServiceConfig.RemainAfterExit = false;
};
}
# Pulled in by every global tunnel and left up when it stops or crashes: only
# proxy-ctl's off verbs take it down. After them, so a first start still fetches
# subscriptions and resolves endpoints directly.
# Up from boot, before any network, and pulled in by every global tunnel; only proxy-ctl's
# off verbs take it down. What the tunnels fetch to come up goes as a user it lets past.
{
enable = killSwitchEnabled;
name = serviceNames.killSwitch;
value =
mkOneshotService {
description = "proxy-suite kill switch - reject traffic outside the global tunnel";
# After the firewall: its start flushes the whole ruleset on some hosts.
after = [
"${serviceNames.socks}.service"
"${serviceNames.tun}.service"
]
++ map (name: "proxy-suite-awg-${name}.service") (builtins.attrNames awgGlobalProfiles);
"sysinit.target"
"nftables.service"
"firewall.service"
];
wants = [ "network-pre.target" ];
wantedBy = [ "multi-user.target" ];
execStart = killSwitchUpScript;
execStop = killSwitchDownScript;
extraServiceConfig.ExecReload = killSwitchUpScript;
@@ -195,100 +356,210 @@ let
# new rules from a switch are swapped in by a reload instead, in one transaction.
// {
reloadIfChanged = true;
before = [ "network-pre.target" ];
unitConfig = {
# Not stopped at shutdown either, unlike the units it guards.
DefaultDependencies = false;
}
# Put back after a firewall reload that flushed the ruleset (see reloadAfterFirewall).
// lib.optionalAttrs (!firewallIncludes) {
ReloadPropagatedFrom = [ "nftables.service" ];
};
};
}
# A start or restart of the firewall, which flushes the ruleset on some hosts, reloads
# what reloadAfterFirewall covers; a reload does nothing to a unit that is not up.
{
enable = ctx.constants.privileged && firewallReapplyUnits != [ ];
name = "proxy-suite-firewall-reapply";
value = mkOneshotService {
description = "proxy-suite - put its nftables tables back after the firewall starts";
after = [ "nftables.service" ];
wantedBy = [ "nftables.service" ];
# --no-block: the units it reloads are ordered after nftables, whose start this is
# part of.
execStart = "-${ctx.constants.systemctl} try-reload-or-restart --no-block ${lib.concatStringsSep " " firewallReapplyUnits}";
# Inactive once done, so the firewall's next start runs it again.
extraServiceConfig.RemainAfterExit = false;
};
}
# The daemon guard (constants.daemonMetadataGuard) on its own as well, so that a firewall
# that flushed the ruleset gets it back, not only the next start of the units that load it.
{
enable = ctx.constants.privileged && (proxyEnabled || proxyInboundsEnabled);
name = "proxy-suite-daemon-guard";
value =
let
load = [
(ctx.constants.daemonMetadataGuard ctx.pkgs)
]
++ lib.optional firewallIncludes "-${routingScripts.persistDaemonGuardScript}";
in
mkOneshotService {
description = "proxy-suite - keep cloud metadata and the loopback hops from other users";
after = [ "nftables.service" ];
wantedBy = [ "multi-user.target" ];
execStart = load;
extraServiceConfig.ExecReload = load;
}
// {
reloadIfChanged = true;
}
// lib.optionalAttrs (!firewallIncludes) {
unitConfig.ReloadPropagatedFrom = [ "nftables.service" ];
};
}
{
enable = proxyEnabled && globalTproxy.enable;
name = serviceNames.tproxy;
value = mkOneshotService {
description = "proxy-suite TProxy - nftables rules and policy routing";
after = [
"network.target"
"${serviceNames.socks}.service"
];
wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ];
requires = [ "${serviceNames.socks}.service" ];
wants = lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service";
conflicts = [
"${serviceNames.tun}.service"
"${serviceNames.perAppTproxy}.service"
];
execStart = tproxyUpScript;
execStop = tproxyDownScript;
};
# Put back with the firewall: all the host's (and the LAN's) traffic, otherwise.
value = restartOnSwitch (
reloadAfterFirewallUnlessIncluded tproxyReloadScript (mkOneshotService {
description = "proxy-suite TProxy - nftables rules and policy routing";
after = [
"network.target"
"${serviceNames.socks}.service"
];
wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ];
# Wants=, not Requires=: a restart of the backend would restart this too, and the
# host's traffic go direct until it is back.
wants = [
"${serviceNames.socks}.service"
]
++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service";
conflicts = [ "${serviceNames.tun}.service" ];
execStartPre = ctx.constants.stopPerAppUnits ctx.pkgs perAppUnderGlobalModes;
execStart = tproxyUpScript;
# Post: also after a start that failed partway, whose marking table would
# otherwise outlive it and send marked traffic out past the kill switch.
execStopPost = tproxyDownScript;
})
);
}
{
enable = proxyEnabled && globalTun.enable;
name = serviceNames.tun;
value = mkRestartingService {
description = "${backendDescription} TUN proxy client";
after = [ "network-online.target" ];
wants = [
"network-online.target"
]
++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service";
wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript;
execStart = scripts.startTun;
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
execStopPost = tunCleanupScript;
runtimeDirectory = serviceNames.tun;
stateDirectory = "proxy-suite";
};
value = restartOnSwitch (
(if pureXrayEnabled then reloadAfterFirewallUnlessIncluded xrayTunReloadScript else lib.id)
(mkRestartingService {
description = "${backendDescription} TUN proxy client";
after = [ "network-online.target" ];
wants = [
"network-online.target"
]
++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service";
wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = [
(ctx.constants.stopPerAppUnits ctx.pkgs perAppUnderGlobalModes)
tunCleanupScript
(ctx.constants.ensureHopLogin ctx.pkgs)
];
execStart = scripts.startTun;
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
execStopPost = tunCleanupScript;
runtimeDirectory = serviceNames.tun;
stateDirectory = "proxy-suite";
})
);
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = serviceNames.perAppTun;
value = mkRestartingService {
description = "proxy-suite per-app-routing TUN backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
execStartPre = perAppRouting.perAppTunDownScript;
execStart = scripts.startPerAppTun;
execStartPost = perAppRouting.perAppTunUpScript;
execStopPost = perAppRouting.perAppTunDownScript;
runtimeDirectory = serviceNames.perAppTun;
stateDirectory = "proxy-suite";
};
value = reloadAfterFirewall perAppRouting.perAppTunReloadScript (
perAppSharedBackend (mkRestartingService {
description = "proxy-suite per-app-routing TUN backend";
after = [
"network-online.target"
(perAppDnsUnit "tun")
];
wants = [
"network-online.target"
(perAppDnsUnit "tun")
];
execStartPre = [
perAppRouting.perAppTunDownScript
(ctx.constants.ensureHopLogin ctx.pkgs)
];
execStart = scripts.startPerAppTun;
execStartPost = perAppRouting.perAppTunUpScript;
execStopPost = perAppRouting.perAppTunDownScript;
runtimeDirectory = serviceNames.perAppTun;
stateDirectory = "proxy-suite";
})
);
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-user@";
value = mkUserRuleService {
# Its rules back in after the backend's table, and the hold's, came back (After=).
value = reloadAfterFirewall "${perAppRouting.perAppTunUserRuleStart} %i" (mkUserRuleService {
description = "Enable proxy-suite app TUN marking for user %i";
backendService = serviceNames.perAppTun;
execStart = "${perAppRouting.perAppTunUserRuleStart} %i";
execStop = "${perAppRouting.perAppTunUserRuleStop} %i";
};
});
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = serviceNames.perAppTproxy;
value = mkOneshotService {
description = "proxy-suite per-app-routing TProxy backend";
after = [
"network.target"
"${serviceNames.socks}.service"
];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tproxy}.service"
"${serviceNames.tun}.service"
];
execStart = perAppRouting.perAppTproxyUpScript;
execStop = perAppRouting.perAppTproxyDownScript;
value = reloadAfterFirewall perAppRouting.perAppTproxyReloadScript (
perAppSharedBackend (mkOneshotService {
description = "proxy-suite per-app-routing TProxy backend";
after = [
"network.target"
"${serviceNames.socks}.service"
(perAppDnsUnit "tproxy")
];
requires = [ "${serviceNames.socks}.service" ];
wants = [ (perAppDnsUnit "tproxy") ];
execStartPre = ctx.constants.refuseUnderGlobal ctx.pkgs globalModeUnits;
execStart = perAppRouting.perAppTproxyUpScript;
# Post: after a start that failed partway too (see the global TProxy unit).
execStopPost = perAppRouting.perAppTproxyDownScript;
})
);
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = "proxy-suite-per-app-tun-dns";
value = mkPerAppDnsForwarder {
route = "tun";
mark = perAppRoutingTun.fwmark;
basePort = ctx.constants.perAppTunDnsBasePort;
pinMarkBase = ctx.constants.perAppPinTunFwmarkBase;
pins = ctx.perAppPinTun;
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = "proxy-suite-per-app-tproxy-dns";
value = mkPerAppDnsForwarder {
route = "tproxy";
mark = perAppRoutingTproxy.fwmark;
basePort = ctx.constants.perAppTproxyDnsBasePort;
pinMarkBase = ctx.constants.perAppPinTproxyFwmarkBase;
pins = ctx.perAppPinTproxy;
# The mark takes the queries to a local route (see per_app_dns.py's BIND).
bind = [ "127.0.0.1" ];
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-user@";
value = mkUserRuleService {
# Its rules back in after the backend's table, and the hold's, came back (After=).
value = reloadAfterFirewall "${perAppRouting.perAppTproxyUserRuleStart} %i" (mkUserRuleService {
description = "Enable proxy-suite app TProxy marking for user %i";
backendService = serviceNames.perAppTproxy;
execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i";
execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i";
};
});
}
# Declared with zapret's own units (zapret.nix, zapret2.nix).
{
enable = perAppZapretEnabled;
name = serviceNames.perAppZapret;
value = perAppSharedBackend { };
}
{
enable = perAppZapretEnabled;
@@ -306,31 +577,54 @@ let
{
enable = perAppViaAwg;
name = "proxy-suite-per-app-via@";
value = mkRestartingService {
description = "proxy-suite per-app routing via %i";
execStartPre = "${perAppRouting.viaUp} %i";
execStart = "${perAppRouting.viaDns} %i";
execStopPost = "${perAppRouting.viaDown} %i";
runtimeDirectory = "proxy-suite-per-app-via-%i";
extraServiceConfig = {
# Ready once the forwarder listens, so the app's first lookup finds it.
Type = "notify";
NotifyAccess = "main";
RestartSec = 2;
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
ProtectClock = true;
ProtectHostname = true;
ProtectKernelLogs = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
LockPersonality = true;
# nft and ip rules, and SO_MARK on the forwarder's sockets.
CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
};
};
# Its table, rules and users' rules back after a firewall reload that flushed them.
value = restartOnSwitch (
reloadAfterFirewall
[
"${perAppRouting.viaUp} %i"
"${perAppRouting.viaReapply} %i"
]
(mkRestartingService {
description = "proxy-suite per-app routing via %i";
execStartPre = "${perAppRouting.viaUp} %i";
execStart = "${perAppRouting.viaDns} %i";
# viaUp starts the table empty: after a restart, the users' rules go back in.
execStartPost = "${perAppRouting.viaReapply} %i";
execStopPost = "${perAppRouting.viaDown} %i";
runtimeDirectory = "proxy-suite-per-app-via-%i";
extraServiceConfig = {
# Ready once the forwarder listens, so the app's first lookup finds it.
Type = "notify";
NotifyAccess = "main";
RestartSec = 2;
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
ProtectClock = true;
ProtectHostname = true;
ProtectKernelLogs = true;
# Root still, though with one capability: the disks' device nodes, /proc/sys and
# cgroups are root's to write without any, and the forwarder answers apps.
PrivateDevices = true;
ProtectKernelTunables = true;
ProtectKernelModules = true;
ProtectControlGroups = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
LockPersonality = true;
# nft and ip rules, and SO_MARK on the forwarder's sockets.
CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
# Netlink for nft and ip, unix for the readiness notice, IP for the forwarder.
RestrictAddressFamilies = [
"AF_UNIX"
"AF_INET"
"AF_INET6"
"AF_NETLINK"
];
};
})
);
}
]
# `apps run --via <tag>` for any other outbound: a pin slot of per-app TProxy or TUN for
@@ -343,21 +637,34 @@ let
let
backend = perAppRouting.pinRoutes.${route}.backend;
in
mkOneshotService {
description = "proxy-suite per-app ${route} pin for the outbound %i (in hex)";
execStart = "${perAppRouting.pinUp.${route}} %i";
execStop = "${perAppRouting.pinDown.${route}} %i";
after = [ backend ];
requires = [ backend ];
# As per-app TProxy: under a global mode, proxy-ctl runs the app without its route.
conflicts = [
"${serviceNames.tproxy}.service"
"${serviceNames.tun}.service"
];
}
// {
partOf = [ backend ];
};
# Its table and its users' rules back after a firewall reload that flushed them. The
# users' holds keep their apps in while it rebuilds.
restartOnSwitch (
reloadAfterFirewall
[
"${perAppRouting.pinUp.${route}} %i"
"${perAppRouting.viaReapply} ${route}-%i"
]
(
mkOneshotService {
description = "proxy-suite per-app ${route} pin for the outbound %i (in hex)";
execStart = "${perAppRouting.pinUp.${route}} %i";
execStartPost = "${perAppRouting.viaReapply} ${route}-%i";
execStop = "${perAppRouting.pinDown.${route}} %i";
after = [
backend
(perAppDnsUnit route)
];
requires = [ backend ];
wants = [ (perAppDnsUnit route) ];
# As per-app TProxy: under a global mode, proxy-ctl runs the app without its route.
execStartPre = ctx.constants.refuseUnderGlobal ctx.pkgs globalModeUnits;
}
// {
partOf = [ backend ];
}
)
);
}) (builtins.attrNames perAppRouting.pinUp)
++ [
{
@@ -367,6 +674,12 @@ let
description = "Enable proxy-suite per-app via marking for %i";
execStart = "${perAppRouting.viaUserStart} %i";
execStop = "${perAppRouting.viaUserStop} %i";
# No unit names the via unit from <uid>-<key>, so no Requires= can hold it for
# StopWhenUnneeded=: the last user's unit takes it down itself.
execStopPost = "${perAppRouting.viaRetire} %i";
# A switch's stop would take the via unit down under the running apps; a new via
# unit puts the rules back itself (viaReapply). In [Service], where the switch reads it.
extraServiceConfig.X-RestartIfChanged = false;
};
}
{
@@ -392,7 +705,20 @@ let
value = mkOneshotService {
description = "Set proxy-suite route mode to %i";
execStart = "${scripts.setRouteModeScript} %i";
extraServiceConfig.RemainAfterExit = false;
# Root, started by userControl's group: it writes the mode file and restarts the
# proxy, nothing else.
extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ ]
// lib.optionalAttrs ctx.constants.privileged {
# Where the mode file lives, which nothing else makes: kept between runs, and
# writable under ProtectSystem, whether or not it exists yet.
RuntimeDirectory = "proxy-suite";
RuntimeDirectoryPreserve = "yes";
NoNewPrivileges = true;
PrivateTmp = true;
};
};
}
{
+23 -3
View File
@@ -10,10 +10,30 @@ let
s = cfg.sshProxy;
inherit (derived.constants) serviceUser unprivilegedServiceConfig;
destination = if s.server.user == null then s.server.host else "${s.server.user}@${s.server.host}";
# ssh reads "::1:1091" as a bad forwarding spec: an IPv6 address goes in brackets.
listenHost =
if lib.hasInfix ":" s.listener.address then "[${s.listener.address}]" else s.listener.address;
extraArgs = lib.concatMapStrings (arg: " args+=(${lib.escapeShellArg arg})\n") s.extraArgs;
# The server's keys: a known-hosts file, the one sing-box reads, or its keys as one.
knownHostsSource =
if s.knownHostsFile != null then
s.knownHostsFile
else if s.hostKeyFile != null then
s.hostKeyFile
else if s.hostKey != [ ] then
pkgs.writeText "proxy-suite-ssh-known-hosts" (
lib.concatMapStrings (
key:
"${
if s.server.port == 22 then s.server.host else "[${s.server.host}]:${toString s.server.port}"
} ${key}\n"
) s.hostKey
)
else
null;
# The service user's home is /var/empty: accepted host keys are kept in the state dir.
knownHosts =
if s.knownHostsFile != null then
if knownHostsSource != null then
''"$CREDENTIALS_DIRECTORY/known_hosts"''
else if s.serviceUser == serviceUser then
''"$STATE_DIRECTORY/known_hosts"''
@@ -30,7 +50,7 @@ let
-o ServerAliveCountMax=3
-o ConnectTimeout=10
-o StrictHostKeyChecking=${lib.escapeShellArg s.strictHostKeyChecking}
-D ${lib.escapeShellArg "${s.listener.address}:${toString s.listener.port}"}
-D ${lib.escapeShellArg "${listenHost}:${toString s.listener.port}"}
)
${lib.optionalString (s.server.port != 22) "args+=(-p ${toString s.server.port})"}
${lib.optionalString (s.identityFile != null) ''args+=(-i "$CREDENTIALS_DIRECTORY/identity")''}
@@ -55,7 +75,7 @@ in
# Copies the service user can read, whoever owns the originals.
LoadCredential =
lib.optional (s.identityFile != null) "identity:${s.identityFile}"
++ lib.optional (s.knownHostsFile != null) "known_hosts:${s.knownHostsFile}";
++ lib.optional (knownHostsSource != null) "known_hosts:${knownHostsSource}";
StateDirectory = "proxy-suite/ssh";
StateDirectoryMode = "0700";
# `ssh -N` exits 0 when the server closes the connection cleanly, which
+13 -3
View File
@@ -94,9 +94,19 @@ in
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig =
derived.constants.unprivilegedServiceConfig [
"net_bind_service"
]
# Not proxy-suite-daemon, whose traffic gets past TUN, TProxy and the kill switch whatever
# bypassTransparentProxy says: the bypass goes by the cgroup mark below.
builtins.removeAttrs
(derived.constants.unprivilegedServiceConfig [
"net_bind_service"
])
[
"User"
"Group"
]
// lib.optionalAttrs cfg.host.privileged {
DynamicUser = true;
}
// {
ExecStart = startScript;
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
+29 -11
View File
@@ -9,7 +9,15 @@
let
t = derived.torCfg;
inherit (derived.constants) unprivilegedServiceConfig;
inherit (derived.constants) torUser;
# As the service user's, but Tor's own user: shares nothing with the inbounds or backend.
unprivilegedServiceConfig =
caps:
derived.constants.unprivilegedServiceConfig caps
// lib.optionalAttrs privileged {
User = torUser;
Group = torUser;
};
inherit (cfg.host) privileged;
inherit (derived.localProxy) auth;
@@ -26,11 +34,11 @@ let
viaProxy = t.upstream == "proxy";
withProxyAuth = viaProxy && derived.localProxy.authEnabled;
bridgesEnabled = t.bridges.lines != [ ] || t.bridges.file != null;
# A torrc string: Tor unescapes \\ and \" inside the quotes.
torQuote = s: ''"${builtins.replaceStrings [ "\\" "\"" ] [ "\\\\" "\\\"" ] s}"'';
# The control socket is Tor's own (and root's): with it, one can publish any loopback
# port as an onion service, point Tor at another upstream, or read the proxy password
# from its config. userControl's group asks for a new identity through
# proxy-suite-tor-newnym instead.
# The control socket is Tor's own user's: userControl's group asks for a new identity
# through proxy-suite-tor-newnym instead.
controlSocket = derived.constants.torControlSocket;
newnymScript = pkgs.writeShellScript "proxy-suite-tor-newnym" ''
set -euo pipefail
@@ -121,8 +129,12 @@ let
echo "DataDirectory $STATE_DIRECTORY"
echo "ControlSocket unix:$RUNTIME_DIRECTORY/control/socket"
${lib.optionalString withProxyAuth ''
echo "Socks5ProxyUsername "${lib.escapeShellArg auth.username}
printf 'Socks5ProxyPassword %s\n' "$(${pkgs.coreutils}/bin/head -n1 "$CREDENTIALS_DIRECTORY/proxy-password")"
# Quoted: bare, a "#" would start a comment, a leading quote open a string and a
# trailing backslash join the next line on.
echo ${lib.escapeShellArg "Socks5ProxyUsername ${torQuote auth.username}"}
password=$(${pkgs.coreutils}/bin/head -n1 "$CREDENTIALS_DIRECTORY/proxy-password")
password=''${password//\\/\\\\}
printf 'Socks5ProxyPassword "%s"\n' "''${password//\"/\\\"}"
''}
${lib.optionalString (t.bridges.file != null) ''
${pkgs.gnused}/bin/sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e '/^$/d' -e '/^#/d' \
@@ -141,6 +153,9 @@ let
'';
in
{
# Whatever the upstream: only its exemption from TUN and TProxy depends on it.
services.proxy-suite.internal.systemUsers = lib.optional privileged torUser;
services.proxy-suite.internal.services.proxy-suite-tor = {
description = "proxy-suite - Tor";
after = [ "network-online.target" ] ++ lib.optional viaProxy "proxy-suite-socks.service";
@@ -154,8 +169,8 @@ in
Type = "simple";
ExecStart = startScript;
ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
# The service user is excluded from TUN and TProxy capture, which is what keeps
# tor's own connections out of the proxy.
# Unless upstream = "proxy", its user is kept out of TUN and TProxy
# (constants.ownTrafficUsers), and with it Tor's own connections.
StateDirectory = "proxy-suite/tor";
StateDirectoryMode = "0700";
RuntimeDirectory = "proxy-suite-tor";
@@ -173,15 +188,18 @@ in
};
# `proxy-ctl tor newnym` for userControl's group ("services" scope), which cannot open
# the control socket. Root.
# the control socket. As Tor's own user: root without capabilities could not even enter
# the 0700 control directory.
services.proxy-suite.internal.services.proxy-suite-tor-newnym = lib.mkIf privileged {
description = "proxy-suite - new Tor circuits for new connections";
after = [ "proxy-suite-tor.service" ];
# Only a running Tor: this never starts one.
unitConfig.Requisite = [ "proxy-suite-tor.service" ];
serviceConfig = {
serviceConfig = unprivilegedServiceConfig [ ] // {
Type = "oneshot";
ExecStart = newnymScript;
# A filesystem socket is all it opens.
RestrictAddressFamilies = [ "AF_UNIX" ];
};
};
}
+40 -17
View File
@@ -38,7 +38,7 @@ let
# Fallback: a third-party generator registers from abroad and hands the profile back.
# curl follows HTTPS_PROXY when it is set.
generate() {
body=$(${pkgs.curl}/bin/curl -fsS --max-time 60 -A proxy-suite \
body=$(${pkgs.curl}/bin/curl -fsS --max-time 60 --proto-redir =https -A proxy-suite \
${lib.escapeShellArg w.generatorUrl}) || return 1
case "$body" in
"[Interface]"*) printf '%s\n' "$body" ;;
@@ -65,8 +65,14 @@ let
proxied() {
HTTPS_PROXY="socks5://''${userinfo}${hostPart}:${toString listener.port}" "$@"
}
proxied register || register${fallbacks}${
lib.optionalString (w.generatorUrl != null) " || proxied generate"
${
# Direct, as the service user: past the kill switch (killSwitch.directFallbacks).
if derived.killSwitchEnabled && !cfg.killSwitch.directFallbacks then
"proxied register${lib.optionalString (w.generatorUrl != null) " || proxied generate"}"
else
"proxied register || register${fallbacks}${
lib.optionalString (w.generatorUrl != null) " || proxied generate"
}"
}
''
else
@@ -132,6 +138,16 @@ in
echo "proxy-suite: waiting for the WARP profile at $profile" >&2
until [ -s "$profile" ]; do sleep 5; done
fi
# Root reads a profile in the service user's directory through no symlink, FIFO or endless
# file; one in a directory of root's (a secret's symlink) as it is.
if [ "$(${pkgs.coreutils}/bin/stat -L -c %u -- "$(${pkgs.coreutils}/bin/dirname -- "$profile")")" != 0 ]; then
(umask 077 && ${pkgs.coreutils}/bin/dd if="$profile" iflag=nofollow,nonblock bs=65536 count=1 status=none \
> "$RUNTIME_DIRECTORY/warp-profile.conf") || {
echo "proxy-suite: the WARP profile at $profile is not a regular file" >&2
exit 1
}
profile="$RUNTIME_DIRECTORY/warp-profile.conf"
fi
'';
inherit (d)
tunnelPort
@@ -152,20 +168,27 @@ in
# Retried until it registers. Not a oneshot: a slow or failed registration must not
# hold up or fail a switch.
startLimitIntervalSec = 0;
serviceConfig = unprivilegedServiceConfig [ ] // {
Type = "simple";
RemainAfterExit = true;
Restart = "on-failure";
RestartSec = 30;
StateDirectory = "proxy-suite/${d.stateSubdir}";
StateDirectoryMode = "0700";
WorkingDirectory = "${derived.constants.stateDir}/${d.stateSubdir}";
UMask = "0077";
LoadCredential = lib.optional (
cfg.proxy.enable && withProxyAuth
) "proxy-password:${passwordSource}";
ExecStart = registerScript;
};
# Its direct lookups work under the kill switch: a global WARP profile waits on it.
# Through the proxy, wgcf hands the name over.
serviceConfig =
unprivilegedServiceConfig [ ]
// lib.optionalAttrs (!cfg.proxy.enable || cfg.killSwitch.directFallbacks) (
derived.constants.killSwitchOwnLookups pkgs
)
// {
Type = "simple";
RemainAfterExit = true;
Restart = "on-failure";
RestartSec = 30;
StateDirectory = "proxy-suite/${d.stateSubdir}";
StateDirectoryMode = "0700";
WorkingDirectory = "${derived.constants.stateDir}/${d.stateSubdir}";
UMask = "0077";
LoadCredential = lib.optional (
cfg.proxy.enable && withProxyAuth
) "proxy-password:${passwordSource}";
ExecStart = registerScript;
};
};
# Only pulls registration in: a simple unit gives the profile no ordering guarantee.
+53 -21
View File
@@ -25,9 +25,14 @@ let
# Past TUN and TProxy. Setting a mark takes CAP_NET_ADMIN, which a rootless host lacks,
# and has nothing to capture its traffic anyway.
mark = if cfg.host.privileged then cfg.proxy.tproxy.proxyMark else null;
# The tunnel's own listener takes the hop login ($HOP_PASSWORD), from curl's stdin.
probe = port: url: ''
${pkgs.curl}/bin/curl -s --noproxy "" -x socks5h://127.0.0.1:${toString port} -m "$timeout" \
-o /dev/null ${url}'';
printf 'proxy-user = "${derived.constants.hopUser}:%s"\n' "$HOP_PASSWORD" | ${pkgs.curl}/bin/curl -K - -s --noproxy "" \
-x socks5h://127.0.0.1:${toString port} -m "$timeout" -o /dev/null ${url}'';
# direct-in takes the login the start drew ($DIRECT_AUTH), from curl's stdin: argv is public.
probeDirect = port: url: ''
printf 'proxy-user = "probe:%s"\n' "$DIRECT_AUTH" | ${pkgs.curl}/bin/curl -K - -s --noproxy "" \
-x socks5h://127.0.0.1:${toString port} -m "$timeout" -o /dev/null ${url}'';
# Some lines drop a share of fresh handshakes for good, and both engines retry on the
# same source port forever. A new process binds a new port, so the watchdog exits when
@@ -36,10 +41,9 @@ let
# gets three misses. sing-box's "direct-in" listener reaches Cloudflare through the uplink
# with the backend's mark (not urlTest.url, which is picked to be blocked here): when that
# fails too, the tunnel could not work from a new port either. wireproxy has no such
# listener (directPort = null), so it is restarted either way.
# listener (directPort = null), so it is restarted either way. The tag is $TUNNEL_TAG.
mkWatchdog =
{
tag,
command,
tunnelPort,
directPort,
@@ -57,13 +61,13 @@ let
kill -0 "$tunnel" 2>/dev/null || { wait "$tunnel"; exit 1; }
timeout=$(( healthy ? 10 : 4 ))
if ${probe tunnelPort "-f ${lib.escapeShellArg cfg.proxy.urlTest.url}"}; then
(( healthy )) || echo "proxy-suite: ${tag} is answering" >&2
(( healthy )) || echo "proxy-suite: $TUNNEL_TAG is answering" >&2
healthy=1 failures=0 uplink_down=0
continue
fi
${lib.optionalString (directPort != null) ''
if ! ${probe directPort "https://1.1.1.1/cdn-cgi/trace"}; then
(( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging ${tag}" >&2
if ! ${probeDirect directPort "https://1.1.1.1/cdn-cgi/trace"}; then
(( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging $TUNNEL_TAG" >&2
uplink_down=1 failures=0 since=$SECONDS
continue
fi
@@ -71,10 +75,10 @@ let
uplink_down=0
# proxy-suite-outbound-groups hears of the first miss: a failover group moves off it now.
if (( healthy && failures == 0 )) && [[ -d ${hintDir} ]]; then
${pkgs.coreutils}/bin/touch ${hintDir}/${lib.escapeShellArg tag} 2>/dev/null || true
${pkgs.coreutils}/bin/touch "${hintDir}/$TUNNEL_TAG" 2>/dev/null || true
fi
if (( healthy ? ++failures >= 3 : SECONDS - since >= 15 )); then
echo "proxy-suite: ${tag} is not answering; restarting the tunnel on a new source port" >&2
echo "proxy-suite: $TUNNEL_TAG is not answering; restarting the tunnel on a new source port" >&2
kill "$tunnel"
wait "$tunnel"
exit 1
@@ -88,7 +92,6 @@ let
# rather than baked into the store; the engine itself runs as ${serviceUser}.
singBoxEngine =
{
tag,
tunnelPort,
directPort,
endpoint,
@@ -96,15 +99,19 @@ let
}:
{
convert = ''
endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag}${markArg "--routing-mark"}${
endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag "$TUNNEL_TAG"${markArg "--routing-mark"}${
lib.optionalString (endpoint != null) " --endpoint ${lib.escapeShellArg endpoint}"
} < "$profile")
# direct-in gets past TProxy and the kill switch: a login drawn per start keeps other local
# users off it (read from the environment, as argv is public).
DIRECT_AUTH=$(${pkgs.coreutils}/bin/od -An -tx1 -N16 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n')
export DIRECT_AUTH
# From a pipe: the endpoint holds the private key, and argv is public.
(umask 027 && ${pkgs.jq}/bin/jq -n --slurpfile ep <(printf '%s' "$endpoint") '$ep[0] as $ep | {
(umask 027 && ${pkgs.jq}/bin/jq -n --arg tag "$TUNNEL_TAG" --slurpfile ep <(printf '%s' "$endpoint") '$ep[0] as $ep | {
log: {level: "warn"},
dns: {servers: [
${builtins.toJSON (dnsServer "local" cfg.proxy.dns.local)},
(${builtins.toJSON (dnsServer "remote" cfg.proxy.dns.remote)} + {detour: "${tag}", domain_resolver: "local"})
(${builtins.toJSON (dnsServer "remote" cfg.proxy.dns.remote)} + {detour: $tag, domain_resolver: "local"})
]},
route: {
default_domain_resolver: ${
@@ -119,11 +126,13 @@ let
)
},
rules: [{inbound: ["direct-in"], outbound: "direct"}],
final: "${tag}"
final: $tag
},
inbounds: [
{type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString tunnelPort}},
{type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString directPort}}
{type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString tunnelPort},
users: [{username: "${derived.constants.hopUser}", password: $ENV.HOP_PASSWORD}]},
{type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString directPort},
users: [{username: "probe", password: $ENV.DIRECT_AUTH}]}
],
outbounds: [{type: "direct", tag: "direct"${
lib.optionalString (mark != null) ", routing_mark: ${toString mark}"
@@ -154,13 +163,13 @@ let
# `endpoint`, a host:port in place of the profile's Endpoint, and `domainStrategy`, the
# address family it dials destinations over first.
#
# A template unit passes `tag` and `tunnelPort` as shell words ("$TUNNEL_TAG") that
# `profile` exports: the watchdog runs as a script of its own, after the exec.
# The tag comes from $TUNNEL_TAG, never spliced in (an attribute name can hold anything). A
# template unit passes `tag = null` and `tunnelPort = "$TUNNEL_PORT"`, both from `profile`.
mkTunnel =
{
description,
unit,
tag,
tag ? null,
profile,
tunnelPort,
directPort ? null,
@@ -176,7 +185,6 @@ let
let
chosen = (if engine == "userspace" then wireproxyEngine else singBoxEngine) {
inherit
tag
tunnelPort
directPort
endpoint
@@ -185,7 +193,14 @@ let
};
tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" ''
set -euo pipefail
${lib.optionalString (tag != null) "TUNNEL_TAG=${lib.escapeShellArg tag}"}
${profile}
export TUNNEL_TAG
# The hop login (constants.ensureHopLogin): the backend dials the listener with it,
# and the watchdog probes it so. Through the environment alone: argv is public.
${derived.constants.ensureHopLogin pkgs}
HOP_PASSWORD=$(< ${lib.escapeShellArg derived.constants.hopLoginFile})
export HOP_PASSWORD
${chosen.convert}
${ifPrivileged ''
@@ -195,7 +210,7 @@ let
exec ${runAsServiceUser pkgs [ "net_admin" ]} ${
mkWatchdog {
inherit tag tunnelPort;
inherit tunnelPort;
inherit (chosen) command directPort;
}
}
@@ -212,9 +227,26 @@ let
ExecStart = if execArgs == "" then tunnelScript else "${tunnelScript}${execArgs}";
Restart = restart;
RestartSec = 2;
# A profile that fails for good backs off to a minute rather than going through its
# conversion as root every 2 s.
RestartSteps = 5;
RestartMaxDelaySec = 60;
RuntimeDirectory = runtimeDirectory;
RuntimeDirectoryMode = "0750";
UMask = "0077";
}
# Root only converts the profile; the engine gets net_admin alone. No ProtectHome: a
# configFile may sit under /home or /root.
// lib.optionalAttrs cfg.host.privileged {
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
# The watchdog's hints go to proxy-suite-outbound-groups' directory, which comes and
# goes with that unit: a bind of the directory itself would go stale.
ReadWritePaths = [ derived.constants.runtimeDir ];
ProtectKernelTunables = true;
ProtectControlGroups = true;
RestrictSUIDSGID = true;
};
};
in
+47 -10
View File
@@ -9,7 +9,11 @@
let
w = derived.whitelistBypassCfg;
inherit (derived.constants) unprivilegedServiceConfig privileged serviceUser;
inherit (derived.constants)
unprivilegedServiceConfig
privileged
serviceUser
;
inherit (derived.localProxy) auth;
# A file in the state directory, which the whitelistBypass scope's group writes to: a
@@ -33,6 +37,9 @@ let
groupAccess = privileged && derived.userControlAnyAllows "whitelistBypass";
stateDir = "${derived.constants.stateDir}/whitelist-bypass";
stateMode = if groupAccess then "0770" else "0700";
# The creators' logins, which they rewrite as they run: the daemon's alone, out of the
# group's directory.
sessionsDir = "${derived.constants.stateDir}/whitelist-bypass-sessions";
stateGroup =
if privileged && derived.userControlAllows "whitelistBypass" then
cfg.userControl.group
@@ -55,12 +62,17 @@ let
// {
Restart = "always";
RestartSec = 5;
RestartSteps = 5;
RestartMaxDelaySec = 120;
StateDirectory = "proxy-suite/whitelist-bypass";
StateDirectoryMode = stateMode;
}
# The group writes the state directory: whatever a name there points at, the daemon
# writes nowhere else.
// lib.optionalAttrs privileged { ProtectSystem = "strict"; }
# writes nowhere else but the creators' sessions ("-": none without creators).
// lib.optionalAttrs privileged {
ProtectSystem = "strict";
ReadWritePaths = [ "-${sessionsDir}" ];
}
// lib.optionalAttrs groupAccess { Group = stateGroup; }
// serviceConfig;
};
@@ -77,8 +89,15 @@ let
# The link from the environment (pkgs/whitelist-bypass.nix): argv is public.
WB_LINK=$(${readState ''"$join"''} | tr -d '[:space:]')
export WB_LINK
exec ${w.package}/bin/headless-${j.platform}-joiner --socks-port ${toString j.port}
# Its listener takes the hop login, which the backend dials it with; the password
# from the environment as well.
WB_SOCKS_PASS=$(< ${lib.escapeShellArg derived.constants.hopLoginFile})
export WB_SOCKS_PASS
exec ${w.package}/bin/headless-${j.platform}-joiner --socks-port ${toString j.port} \
--socks-user ${derived.constants.hopUser}
'';
# Root draws it, where nothing has yet this boot (the daemon cannot write there).
ExecStartPre = "+${derived.constants.ensureHopLogin pkgs}";
LoadCredential = lib.optional (j.linkFile != null) "link:${j.linkFile}";
}
// lib.optionalAttrs (j.linkFile == null) (waitFor "${j.tag}.join")
@@ -92,10 +111,19 @@ let
unit = mkUnit "proxy-suite - whitelist-bypass creator ${name}" {
ExecStart = pkgs.writeShellScript "proxy-suite-wb-creator-${name}" ''
set -euo pipefail
cookies="$STATE_DIRECTORY/${name}.cookies.json"
shared="$STATE_DIRECTORY/${name}.cookies.json"
cookies=${lib.escapeShellArg "${sessionsDir}/${name}.cookies.json"}
links="$STATE_DIRECTORY/${name}.link"
# The creator opens it by name: not through a symlink the group left there.
if [ -L "$cookies" ]; then rm -f -- "$cookies"; fi
umask 077
# A login `proxy-ctl wl auth` left replaces the working copy, read without following
# a symlink, then goes: what the creator refreshes is the copy's.
if [ -L "$shared" ]; then
rm -f -- "$shared"
elif [ -f "$shared" ]; then
${readState ''"$shared"''} > "$cookies.new"
mv -f -- "$cookies.new" "$cookies"
rm -f -- "$shared"
fi
${lib.optionalString (c.cookiesFile != null) ''
[ -e "$cookies" ] || install -m 600 "$CREDENTIALS_DIRECTORY/cookies" "$cookies"
''}
@@ -127,8 +155,14 @@ let
lib.nameValuePair "proxy-suite-wb-creator-${name}" (
unit
// lib.optionalAttrs viaProxy { after = unit.after ++ [ "proxy-suite-socks.service" ]; }
# Without a login it has nothing to run on until `proxy-ctl wl auth` writes one.
// lib.optionalAttrs (c.cookiesFile == null) (waitFor "${name}.cookies.json")
# Without a login it has nothing to run on until `proxy-ctl wl auth` writes one, or
# one is in its working copy already.
// lib.optionalAttrs (c.cookiesFile == null) {
unitConfig.ConditionPathExists = [
"|%S/proxy-suite/whitelist-bypass/${name}.cookies.json"
"|${sessionsDir}/${name}.cookies.json"
];
}
);
in
{
@@ -138,6 +172,9 @@ in
);
tmpfiles = [
"d ${stateDir} ${stateMode} ${if privileged then "${serviceUser} ${stateGroup}" else "- -"} -"
];
]
++
lib.optional (w.creators != { })
"d ${sessionsDir} 0700 ${if privileged then "${serviceUser} ${serviceUser}" else "- -"} -";
};
}
+37 -21
View File
@@ -26,7 +26,8 @@ let
;
})
awgServiceNames
perAppConflicts
perAppRefuseUnderGlobal
daemonSandbox
perAppZapretMarkUpScript
perAppZapretMarkDownScript
;
@@ -46,6 +47,7 @@ let
;
iptables = "${pkgs.iptables}/bin/iptables";
ip6tables = "${pkgs.iptables}/bin/ip6tables";
zapretCommonPreStart = package: ''
${package}/opt/zapret/init.d/sysv/zapret stop || true
@@ -59,22 +61,24 @@ let
fi
'';
# An IPv6 range to iptables failed the script (set -e), and every range after it with it.
tablesFor = cidr: if lib.hasInfix ":" cidr then ip6tables else iptables;
exemptStart = ''
set -euo pipefail
''
+ lib.concatMapStrings (cidr: ''
while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
while ${tablesFor cidr} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
while ${tablesFor cidr} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
${tablesFor cidr} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
${tablesFor cidr} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
'') zapretCfg.cidrExemption.cidrs;
exemptStop = ''
set +e
''
+ lib.concatMapStrings (cidr: ''
while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
while ${tablesFor cidr} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
while ${tablesFor cidr} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
'') zapretCfg.cidrExemption.cidrs;
in
{
@@ -100,24 +104,36 @@ in
extraServiceConfig = {
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
Environment = globalZapretEnv;
};
}
// daemonSandbox;
});
services.proxy-suite.internal.services.proxy-suite-per-app-zapret =
lib.mkIf perAppZapretCfg.enable
(mkOneshotService {
description = "proxy-suite per-app-routing zapret backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = perAppConflicts ++ awgServiceNames;
preStart = zapretCommonPreStart perAppZapretPackage;
runtimeDirectory = "proxy-suite-per-app-zapret";
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = perAppZapretEnv;
});
(
lib.mkMerge [
(mkOneshotService {
description = "proxy-suite per-app-routing zapret backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
preStart = zapretCommonPreStart perAppZapretPackage;
runtimeDirectory = "proxy-suite-per-app-zapret";
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig = {
Environment = perAppZapretEnv;
}
// daemonSandbox;
})
{
# Ahead of everything, preStart's script among them (mkBefore there): under a global
# mode nothing of it runs, not even the queue's firewall rules.
serviceConfig.ExecStartPre = lib.mkOrder 400 [ perAppRefuseUnderGlobal ];
}
]
);
services.proxy-suite.internal.services.proxy-suite-zapret-vm-exempt =
lib.mkIf (zapretGlobalEnabled && zapretCfg.cidrExemption.enable)
+31 -4
View File
@@ -36,10 +36,37 @@ in
);
# The transparent backends steer the same packets; a per-app zapret instance replaces them.
perAppConflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
];
# The zapret units run as root: capabilities bounded to what the init scripts and nfqws
# use, and no new privileges (nfqws narrows itself further).
daemonSandbox = lib.optionalAttrs cfg.host.privileged {
NoNewPrivileges = true;
CapabilityBoundingSet = [
"CAP_NET_ADMIN"
"CAP_NET_RAW"
"CAP_SETUID"
"CAP_SETGID"
"CAP_SETPCAP"
"CAP_SYS_MODULE"
"CAP_CHOWN"
"CAP_FOWNER"
"CAP_DAC_OVERRIDE"
"CAP_KILL"
];
LockPersonality = true;
RestrictRealtime = true;
};
# The per-app instance's ExecStartPre: it has nothing to add under a global mode, which
# it never displaces (constants.refuseUnderGlobal); those take it down as they start.
perAppRefuseUnderGlobal = derived.constants.refuseUnderGlobal pkgs (
[
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles)
)
++ lib.optional derived.awgRuntimeGlobal "proxy-suite-awg@*.service"
);
perAppZapretMarkUpScript = pkgs.writeShellScript scriptName ''
set -euo pipefail
+72 -32
View File
@@ -38,7 +38,8 @@ let
})
awgServiceNames
tunInterfaces
perAppConflicts
perAppRefuseUnderGlobal
daemonSandbox
perAppZapretMarkUpScript
perAppZapretMarkDownScript
;
@@ -89,17 +90,22 @@ let
# nfqws2 and proxy-ctl expect the list files to exist. With userControl its group
# edits them: proxy-ctl renames a new list in, so the directories are what it writes.
stateDirMode =
if userControlAllows "zapret" then
"2775 -g ${lib.escapeShellArg cfg.userControl.group}"
# userControl.groups only, through ACLs: the group bits (their mask) stay open.
else if userControlAnyAllows "zapret" then
"2775"
else
"0755";
mkPreStart = ''
${lib.getExe' pkgs.kmod "modprobe"} nfnetlink_queue 2>/dev/null || true
install -d -m ${
if userControlAllows "zapret" then
"2775 -g ${lib.escapeShellArg cfg.userControl.group}"
# userControl.groups only, through ACLs: the group bits (their mask) stay open.
else if userControlAnyAllows "zapret" then
"2775"
else
"0755"
} ${runtime.stateDir} ${runtime.circularStateDir}
install -d -m ${stateDirMode} ${runtime.stateDir}
# A plain mkdir, not install -d, which would chmod and chown a symlink a member left in the
# group's state directory.
circular=${runtime.circularStateDir}
if [ -L "$circular" ]; then rm -f -- "$circular"; fi
mkdir -m ${lib.head (lib.splitString " " stateDirMode)} -- "$circular" 2>/dev/null || true
touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile}
# In this unit's sandbox: a name a member left here leads nowhere else.
${constants.grantDirAcl pkgs runtime.stateDir (userControlExtraGroupsFor "zapret") "rwX"}
@@ -121,7 +127,8 @@ let
// lib.optionalAttrs (userControlAllows "zapret") { Group = cfg.userControl.group; }
# nfqws2 runs as root and writes its lists in a directory the zapret scope's group
# writes to as well.
// constants.rootInSharedDirConfig;
// constants.rootInSharedDirConfig
// daemonSandbox;
cutoff = import ./zapret2/cutoff.nix {
inherit
@@ -135,6 +142,25 @@ let
directSync = import ./zapret2/direct-sync.nix { inherit lib pkgs cfg; };
# autohostlist wants nf_conntrack_tcp_be_liberal on; the stop puts back what the host had.
# Outside the sandbox ("+"), which keeps /proc/sys read-only.
conntrackLiberalKey = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
conntrackLiberalOn = "-+${pkgs.writeShellScript "proxy-suite-zapret2-liberal" ''
saved="$RUNTIME_DIRECTORY/conntrack-liberal"
# Created, never followed: this runs as root outside the sandbox.
if [ ! -e "$saved" ] && [ ! -L "$saved" ]; then
${pkgs.coreutils}/bin/cat ${conntrackLiberalKey} | (set -o noclobber; cat > "$saved") 2>/dev/null || true
fi
echo 1 > ${conntrackLiberalKey}
''}";
conntrackLiberalRestore = "-+${pkgs.writeShellScript "proxy-suite-zapret2-liberal" ''
saved="$RUNTIME_DIRECTORY/conntrack-liberal"
value=$(${pkgs.coreutils}/bin/cat "$saved" 2>/dev/null || echo 0)
[[ $value =~ ^[01]$ ]] || value=0
echo "$value" > ${conntrackLiberalKey}
${pkgs.coreutils}/bin/rm -f "$saved"
''}";
in
{
services.proxy-suite.internal.services.proxy-suite-zapret2-direct = lib.mkIf (
@@ -166,7 +192,13 @@ in
runtimeDirectory = "proxy-suite-zapret";
stateDirectory = "proxy-suite/zapret2";
execStart = "${runtime.daemonScript}";
execStopPost = "${runtime.initScript} stop_fw";
execStopPost = [
"${runtime.initScript} stop_fw"
]
++ lib.optional zapretCfg.zapret2.autoHostlist.enable conntrackLiberalRestore;
# What zapret's start_fw would do for autohostlist, here outside the sandbox ("+"),
# once the firewall has loaded nf_conntrack.
execStartPost = if zapretCfg.zapret2.autoHostlist.enable then conntrackLiberalOn else null;
extraServiceConfig = daemonConfig (
runtime.mkEnv {
runtime = globalRuntime;
@@ -177,25 +209,33 @@ in
services.proxy-suite.internal.services.proxy-suite-per-app-zapret =
lib.mkIf perAppZapretCfg.enable
(mkRestartingService {
description = "proxy-suite per-app-routing zapret2 backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = perAppConflicts ++ awgServiceNames;
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-per-app-zapret";
stateDirectory = "proxy-suite/zapret2";
execStart = "${runtime.daemonScript}";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = [
"${runtime.initScript} stop_fw"
"${perAppZapretMarkDownScript}"
];
extraServiceConfig = daemonConfig (
runtime.mkEnv {
runtime = perAppRuntime;
pidDir = "/run/proxy-suite-per-app-zapret";
(
lib.mkMerge [
(mkRestartingService {
description = "proxy-suite per-app-routing zapret2 backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-per-app-zapret";
stateDirectory = "proxy-suite/zapret2";
execStart = "${runtime.daemonScript}";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = [
"${runtime.initScript} stop_fw"
"${perAppZapretMarkDownScript}"
];
extraServiceConfig = daemonConfig (
runtime.mkEnv {
runtime = perAppRuntime;
pidDir = "/run/proxy-suite-per-app-zapret";
}
);
})
{
# Ahead of everything, preStart's script among them (mkBefore there): under a global
# mode nothing of it runs, not even the queue's firewall rules.
serviceConfig.ExecStartPre = lib.mkOrder 400 [ perAppRefuseUnderGlobal ];
}
);
});
]
);
}
@@ -11,9 +11,11 @@ for f in asn.txt sni.txt asn.new sni.new proxy.json proxy.json.tmp egress ts for
done
touch asn.txt sni.txt
force=0
if [ -e requests/force ]; then
if [ -e requests/force ] || [ -L requests/force ]; then
force=1
rm -f requests/force
# Whatever the group left under the name, a directory too: rm -f alone failed on one, and
# under set -e every run stopped here.
rm -rf -- requests/force
fi
now=$(date +%s)
# Digits only: $(( )) would run what a[$(...)] in it names.
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff. Show more