feat: add connectivity fix options + hardening
This commit is contained in:
41 files changed
+626
-111
No files matched your search
+8
-1
@@ -113,6 +113,12 @@ ask_all() {
|
||||
fi
|
||||
reject "A free port from 1 to 65535 (80, 443, 2053 and 8443 are taken)." SSH_PORT
|
||||
done
|
||||
say "With a public key, SSH takes no passwords (the console still does)."
|
||||
while true; do
|
||||
ask SSH_KEY "SSH public key for $ADMIN_USER (empty: the password)" ""
|
||||
[[ -z $SSH_KEY || $SSH_KEY =~ ^(ssh-|ecdsa-sha2-|sk-)[a-z0-9@.-]+\ [A-Za-z0-9+/]+=*(\ [^[:cntrl:]]*)?$ ]] && break
|
||||
reject "Not an OpenSSH public key (ssh-ed25519 AAAA... comment)." SSH_KEY
|
||||
done
|
||||
ask_yes QEMU_GUEST "QEMU guest agent (lets the VPS panel see the server's state)" "y"
|
||||
|
||||
# --- Proxy --------------------------------------------------------------------
|
||||
@@ -202,7 +208,7 @@ show_summary() {
|
||||
DNS $NET_DNS
|
||||
Public IP $PUBLIC_IP
|
||||
Hostname $HOST_NAME
|
||||
SSH $ADMIN_USER@$PUBLIC_IP port $SSH_PORT (password shown at the end)
|
||||
SSH $ADMIN_USER@$PUBLIC_IP port $SSH_PORT ($(if [[ -n $SSH_KEY ]]; then echo "your key; password for the console"; else echo "password shown at the end"; fi))
|
||||
Guest agent $(if [[ $QEMU_GUEST == true ]]; then echo yes; else echo no; fi)
|
||||
Proxy user $PROXY_USER
|
||||
Certificate ${DOMAIN:-$PUBLIC_IP (IP certificate)}${ACME_EMAIL:+, $ACME_EMAIL}
|
||||
@@ -277,6 +283,7 @@ cat >"$etc_nixos/host.nix" <<HOST
|
||||
disko.enable = true;
|
||||
adminUser = $(nix_str "$ADMIN_USER");
|
||||
sshPort = $SSH_PORT;
|
||||
sshKeys = [ $(if [[ -n $SSH_KEY ]]; then nix_str "$SSH_KEY"; fi) ];
|
||||
$(print_network_nix " ")
|
||||
publicAddress = $(nix_str "$PUBLIC_IP");
|
||||
domain = $(if [[ -n $DOMAIN ]]; then nix_str "$DOMAIN"; else printf null; fi);
|
||||
|
||||
@@ -77,6 +77,16 @@ in
|
||||
description = "SSH port.";
|
||||
};
|
||||
|
||||
sshKeys = mkOption {
|
||||
type = types.listOf (types.strMatching "(ssh-|ecdsa-sha2-|sk-)[^\n]+");
|
||||
default = [ ];
|
||||
description = ''
|
||||
Public keys adminUser logs in with over SSH. With any, SSH takes no passwords (the
|
||||
console still does); without, it takes the password, and fail2ban bans guessers.
|
||||
'';
|
||||
example = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... admin@laptop" ];
|
||||
};
|
||||
|
||||
tools.enable = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
@@ -261,9 +271,13 @@ in
|
||||
enable = true;
|
||||
ports = [ cfg.sshPort ];
|
||||
settings = {
|
||||
PasswordAuthentication = true;
|
||||
PasswordAuthentication = cfg.sshKeys == [ ];
|
||||
KbdInteractiveAuthentication = false;
|
||||
PermitRootLogin = "no";
|
||||
# The one login this server has: an account some package adds later gets no SSH.
|
||||
AllowUsers = [ cfg.adminUser ];
|
||||
MaxAuthTries = 3;
|
||||
X11Forwarding = false;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -271,6 +285,7 @@ in
|
||||
users.users.${cfg.adminUser} = {
|
||||
isNormalUser = true;
|
||||
extraGroups = [ "wheel" ];
|
||||
openssh.authorizedKeys.keys = cfg.sshKeys;
|
||||
};
|
||||
|
||||
boot.kernel.sysctl = {
|
||||
@@ -415,6 +430,14 @@ in
|
||||
# Bandwidth per process and connection, without sudo (a capability wrapper).
|
||||
bandwhich.enable = true;
|
||||
};
|
||||
# Wheel only: the wrapper's capabilities (sys_ptrace, dac_read_search, net_raw) show
|
||||
# every connection on the host, the proxy users' included, to whoever runs it.
|
||||
security.wrappers = lib.mkIf cfg.tools.enable {
|
||||
bandwhich = {
|
||||
group = lib.mkForce "wheel";
|
||||
permissions = "u+rx,g+x";
|
||||
};
|
||||
};
|
||||
users.defaultUserShell = lib.mkIf cfg.tools.enable pkgs.fish;
|
||||
|
||||
# Man pages stay; the NixOS manual, info and HTML docs are a download no server needs.
|
||||
|
||||
@@ -123,6 +123,7 @@ Part of the [proxy-suite options reference](./index.md).
|
||||
- [zapretDirect](#services-proxy-suite-inbounds-routing-zapretdirect)
|
||||
- [serverAddress](#services-proxy-suite-inbounds-serveraddress)
|
||||
- [serverAliases](#services-proxy-suite-inbounds-serveraliases)
|
||||
- [serverPorts](#services-proxy-suite-inbounds-serverports)
|
||||
- [shareLinks](#services-proxy-suite-inbounds-sharelinks)
|
||||
- subscriptions
|
||||
- [enable](#services-proxy-suite-inbounds-subscriptions-enable)
|
||||
@@ -1145,11 +1146,33 @@ Other names and IPs of this host that clients reach through the tunnel, such as
|
||||
TURN relay’s name beside the site on ` serverAddress `\. Like ` serverAddress `, they go
|
||||
direct on the listener ports instead of looping back through ` routing.via `, which
|
||||
often cannot reach this host at all\. List the IPs too: a client that resolves a name
|
||||
itself hands XRay the address, which no name rule matches\.
|
||||
itself hands XRay the address, which no name rule matches\. ` domain:example.com `
|
||||
covers that name and every name under it, for a host behind a wildcard record\.
|
||||
|
||||
**Type:** list of string matching the pattern \[^\[:space:]]+\
|
||||
**Default:** `[ ]`\
|
||||
**Example:** `[ "turn.example.com" "203.0.113.10" "2001:db8::10" ]`
|
||||
**Example:**
|
||||
|
||||
```nix
|
||||
[
|
||||
"turn.example.com"
|
||||
"domain:example.com"
|
||||
"203.0.113.10"
|
||||
"2001:db8::10"
|
||||
]
|
||||
```
|
||||
|
||||
<a id="services-proxy-suite-inbounds-serverports"></a>
|
||||
## services\.proxy-suite\.inbounds\.serverPorts
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string matching the pattern \[0-9]±\[0-9]+)\
|
||||
**Default:** `[ ]`\
|
||||
**Example:** `config.networking.firewall.allowedTCPPorts`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-sharelinks"></a>
|
||||
## services\.proxy-suite\.inbounds\.shareLinks
|
||||
|
||||
@@ -86,6 +86,7 @@ services.proxy-suite = {
|
||||
};
|
||||
serverAddress = null;
|
||||
serverAliases = [ ];
|
||||
serverPorts = [ ];
|
||||
shareLinks = true;
|
||||
subscriptions = {
|
||||
baseUrl = null;
|
||||
|
||||
@@ -575,7 +575,8 @@ let
|
||||
echo "proxy-suite: no AmneziaWG outbound '$TUNNEL_TAG' in ${runtimeOutboundsDir}" >&2
|
||||
exit 0
|
||||
fi
|
||||
TUNNEL_PORT=$(${pkgs.coreutils}/bin/head -n 1 "${runtimeOutboundsDir}/$TUNNEL_TAG.port" 2>/dev/null || true)
|
||||
# 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
|
||||
echo "proxy-suite: AmneziaWG outbound '$TUNNEL_TAG' needs a port in ${toString awgRuntimeTunnelBasePort}-${toString runtimeTunnelLastPort} in $TUNNEL_TAG.port" >&2
|
||||
exit 1
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
let
|
||||
apCfg = cfg.proxy.autoProxy;
|
||||
inherit ((import ./derived.nix { inherit lib cfg; }).constants) rootInSharedDirConfig;
|
||||
# The autoProxy scope's group writes the directory: `proxy auto learn` queues there.
|
||||
stateDirMode = if userControlAllows "autoProxy" then "0771" else "0751";
|
||||
render = import ./autoproxy-render.nix {
|
||||
@@ -41,13 +42,13 @@ let
|
||||
|
||||
excludePattern = lib.concatStringsSep "|" (map lib.escapeRegex apCfg.exclude);
|
||||
|
||||
# Sets $clash_api (empty when the API is off) and $clash_auth (curl args).
|
||||
# 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 = ''
|
||||
socks_config="$(dirname "$index")/config.json"
|
||||
clash_api=$(jq -r '.experimental.clash_api.external_controller // empty' "$socks_config" 2>/dev/null || true)
|
||||
clash_secret=$(jq -r '.experimental.clash_api.secret // empty' "$socks_config" 2>/dev/null || true)
|
||||
clash_auth=()
|
||||
[ -z "$clash_secret" ] || clash_auth=(-H "Authorization: Bearer $clash_secret")
|
||||
clash_auth_header() { printf 'Authorization: Bearer %s\n' "$clash_secret"; }
|
||||
'';
|
||||
|
||||
sampler = pkgs.writeShellScript "proxy-suite-autoproxy" ''
|
||||
@@ -66,7 +67,7 @@ let
|
||||
lines=$(
|
||||
for i in $(seq 0 10); do
|
||||
[ "$i" -eq 0 ] || sleep 1
|
||||
curl -sS --noproxy '*' --max-time 1 "''${clash_auth[@]}" "http://$clash_api/connections" 2>/dev/null ||
|
||||
curl -sS --noproxy '*' --max-time 1 -H @<(clash_auth_header) "http://$clash_api/connections" 2>/dev/null ||
|
||||
echo '{}'
|
||||
done | jq -s -r --argjson min ${toString (300 * 1024)} \
|
||||
--argjson below ${
|
||||
@@ -470,7 +471,10 @@ let
|
||||
StateDirectoryMode = stateDirMode;
|
||||
UMask = "0027";
|
||||
}
|
||||
// lib.optionalAttrs (userControlAllows "autoProxy") { Group = cfg.userControl.group; };
|
||||
// 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;
|
||||
|
||||
mkUnit = description: args: {
|
||||
inherit description;
|
||||
|
||||
@@ -402,6 +402,14 @@ let
|
||||
RestrictSUIDSGID = true;
|
||||
LockPersonality = true;
|
||||
};
|
||||
# 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.
|
||||
rootInSharedDirConfig = lib.optionalAttrs cfg.host.privileged {
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
PrivateTmp = true;
|
||||
};
|
||||
# Socket marks and IP_TRANSPARENT, TUN and auto_redirect, listeners below 1024, ICMP.
|
||||
backendCaps = [
|
||||
"net_admin"
|
||||
@@ -410,7 +418,9 @@ let
|
||||
];
|
||||
|
||||
zapret2StateDir = "${stateDir}/zapret2";
|
||||
zapret2CutoffDir = "${stateDir}/zapret2/cutoff";
|
||||
# Not under zapret2/, which the zapret scope's group writes to: root works here by
|
||||
# fixed names (the group asks for probes in requests/).
|
||||
zapret2CutoffDir = "${stateDir}/zapret2-cutoff";
|
||||
# Conntrack bit on the cutoff probe's own connections, which zapret2 leaves alone.
|
||||
zapret2CutoffProbeCtMark = 33554432; # 0x2000000
|
||||
|
||||
@@ -430,6 +440,24 @@ let
|
||||
pinnedOutboundFile = "${stateDir}/pinned-outbound";
|
||||
runtimeOutboundsDir = "${stateDir}/outbounds.d";
|
||||
runtimeSubscriptionsDir = "${stateDir}/subscriptions.d";
|
||||
# Shell function for the scripts that read those spools as root. $1 a file: in a spool,
|
||||
# a regular file only, and never through a symlink, which would hand over any file root
|
||||
# can read (a share link or an error message then shows it), nor a FIFO, which would
|
||||
# hang the start. Declared files elsewhere (a sops symlink, say) are read as they are.
|
||||
readSourceFunction = pkgs: ''
|
||||
_proxy_suite_read_source() {
|
||||
case "$1" in
|
||||
${stateDir}/outbounds.d/* | ${stateDir}/subscriptions.d/*)
|
||||
if [ ! -f "$1" ] || [ -L "$1" ]; then
|
||||
echo "proxy-suite: $1 is not a regular file" >&2
|
||||
return 1
|
||||
fi
|
||||
${pkgs.coreutils}/bin/dd if="$1" iflag=nofollow,nonblock status=none
|
||||
;;
|
||||
*) ${pkgs.coreutils}/bin/cat -- "$1" ;;
|
||||
esac
|
||||
}
|
||||
'';
|
||||
# Written by every backend start script; proxy-ctl reads the socks copy.
|
||||
outboundInventoryFile = "${runtimeDir}/proxy-suite-socks/outbounds.json";
|
||||
|
||||
|
||||
@@ -38,15 +38,29 @@ in
|
||||
TURN relay's name beside the site on `serverAddress`. Like `serverAddress`, they go
|
||||
direct on the listener ports instead of looping back through `routing.via`, which
|
||||
often cannot reach this host at all. List the IPs too: a client that resolves a name
|
||||
itself hands XRay the address, which no name rule matches.
|
||||
itself hands XRay the address, which no name rule matches. `domain:example.com`
|
||||
covers that name and every name under it, for a host behind a wildcard record.
|
||||
'';
|
||||
example = [
|
||||
"turn.example.com"
|
||||
"domain:example.com"
|
||||
"203.0.113.10"
|
||||
"2001:db8::10"
|
||||
];
|
||||
};
|
||||
|
||||
serverPorts = mkOption {
|
||||
type = types.listOf (types.either types.port (types.strMatching "[0-9]+-[0-9]+"));
|
||||
default = [ ];
|
||||
description = ''
|
||||
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.
|
||||
'';
|
||||
example = literalExpression "config.networking.firewall.allowedTCPPorts";
|
||||
};
|
||||
|
||||
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.";
|
||||
|
||||
|
||||
@@ -40,16 +40,20 @@ let
|
||||
# The address clients dial must stay reachable even when blockRu covers it
|
||||
# (a .ru domain or IP). After blockPrivate, so it cannot open the LAN. Its aliases
|
||||
# too: routing.via usually cannot loop back to this host, so they would fail there.
|
||||
# A "domain:" alias is a suffix, for a wildcard DNS record: the name and every name under it.
|
||||
isSuffix = lib.hasPrefix "domain:";
|
||||
isIp =
|
||||
addr: lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null;
|
||||
addr:
|
||||
!isSuffix addr
|
||||
&& (lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null);
|
||||
serverAddresses =
|
||||
lib.optional (proxyInboundsCfg.serverAddress != null) proxyInboundsCfg.serverAddress
|
||||
++ proxyInboundsCfg.serverAliases;
|
||||
serverIps = lib.unique (builtins.filter isIp serverAddresses);
|
||||
serverNames = lib.unique (builtins.filter (addr: !isIp addr) serverAddresses);
|
||||
|
||||
# Only the ports clients dial there: the rest of this host (wildcard services the
|
||||
# firewall keeps from the internet) must not be reachable through it.
|
||||
# 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.
|
||||
@@ -59,6 +63,7 @@ let
|
||||
80
|
||||
443
|
||||
]
|
||||
++ proxyInboundsCfg.serverPorts
|
||||
);
|
||||
|
||||
# Names and IPs in rules of their own: XRay ANDs the fields of one rule.
|
||||
@@ -75,7 +80,7 @@ let
|
||||
|
||||
serverAddressRule =
|
||||
mkServerAddressRule "inbound-server-address-direct" "domain" (
|
||||
map (name: "full:${name}") serverNames
|
||||
map (name: if isSuffix name then name else "full:${name}") serverNames
|
||||
)
|
||||
++ mkServerAddressRule "inbound-server-address-direct-ip" "ip" serverIps;
|
||||
|
||||
|
||||
@@ -38,9 +38,16 @@ let
|
||||
fetchScript = pkgs.writeShellScript "proxy-suite-rulesets" ''
|
||||
set -uo pipefail
|
||||
proxy=(--proxy socks5h://${localProxy.hostPart}:${toString cfg.proxy.listener.port})
|
||||
${lib.optionalString withProxyAuth ''
|
||||
proxy+=(--proxy-user ${lib.escapeShellArg auth.username}:"$(< "$CREDENTIALS_DIRECTORY/proxy-password")")
|
||||
''}
|
||||
# The listener's login as curl config on a pipe (-K): argv is readable by every local user.
|
||||
proxy_login() {
|
||||
[ "$1" = proxy ] || return 0
|
||||
${lib.optionalString withProxyAuth ''
|
||||
local login
|
||||
login=${lib.escapeShellArg auth.username}:"$(< "$CREDENTIALS_DIRECTORY/proxy-password")"
|
||||
login=''${login//\\/\\\\}
|
||||
printf 'proxy-user = "%s"\n' "''${login//\"/\\\"}"
|
||||
''}
|
||||
}
|
||||
failed=0
|
||||
|
||||
# A download replaces the file only once sing-box has read it back, so a bad one never
|
||||
@@ -52,7 +59,7 @@ let
|
||||
[ "$detour" = proxy ] && args+=("''${proxy[@]}")
|
||||
tmp=$(${pkgs.coreutils}/bin/mktemp "$path.XXXXXX") || { failed=1; return; }
|
||||
dnsTmp=$(${pkgs.coreutils}/bin/mktemp "$dns.XXXXXX") || { rm -f "$tmp"; failed=1; return; }
|
||||
if ${curl} "''${args[@]}" --output "$tmp" "$url" && valid "$tmp" "$format" &&
|
||||
if ${curl} "''${args[@]}" -K <(proxy_login "$detour") --output "$tmp" "$url" && valid "$tmp" "$format" &&
|
||||
domains "$tmp" "$format" > "$dnsTmp" && valid "$dnsTmp" source; then
|
||||
chmod 0644 "$tmp" "$dnsTmp"
|
||||
mv -f "$dnsTmp" "$dns"
|
||||
|
||||
@@ -51,7 +51,18 @@ let
|
||||
|
||||
builders = import ./builders.nix { inherit lib pkgs; };
|
||||
|
||||
polkit = import ./polkit.nix { inherit userControlCfg; };
|
||||
polkit = import ./polkit.nix {
|
||||
inherit lib pkgs userControlCfg;
|
||||
unitNames =
|
||||
let
|
||||
declared =
|
||||
suffix: units:
|
||||
map (name: if lib.hasSuffix "@" name then name else "${name}.${suffix}") (
|
||||
lib.attrNames (lib.filterAttrs (_: unit: unit.enable) units)
|
||||
);
|
||||
in
|
||||
declared "service" cfg.internal.services ++ declared "timer" cfg.internal.timers;
|
||||
};
|
||||
|
||||
# One context for the service layer: everything derived.nix computes, the tool paths and
|
||||
# generated files above, and the shell-snippet builders. Sub-modules take it whole and
|
||||
|
||||
@@ -102,8 +102,13 @@ let
|
||||
printf '%s\n' "$tag" > "${pinnedOutboundFile}"
|
||||
# Live switch when the running config exposes a selector; the persisted pin
|
||||
# is what keeps it after the next restart.
|
||||
CLASH_SECRET_FILE="$(dirname "${outboundInventoryFile}")/clash-secret"
|
||||
CLASH_SECRET=""
|
||||
[ ! -r "$CLASH_SECRET_FILE" ] || CLASH_SECRET=$(${pkgs.coreutils}/bin/tr -d '\r\n' < "$CLASH_SECRET_FILE")
|
||||
# The header from a pipe: argv is readable by every local user.
|
||||
if ${curl} -sf -X PUT "${clashApi}/proxies/proxy" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H @<(printf 'Authorization: Bearer %s\n' "$CLASH_SECRET") \
|
||||
-d "$(${jq} -cn --arg name "$tag" '{name:$name}')" >/dev/null 2>&1; then
|
||||
# A live switch skips the restart that rewrites the inventory, and the pin
|
||||
# is only ever read from there: without this the outbound reads as merely
|
||||
|
||||
@@ -115,6 +115,7 @@ in
|
||||
ZAPRET_AUTO_ENABLED = flag (zapretEngine == "zapret2" && zapretGlobalEnabled);
|
||||
ZAPRET_STATE_DIR = constants.zapret2StateDir;
|
||||
ZAPRET_CUTOFF_ENABLED = flag zapretCutoffEnabled;
|
||||
ZAPRET_CUTOFF_DIR = constants.zapret2CutoffDir;
|
||||
OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile;
|
||||
RUNTIME_OUTBOUNDS_DIR = constants.runtimeOutboundsDir;
|
||||
RUNTIME_SUBS_DIR = constants.runtimeSubscriptionsDir;
|
||||
|
||||
@@ -250,10 +250,27 @@ lib.mkMerge [
|
||||
;
|
||||
};
|
||||
|
||||
warnings = lib.optional (proxyEnabled && !derived.hasAvailableOutbounds) (
|
||||
"proxy-suite: no outbounds or subscriptions are declared; the proxy will not start"
|
||||
+ " until one is added with `proxy-ctl proxy outbounds add`"
|
||||
);
|
||||
warnings =
|
||||
lib.optional (proxyEnabled && !derived.hasAvailableOutbounds) (
|
||||
"proxy-suite: no outbounds or subscriptions are declared; the proxy will not start"
|
||||
+ " until one is added with `proxy-ctl proxy outbounds add`"
|
||||
)
|
||||
++
|
||||
lib.optional
|
||||
(
|
||||
proxyEnabled
|
||||
&& !localProxyAuthEnabled
|
||||
&& !(
|
||||
lib.hasPrefix "127." proxyCfg.listener.address
|
||||
|| proxyCfg.listener.address == "::1"
|
||||
|| proxyCfg.listener.address == "localhost"
|
||||
)
|
||||
)
|
||||
(
|
||||
"proxy-suite: proxy.listener.address is ${proxyCfg.listener.address} without listener.auth:"
|
||||
+ " anyone who reaches the port uses your outbounds; set listener.auth, or keep it off the"
|
||||
+ " firewall's allowed ports"
|
||||
);
|
||||
}
|
||||
|
||||
# A certificate or key XRay cannot read is copied in at start (proxy-inbounds-scripts.nix),
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
# Polkit rule body granting userControl group members passwordless control over the
|
||||
# units of their scopes.
|
||||
{ userControlCfg }:
|
||||
#
|
||||
# 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
|
||||
# (`systemd-run --unit=proxy-suite-x ...`), so a prefix match would run any command as
|
||||
# root. A declared unit has a fragment, and systemd refuses a transient one of its name.
|
||||
{
|
||||
lib,
|
||||
pkgs,
|
||||
userControlCfg,
|
||||
# Declared system units, "name.service" or "name.timer"; templates as "name@".
|
||||
unitNames,
|
||||
}:
|
||||
|
||||
let
|
||||
# Units a narrower scope starts; every other proxy-suite unit is "services".
|
||||
@@ -20,11 +31,56 @@ let
|
||||
"proxy-suite-inbound-stats." = "stats";
|
||||
"proxy-suite-wb-" = "whitelistBypass";
|
||||
};
|
||||
templates = lib.filter (lib.hasSuffix "@") unitNames;
|
||||
units = lib.filter (name: !lib.hasSuffix "@" name) unitNames;
|
||||
# What proxy-ctl asks for; not kill, clean, set-property, freeze or thaw.
|
||||
verbs = [
|
||||
"start"
|
||||
"stop"
|
||||
"restart"
|
||||
"try-restart"
|
||||
"reload"
|
||||
"reload-or-restart"
|
||||
"reload-or-try-restart"
|
||||
"reset-failed"
|
||||
];
|
||||
in
|
||||
{
|
||||
userControlPolkitRules = ''
|
||||
var verb = action.lookup("verb");
|
||||
if (typeof unit !== "string" || ${builtins.toJSON verbs}.indexOf(verb) === -1) {
|
||||
return null;
|
||||
}
|
||||
var known = ${builtins.toJSON units}.indexOf(unit) !== -1;
|
||||
var templates = ${builtins.toJSON templates};
|
||||
for (var i = 0; !known && i < templates.length; i++) {
|
||||
var template = templates[i];
|
||||
if (unit.indexOf(template) !== 0) {
|
||||
continue;
|
||||
}
|
||||
var instance = unit.slice(template.length).replace(/\.service$/, "");
|
||||
if (!/^[A-Za-z0-9:_.\\-]+$/.test(instance) || unit !== template + instance + ".service") {
|
||||
continue;
|
||||
}
|
||||
// Per-app marking follows one user's apps: only that user's own instance.
|
||||
if (/-user@$/.test(template)) {
|
||||
try {
|
||||
var uid = polkit.spawn(["${pkgs.coreutils}/bin/id", "-u", "--", subject.user]).trim();
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
if (instance !== uid) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
known = true;
|
||||
}
|
||||
if (!known) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var scopeByUnitPrefix = ${builtins.toJSON scopeByUnitPrefix};
|
||||
var scope = unit.indexOf("proxy-suite-") === 0 ? "services" : null;
|
||||
var scope = "services";
|
||||
for (var prefix in scopeByUnitPrefix) {
|
||||
if (unit.indexOf(prefix) === 0) {
|
||||
scope = scopeByUnitPrefix[prefix];
|
||||
@@ -33,7 +89,7 @@ in
|
||||
}
|
||||
// No scopes listed means all of them.
|
||||
var scopes = ${builtins.toJSON userControlCfg.scopes};
|
||||
if (scope !== null && (scopes.length === 0 || scopes.indexOf(scope) !== -1)) {
|
||||
if (scopes.length === 0 || scopes.indexOf(scope) !== -1) {
|
||||
return polkit.Result.YES;
|
||||
}
|
||||
'';
|
||||
|
||||
@@ -99,7 +99,7 @@ let
|
||||
pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON (ob.xrayJson // { inherit (ob) tag; }))
|
||||
})
|
||||
${dialerBlock}
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON")
|
||||
''
|
||||
else
|
||||
''
|
||||
@@ -108,7 +108,7 @@ let
|
||||
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \
|
||||
--backend xray --tag ${lib.escapeShellArg ob.tag})
|
||||
${dialerBlock}
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
|
||||
viaOutboundsBlock = lib.concatMapStrings mkViaOutboundBlock proxyInboundViaOutbounds;
|
||||
@@ -168,13 +168,18 @@ let
|
||||
''}
|
||||
|
||||
${jq} \
|
||||
--argjson ibs "$INBOUNDS_JSON" \
|
||||
--argjson obs "$OUTBOUNDS_JSON" \
|
||||
--slurpfile ibs <(printf '%s' "$INBOUNDS_JSON") \
|
||||
--slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \
|
||||
--argjson auth_enabled ${if needsLocalProxyAuth then "true" else "false"} \
|
||||
--arg user ${if needsLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
|
||||
--arg password ${if needsLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
|
||||
'.inbounds += $ibs
|
||||
| .outbounds = $obs + .outbounds
|
||||
${
|
||||
if needsLocalProxyAuth then
|
||||
"--rawfile password <(printf '%s' \"$LOCAL_PROXY_PASSWORD\")"
|
||||
else
|
||||
"--arg password ''"
|
||||
} \
|
||||
'.inbounds += $ibs[0]
|
||||
| .outbounds = $obs[0] + .outbounds
|
||||
| if $auth_enabled then
|
||||
(.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users)
|
||||
= [{user:$user,pass:$password}]
|
||||
|
||||
@@ -53,7 +53,7 @@ if pureXrayEnabled then
|
||||
else .dns.servers += [.dns.servers[] | select((.tag? // "") == "local")
|
||||
| . + {domains: ($names | map("full:" + .)), skipFallback: true}]
|
||||
end;
|
||||
.outbounds = ($obs + .outbounds)
|
||||
.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"
|
||||
@@ -95,7 +95,7 @@ else
|
||||
[.route.rules[]
|
||||
| select(((.action? // "") == "hijack-dns")
|
||||
and (((.inbound? // []) | index("xray-dns-in")) != null))];
|
||||
.outbounds = ($obs + .outbounds)
|
||||
.outbounds = ($obs[0] + .outbounds)
|
||||
| if $auth_enabled then
|
||||
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
|
||||
else . end
|
||||
@@ -112,6 +112,12 @@ else
|
||||
# (they only match their own listener), learned rules last before final, so
|
||||
# explicit rules win. All [] when off.
|
||||
| .inbounds += $probe_inbounds
|
||||
# The loopback probe and test listeners reach every exit: with listener.auth, the
|
||||
# same login, or any local user would get past it through them.
|
||||
| if $auth_enabled then
|
||||
(.inbounds[] | select(.type == "mixed" and (.tag == "proxy-suite-test-in" or (.tag | startswith("probe-in-")))) | .users)
|
||||
= [{username:$user,password:$password}]
|
||||
else . end
|
||||
| .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets)
|
||||
| .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules)
|
||||
''
|
||||
|
||||
@@ -24,7 +24,7 @@ lib.optionalString hybridEnabled ''
|
||||
|
||||
_proxy_suite_add_sing_box_ob() {
|
||||
local ob="$1"
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON")
|
||||
}
|
||||
|
||||
# $1 a JSON array of XRay outbounds, each tagged. One jq pass for the lot: each gets a
|
||||
@@ -35,7 +35,7 @@ lib.optionalString hybridEnabled ''
|
||||
local batch
|
||||
batch=$(${jq} -c \
|
||||
--argjson next "$XRAY_SIDECAR_NEXT_ID" \
|
||||
--arg secret "$XRAY_SIDECAR_SECRET" \
|
||||
--rawfile secret <(printf '%s' "$XRAY_SIDECAR_SECRET") \
|
||||
--argjson port "$XRAY_SIDECAR_PORT" \
|
||||
--argjson mark ${
|
||||
if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark
|
||||
|
||||
@@ -97,7 +97,7 @@ let
|
||||
else
|
||||
''
|
||||
ob=$(_proxy_suite_parse_url "$tag" "$url") || return 1
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
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).
|
||||
singBoxMark = lib.optionalString (routingMark != null) " | .routing_mark = ${toString routingMark}";
|
||||
@@ -122,12 +122,13 @@ let
|
||||
echo "proxy-suite: outbound '$tag' is not ${want} JSON" >&2
|
||||
return 1
|
||||
fi
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob${
|
||||
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + [$ob[0]${
|
||||
if pureXrayEnabled then xrayMark else singBoxMark
|
||||
}]' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
in
|
||||
''
|
||||
${constants.readSourceFunction pkgs}
|
||||
OUTBOUND_SOURCES_JSON='{}'
|
||||
# What proxy-ctl shares back: tag -> the URL it was given, sub tag -> its URL.
|
||||
OUTBOUND_URLS_JSON='{}'
|
||||
@@ -153,7 +154,7 @@ let
|
||||
if hybridEnabled then
|
||||
''_proxy_suite_add_sing_box_ob "$ob"''
|
||||
else
|
||||
''OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")''
|
||||
''OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON")''
|
||||
}
|
||||
_proxy_suite_record_tag_source "$1" "$3"
|
||||
}
|
||||
@@ -161,7 +162,7 @@ let
|
||||
# $1 sub tag, $2 file holding its URL, $3 its links file (absent for a cache
|
||||
# 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 "$2" '.[$t] = ($u | rtrimstr("\n"))' <<< "$SUBSCRIPTION_URLS_JSON")
|
||||
SUBSCRIPTION_URLS_JSON=$(${jq} --arg t "$1" --rawfile u <(_proxy_suite_read_source "$2") '.[$t] = ($u | rtrimstr("\n"))' <<< "$SUBSCRIPTION_URLS_JSON")
|
||||
if [ -s "$3" ]; then
|
||||
OUTBOUND_URLS_JSON=$(${jq} --slurpfile l "$3" '. + $l[0]' <<< "$OUTBOUND_URLS_JSON") || true
|
||||
fi
|
||||
@@ -206,13 +207,13 @@ let
|
||||
local tag="$1" url="$2" source="$3" pref="''${4:-auto}" ob
|
||||
${addBlock}
|
||||
_proxy_suite_record_tag_source "$tag" "$source"
|
||||
OUTBOUND_URLS_JSON=$(${jq} --arg t "$tag" --arg u "$url" '.[$t] = $u' <<< "$OUTBOUND_URLS_JSON")
|
||||
OUTBOUND_URLS_JSON=$(${jq} --arg t "$tag" --rawfile u <(printf '%s' "$url") '.[$t] = $u' <<< "$OUTBOUND_URLS_JSON")
|
||||
}
|
||||
|
||||
# $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
|
||||
ob=$(${jq} -ce --arg t "$tag" 'select(type == "object") | .tag = $t' "$2" 2>/dev/null) || return 1
|
||||
ob=$(${jq} -ce --arg t "$tag" 'select(type == "object") | .tag = $t' <(_proxy_suite_read_source "$2") 2>/dev/null) || return 1
|
||||
kind=$(${jq} -r 'if has("protocol") then "xray" elif has("type") then "sing-box" else "" end' <<< "$ob")
|
||||
${jsonAddBlock}
|
||||
_proxy_suite_record_tag_source "$tag" "$source"
|
||||
@@ -226,7 +227,7 @@ let
|
||||
local f tag
|
||||
[ -d "${runtimeOutboundsDir}" ] || return 0
|
||||
for f in "${runtimeOutboundsDir}"/*.url "${runtimeOutboundsDir}"/*.json${lib.optionalString awgRuntimeOutbounds ''"${runtimeOutboundsDir}"/*.awg''}; do
|
||||
[ -e "$f" ] || continue
|
||||
[ -f "$f" ] && [ ! -L "$f" ] || continue
|
||||
tag="''${f##*/}"
|
||||
tag="''${tag%.*}"
|
||||
case "$tag" in
|
||||
@@ -250,7 +251,7 @@ let
|
||||
''
|
||||
# outbound: ${tag} (static ${backend} json)
|
||||
OB_JSON=$(cat "${jsonFile}")
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON")
|
||||
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
|
||||
''
|
||||
else
|
||||
@@ -373,7 +374,7 @@ let
|
||||
if hybridEnabled then
|
||||
''_proxy_suite_add_sing_box_ob "$OB_JSON"''
|
||||
else
|
||||
''OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")''
|
||||
''OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON")''
|
||||
}
|
||||
_proxy_suite_record_tag_source ${sshProxyTag} ssh
|
||||
'';
|
||||
@@ -386,7 +387,7 @@ let
|
||||
if hybridEnabled then
|
||||
''_proxy_suite_add_sing_box_ob "$OB_JSON"''
|
||||
else
|
||||
''OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")''
|
||||
''OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON")''
|
||||
}
|
||||
_proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source}
|
||||
'';
|
||||
@@ -472,11 +473,11 @@ let
|
||||
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.
|
||||
*.awg) _proxy_suite_add_socks_hop "$RUNTIME_OB_TAG" "$(head -n 1 "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.port" 2>/dev/null)" runtime ;;
|
||||
*) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime ;;
|
||||
*.awg) _proxy_suite_add_socks_hop "$RUNTIME_OB_TAG" "$(_proxy_suite_read_source "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.port" 2>/dev/null | head -n 1)" runtime ;;
|
||||
*) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(_proxy_suite_read_source "$RUNTIME_OB_SRC")" runtime ;;
|
||||
esac || { echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2; continue; }
|
||||
if [ -s "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" ]; then
|
||||
RUNTIME_DETOURS_JSON=$(${jq} -c --arg t "$RUNTIME_OB_TAG" --rawfile h "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" \
|
||||
RUNTIME_DETOURS_JSON=$(${jq} -c --arg t "$RUNTIME_OB_TAG" --rawfile h <(_proxy_suite_read_source "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour") \
|
||||
'.[$t] = ($h | rtrimstr("\n"))' <<< "$RUNTIME_DETOURS_JSON")
|
||||
fi
|
||||
done < <(_proxy_suite_runtime_outbounds)
|
||||
@@ -508,9 +509,9 @@ let
|
||||
DETOURS_JSON=$(${jq} -c --argjson runtime "$RUNTIME_DETOURS_JSON" '.outbounds = $runtime + .outbounds' \
|
||||
<<< ${lib.escapeShellArg (builtins.toJSON detours)})
|
||||
while [ "$DETOURS_JSON" != '{"outbounds":{},"subscriptions":{}}' ]; do
|
||||
DETOUR_RESULT=$(${jq} -c --argjson xob "${
|
||||
DETOUR_RESULT=$(${jq} -c --slurpfile xob <(printf '%s' "${
|
||||
if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"
|
||||
}" '{outbounds: ., xray: $xob}' <<< "$OUTBOUNDS_JSON" \
|
||||
}") '{outbounds: ., xray: $xob[0]}' <<< "$OUTBOUNDS_JSON" \
|
||||
| ${jq} -c -f ${
|
||||
builtins.path {
|
||||
name = "proxy-suite-outbound-detours";
|
||||
@@ -601,12 +602,12 @@ let
|
||||
--argjson sources "$OUTBOUND_SOURCES_JSON" \
|
||||
--arg pinned "$PINNED_OUTBOUND" \
|
||||
--arg selection ${lib.escapeShellArg selectionMode} \
|
||||
--argjson obs "$OUTBOUNDS_JSON" \
|
||||
--argjson xobs "${if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"}" \
|
||||
--slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \
|
||||
--slurpfile xobs <(printf '%s' "${if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"}") \
|
||||
--argjson selectable "$SELECTABLE_TAGS_JSON" \
|
||||
--argjson disabled "$DISABLED_TAGS_JSON" \
|
||||
'{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection,
|
||||
detours: ([($xobs + $obs)[] | (.detour // .streamSettings.sockopt.dialerProxy?) as $h
|
||||
detours: ([($xobs[0] + $obs[0])[] | (.detour // .streamSettings.sockopt.dialerProxy?) as $h
|
||||
| select($h != null) | {key: .tag, value: $h}] | from_entries),
|
||||
excluded: ($tags - $selectable), disabled: $disabled}' \
|
||||
> "$RUNTIME_DIR/outbounds.json"
|
||||
|
||||
@@ -31,6 +31,7 @@ let
|
||||
# Defined in every script that touches a cache: the start scripts and the
|
||||
# update unit.
|
||||
subscriptionCacheHelpersBlock = ''
|
||||
${constants.readSourceFunction pkgs}
|
||||
SUB_CACHE_DIR="${subscriptionCacheDir}"
|
||||
RUNTIME_SUBS_DIR="${runtimeSubscriptionsDir}"
|
||||
|
||||
@@ -69,7 +70,7 @@ let
|
||||
_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' "$(cat "$src")" \
|
||||
if printf '%s' "$(_proxy_suite_read_source "$src")" \
|
||||
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} \
|
||||
${subscriptionBackendArg} --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then
|
||||
if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then
|
||||
@@ -89,7 +90,7 @@ let
|
||||
local f tag
|
||||
[ -d "$RUNTIME_SUBS_DIR" ] || return 0
|
||||
for f in "$RUNTIME_SUBS_DIR"/*.url; do
|
||||
[ -e "$f" ] || continue
|
||||
[ -f "$f" ] && [ ! -L "$f" ] || continue
|
||||
tag="''${f##*/}"
|
||||
tag="''${tag%.url}"
|
||||
printf '%s\t%s\n' "$tag" "$f"
|
||||
@@ -113,13 +114,13 @@ let
|
||||
if hybridEnabled then
|
||||
''
|
||||
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$cache")
|
||||
${markBlock}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
|
||||
${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")"
|
||||
''
|
||||
else
|
||||
''
|
||||
SUB_JSON=$(cat "$cache")
|
||||
${markBlock}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
|
||||
${markBlock}OUTBOUNDS_JSON=$(${jq} --slurpfile sub <(printf '%s' "$SUB_JSON") '. + $sub[0]' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
in
|
||||
''
|
||||
|
||||
@@ -269,8 +269,9 @@ 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 --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" '
|
||||
def endpoint:
|
||||
${jq} -c --slurpfile sidecar <(printf '%s' "''${XRAY_OUTBOUNDS_JSON:-[]}") '
|
||||
$sidecar[0] as $sidecar
|
||||
| def endpoint:
|
||||
if .server then {server, port: .server_port}
|
||||
elif .settings.address then {server: .settings.address, port: .settings.port}
|
||||
elif .settings.vnext then {server: .settings.vnext[0].address, port: .settings.vnext[0].port}
|
||||
@@ -299,9 +300,10 @@ let
|
||||
# proxy-ctl's share links: the URL each outbound was given, and its backend JSON.
|
||||
# Credentials: root and the userControl group only.
|
||||
SHARE_TMP="$RUNTIME_DIR/outbound-share.json.tmp"
|
||||
(umask 077 && ${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" \
|
||||
--argjson urls "$OUTBOUND_URLS_JSON" --argjson subs "$SUBSCRIPTION_URLS_JSON" '
|
||||
($sidecar | map({key: .tag, value: .}) | from_entries) as $real
|
||||
(umask 077 && ${jq} -c --slurpfile sidecar <(printf '%s' "''${XRAY_OUTBOUNDS_JSON:-[]}") \
|
||||
--slurpfile urls <(printf '%s' "$OUTBOUND_URLS_JSON") --slurpfile subs <(printf '%s' "$SUBSCRIPTION_URLS_JSON") '
|
||||
$sidecar[0] as $sidecar | $urls[0] as $urls | $subs[0] as $subs
|
||||
| ($sidecar | map({key: .tag, value: .}) | from_entries) as $real
|
||||
| {outbounds: ([.[] | select(.type != "selector" and .type != "urltest")
|
||||
| (.tag | ltrimstr("proxy-suite-ob-")) as $tag
|
||||
| {key: $tag, value: {url: $urls[$tag], outbound: (($real[$tag] // $real[.tag] // .) | .tag = $tag)}}]
|
||||
@@ -347,15 +349,22 @@ let
|
||||
fi
|
||||
''}
|
||||
|
||||
${jq} \
|
||||
--argjson obs "$OUTBOUNDS_JSON" \
|
||||
# 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" \
|
||||
--argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
|
||||
--arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
|
||||
--arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
|
||||
${
|
||||
if enableLocalProxyAuth then
|
||||
"--rawfile password <(printf '%s' \"$LOCAL_PROXY_PASSWORD\")"
|
||||
else
|
||||
"--arg password ''"
|
||||
} \
|
||||
--argjson route_enabled "$ROUTE_MODE_ACTIVE" \
|
||||
--argjson route_rules "$ROUTE_RULES_JSON" \
|
||||
--arg route_final "$ROUTE_FINAL" \
|
||||
@@ -366,15 +375,35 @@ let
|
||||
--argjson xray_selectable "$SELECTABLE_TAGS_JSON" \
|
||||
--argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \
|
||||
-f "$BACKEND_JQ_FILTER" \
|
||||
"${configFile}" > "$RUNTIME_DIR/config.json"
|
||||
"${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})
|
||||
${jq} --argjson uid "$SERVICE_UID" '(.inbounds[] | select(.type == "tun") | .exclude_uid) = [$uid]' \
|
||||
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next"
|
||||
(umask 077 && ${jq} --argjson uid "$SERVICE_UID" '(.inbounds[] | select(.type == "tun") | .exclude_uid) = [$uid]' \
|
||||
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next")
|
||||
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json"
|
||||
''}
|
||||
# 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, readable where outbound-endpoints.json is.
|
||||
if ${jq} -e '.experimental.clash_api? != null' "$RUNTIME_DIR/config.json" >/dev/null; then
|
||||
CLASH_SECRET=$(${pkgs.coreutils}/bin/od -An -tx1 -N24 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n')
|
||||
(umask 077 && ${jq} --rawfile s <(printf '%s' "$CLASH_SECRET") '.experimental.clash_api.secret = $s' \
|
||||
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next")
|
||||
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json"
|
||||
(umask 077 && printf '%s\n' "$CLASH_SECRET" > "$RUNTIME_DIR/clash-secret.tmp")
|
||||
${
|
||||
if userControlCfg.enable || localProxyAuthEnabled then
|
||||
''
|
||||
${constants.ifPrivileged ''${chgrp} ${userControlGroup} "$RUNTIME_DIR/clash-secret.tmp"''}
|
||||
chmod 640 "$RUNTIME_DIR/clash-secret.tmp"
|
||||
''
|
||||
else
|
||||
''chmod 600 "$RUNTIME_DIR/clash-secret.tmp"''
|
||||
}
|
||||
mv "$RUNTIME_DIR/clash-secret.tmp" "$RUNTIME_DIR/clash-secret"
|
||||
fi
|
||||
# Credentials, read by the backend running as ${constants.serviceUser}. With
|
||||
# userControl its group reads them too; a file has one group, so the daemon
|
||||
# reads as owner then.
|
||||
|
||||
@@ -94,7 +94,8 @@ let
|
||||
endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag}${markArg "--routing-mark"}${
|
||||
lib.optionalString (endpoint != null) " --endpoint ${lib.escapeShellArg endpoint}"
|
||||
} < "$profile")
|
||||
(umask 027 && ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{
|
||||
# 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 | {
|
||||
log: {level: "warn"},
|
||||
dns: {servers: [
|
||||
${builtins.toJSON (dnsServer "local" cfg.proxy.dns.local)},
|
||||
|
||||
@@ -105,7 +105,10 @@ let
|
||||
${lib.optionalString viaProxy ''
|
||||
args+=(--upstream-socks ${derived.localProxy.hostPart}:${toString cfg.proxy.listener.port})
|
||||
''}${lib.optionalString withProxyAuth ''
|
||||
args+=(--upstream-user ${lib.escapeShellArg auth.username} --upstream-pass "$(< "$CREDENTIALS_DIRECTORY/proxy-password")")
|
||||
args+=(--upstream-user ${lib.escapeShellArg auth.username})
|
||||
# The package reads it from here (pkgs/whitelist-bypass.nix): argv is public.
|
||||
WB_UPSTREAM_PASS="$(< "$CREDENTIALS_DIRECTORY/proxy-password")"
|
||||
export WB_UPSTREAM_PASS
|
||||
''}
|
||||
exec ${w.package}/bin/headless-${c.platform}-creator "''${args[@]}"
|
||||
'';
|
||||
|
||||
@@ -95,11 +95,16 @@ let
|
||||
'';
|
||||
|
||||
# nfqws2 runs supervised; the firewall comes and goes around it.
|
||||
daemonConfig = runtimeEnv: {
|
||||
Type = "notify";
|
||||
ExecReload = "${lib.getExe' pkgs.coreutils "kill"} -HUP $MAINPID";
|
||||
Environment = runtimeEnv;
|
||||
};
|
||||
daemonConfig =
|
||||
runtimeEnv:
|
||||
{
|
||||
Type = "notify";
|
||||
ExecReload = "${lib.getExe' pkgs.coreutils "kill"} -HUP $MAINPID";
|
||||
Environment = runtimeEnv;
|
||||
}
|
||||
# nfqws2 runs as root and writes its lists in a directory the zapret scope's group
|
||||
# writes to as well.
|
||||
// constants.rootInSharedDirConfig;
|
||||
|
||||
cutoff = import ./zapret2/cutoff.nix {
|
||||
inherit
|
||||
@@ -119,6 +124,7 @@ in
|
||||
lib.mkIf cutoffCfg.enable cutoff.service;
|
||||
services.proxy-suite.internal.timers.proxy-suite-zapret2-cutoff =
|
||||
lib.mkIf cutoffCfg.enable cutoff.timer;
|
||||
services.proxy-suite.internal.tmpfiles = lib.mkIf cutoffCfg.enable cutoff.tmpfiles;
|
||||
|
||||
services.proxy-suite.internal.services.proxy-suite-zapret =
|
||||
lib.mkIf zapretGlobalEnabled
|
||||
|
||||
@@ -66,13 +66,24 @@ let
|
||||
]
|
||||
}
|
||||
cd ${lib.escapeShellArg dir}
|
||||
# Root works only here, which nobody else writes to now; the group's probe requests
|
||||
# come through requests/. Anything left from when the group could write here goes:
|
||||
# a symlink under a name below would have root write, or read, where it points.
|
||||
for f in asn.txt sni.txt asn.new sni.new proxy.json proxy.json.tmp egress ts force; do
|
||||
if [ -L "$f" ] || { [ -e "$f" ] && [ ! -O "$f" ]; }; then
|
||||
rm -f -- "$f"
|
||||
fi
|
||||
done
|
||||
touch asn.txt sni.txt
|
||||
force=0
|
||||
if [ -e force ]; then
|
||||
if [ -e requests/force ]; then
|
||||
force=1
|
||||
rm -f force
|
||||
rm -f requests/force
|
||||
fi
|
||||
now=$(date +%s)
|
||||
# Digits only: $(( )) would run what a[$(...)] in it names.
|
||||
last=$(cat ts 2>/dev/null || true)
|
||||
[[ $last =~ ^[0-9]+$ ]] || last=0
|
||||
|
||||
# The name map belongs to this line: probe again when its network changes, else
|
||||
# once a day. No answer (offline, captive portal) is no reason to probe.
|
||||
@@ -84,7 +95,7 @@ let
|
||||
exit 0
|
||||
fi
|
||||
if [ "$force" = 0 ] && [ "$egress" = "$(cat egress 2>/dev/null || true)" ] &&
|
||||
[ $((now - $(cat ts 2>/dev/null || echo 0))) -lt 86400 ]; then
|
||||
[ $((now - last)) -lt 86400 ]; then
|
||||
exit 0
|
||||
fi
|
||||
echo "probing the line from $egress"
|
||||
@@ -156,18 +167,23 @@ in
|
||||
wants = [ "network-online.target" ];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
StateDirectory = "proxy-suite/zapret2/cutoff";
|
||||
StateDirectory = "proxy-suite/zapret2-cutoff";
|
||||
ExecStartPre = "${exempt}";
|
||||
ExecStart = "${probe}";
|
||||
ExecStopPost = "-${nft} delete table inet ${table}";
|
||||
# Root writes and reads here by fixed names: only root may add entries. The group's
|
||||
# `proxy-ctl zapret cutoff probe` drops its `force` file in requests/ instead.
|
||||
StateDirectoryMode = "0755";
|
||||
}
|
||||
# The group's `proxy-ctl zapret cutoff probe` drops its `force` file here.
|
||||
// lib.optionalAttrs (userControlAllows "zapret") {
|
||||
Group = cfg.userControl.group;
|
||||
StateDirectoryMode = "2775";
|
||||
};
|
||||
// constants.rootInSharedDirConfig;
|
||||
};
|
||||
|
||||
tmpfiles = [
|
||||
"d ${dir}/requests ${
|
||||
if userControlAllows "zapret" then "2770 root ${cfg.userControl.group}" else "0700 root root"
|
||||
} -"
|
||||
];
|
||||
|
||||
timer = {
|
||||
description = "proxy-suite 16 KB cutoff probe schedule";
|
||||
wantedBy = [ "timers.target" ];
|
||||
|
||||
@@ -348,8 +348,12 @@ in
|
||||
assert builtins.elem fakeTools overrideFixture.config.environment.systemPackages;
|
||||
assert builtins.elem fakeUserspace overrideFixture.config.environment.systemPackages;
|
||||
assert builtins.elem fakeKernelModule overrideFixture.config.boot.extraModulePackages;
|
||||
assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0"
|
||||
# userControl covers the profile's unit by name, never by prefix: a prefix would also
|
||||
# match a transient unit (systemd-run --unit=proxy-suite-x), which runs anything as root.
|
||||
assert pkgs.lib.hasInfix "\"proxy-suite-awg-home.service\""
|
||||
awgOnly.config.security.polkit.extraConfig;
|
||||
assert
|
||||
!(pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" awgOnly.config.security.polkit.extraConfig);
|
||||
true
|
||||
)
|
||||
(
|
||||
|
||||
@@ -99,7 +99,10 @@ in
|
||||
assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" localProxyAuthStartScript;
|
||||
assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' localProxyAuthStartScript;
|
||||
assert pkgs.lib.hasInfix "--arg user local-user" localProxyAuthStartScript;
|
||||
assert pkgs.lib.hasInfix ''--arg password "$LOCAL_PROXY_PASSWORD"'' localProxyAuthStartScript;
|
||||
# From a pipe: argv is readable by every local user.
|
||||
assert pkgs.lib.hasInfix ''--rawfile password <(printf '%s' "$LOCAL_PROXY_PASSWORD")''
|
||||
localProxyAuthStartScript;
|
||||
assert !(pkgs.lib.hasInfix ''--arg password "$LOCAL_PROXY_PASSWORD"'' localProxyAuthStartScript);
|
||||
assert pkgs.lib.hasInfix ''select(.type == "mixed" and .tag == "mixed-in") | .users''
|
||||
localProxyAuthBackendJqFilter;
|
||||
# The password is in the config: root and the backend's group only.
|
||||
|
||||
@@ -127,10 +127,16 @@ let
|
||||
serverAddress = "vpn.example.com";
|
||||
serverAliases = [
|
||||
"turn.example.com"
|
||||
"domain:example.net"
|
||||
"203.0.113.10"
|
||||
"2001:db8::10"
|
||||
"vpn.example.com"
|
||||
];
|
||||
serverPorts = [
|
||||
993
|
||||
"7882-7885"
|
||||
443
|
||||
];
|
||||
listeners.vless-in = realityListener;
|
||||
};
|
||||
aliasedConfig = mkInboundsConfig aliasedFixture;
|
||||
@@ -834,6 +840,7 @@ let
|
||||
(ruleByTag aliasedConfig "inbound-server-address-direct").domain == [
|
||||
"full:vpn.example.com"
|
||||
"full:turn.example.com"
|
||||
"domain:example.net"
|
||||
];
|
||||
true
|
||||
)
|
||||
@@ -845,7 +852,9 @@ let
|
||||
];
|
||||
true
|
||||
)
|
||||
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").port == "443"))
|
||||
# serverPorts join the listener's, ranges as they are.
|
||||
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct").port == "443,993,7882-7885"))
|
||||
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").port == "443,993,7882-7885"))
|
||||
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").outboundTag == "direct"))
|
||||
(ok (!builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig)))
|
||||
|
||||
|
||||
+1
-1
@@ -446,7 +446,7 @@ in
|
||||
printf 'AS12389\n' > "$state/cutoff/egress"
|
||||
printf '24940\n14061\n' > "$state/cutoff/asn.txt"
|
||||
printf '24940\t300.ya.ru\n' > "$state/cutoff/sni.txt"
|
||||
cutoff=$(env ZAPRET_CUTOFF_ENABLED=1 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret cutoff)
|
||||
cutoff=$(env ZAPRET_CUTOFF_ENABLED=1 ZAPRET_CUTOFF_DIR="$state/cutoff" python3 "$proxy_ctl" zapret cutoff)
|
||||
printf '%s\n' "$cutoff" | grep -q 'from AS12389$'
|
||||
printf '%s\n' "$cutoff" | grep -qx 'Cutoff: 2 network(s)'
|
||||
printf '%s\n' "$cutoff" | grep -qE '^ AS24940 +300\.ya\.ru$'
|
||||
|
||||
+1
-1
@@ -175,7 +175,7 @@ let
|
||||
);
|
||||
guardRuntime = pkgs.runCommand "proxy-suite-tor-guard-check" { nativeBuildInputs = [ pkgs.jq ]; } ''
|
||||
echo '{"inbounds":[],"outbounds":[],"dns":{"rules":[]},"route":{"rules":[]}}' |
|
||||
jq --argjson obs '[]' --argjson auth_enabled false --arg user "" --arg password "" \
|
||||
jq --slurpfile obs <(echo '[]') --argjson auth_enabled false --arg user "" --arg password "" \
|
||||
--argjson route_enabled true --argjson route_rules "$(cat ${guardRouteRules})" \
|
||||
--arg route_final proxy --arg dns_final remote --argjson clear_dns_rules false \
|
||||
--argjson probe_inbounds '[]' --argjson autoproxy_rule_sets '[]' --argjson autoproxy_rules '[]' \
|
||||
|
||||
@@ -78,6 +78,18 @@ in
|
||||
assert hasInfix "var scopes = [];" (polkitConfig allFixture);
|
||||
assert hasInfix "subject.isInGroup(\"proxy-suite\")" (polkitConfig allFixture);
|
||||
assert hasInfix "\"proxy-suite-zapret2-cutoff.\":\"zapret\"" (polkitConfig allFixture);
|
||||
# Declared units by name: systemd asks polkit the same question, with the same unit
|
||||
# name, for a transient unit, so a prefix match would run any command as root.
|
||||
assert hasInfix "\"proxy-suite-socks.service\"" (polkitConfig allFixture);
|
||||
assert hasInfix "\"proxy-suite-per-app-tun-user@\"" (polkitConfig allFixture);
|
||||
assert !(hasInfix "unit.indexOf(\"proxy-suite-\") === 0 ?" (polkitConfig allFixture));
|
||||
# Only start, stop and the like: not set-property, kill or clean.
|
||||
assert hasInfix "\"reload-or-try-restart\",\"reset-failed\"].indexOf(verb)" (
|
||||
polkitConfig allFixture
|
||||
);
|
||||
assert !(hasInfix "\"set-property\"" (polkitConfig allFixture));
|
||||
# A user's per-app marking is theirs alone.
|
||||
assert hasInfix "if (instance !== uid)" (polkitConfig allFixture);
|
||||
assert groupReadsSecrets allFixture;
|
||||
assert hasInfix "chown proxy-suite-daemon:proxy-suite \"$backend_config\"" (socksStart allFixture);
|
||||
assert
|
||||
@@ -87,6 +99,20 @@ in
|
||||
"proxy-suite"
|
||||
];
|
||||
assert (service allFixture "proxy-suite-autoproxy").StateDirectoryMode == "0771";
|
||||
# Root writes by fixed names in that group-writable directory: nowhere else.
|
||||
assert builtins.all
|
||||
(
|
||||
unit:
|
||||
let
|
||||
c = service allFixture unit;
|
||||
in
|
||||
c.ProtectSystem == "strict" && c.ProtectHome && c.PrivateTmp
|
||||
)
|
||||
[
|
||||
"proxy-suite-autoproxy"
|
||||
"proxy-suite-autoproxy-learn"
|
||||
"proxy-suite-autoproxy-sample"
|
||||
];
|
||||
assert builtins.elem "d /var/lib/proxy-suite/outbounds.d 2770 root proxy-suite -" (
|
||||
allFixture.config.systemd.tmpfiles.rules
|
||||
);
|
||||
|
||||
@@ -54,7 +54,7 @@ let
|
||||
local output="$TMPDIR/$name.json"
|
||||
|
||||
jq \
|
||||
--argjson obs "$OBS" \
|
||||
--slurpfile obs <(printf "%s" "$OBS") \
|
||||
--argjson auth_enabled false \
|
||||
--arg user "" \
|
||||
--arg password "" \
|
||||
|
||||
+25
-1
@@ -74,6 +74,24 @@ in
|
||||
true
|
||||
)
|
||||
|
||||
# Root works in directories the zapret scope's group writes to: nfqws2 and the cutoff
|
||||
# probe write nowhere else, whatever a name there points at. The probe's own directory
|
||||
# is root's alone, apart from requests/.
|
||||
(
|
||||
let
|
||||
gc = zapret2Global.config.systemd.services.${globalService}.serviceConfig;
|
||||
pc = zapret2PerApp.config.systemd.services.${perAppService}.serviceConfig;
|
||||
cc = zapret2Global.config.systemd.services.proxy-suite-zapret2-cutoff.serviceConfig;
|
||||
sandboxed = c: c.ProtectSystem == "strict" && c.ProtectHome && c.PrivateTmp;
|
||||
in
|
||||
assert sandboxed gc && sandboxed pc && sandboxed cc;
|
||||
assert cc.StateDirectory == "proxy-suite/zapret2-cutoff" && cc.StateDirectoryMode == "0755";
|
||||
assert !(cc ? Group);
|
||||
assert builtins.any (lib.hasPrefix "d /var/lib/proxy-suite/zapret2-cutoff/requests ")
|
||||
zapret2Global.config.systemd.tmpfiles.rules;
|
||||
true
|
||||
)
|
||||
|
||||
# Two nfqws2 processes must not share a pidfile or a config.
|
||||
(
|
||||
assert envValue zapret2PerApp globalService "PIDDIR=" == "/run/proxy-suite-zapret";
|
||||
@@ -102,7 +120,7 @@ in
|
||||
assert !(zapretDiscordYoutubeGlobal.config.systemd.services ? proxy-suite-zapret2-cutoff);
|
||||
assert (proxyCtlEnv zapret2Global).ZAPRET_CUTOFF_ENABLED == "1";
|
||||
assert
|
||||
envValue zapret2Z2k globalService "Z2K_TCP16_ASN=" == "/var/lib/proxy-suite/zapret2/cutoff/asn.txt";
|
||||
envValue zapret2Z2k globalService "Z2K_TCP16_ASN=" == "/var/lib/proxy-suite/zapret2-cutoff/asn.txt";
|
||||
assert
|
||||
!(builtins.any (lib.hasPrefix "Z2K_TCP16_ASN=")
|
||||
zapret2Global.config.systemd.services.${globalService}.serviceConfig.Environment
|
||||
@@ -206,6 +224,12 @@ in
|
||||
# zapret2 leaves the probe's own connections alone, in every chain.
|
||||
test "$(grep -c 'ct mark and 0x2000000 != 0 return' "${globalRuntime}/init.d/sysv/custom.d/50-proxy-suite-custom.sh")" = 4
|
||||
|
||||
# ts is checked for digits before arithmetic, which would run what a[$(...)] in it names.
|
||||
grep -qF -- '[[ $last =~ ^[0-9]+$ ]] || last=0' ${cutoffProbe}
|
||||
if grep -qF -- '$((now - $(cat ts' ${cutoffProbe}; then exit 1; fi
|
||||
# The group's probe request comes through requests/, not the directory root works in.
|
||||
grep -qF -- 'if [ -e requests/force ]; then' ${cutoffProbe}
|
||||
|
||||
# Cut-off networks without a name become the proxy's rule-set; named ones stay with zapret2.
|
||||
rules=$(grep -oE '/nix/store/[^ ]+-proxy-suite-zapret2 asn.txt' ${cutoffProbe} | cut -d' ' -f1)
|
||||
printf '# networks\n24940\n14061\n' >asn.txt
|
||||
|
||||
@@ -1098,20 +1098,45 @@ def _outbound_current():
|
||||
return "" if now is None else _s(now)
|
||||
|
||||
|
||||
def _local_proxy_login():
|
||||
"""(user, password) the loopback listeners take with listener.auth, else None.
|
||||
|
||||
From the proxychains config the socks start script writes for it, which root and the
|
||||
userControl group read; without auth that file names no login.
|
||||
"""
|
||||
try:
|
||||
with open(env("PROXYCHAINS_CONFIG"), encoding="utf-8") as f:
|
||||
for line in f:
|
||||
fields = line.split()
|
||||
if len(fields) == 5 and fields[0] == "socks5":
|
||||
return fields[3], fields[4]
|
||||
except (OSError, UnicodeError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _clash(method, path, body=None, timeout=10):
|
||||
"""(HTTP status, JSON body or None) from the backend's Clash API; status 0 when unreachable."""
|
||||
# The API is on loopback: never through the shell's HTTP(S)_PROXY.
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
headers = {"Content-Type": "application/json"}
|
||||
# The socks start script's secret for this run: root and the userControl group read it.
|
||||
# Anyone else gets 401, which reads as no API.
|
||||
try:
|
||||
with open(_runtime_file("clash-secret"), encoding="utf-8") as f:
|
||||
headers["Authorization"] = f"Bearer {f.read().strip()}"
|
||||
except (OSError, UnicodeError):
|
||||
pass
|
||||
try:
|
||||
# Building the request is part of reaching the API: an unset or malformed
|
||||
# CLASH_API is "unreachable", not a traceback out of `status` or `where`.
|
||||
request = urllib.request.Request(
|
||||
f"{env('CLASH_API')}{path}", data=data, method=method, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
request = urllib.request.Request(f"{env('CLASH_API')}{path}", data=data, method=method, headers=headers)
|
||||
with opener.open(request, timeout=timeout) as r:
|
||||
status, raw = r.status, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 401:
|
||||
return 0, None
|
||||
status, raw = e.code, e.read()
|
||||
except (OSError, ValueError, http.client.HTTPException):
|
||||
return 0, None
|
||||
@@ -1180,7 +1205,9 @@ def _timed_download(port):
|
||||
anywhere else.
|
||||
"""
|
||||
conn = http.client.HTTPSConnection("127.0.0.1", port, timeout=TEST_DOWNLOAD_SECONDS)
|
||||
conn.set_tunnel(TEST_DOWNLOAD_HOST)
|
||||
login = _local_proxy_login()
|
||||
auth = {"Proxy-Authorization": "Basic " + base64.b64encode(":".join(login).encode()).decode()} if login else {}
|
||||
conn.set_tunnel(TEST_DOWNLOAD_HOST, headers=auth)
|
||||
got = 0
|
||||
start = time.monotonic()
|
||||
try:
|
||||
@@ -1943,6 +1970,15 @@ def _probe_fetch(domain, path, *selector):
|
||||
ua = [] if curl else ["-A", env("PROBE_UA", "Mozilla/5.0 (X11; Linux x86_64) proxy-suite-probe")]
|
||||
result = ""
|
||||
with tempfile.TemporaryDirectory(prefix="proxy-ctl-probe-") as tmp:
|
||||
# The listener's login through a file in this private directory: argv is public.
|
||||
login = _local_proxy_login() if "--proxy" in selector else None
|
||||
auth = []
|
||||
if login:
|
||||
curlrc = os.path.join(tmp, "login.curlrc")
|
||||
quoted = ":".join(login).replace("\\", "\\\\").replace('"', '\\"')
|
||||
with open(os.open(curlrc, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as f:
|
||||
f.write(f'proxy-user = "{quoted}"\n')
|
||||
auth = ["-K", curlrc]
|
||||
for hop in range(6):
|
||||
head, body = os.path.join(tmp, f"{hop}.head"), os.path.join(tmp, f"{hop}.body")
|
||||
status, out = run_curl(
|
||||
@@ -1960,6 +1996,7 @@ def _probe_fetch(domain, path, *selector):
|
||||
env("PROBE_MAX_TIME", "15"),
|
||||
"-w",
|
||||
PROBE_WRITE_OUT,
|
||||
*auth,
|
||||
*selector,
|
||||
url,
|
||||
]
|
||||
@@ -2515,6 +2552,11 @@ def _zapret_state_dir():
|
||||
return env("ZAPRET_STATE_DIR", f"{state_dir()}/zapret2")
|
||||
|
||||
|
||||
def _zapret_cutoff_dir():
|
||||
"""The cutoff probe's own directory, outside the one the group writes to."""
|
||||
return env("ZAPRET_CUTOFF_DIR", f"{state_dir()}/zapret2-cutoff")
|
||||
|
||||
|
||||
def _zapret_auto_file(name):
|
||||
return os.path.join(_zapret_state_dir(), name)
|
||||
|
||||
@@ -2640,14 +2682,16 @@ def _tsv(path):
|
||||
|
||||
|
||||
def cmd_zapret_cutoff(verb="status", *_):
|
||||
path = os.path.join(_zapret_state_dir(), "cutoff")
|
||||
path = _zapret_cutoff_dir()
|
||||
if env("ZAPRET_CUTOFF_ENABLED") != "1":
|
||||
die('The cutoff probe needs zapret.engine = "zapret2" with zapret2.cutoff.enable.')
|
||||
if verb == "probe":
|
||||
# requests/: the only part of the probe's directory the group writes to.
|
||||
requests = os.path.join(path, "requests")
|
||||
try:
|
||||
open(os.path.join(path, "force"), "w").close()
|
||||
open(os.path.join(requests, "force"), "w").close()
|
||||
except OSError:
|
||||
denied(path, "write")
|
||||
denied(requests, "write")
|
||||
print("Probing this line; this takes a few minutes...")
|
||||
if systemctl("start", "proxy-suite-zapret2-cutoff.service")[0]:
|
||||
die(f"The probe failed. Details: {journal_hint('proxy-suite-zapret2-cutoff', 30)}")
|
||||
|
||||
@@ -382,7 +382,7 @@ _cutoff = {} # ts mtime -> status text: a probe rewrites ts
|
||||
|
||||
def _cutoff_status():
|
||||
try:
|
||||
mtime = os.path.getmtime(os.path.join(ctl._zapret_state_dir(), "cutoff", "ts"))
|
||||
mtime = os.path.getmtime(os.path.join(ctl._zapret_cutoff_dir(), "ts"))
|
||||
except OSError:
|
||||
mtime = None
|
||||
if mtime not in _cutoff:
|
||||
|
||||
@@ -141,6 +141,27 @@ class ProbeVerdictTest(unittest.TestCase):
|
||||
|
||||
|
||||
class ProbeFetchTest(EnvTest):
|
||||
def test_listener_login_goes_through_a_file(self):
|
||||
"""With listener.auth the probe listeners want the login; never on curl's argv."""
|
||||
os.environ["PROXYCHAINS_CONFIG"] = self.write(
|
||||
"proxychains.conf", 'strict_chain\n\n[ProxyList]\nsocks5 127.0.0.1 1080 user pa"ss\\w\n'
|
||||
)
|
||||
seen = []
|
||||
|
||||
def curl(argv):
|
||||
with open(argv[argv.index("-K") + 1]) as f:
|
||||
seen.append((argv, f.read()))
|
||||
return 0, "0|0.1|200|10|"
|
||||
|
||||
self.patch("run_curl", curl)
|
||||
ctl._probe_fetch("site.test", "/", "--proxy", "http://127.0.0.1:18600")
|
||||
argv, curlrc = seen[0]
|
||||
self.assertEqual(curlrc, 'proxy-user = "user:pa\\"ss\\\\w"\n')
|
||||
self.assertFalse(any("pa" in a and "ss" in a for a in argv))
|
||||
# Direct fetches, and a config without a login, carry none.
|
||||
self.write("proxychains.conf", "strict_chain\n\n[ProxyList]\nsocks5 127.0.0.1 1080\n")
|
||||
self.assertIsNone(ctl._local_proxy_login())
|
||||
|
||||
def test_redirect_chains(self):
|
||||
calls = []
|
||||
table = {
|
||||
|
||||
@@ -26,6 +26,15 @@ pkgs.buildGo126Module (finalAttrs: {
|
||||
"headless/dion-joiner"
|
||||
"headless/bitrix-joiner"
|
||||
];
|
||||
# The local proxy's password from the environment, not argv: a creator runs for good,
|
||||
# and every local user reads its command line.
|
||||
postPatch = ''
|
||||
for p in vk telemost wbstream dion bitrix; do
|
||||
substituteInPlace headless/$p/main.go --replace-fail \
|
||||
'flag.String("upstream-pass", "",' \
|
||||
'flag.String("upstream-pass", os.Getenv("WB_UPSTREAM_PASS"),'
|
||||
done
|
||||
'';
|
||||
ldflags = [
|
||||
"-s"
|
||||
"-w"
|
||||
|
||||
@@ -11,6 +11,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import zlib
|
||||
@@ -67,8 +68,26 @@ class ConfigError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _shared_directory(path: str) -> bool:
|
||||
"""Whether someone besides this user may add files next to path.
|
||||
|
||||
Runtime profiles come from a group-writable spool and are read as root: a symlink
|
||||
there would hand over any file root can read, and a FIFO would hang the unit.
|
||||
"""
|
||||
try:
|
||||
info = os.stat(os.path.dirname(os.path.abspath(path)))
|
||||
except OSError:
|
||||
return True
|
||||
return info.st_uid != os.geteuid() or bool(info.st_mode & (stat.S_IWGRP | stat.S_IWOTH))
|
||||
|
||||
|
||||
def _read_limited(path: str) -> str:
|
||||
with Path(path).open("rb") as handle:
|
||||
"""At most MAX_INPUT_BYTES of path, as UTF-8; in a shared directory, only a regular file."""
|
||||
shared = _shared_directory(path)
|
||||
fd = os.open(path, os.O_RDONLY | (os.O_NOFOLLOW | os.O_NONBLOCK if shared else 0))
|
||||
with os.fdopen(fd, "rb") as handle:
|
||||
if shared and not stat.S_ISREG(os.fstat(fd).st_mode):
|
||||
raise ConfigError(f"{path} is not a regular file")
|
||||
data = handle.read(MAX_INPUT_BYTES + 1)
|
||||
if len(data) > MAX_INPUT_BYTES:
|
||||
raise ConfigError(f"input exceeds {MAX_INPUT_BYTES} bytes")
|
||||
@@ -659,16 +678,24 @@ def render_settings(settings: dict[str, Any]) -> str:
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
# What ends a line for str.splitlines(), which the rewrites here split on, but not for
|
||||
# awg-quick's `read -r`, plus NUL, which bash drops from what it reads: "PostUp \f= cmd"
|
||||
# or "Post\0Up = cmd" would reach awg-quick as a hook no check here saw. A lone CR too;
|
||||
# a CRLF line end is fine. No real configuration has any of them.
|
||||
_AMBIGUOUS_CHARACTERS = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x85\u2028\u2029]|\r(?!\n)")
|
||||
|
||||
|
||||
def validate_config(config: str, allow_hooks: bool = False) -> None:
|
||||
if _AMBIGUOUS_CHARACTERS.search(config):
|
||||
raise ConfigError("configuration contains control characters")
|
||||
lowered = config.lower()
|
||||
if "[interface]" not in lowered or "[peer]" not in lowered:
|
||||
raise ConfigError("configuration requires [Interface] and [Peer] sections")
|
||||
if not allow_hooks:
|
||||
for line in config.splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith(("#", ";")) or "=" not in stripped:
|
||||
continue
|
||||
key = stripped.split("=", 1)[0].strip().lower()
|
||||
# Read as awg-quick reads it: lines end at \n, a comment starts at #, and the
|
||||
# key is what precedes the first =, or the whole line without one.
|
||||
for line in config.split("\n"):
|
||||
key = line.split("#", 1)[0].split("=", 1)[0].strip().lower()
|
||||
if key in FORBIDDEN_WG_QUICK_KEYS:
|
||||
raise ConfigError(
|
||||
f"configuration contains privileged wg-quick directive '{key}'; "
|
||||
@@ -875,6 +902,9 @@ def main() -> int:
|
||||
config = _set_interface_value(config, "FwMark", str(args.fwmark))
|
||||
if args.resolve_endpoints:
|
||||
config = resolve_endpoints(config)
|
||||
if args.wireproxy is None:
|
||||
# What awg-quick runs, checked again after the rewrites above.
|
||||
validate_config(config, bool(manifest.get("allowConfigHooks", False)))
|
||||
write_private(args.output, config)
|
||||
except (ConfigError, KeyError, OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
parser.exit(1, f"amneziawg-config: {exc}\n")
|
||||
|
||||
@@ -229,17 +229,27 @@ def build_outbound(
|
||||
MAX_SUBSCRIPTION_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
class _HttpOnlyRedirects(urllib.request.HTTPRedirectHandler):
|
||||
"""Redirects stay on http and https: urllib's own also follows one to ftp:."""
|
||||
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
if urllib.parse.urlsplit(newurl).scheme not in ("http", "https"):
|
||||
raise ValueError("subscription redirected off http:// and https://")
|
||||
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
||||
|
||||
|
||||
def fetch_raw(url: str) -> bytes:
|
||||
# urlopen also speaks file:, ftp: and data:. This runs as root over a URL that
|
||||
# reaches it from a group-writable spool, so only the two a subscription is
|
||||
# ever served over.
|
||||
# ever served over, redirects included.
|
||||
if urllib.parse.urlsplit(url).scheme not in ("http", "https"):
|
||||
raise ValueError("subscription URL must be http:// or https://")
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers={"User-Agent": "v2rayN/6.0"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
opener = urllib.request.build_opener(_HttpOnlyRedirects)
|
||||
with opener.open(request, timeout=30) as response:
|
||||
data = response.read(MAX_SUBSCRIPTION_BYTES + 1)
|
||||
if len(data) > MAX_SUBSCRIPTION_BYTES:
|
||||
raise ValueError(f"subscription is larger than {MAX_SUBSCRIPTION_BYTES} bytes")
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -342,6 +343,46 @@ class AmneziaWgConfigTests(unittest.TestCase):
|
||||
validate_config(hooked)
|
||||
validate_config(hooked, allow_hooks=True)
|
||||
|
||||
def test_hooks_hidden_from_python_line_splitting_rejected(self):
|
||||
# Each is one line to awg-quick, whose key comes out as PostUp; splitlines()
|
||||
# would cut it before the "=", or a later rewrite would turn it into two lines.
|
||||
for hidden in (
|
||||
"PostUp \f= touch /root/pwned",
|
||||
"PostUp \v= touch /root/pwned",
|
||||
"PostUp \x1c= touch /root/pwned",
|
||||
"PostUp \u2028= touch /root/pwned",
|
||||
"PostUp \r= touch /root/pwned",
|
||||
"Post\0Up = touch /root/pwned",
|
||||
"MTU = 1280\fPostUp = touch /root/pwned",
|
||||
):
|
||||
with self.subTest(hidden=hidden), self.assertRaises(ConfigError):
|
||||
validate_config(BASE_CONFIG.replace("Address =", f"{hidden}\nAddress ="))
|
||||
# A line without "=" is still a PostUp to awg-quick.
|
||||
with self.assertRaisesRegex(ConfigError, "privileged"):
|
||||
validate_config(BASE_CONFIG.replace("Address =", "PostUp\nAddress ="))
|
||||
validate_config(BASE_CONFIG.replace("\n", "\r\n"))
|
||||
|
||||
def test_shared_directory_refuses_symlinks_and_fifos(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
directory = Path(directory)
|
||||
secret = directory / "secret.conf"
|
||||
secret.write_text(BASE_CONFIG)
|
||||
spool = directory / "spool"
|
||||
spool.mkdir()
|
||||
(spool / "link.conf").symlink_to(secret)
|
||||
os.mkfifo(spool / "fifo.conf")
|
||||
(spool / "plain.conf").write_text(BASE_CONFIG)
|
||||
# Private: a declared secret may well be a symlink (sops, agenix).
|
||||
spool.chmod(0o700)
|
||||
self.assertEqual(amneziawg_config._read_limited(str(spool / "link.conf")), BASE_CONFIG)
|
||||
# Group-writable, as the runtime spool is.
|
||||
spool.chmod(0o770)
|
||||
with self.assertRaises(OSError):
|
||||
amneziawg_config._read_limited(str(spool / "link.conf"))
|
||||
with self.assertRaisesRegex(ConfigError, "not a regular file"):
|
||||
amneziawg_config._read_limited(str(spool / "fifo.conf"))
|
||||
self.assertEqual(amneziawg_config._read_limited(str(spool / "plain.conf")), BASE_CONFIG)
|
||||
|
||||
def test_declarative_awg3_and_secret_files(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
directory = Path(directory)
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import http.server
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.error
|
||||
from proxy_parsing import (
|
||||
decode_subscription,
|
||||
fetch_raw,
|
||||
@@ -43,6 +46,26 @@ class FetchSubscriptionTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, "http"):
|
||||
fetch_raw(url)
|
||||
|
||||
def test_fetch_refuses_redirects_off_http(self):
|
||||
# A subscription server may redirect; not to a local file or FTP, which root would fetch.
|
||||
class Redirect(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(302)
|
||||
self.send_header("Location", "ftp://127.0.0.1/sub" if self.path == "/ftp" else "file:///etc/passwd")
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
server = http.server.HTTPServer(("127.0.0.1", 0), Redirect)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
self.addCleanup(server.shutdown)
|
||||
base = f"http://127.0.0.1:{server.server_port}"
|
||||
# urllib refuses file: itself, and follows ftp: unless told not to.
|
||||
with self.assertRaises(urllib.error.HTTPError):
|
||||
fetch_raw(f"{base}/file")
|
||||
with self.assertRaisesRegex(ValueError, "redirected off http"):
|
||||
fetch_raw(f"{base}/ftp")
|
||||
|
||||
def test_base64_payload_mixed_protocols(self):
|
||||
payload = _make_b64_payload(VLESS_URI, SS_URI, HY2_URI)
|
||||
|
||||
Reference in new issue
Block a user