fix: hardening

This commit is contained in:
fufsob committed 2026-09-30 09:16:21 +00:00
1 parent f609334849
commit 18a2049a1c
19 files changed
+486 -119

No files matched your search

+10 -3
View File
@@ -34,10 +34,14 @@ jobs:
set -euo pipefail set -euo pipefail
scripts/check-nixpkgs-relevance.sh >> "$GITHUB_OUTPUT" scripts/check-nixpkgs-relevance.sh >> "$GITHUB_OUTPUT"
# Step outputs and inputs reach scripts through the environment, never spliced into them.
- name: Update flake inputs - name: Update flake inputs
env:
SHOULD_UPDATE_NIXPKGS: ${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}
FORCE_NIXPKGS: ${{ inputs.force_nixpkgs }}
run: | run: |
set -euo pipefail set -euo pipefail
if [[ "${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}" == "true" || "${{ inputs.force_nixpkgs }}" == "true" ]]; then if [[ "$SHOULD_UPDATE_NIXPKGS" == "true" || "$FORCE_NIXPKGS" == "true" ]]; then
nix flake update nixpkgs nix flake update nixpkgs
else else
echo "Skipping nixpkgs update: watched package versions on nixos-unstable are unchanged." echo "Skipping nixpkgs update: watched package versions on nixos-unstable are unchanged."
@@ -80,6 +84,9 @@ jobs:
- name: Compose pull request body - name: Compose pull request body
if: steps.changes.outputs.has_changes == 'true' if: steps.changes.outputs.has_changes == 'true'
env:
SHOULD_UPDATE_NIXPKGS: ${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}
CHANGED_WATCH_ATTRS: ${{ steps.nixpkgs_gate.outputs.nixpkgs_changed_watch_attrs }}
run: | run: |
set -euo pipefail set -euo pipefail
{ {
@@ -95,8 +102,8 @@ jobs:
fi fi
echo echo
echo "### Flake inputs" echo "### Flake inputs"
echo "- nixpkgs updated: \`${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}\`" echo "- nixpkgs updated: \`$SHOULD_UPDATE_NIXPKGS\`"
echo "- changed watched attrs: \`${{ steps.nixpkgs_gate.outputs.nixpkgs_changed_watch_attrs }}\`" echo "- changed watched attrs: \`$CHANGED_WATCH_ATTRS\`"
echo "- zapret: refreshed every run" echo "- zapret: refreshed every run"
echo echo
echo '```' echo '```'
+3
View File
@@ -59,6 +59,9 @@ proxy-ctl proxy subs update # refetch subscriptions now
- `urltest` tests each outbound by fetching `proxy.urlTest.url`. Set it to a site that is - `urltest` tests each outbound by fetching `proxy.urlTest.url`. Set it to a site that is
blocked where you are, so an outbound only passes if it really gets around the block. blocked where you are, so an outbound only passes if it really gets around the block.
- Set `proxy.listener.auth` before exposing the port with `listener.address = "0.0.0.0"`. - Set `proxy.listener.auth` before exposing the port with `listener.address = "0.0.0.0"`.
- `outbounds add` also takes one outbound as sing-box or XRay JSON. Such an outbound cannot
name a local file or program (a `tor` outbound, `*_path`, `*File`, `masterKeyLog`): the
backend would open or run it with its own privileges. Declare those in `proxy.outbounds`.
## See also ## See also
+3 -1
View File
@@ -583,7 +583,9 @@ let
echo "proxy-suite: $1 is not a regular file" >&2 echo "proxy-suite: $1 is not a regular file" >&2
return 1 return 1
fi fi
${pkgs.coreutils}/bin/dd if="$1" iflag=nofollow,nonblock status=none # A MiB at most: an entry is a URL or one outbound, and the start script holds
# what it reads in shell variables.
${pkgs.coreutils}/bin/dd if="$1" iflag=nofollow,nonblock,fullblock bs=1M count=1 status=none
;; ;;
*) ${pkgs.coreutils}/bin/cat -- "$1" ;; *) ${pkgs.coreutils}/bin/cat -- "$1" ;;
esac esac
@@ -76,6 +76,12 @@ types.submodule {
type = types.nullOr types.int; type = types.nullOr types.int;
default = null; default = null;
}; };
# NixOS's: a switch reloads the unit when it changed, rather than restarting it. Other
# hosts restart it as before.
reloadIfChanged = mkOption {
type = types.bool;
default = false;
};
unitConfig = section; unitConfig = section;
serviceConfig = section; serviceConfig = section;
timerConfig = section; timerConfig = section;
+4 -1
View File
@@ -7,7 +7,8 @@
# its Clash API. Without it (the TUN instances) a failover group is sing-box's own urltest. # its Clash API. Without it (the TUN instances) a failover group is sing-box's own urltest.
# #
# Output: {groups: {name: {strategy, failback, interval, members, pinned}}, outbounds: [the # Output: {groups: {name: {strategy, failback, interval, members, pinned}}, outbounds: [the
# sing-box group outbounds], top: [what the top level picks among, in order], warnings, errors}. # sing-box group outbounds], top: [what the top level picks among, in order], loops: [groups
# inside themselves], warnings, errors}.
# Errors mean the config cannot be built (a group inside itself); warnings are dropped members # Errors mean the config cannot be built (a group inside itself); warnings are dropped members
# and pins. # and pins.
@@ -90,4 +91,6 @@ def glob_regex: "^" + (gsub("(?<c>[.+^$()\\[\\]{}|\\\\])"; "\\\(.c)") | gsub("\\
outbounds: ($built.outbounds | sort_by(.tag as $t | [$names[] | select(reach(.; [.]) | index([$t]))] | -length)), outbounds: ($built.outbounds | sort_by(.tag as $t | [$names[] | select(reach(.; [.]) | index([$t]))] | -length)),
top: $top, top: $top,
warnings: ($resolved.warnings + $built.warnings), warnings: ($resolved.warnings + $built.warnings),
# The start script drops a runtime group in a loop and tries again; a declared one is fatal.
loops: $loops,
errors: [$loops[] | "group '\(.)' contains itself"]} errors: [$loops[] | "group '\(.)' contains itself"]}
@@ -221,6 +221,14 @@ let
cfg.inbounds.routing.serverSource.ipv6 == null cfg.inbounds.routing.serverSource.ipv6 == null
|| lib.toInt (lib.last (lib.splitString "/" cfg.inbounds.routing.serverSource.ipv6)) <= 112 || lib.toInt (lib.last (lib.splitString "/" cfg.inbounds.routing.serverSource.ipv6)) <= 112
) "proxy-suite: inbounds.routing.serverSource.ipv6 must be a prefix of /112 or shorter") ) "proxy-suite: inbounds.routing.serverSource.ipv6 must be a prefix of /112 or shorter")
# A user's number is the last group of their IPv6 address.
(mkAssertion
(
cfg.inbounds.routing.serverSource.ipv6 == null
|| lib.all (s: s.number <= 65535) derived.proxyInboundsSelfSources
)
"proxy-suite: with inbounds.routing.serverSource.ipv6, inbounds.users orders must be 65535 or less"
)
(mkAssertion (mkAssertion
( (
( (
+10
View File
@@ -332,6 +332,16 @@ lib.mkMerge [
+ " anyone who reaches the port uses your outbounds; set listener.auth, or keep it off the" + " anyone who reaches the port uses your outbounds; set listener.auth, or keep it off the"
+ " firewall's allowed ports" + " firewall's allowed ports"
) )
# The prober and proxy-ctl's outbound test dial these without credentials.
++
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"
)
# rules/proxy-inbounds.nix guards the names of this host only where XRay leaves names # 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. # unresolved, or where IP aliases catch a name that resolves here first.
++ ++
@@ -29,6 +29,10 @@ let
pkgs.writeShellScript "proxy-suite-per-app" '' pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail set -euo pipefail
uid="$1" uid="$1"
if ! [[ $uid =~ ^[0-9]+$ ]]; then
echo "proxy-suite: '$uid' is not a uid" >&2
exit 1
fi
rule_comment_prefix="proxy-suite-${name}-user-$uid" rule_comment_prefix="proxy-suite-${name}-user-$uid"
mark_comment="$rule_comment_prefix-mark" mark_comment="$rule_comment_prefix-mark"
cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service" cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service"
@@ -37,7 +41,11 @@ let
exit 1 exit 1
fi fi
cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} | ${headBin} -n1 || true) # The user owns this subtree and names its directories, quotes and semicolons included:
# only a path nft reads as the one quoted string below, never one that closes the quote
# and runs nft commands of its own as root. systemd's names never need more.
cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} \
| ${grepBin} -E '^[A-Za-z0-9@._:+,=\\/-]+$' | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2 echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2
exit 1 exit 1
@@ -71,10 +71,15 @@ let
}; };
in 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).
killSwitchUpScript = pkgs.writeShellScript "proxy-suite-routing" '' killSwitchUpScript = pkgs.writeShellScript "proxy-suite-routing" ''
set -euo pipefail set -euo pipefail
${deleteKillSwitchTable} ${nft} -f - <<'EOF'
${nft} -f ${killSwitchRulesFile} add table inet proxy_suite_killswitch
delete table inet proxy_suite_killswitch
include "${killSwitchRulesFile}"
EOF
''; '';
killSwitchDownScript = pkgs.writeShellScript "proxy-suite-routing" '' killSwitchDownScript = pkgs.writeShellScript "proxy-suite-routing" ''
@@ -38,6 +38,17 @@ let
# `proxy-ctl proxy pin <tag> --in <group>`: one file per group, next to the top-level pin. # `proxy-ctl proxy pin <tag> --in <group>`: one file per group, next to the top-level pin.
groupPinsDir = "${dirOf pinnedOutboundFile}/group-pins"; groupPinsDir = "${dirOf pinnedOutboundFile}/group-pins";
# 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.
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")))]
| unique | join(", ")
'';
# sing-box domain strategies in XRay's names (UseIPv4v6 = prefer IPv4). # sing-box domain strategies in XRay's names (UseIPv4v6 = prefer IPv4).
xrayDomainStrategies = { xrayDomainStrategies = {
prefer_ipv4 = "UseIPv4v6"; prefer_ipv4 = "UseIPv4v6";
@@ -148,6 +159,12 @@ let
# only known at runtime (an AmneziaWG outbound added with proxy-ctl). # only known at runtime (an AmneziaWG outbound added with proxy-ctl).
_proxy_suite_add_socks_hop() { _proxy_suite_add_socks_hop() {
local ob local ob
# A runtime one's port comes from the group-writable spool: any other JSON would
# reach the config as it is.
case "$2" in
"" | *[!0-9]*) return 1 ;;
esac
[ "$2" -ge 1 ] && [ "$2" -le 65535 ] || return 1
ob=$(${jq} -nc --arg t "$1" --argjson p "$2" ${ ob=$(${jq} -nc --arg t "$1" --argjson p "$2" ${
lib.escapeShellArg ( lib.escapeShellArg (
if pureXrayEnabled then if pureXrayEnabled then
@@ -218,8 +235,19 @@ let
# $1 tag, $2 file holding one sing-box or XRay outbound, $3 source label. # $1 tag, $2 file holding one sing-box or XRay outbound, $3 source label.
_proxy_suite_add_json_outbound() { _proxy_suite_add_json_outbound() {
local tag="$1" source="$3" ob kind local tag="$1" source="$3" ob kind unsafe
ob=$(${jq} -ce --arg t "$tag" 'select(type == "object") | .tag = $t' <(_proxy_suite_read_source "$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
# The runtime spool is group-writable, and the backend holds CAP_NET_ADMIN and the
# daemon user's files: a sing-box tor outbound's executable_path is a program it runs
# with them, a *_path or *File one it reads, XRay's masterKeyLog one it writes. Only a
# declared outbound may name those.
if [ "$source" = runtime ]; then
unsafe=$(${jq} -r ${lib.escapeShellArg localFileKeysJq} <<< "$ob")
if [ -n "$unsafe" ]; then
echo "proxy-suite: runtime outbound '$tag' names local files or programs ($unsafe); declare it in proxy.outbounds instead" >&2
return 1
fi
fi
kind=$(${jq} -r 'if has("protocol") then "xray" elif has("type") then "sing-box" else "" end' <<< "$ob") kind=$(${jq} -r 'if has("protocol") then "xray" elif has("type") then "sing-box" else "" end' <<< "$ob")
${jsonAddBlock} ${jsonAddBlock}
_proxy_suite_record_tag_source "$tag" "$source" _proxy_suite_record_tag_source "$tag" "$source"
@@ -599,6 +627,14 @@ let
[ -e "$GROUP_FILE" ] || continue [ -e "$GROUP_FILE" ] || continue
GROUP_NAME="''${GROUP_FILE##*/}" GROUP_NAME="''${GROUP_FILE##*/}"
GROUP_NAME="''${GROUP_NAME%.group}" GROUP_NAME="''${GROUP_NAME%.group}"
# 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._-]*)
echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': reserved or invalid name" >&2
continue
;;
esac
if ${jq} -e --arg g "$GROUP_NAME" 'has($g)' <<< "$GROUPS_CONFIG_JSON" >/dev/null; then if ${jq} -e --arg g "$GROUP_NAME" 'has($g)' <<< "$GROUPS_CONFIG_JSON" >/dev/null; then
echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': proxy.groups declares it" >&2 echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': proxy.groups declares it" >&2
continue continue
@@ -608,7 +644,8 @@ let
strategy: (.strategy // "failover"), failback: (.failback != false), interval: (.interval // null), strategy: (.strategy // "failover"), failback: (.failback != false), interval: (.interval // null),
runtime: true} runtime: true}
| select(.strategy | IN("failover", "urltest", "selector")) | select(.strategy | IN("failover", "urltest", "selector"))
| select([.outbounds, .subscriptions, .match] | all(type == "array" and all(type == "string")))'); then | select([.outbounds, .subscriptions, .match] | all(type == "array" and all(type == "string")))
| select(.interval == null or (.interval | type == "string" and test("^([0-9]+(\\.[0-9]+)?(ns|us|ms|s|m|h))+$")))'); then
echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': not a valid group" >&2 echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': not a valid group" >&2
continue continue
fi fi
@@ -632,21 +669,29 @@ let
fi fi
''} ''}
# A runtime outbound may have taken a group's name: the outbound stays. # A runtime outbound may have taken a group's name: the outbound stays.
for GROUP_NAME in $(${jq} -r --argjson tags "$OUTBOUND_TAGS_JSON" 'keys[] | select(. as $g | $tags | index([$g]))' <<< "$GROUPS_CONFIG_JSON"); do while IFS= read -r GROUP_NAME; do
echo "proxy-suite: warning: ignoring group '$GROUP_NAME': an outbound has that tag" >&2 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") 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")
# 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}' \
| ${jq} -c -f ${groupsJq} \
--argjson groups "$GROUPS_CONFIG_JSON" \
--argjson priority "$PRIORITY_JSON" \
--argjson disabled "$DISABLED_TAGS_JSON" \
--argjson pins "$GROUP_PINS_JSON" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
--argjson watched "''${GROUPS_WATCHED:-true}")
GROUPS_LOOP_DROP=$(${jq} -c --argjson g "$GROUPS_CONFIG_JSON" '[.loops[] | select($g[.].runtime == true)]' <<< "$GROUPS_RESULT")
[ "$GROUPS_LOOP_DROP" != '[]' ] || break
${jq} -r '.[] | "proxy-suite: warning: ignoring runtime group '"'"'\(.)'"'"': it contains itself"' <<< "$GROUPS_LOOP_DROP" >&2
GROUPS_CONFIG_JSON=$(${jq} -c --argjson drop "$GROUPS_LOOP_DROP" 'with_entries(select(.key as $k | $drop | index([$k]) | not))' <<< "$GROUPS_CONFIG_JSON")
done done
GROUPS_RESULT=$(${jq} -nc --argjson tags "$OUTBOUND_TAGS_JSON" --argjson sources "''${OUTBOUND_SOURCES_JSON:-{\}}" \
'{tags: $tags, sources: $sources}' \
| ${jq} -c -f ${groupsJq} \
--argjson groups "$GROUPS_CONFIG_JSON" \
--argjson priority "$PRIORITY_JSON" \
--argjson disabled "$DISABLED_TAGS_JSON" \
--argjson pins "$GROUP_PINS_JSON" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
--argjson watched "''${GROUPS_WATCHED:-true}")
${jq} -r '.warnings[] | "proxy-suite: warning: " + .' <<< "$GROUPS_RESULT" >&2 ${jq} -r '.warnings[] | "proxy-suite: warning: " + .' <<< "$GROUPS_RESULT" >&2
if ${jq} -e '.errors != []' <<< "$GROUPS_RESULT" >/dev/null; then if ${jq} -e '.errors != []' <<< "$GROUPS_RESULT" >/dev/null; then
${jq} -r '.errors[] | "proxy-suite: " + .' <<< "$GROUPS_RESULT" >&2 ${jq} -r '.errors[] | "proxy-suite: " + .' <<< "$GROUPS_RESULT" >&2
@@ -854,4 +899,6 @@ in
inherit mkOutboundScript rawOutboundJson; inherit mkOutboundScript rawOutboundJson;
# For the checks: groups, and which outbounds a pin and selection may take. # For the checks: groups, and which outbounds a pin and selection may take.
selectionBlocks = tagsBlock + groupsBlock + pinBlock + selectableBlock + inventoryBlock; selectionBlocks = tagsBlock + groupsBlock + pinBlock + selectableBlock + inventoryBlock;
# And what the runtime spool is read into.
runtimeOutboundBlocks = mkUrlOutboundHelpersBlock null + runtimeOutboundsBlock;
} }
+50 -15
View File
@@ -69,6 +69,21 @@ let
localProxyAuthEnabled = ctx.localProxy.authEnabled; localProxyAuthEnabled = ctx.localProxy.authEnabled;
# 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
# mistake in reading those spools can write anywhere else. Reads are untouched, secrets
# under /root or /home included. `extra`: other paths they update.
spoolReaderSandbox =
extra:
lib.optionalAttrs ctx.constants.privileged (
{
ProtectSystem = "strict";
}
# "-": the socks unit may not have made its runtime directory yet.
// lib.optionalAttrs (extra != [ ]) { ReadWritePaths = map (path: "-${path}") extra; }
);
socksRuntimeDir = "${ctx.constants.runtimeDir}/${serviceNames.socks}";
# XRay finds geoip.dat/geosite.dat through this; sing-box ignores it. # XRay finds geoip.dat/geosite.dat through this; sing-box ignores it.
xrayAssetEnv = lib.optionalAttrs (geodata.xray.assets != null) { xrayAssetEnv = lib.optionalAttrs (geodata.xray.assets != null) {
Environment = [ "XRAY_LOCATION_ASSET=${geodata.xray.assets}/share/v2ray" ]; Environment = [ "XRAY_LOCATION_ASSET=${geodata.xray.assets}/share/v2ray" ];
@@ -96,7 +111,7 @@ let
execStart = scripts.startSocks; execStart = scripts.startSocks;
runtimeDirectory = serviceNames.socks; runtimeDirectory = serviceNames.socks;
stateDirectory = "proxy-suite"; stateDirectory = "proxy-suite";
extraServiceConfig = xrayAssetEnv; extraServiceConfig = xrayAssetEnv // spoolReaderSandbox [ ];
}; };
} }
{ {
@@ -158,16 +173,23 @@ let
{ {
enable = killSwitchEnabled; enable = killSwitchEnabled;
name = serviceNames.killSwitch; name = serviceNames.killSwitch;
value = mkOneshotService { value =
description = "proxy-suite kill switch - reject traffic outside the global tunnel"; mkOneshotService {
after = [ description = "proxy-suite kill switch - reject traffic outside the global tunnel";
"${serviceNames.socks}.service" after = [
"${serviceNames.tun}.service" "${serviceNames.socks}.service"
] "${serviceNames.tun}.service"
++ map (name: "proxy-suite-awg-${name}.service") (builtins.attrNames awgGlobalProfiles); ]
execStart = killSwitchUpScript; ++ map (name: "proxy-suite-awg-${name}.service") (builtins.attrNames awgGlobalProfiles);
execStop = killSwitchDownScript; execStart = killSwitchUpScript;
}; execStop = killSwitchDownScript;
extraServiceConfig.ExecReload = killSwitchUpScript;
}
# A restart runs ExecStop, which lifts the kill switch until ExecStart puts it back:
# new rules from a switch are swapped in by a reload instead, in one transaction.
// {
reloadIfChanged = true;
};
} }
{ {
enable = proxyEnabled && globalTproxy.enable; enable = proxyEnabled && globalTproxy.enable;
@@ -283,7 +305,10 @@ let
execStart = scripts.subscriptionUpdateScript; execStart = scripts.subscriptionUpdateScript;
stateDirectory = "proxy-suite"; stateDirectory = "proxy-suite";
# Run by a timer and by `proxy subs update`: a unit left "active" would never run again. # Run by a timer and by `proxy subs update`: a unit left "active" would never run again.
extraServiceConfig.RemainAfterExit = false; extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ ];
}; };
} }
{ {
@@ -303,7 +328,11 @@ let
description = "Pin the proxy-suite outbound to %I"; description = "Pin the proxy-suite outbound to %I";
execStart = "${scripts.pinOutboundScript} %I"; execStart = "${scripts.pinOutboundScript} %I";
stateDirectory = "proxy-suite"; stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false; # It updates the pin in the running proxy's inventory.
extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ socksRuntimeDir ];
}; };
} }
{ {
@@ -313,7 +342,10 @@ let
description = "Unpin the proxy-suite outbound"; description = "Unpin the proxy-suite outbound";
execStart = "${scripts.pinOutboundScript}"; execStart = "${scripts.pinOutboundScript}";
stateDirectory = "proxy-suite"; stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false; extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ socksRuntimeDir ];
}; };
} }
{ {
@@ -323,7 +355,10 @@ let
description = "Apply proxy-suite outbounds and subscriptions added at runtime"; description = "Apply proxy-suite outbounds and subscriptions added at runtime";
execStart = scripts.reloadOutboundsScript; execStart = scripts.reloadOutboundsScript;
stateDirectory = "proxy-suite"; stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false; extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ ];
}; };
} }
]; ];
+4
View File
@@ -131,6 +131,10 @@ in
assert before "ip daddr 172.19.0.1/30 accept" "th dport 53 reject"; assert before "ip daddr 172.19.0.1/30 accept" "th dport 53 reject";
assert before "th dport 53 reject" "ip daddr $RESERVED_IP accept"; assert before "th dport 53 reject" "ip daddr $RESERVED_IP accept";
assert pkgs.lib.hasInfix ''iifname { "br0" } reject'' rules; assert pkgs.lib.hasInfix ''iifname { "br0" } reject'' rules;
# A switch reloads it: the new rules replace the old in one transaction, never a stop
# that lifts it first.
assert ks.reloadIfChanged;
assert ks.serviceConfig.ExecReload == ks.serviceConfig.ExecStart;
assert !(tproxyManualFixture.config.systemd.services ? "proxy-suite-killswitch"); assert !(tproxyManualFixture.config.systemd.services ? "proxy-suite-killswitch");
true true
) )
+84 -44
View File
@@ -24,6 +24,50 @@ let
ROUTE_MODE_STATE_FILE="$PWD/route-mode" \ ROUTE_MODE_STATE_FILE="$PWD/route-mode" \
DEFAULT_ROUTE_MODE="blacklist" \ DEFAULT_ROUTE_MODE="blacklist" \
''; '';
# The start script's outbound blocks, reading the runtime spool from obd/ in the build dir.
outboundScriptBlocks =
groups:
import ../../modules/proxy-suite/service/script-blocks/outbounds.nix {
lib = pkgs.lib;
inherit pkgs;
jq = "${pkgs.jq}/bin/jq";
proxyCfg = {
selectionExclude = [ "ex" ];
inherit groups;
priority = { };
urlTest = {
url = "https://t";
interval = "3m";
};
};
selectionMode = "urltest";
hybridEnabled = false;
# Relative: the build directory.
pinnedOutboundFile = "pinned";
runtimeOutboundsDir = "obd";
singBoxCfg.urlTest.tolerance = 50;
sshProxyCfg = null;
warpCfg = null;
torCfg = null;
whitelistBypassJoiners = [ ];
awgOutbounds = null;
# The start script checks for symlinks in the spool; here it is only this build's.
constants.readSourceFunction = _: ''
_proxy_suite_read_source() { cat -- "$1"; }
'';
pureXrayEnabled = false;
collapseNamedOutbounds = null;
backend = null;
backendArg = "--backend sing-box";
xraySidecarRoutingMark = null;
# A runtime .url outbound would need the parsers; the checks only drop JSON ones.
python3 = "false";
parserScriptsPythonPath = "";
buildOutboundPy = "";
mkSubscriptionBlock = null;
mkSubscriptionLoadHelperBlock = null;
runtimeSubscriptionsBlock = null;
};
in in
{ {
no-secrets = pkgs.runCommand "proxy-suite-no-secrets-check" { } '' no-secrets = pkgs.runCommand "proxy-suite-no-secrets-check" { } ''
@@ -849,46 +893,7 @@ in
mkSelection = mkSelection =
groups: groups:
let let
inherit inherit (outboundScriptBlocks groups) selectionBlocks;
(import ../../modules/proxy-suite/service/script-blocks/outbounds.nix {
lib = pkgs.lib;
inherit pkgs;
jq = "${pkgs.jq}/bin/jq";
proxyCfg = {
selectionExclude = [ "ex" ];
inherit groups;
priority = { };
urlTest = {
url = "https://t";
interval = "3m";
};
};
selectionMode = "urltest";
hybridEnabled = false;
# Relative: the build directory.
pinnedOutboundFile = "pinned";
runtimeOutboundsDir = "obd";
singBoxCfg.urlTest.tolerance = 50;
sshProxyCfg = null;
warpCfg = null;
torCfg = null;
whitelistBypassJoiners = [ ];
awgOutbounds = null;
constants = null;
pureXrayEnabled = false;
collapseNamedOutbounds = null;
backend = null;
backendArg = null;
xraySidecarRoutingMark = null;
python3 = null;
parserScriptsPythonPath = null;
buildOutboundPy = null;
mkSubscriptionBlock = null;
mkSubscriptionLoadHelperBlock = null;
runtimeSubscriptionsBlock = null;
})
selectionBlocks
;
in in
pkgs.writeShellScript "outbound-selection" '' pkgs.writeShellScript "outbound-selection" ''
set -euo pipefail set -euo pipefail
@@ -933,12 +938,20 @@ in
export -f _proxy_suite_read_source export -f _proxy_suite_read_source
${grouped} ${grouped}
jq -e '.top == ["h", "g"] and .groups.g.pinned == "a" and .groups.h.runtime and .priority.h == 1' outbounds.json > /dev/null jq -e '.top == ["h", "g"] and .groups.g.pinned == "a" and .groups.h.runtime and .priority.h == 1' outbounds.json > /dev/null
# A group inside itself stops the start. # The spool is group-writable: a runtime group inside itself, one that is not a group, and
# one taking a reserved name are left out, and the start goes on without them.
echo '{"outbounds": ["h3"]}' > obd/h2.group echo '{"outbounds": ["h3"]}' > obd/h2.group
echo '{"outbounds": ["h2"]}' > obd/h3.group echo '{"outbounds": ["h2"]}' > obd/h3.group
! ${grouped} 2> err echo '{"outbounds": ["x"], "interval": {"s": 1}}' > obd/h4.group
grep -q "group 'h2' contains itself" err echo '{"outbounds": ["x"]}' > obd/proxy.group
rm -r obd/h.group obd/h2.group obd/h3.group obd/priority.json group-pins ${grouped} 2> err
grep -q "ignoring runtime group 'h2': it contains itself" err
grep -q "ignoring runtime group 'h3': it contains itself" err
grep -q "ignoring runtime group 'h4': not a valid group" err
grep -q "ignoring runtime group 'proxy': reserved or invalid name" err
jq -e '.groups | (has("h2") or has("h3") or has("h4") or has("proxy")) | not' outbounds.json > /dev/null
jq -e '.groups.h.runtime' outbounds.json > /dev/null
rm -r obd/h.group obd/h2.group obd/h3.group obd/h4.group obd/proxy.group obd/priority.json group-pins
export OUTBOUNDS_JSON='[{"tag":"a"},{"tag":"b"},{"tag":"ex"}]' export OUTBOUNDS_JSON='[{"tag":"a"},{"tag":"b"},{"tag":"ex"}]'
@@ -960,6 +973,33 @@ in
touch "$out" touch "$out"
''; '';
# The spool is group-writable and the backend privileged: a runtime JSON outbound naming a program
# or a file to read or write is left out, and a runtime AmneziaWG port must be a port.
runtime-outbound-spool =
let
loadRuntime = pkgs.writeShellScript "runtime-outbounds" ''
set -euo pipefail
OUTBOUNDS_JSON='[]'
${(outboundScriptBlocks { }).runtimeOutboundBlocks}
printf '%s' "$OUTBOUNDS_JSON" > outbounds.json
'';
in
pkgs.runCommand "proxy-suite-runtime-outbound-spool-check" { nativeBuildInputs = [ pkgs.jq ]; } ''
mkdir obd
echo '{"type": "socks", "server": "127.0.0.1", "server_port": 1080}' > obd/ok.json
echo '{"type": "vless", "server": "h", "transport": {"type": "ws", "path": "/x"}}' > obd/ws.json
echo '{"type": "tor", "executable_path": "/tmp/x"}' > obd/tor.json
echo '{"type": "ssh", "server": "h", "private_key_path": "/root/.ssh/id_ed25519"}' > obd/ssh.json
echo '{"type": "vless", "server": "h", "tls": {"enabled": true, "certificate_path": "/etc/shadow"}}' > obd/cert.json
${loadRuntime} 2> err
cat err
jq -e '[.[].tag] == ["ok", "ws"]' outbounds.json > /dev/null
grep -q "runtime outbound 'tor' names local files or programs (executable_path, type: tor)" err
grep -q "runtime outbound 'ssh' names local files or programs (private_key_path)" err
grep -q "runtime outbound 'cert' names local files or programs (certificate_path)" err
touch "$out"
'';
proxy-ctl-amneziawg = proxy-ctl-amneziawg =
pkgs.runCommand "proxy-suite-proxy-ctl-amneziawg-check" pkgs.runCommand "proxy-suite-proxy-ctl-amneziawg-check"
{ {
+93 -33
View File
@@ -15,6 +15,7 @@ import re
import shutil import shutil
import signal import signal
import socket import socket
import stat
import subprocess import subprocess
import sys import sys
import tempfile import tempfile
@@ -297,6 +298,27 @@ def denied(path, what="read"):
die(f"Cannot {what} {path} - {ask_group()}.") die(f"Cannot {what} {path} - {ask_group()}.")
def _spool_write(path, text=""):
"""Replaces path whole, 0640, in a directory userControl's group may write to.
Through a new file renamed over it: a symlink a member left at path is replaced rather
than followed, so proxy-ctl run as root never writes where it points. The file takes
the directory's group (the spools are setgid). Raises OSError.
"""
fd, tmp = tempfile.mkstemp(prefix=f".{os.path.basename(path)}.", dir=os.path.dirname(path) or ".")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(text)
os.chmod(tmp, 0o640)
os.replace(tmp, path)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
def _run(argv, capture=False, quiet=False, stdin=None): def _run(argv, capture=False, quiet=False, stdin=None):
"""Runs argv; (exit status, stdout if captured). A missing binary is 127.""" """Runs argv; (exit status, stdout if captured). A missing binary is 127."""
sys.stdout.flush() sys.stdout.flush()
@@ -1954,15 +1976,10 @@ def _read_group_file(tag):
def _write_group_file(tag, data): def _write_group_file(tag, data):
path = _group_file(tag) path = _group_file(tag)
old = os.umask(0o027)
try: try:
with open(path, "w", encoding="utf-8") as f: _spool_write(path, json.dumps(data, indent=2) + "\n")
json.dump(data, f, indent=2)
f.write("\n")
except OSError: except OSError:
denied(path, "write") denied(path, "write")
finally:
os.umask(old)
def _group_contains(groups, outer, tag, seen=()): def _group_contains(groups, outer, tag, seen=()):
@@ -2159,15 +2176,10 @@ def cmd_priority(*args):
else: else:
usage("proxy priority <tag> <number>|up|down|--clear") usage("proxy priority <tag> <number>|up|down|--clear")
path = _priority_file() path = _priority_file()
old = os.umask(0o027)
try: try:
with open(path, "w", encoding="utf-8") as f: _spool_write(path, json.dumps(data, indent=2, sort_keys=True) + "\n")
json.dump(data, f, indent=2, sort_keys=True)
f.write("\n")
except OSError: except OSError:
denied(path, "write") denied(path, "write")
finally:
os.umask(old)
_runtime_reload() _runtime_reload()
print(f"{tag}: {'default order' if value == '--clear' else 'moved ' + value if value in ('up', 'down') else value}") print(f"{tag}: {'default order' if value == '--clear' else 'moved ' + value if value in ('up', 'down') else value}")
@@ -2213,6 +2225,30 @@ def _runtime_path(kind, tag):
return os.path.join(_runtime_dir(kind), f"{tag}.url") return os.path.join(_runtime_dir(kind), f"{tag}.url")
def _local_file_keys(ob):
"""What in an outbound points the root backend at a local file or program.
The start script ignores a runtime outbound that has any (localFileKeysJq there).
"""
found = {"type: tor"} if ob.get("type") == "tor" else set()
stack = [ob]
while stack:
item = stack.pop()
if isinstance(item, dict):
for key, child in item.items():
k = str(key).lower()
if (
k.endswith(("file", "directory"))
or (k.endswith("path") and k != "path")
or k in ("masterkeylog", "torrc", "extra_args")
):
found.add(k)
stack.append(child)
elif isinstance(item, list):
stack.extend(item)
return sorted(found)
def _runtime_json_outbound(text): def _runtime_json_outbound(text):
"""One outbound object from `text`, the tag left to the entry's name.""" """One outbound object from `text`, the tag left to the entry's name."""
try: try:
@@ -2221,6 +2257,11 @@ def _runtime_json_outbound(text):
die(f"Not a URL, and not valid JSON: {e}") die(f"Not a URL, and not valid JSON: {e}")
if not isinstance(ob, dict) or not ("type" in ob or "protocol" in ob): if not isinstance(ob, dict) or not ("type" in ob or "protocol" in ob):
die('JSON must be one outbound object: sing-box ("type") or XRay ("protocol").') die('JSON must be one outbound object: sing-box ("type") or XRay ("protocol").')
if unsafe := _local_file_keys(ob):
die(
f"An outbound added at runtime cannot name local files or programs ({', '.join(unsafe)}): "
"the backend runs them with its privileges. Declare it in proxy.outbounds instead."
)
ob.pop("tag", None) ob.pop("tag", None)
return json.dumps(ob, ensure_ascii=False) return json.dumps(ob, ensure_ascii=False)
@@ -2348,21 +2389,16 @@ def _runtime_entry_add(kind, *args, detour="", container=""):
else: else:
url = url.strip() url = url.strip()
path = os.path.join(_runtime_dir(kind), tag + ext) path = os.path.join(_runtime_dir(kind), tag + ext)
old = os.umask(0o027)
try: try:
# The hop first: the entry is what the start script looks for. # The hop first: the entry is what the start script looks for.
hop = os.path.join(_runtime_dir(kind), f"{tag}.detour") hop = os.path.join(_runtime_dir(kind), f"{tag}.detour")
if detour: if detour:
with open(hop, "w", encoding="utf-8") as f: _spool_write(hop, f"{detour}\n")
f.write(f"{detour}\n") elif os.path.lexists(hop):
elif os.path.exists(hop):
os.unlink(hop) # left from an earlier entry of this name: it would chain this one too os.unlink(hop) # left from an earlier entry of this name: it would chain this one too
with open(path, "w", encoding="utf-8") as f: _spool_write(path, f"{url}\n")
f.write(f"{url}\n")
except OSError: except OSError:
denied(path, "write") denied(path, "write")
finally:
os.umask(old)
_runtime_reload() _runtime_reload()
_runtime_entry_verify(kind, tag) _runtime_entry_verify(kind, tag)
@@ -2457,14 +2493,10 @@ def cmd_outbound_disable(tag="", *_):
# With none left to pick the proxy would not start, pinned or not: an unpin falls back to selection. # With none left to pick the proxy would not start, pinned or not: an unpin falls back to selection.
if [t for t in _outbound_tags() if t not in excluded] == [tag]: if [t for t in _outbound_tags() if t not in excluded] == [tag]:
die(f"'{tag}' is the only outbound selection can pick; enable or add another first.") die(f"'{tag}' is the only outbound selection can pick; enable or add another first.")
old = os.umask(0o027)
try: try:
with open(marker, "w", encoding="utf-8"): _spool_write(marker)
pass
except OSError: except OSError:
denied(marker, "write") denied(marker, "write")
finally:
os.umask(old)
# The reload drops a pin on it too. # The reload drops a pin on it too.
_runtime_reload() _runtime_reload()
if tag in _outbound_disabled(): if tag in _outbound_disabled():
@@ -3182,7 +3214,12 @@ def _autoproxy_queue(name, line):
"""Appends a line for the prober's own unit, which takes it under the same lock as a timer run.""" """Appends a line for the prober's own unit, which takes it under the same lock as a timer run."""
path = os.path.join(_autoproxy_dir(), name) path = os.path.join(_autoproxy_dir(), name)
try: try:
with open(path, "a", encoding="utf-8") as f: # Appended in place, as the prober takes it, but never through a symlink or into a
# FIFO a member left there: proxy-ctl may run as root.
fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o666)
with os.fdopen(fd, "a", encoding="utf-8") as f:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise OSError(f"{path} is not a regular file")
f.write(f"{line}\n") f.write(f"{line}\n")
except OSError: except OSError:
denied(path, "write") denied(path, "write")
@@ -3421,7 +3458,7 @@ def cmd_zapret_cutoff(verb="status", *_):
# requests/: the only part of the probe's directory the group writes to. # requests/: the only part of the probe's directory the group writes to.
requests = os.path.join(path, "requests") requests = os.path.join(path, "requests")
try: try:
open(os.path.join(requests, "force"), "w").close() _spool_write(os.path.join(requests, "force"))
except OSError: except OSError:
denied(requests, "write") denied(requests, "write")
print("Probing this line; this takes a few minutes...") print("Probing this line; this takes a few minutes...")
@@ -3789,18 +3826,14 @@ def _awg_outbound_add(tag, text, detour, container):
if not os.access(directory, os.W_OK | os.X_OK): if not os.access(directory, os.W_OK | os.X_OK):
denied(directory, "write to") denied(directory, "write to")
port = _awg_free_port() port = _awg_free_port()
old = os.umask(0o027)
try: try:
# The port first: the config is what the start script and the sync unit look for. # The port first: the config is what the start script and the sync unit look for.
for extra in (".detour", ".disabled"): for extra in (".detour", ".disabled"):
if os.path.exists(os.path.join(directory, tag + extra)): if os.path.lexists(os.path.join(directory, tag + extra)):
os.unlink(os.path.join(directory, tag + extra)) # left from an earlier entry of this name os.unlink(os.path.join(directory, tag + extra)) # left from an earlier entry of this name
with open(os.path.join(directory, f"{tag}.port"), "w", encoding="utf-8") as f: _spool_write(os.path.join(directory, f"{tag}.port"), f"{port}\n")
f.write(f"{port}\n")
except OSError: except OSError:
denied(directory, "write to") denied(directory, "write to")
finally:
os.umask(old)
_awg_write(text, os.path.join(directory, f"{tag}.awg"), container) _awg_write(text, os.path.join(directory, f"{tag}.awg"), container)
_runtime_reload() _runtime_reload()
_runtime_entry_verify("outbound", tag) _runtime_entry_verify("outbound", tag)
@@ -4662,9 +4695,36 @@ COMMANDS = {
} }
# Control characters but tab and newline: C0, DEL and C1.
_UNPRINTABLE = re.compile("[\x00-\x08\x0b-\x1f\x7f-\x9f]")
class _TerminalSafe:
"""A terminal stream that shows control characters rather than obeying them.
Much of what proxy-ctl prints comes from elsewhere: share links a subscription served,
entries the userControl group wrote. An escape sequence among them could set the
clipboard or rewrite the screen of whoever reads it, root included. proxy-ctl prints
none of its own.
"""
def __init__(self, stream):
self._stream = stream
def write(self, text):
return self._stream.write(_UNPRINTABLE.sub(lambda m: f"\\x{ord(m.group()):02x}", text))
def __getattr__(self, name):
return getattr(self._stream, name)
def main(argv): def main(argv):
# Die quietly on a closed pipe (`proxy-ctl help | head`), as a shell tool does. # Die quietly on a closed pipe (`proxy-ctl help | head`), as a shell tool does.
signal.signal(signal.SIGPIPE, signal.SIG_DFL) signal.signal(signal.SIGPIPE, signal.SIG_DFL)
for name in ("stdout", "stderr"):
stream = getattr(sys, name)
if stream.isatty():
setattr(sys, name, _TerminalSafe(stream))
if argv and argv[0] in ALIASES: if argv and argv[0] in ALIASES:
argv = ALIASES[argv[0]] + argv[1:] argv = ALIASES[argv[0]] + argv[1:]
cmd, args = (argv[0], argv[1:]) if argv else ("status", []) cmd, args = (argv[0], argv[1:]) if argv else ("status", [])
+38
View File
@@ -45,6 +45,14 @@ def ok(fn, *args):
return out return out
class TerminalSafeTest(unittest.TestCase):
def test_control_characters_are_shown_not_obeyed(self):
"""A share link a subscription served may carry escapes: OSC 52 would set the clipboard."""
out = io.StringIO()
ctl._TerminalSafe(out).write("vless://u@h:1#\x1b]52;c;cm0gLXJmIH4=\x07name\r\tok\n\x9b2J")
self.assertEqual(out.getvalue(), "vless://u@h:1#\\x1b]52;c;cm0gLXJmIH4=\\x07name\\x0d\tok\n\\x9b2J")
class StubResolverTest(unittest.TestCase): class StubResolverTest(unittest.TestCase):
def resolv(self, content): def resolv(self, content):
tmp = tempfile.NamedTemporaryFile("w", suffix=".conf", delete=False) tmp = tempfile.NamedTemporaryFile("w", suffix=".conf", delete=False)
@@ -860,6 +868,36 @@ class RuntimeEntryTest(RuntimeSpoolTest):
self.assertTrue(os.path.exists(self.path("outbounds.d/socks.json"))) self.assertTrue(os.path.exists(self.path("outbounds.d/socks.json")))
self.assertNotEqual(run(ctl.cmd_subscription, "add", "-")[0], 0) self.assertNotEqual(run(ctl.cmd_subscription, "add", "-")[0], 0)
def test_json_naming_local_files_is_refused(self):
"""The backend holds CAP_NET_ADMIN: a tor outbound runs a program, *_path and *File are read."""
for tag, ob in (
("t", {"type": "tor", "executable_path": "/tmp/x"}),
("s", {"type": "ssh", "server": "h", "private_key_path": "/root/.ssh/id_ed25519"}),
("x", {"protocol": "vless", "streamSettings": {"tlsSettings": {"masterKeyLog": "/etc/x"}}}),
):
status, _, err = run(ctl.cmd_outbounds, "add", tag, json.dumps(ob))
self.assertNotEqual(status, 0)
self.assertIn("cannot name local files or programs", err)
self.assertFalse(os.path.exists(self.path(f"outbounds.d/{tag}.json")))
# A transport's path is a URL path, not a file.
ok(ctl.cmd_outbounds, "add", "ws", '{"type": "vless", "transport": {"type": "ws", "path": "/x"}}')
def test_symlinks_in_the_spool_are_replaced_not_followed(self):
"""proxy-ctl may run as root in a dir the group writes to: a planted link leads nowhere."""
victim = self.write("victim", "untouched\n")
os.symlink(victim, self.path("outbounds.d/priority.json"))
# Dangling: followed, the write would create a file wherever they point.
for name in ("new.detour", "primary.disabled"):
os.symlink(self.path(f"created-{name}"), self.path(f"outbounds.d/{name}"))
ok(ctl.cmd_outbounds, "add", "new", "vless://u@new.test:443", "--detour", "primary")
ok(ctl.cmd_outbounds, "disable", "primary")
ok(ctl.cmd_priority, "primary", "5")
self.assertEqual(ctl.read_text(victim), "untouched\n")
for name in ("new.detour", "primary.disabled", "priority.json"):
self.assertFalse(os.path.islink(self.path(f"outbounds.d/{name}")), name)
self.assertFalse(os.path.exists(self.path(f"created-{name}")), name)
self.assertEqual(ctl.read_text(self.path("outbounds.d/new.detour")), "primary\n")
def test_disable_enable(self): def test_disable_enable(self):
self.pinned = "primary" self.pinned = "primary"
self.backend_start() self.backend_start()
+31 -5
View File
@@ -32,6 +32,7 @@ import socket
import stat import stat
import subprocess import subprocess
import sys import sys
import tempfile
import uuid import uuid
# User names and listener tags: they become file names, XRay emails and tags, and URL parts. # User names and listener tags: they become file names, XRay emails and tags, and URL parts.
@@ -136,13 +137,23 @@ def write_entry(spool: str, kind: str, name: str, entry: dict) -> None:
old = os.umask(0o027) old = os.umask(0o027)
try: try:
os.makedirs(directory, exist_ok=True) os.makedirs(directory, exist_ok=True)
path = os.path.join(directory, f"{name}.json")
tmp = os.path.join(directory, f".{name}.json.tmp")
with open(tmp, "w", encoding="utf-8") as handle:
handle.write(json.dumps(entry, indent=2, sort_keys=True) + "\n")
os.replace(tmp, path)
finally: finally:
os.umask(old) os.umask(old)
path = os.path.join(directory, f"{name}.json")
# A new file of its own, never a fixed name: a symlink a member left there would take
# the write of this tool run as root wherever it points.
fd, tmp = tempfile.mkstemp(prefix=f".{name}.json.", dir=directory)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(json.dumps(entry, indent=2, sort_keys=True) + "\n")
os.chmod(tmp, 0o640)
os.replace(tmp, path)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
def remove_entry(spool: str, kind: str, name: str) -> None: def remove_entry(spool: str, kind: str, name: str) -> None:
@@ -352,6 +363,14 @@ def port_free(address: str, port: int, kinds: list[int]) -> bool:
return True return True
def _is_ip(address) -> bool:
try:
ipaddress.ip_address(address)
except (TypeError, ValueError):
return False
return True
def _loopback(address: str) -> bool: def _loopback(address: str) -> bool:
return address.startswith("127.") or address in ("::1", "localhost") return address.startswith("127.") or address in ("::1", "localhost")
@@ -431,6 +450,8 @@ def listener_problems(listener: dict, runtime: dict, share_links: bool) -> list[
need(_port_allowed(listener["port"], runtime.get("ports") or []), need(_port_allowed(listener["port"], runtime.get("ports") or []),
f"port {listener['port']} is not in inbounds.runtime.ports") f"port {listener['port']} is not in inbounds.runtime.ports")
# XRay takes a path or an @name for a Unix socket: a runtime listener binds an IP only.
need(_is_ip(listener["listen"]), f"address '{listener['listen']}' is not an IP address")
need(listener["via"] in runtime.get("vias") or [], need(listener["via"] in runtime.get("vias") or [],
f"via '{listener['via']}' is not routing.via, \"block\" or in inbounds.runtime.vias") f"via '{listener['via']}' is not routing.via, \"block\" or in inbounds.runtime.vias")
need(not (tls["enable"] and reality["enable"]), "tls and reality are mutually exclusive") need(not (tls["enable"] and reality["enable"]), "tls and reality are mutually exclusive")
@@ -586,6 +607,11 @@ def number_users(spec: dict, names: list[str], state_users: dict, warnings: list
if size is not None and number + 2 > size: if size is not None and number + 2 > size:
warnings.append(f"runtime user '{name}': number {number} does not fit in serverSource.ipv4; no own address") warnings.append(f"runtime user '{name}': number {number} does not fit in serverSource.ipv4; no own address")
continue continue
# The number is the last group of the IPv6 address (the prefix is /112 or shorter):
# five hex digits would be no address, and the start script would fail on it.
if source.get("ipv6") is not None and number > 0xFFFF:
warnings.append(f"runtime user '{name}': number {number} does not fit in serverSource.ipv6; no own address")
continue
taken.add(number) taken.add(number)
numbered.append( numbered.append(
{ {
+29
View File
@@ -70,6 +70,33 @@ def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
return userinfo, host, port, _qs(query) return userinfo, host, port, _qs(query)
def local_file_keys(value) -> list[str]:
"""The keys anywhere in `value` that point a backend at a local file or program.
The backends hold CAP_NET_ADMIN, and a share link is whatever a subscription serves:
xhttp's extra carries a whole streamSettings (downloadSettings), where
certificateFile is a file XRay reads and masterKeyLog one it writes. The start
script's localFileKeysJq applies the same rule to runtime JSON outbounds.
"""
found: set[str] = set()
stack = [value]
while stack:
item = stack.pop()
if isinstance(item, dict):
for key, child in item.items():
k = str(key).lower()
if (
k.endswith(("file", "directory"))
or (k.endswith("path") and k != "path")
or k in ("masterkeylog", "torrc", "extra_args")
):
found.add(k)
stack.append(child)
elif isinstance(item, list):
stack.extend(item)
return sorted(found)
def _parse_json_param(value: str, name: str) -> dict: def _parse_json_param(value: str, name: str) -> dict:
try: try:
parsed = json.loads(value) parsed = json.loads(value)
@@ -77,6 +104,8 @@ def _parse_json_param(value: str, name: str) -> dict:
raise ValueError(f"invalid {name} JSON: {exc}") from exc raise ValueError(f"invalid {name} JSON: {exc}") from exc
if not isinstance(parsed, dict): if not isinstance(parsed, dict):
raise ValueError(f"invalid {name} JSON: expected object") raise ValueError(f"invalid {name} JSON: expected object")
if unsafe := local_file_keys(parsed):
raise ValueError(f"{name} JSON names local files: {', '.join(unsafe)}")
return parsed return parsed
+24
View File
@@ -3,6 +3,7 @@
import base64 import base64
import json import json
import unittest import unittest
import urllib.parse
import proxy_parsing import proxy_parsing
from proxy_parsing import build_outbound from proxy_parsing import build_outbound
@@ -141,6 +142,29 @@ class BuildOutboundTests(unittest.TestCase):
self.assertEqual(ob["streamSettings"]["network"], "xhttp") self.assertEqual(ob["streamSettings"]["network"], "xhttp")
self.assertEqual(ob["streamSettings"]["xhttpSettings"]["path"], "/x") self.assertEqual(ob["streamSettings"]["xhttpSettings"]["path"], "/x")
def test_xray_xhttp_extra_keeps_ordinary_settings(self):
extra = json.dumps({"xPaddingBytes": "100-1000", "downloadSettings": {"address": "dl.example.com"}})
ob = run_xray_parser(
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra="
+ urllib.parse.quote(extra)
)
self.assertEqual(ob["streamSettings"]["xhttpSettings"]["extra"]["xPaddingBytes"], "100-1000")
def test_xray_xhttp_extra_cannot_name_local_files(self):
# XRay holds CAP_NET_ADMIN: a subscription must not make it write masterKeyLog or read a key.
extra = json.dumps(
{
"downloadSettings": {
"tlsSettings": {"masterKeyLog": "/etc/x", "certificates": [{"keyFile": "/root/k"}]}
}
}
)
with self.assertRaisesRegex(ValueError, "keyfile, masterkeylog"):
run_xray_parser(
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra="
+ urllib.parse.quote(extra)
)
def test_xray_vless_ech(self): def test_xray_vless_ech(self):
ob = run_xray_parser( ob = run_xray_parser(
"vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1" "vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1"
+12
View File
@@ -149,6 +149,15 @@ class RuntimeTest(unittest.TestCase):
rt.cmd_users_order(self.spec, self.spool, "alice", 12) rt.cmd_users_order(self.spec, self.spool, "alice", 12)
self.assertEqual(self.state()["users"]["alice"]["order"], 12) self.assertEqual(self.state()["users"]["alice"]["order"], 12)
def test_a_number_past_the_ipv6_group_gets_no_address(self):
# The last group holds four hex digits: 0x10000 would be no address, and the start
# script would fail on it for every listener.
spec = {"serverSource": {"ipv4": None, "ipv6": "fd78::/64", "declared": []}, "users": {}}
warnings = []
numbered = rt.number_users(spec, ["big", "ok"], {"big": {"order": 70000}, "ok": {"order": 65535}}, warnings)
self.assertEqual([(n["email"], n["ipv6"]) for n in numbered], [("ok", "fd78::ffff")])
self.assertIn("runtime user 'big': number 70000 does not fit in serverSource.ipv6", warnings[0])
def test_runtime_users_join_declared_listeners(self): def test_runtime_users_join_declared_listeners(self):
rt.cmd_users_add(self.spec, self.spool, "alice", None, ["vless-in", "awg"]) rt.cmd_users_add(self.spec, self.spool, "alice", None, ["vless-in", "awg"])
merged, result, warnings = rt.merge(self.spec) merged, result, warnings = rt.merge(self.spec)
@@ -255,6 +264,9 @@ class RuntimeTest(unittest.TestCase):
({"type": "vless", "port": 20001, "fallbacks": [{"listener": "vless-in"}]}, "must be another runtime listener"), ({"type": "vless", "port": 20001, "fallbacks": [{"listener": "vless-in"}]}, "must be another runtime listener"),
({"type": "vless", "port": 20001, "flow": "xtls-rprx-vision", "transport": {"type": "ws"}}, "flow is only valid"), ({"type": "vless", "port": 20001, "flow": "xtls-rprx-vision", "transport": {"type": "ws"}}, "flow is only valid"),
({"type": "vmess", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"]}}, "reality only for vless"), ({"type": "vmess", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"]}}, "reality only for vless"),
# XRay would take these as Unix socket paths.
({"type": "vless", "port": 20001, "address": "/run/x.sock"}, "not an IP address"),
({"type": "vless", "port": 20001, "address": "@abstract"}, "not an IP address"),
] ]
for entry, message in cases: for entry, message in cases:
with self.subTest(entry=entry), self.assertRaisesRegex(rt.RuntimeError_, message): with self.subTest(entry=entry), self.assertRaisesRegex(rt.RuntimeError_, message):