fix: hardening
This commit is contained in:
19 files changed
+486
-119
No files matched your search
@@ -583,7 +583,9 @@ let
|
||||
echo "proxy-suite: $1 is not a regular file" >&2
|
||||
return 1
|
||||
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" ;;
|
||||
esac
|
||||
|
||||
@@ -76,6 +76,12 @@ types.submodule {
|
||||
type = types.nullOr types.int;
|
||||
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;
|
||||
serviceConfig = section;
|
||||
timerConfig = section;
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
# 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
|
||||
# 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
|
||||
# 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)),
|
||||
top: $top,
|
||||
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"]}
|
||||
@@ -221,6 +221,14 @@ let
|
||||
cfg.inbounds.routing.serverSource.ipv6 == null
|
||||
|| 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")
|
||||
# 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
|
||||
(
|
||||
(
|
||||
|
||||
@@ -332,6 +332,16 @@ lib.mkMerge [
|
||||
+ " anyone who reaches the port uses your outbounds; set listener.auth, or keep it off the"
|
||||
+ " firewall's allowed ports"
|
||||
)
|
||||
# The prober and proxy-ctl's outbound test dial these without credentials.
|
||||
++
|
||||
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
|
||||
# unresolved, or where IP aliases catch a name that resolves here first.
|
||||
++
|
||||
|
||||
@@ -29,6 +29,10 @@ let
|
||||
pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
set -euo pipefail
|
||||
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"
|
||||
mark_comment="$rule_comment_prefix-mark"
|
||||
cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service"
|
||||
@@ -37,7 +41,11 @@ let
|
||||
exit 1
|
||||
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
|
||||
echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2
|
||||
exit 1
|
||||
|
||||
@@ -71,10 +71,15 @@ let
|
||||
};
|
||||
in
|
||||
{
|
||||
# One nft transaction swaps the old table for the new: traffic never sees neither. Also the
|
||||
# unit's reload, which a switch runs instead of a restart (units.nix).
|
||||
killSwitchUpScript = pkgs.writeShellScript "proxy-suite-routing" ''
|
||||
set -euo pipefail
|
||||
${deleteKillSwitchTable}
|
||||
${nft} -f ${killSwitchRulesFile}
|
||||
${nft} -f - <<'EOF'
|
||||
add table inet proxy_suite_killswitch
|
||||
delete table inet proxy_suite_killswitch
|
||||
include "${killSwitchRulesFile}"
|
||||
EOF
|
||||
'';
|
||||
|
||||
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.
|
||||
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).
|
||||
xrayDomainStrategies = {
|
||||
prefer_ipv4 = "UseIPv4v6";
|
||||
@@ -148,6 +159,12 @@ let
|
||||
# only known at runtime (an AmneziaWG outbound added with proxy-ctl).
|
||||
_proxy_suite_add_socks_hop() {
|
||||
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" ${
|
||||
lib.escapeShellArg (
|
||||
if pureXrayEnabled then
|
||||
@@ -218,8 +235,19 @@ let
|
||||
|
||||
# $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
|
||||
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
|
||||
# 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")
|
||||
${jsonAddBlock}
|
||||
_proxy_suite_record_tag_source "$tag" "$source"
|
||||
@@ -599,6 +627,14 @@ let
|
||||
[ -e "$GROUP_FILE" ] || continue
|
||||
GROUP_NAME="''${GROUP_FILE##*/}"
|
||||
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
|
||||
echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': proxy.groups declares it" >&2
|
||||
continue
|
||||
@@ -608,7 +644,8 @@ let
|
||||
strategy: (.strategy // "failover"), failback: (.failback != false), interval: (.interval // null),
|
||||
runtime: true}
|
||||
| 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
|
||||
continue
|
||||
fi
|
||||
@@ -632,21 +669,29 @@ let
|
||||
fi
|
||||
''}
|
||||
# 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
|
||||
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
|
||||
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
|
||||
if ${jq} -e '.errors != []' <<< "$GROUPS_RESULT" >/dev/null; then
|
||||
${jq} -r '.errors[] | "proxy-suite: " + .' <<< "$GROUPS_RESULT" >&2
|
||||
@@ -854,4 +899,6 @@ in
|
||||
inherit mkOutboundScript rawOutboundJson;
|
||||
# For the checks: groups, and which outbounds a pin and selection may take.
|
||||
selectionBlocks = tagsBlock + groupsBlock + pinBlock + selectableBlock + inventoryBlock;
|
||||
# And what the runtime spool is read into.
|
||||
runtimeOutboundBlocks = mkUrlOutboundHelpersBlock null + runtimeOutboundsBlock;
|
||||
}
|
||||
@@ -69,6 +69,21 @@ let
|
||||
|
||||
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.
|
||||
xrayAssetEnv = lib.optionalAttrs (geodata.xray.assets != null) {
|
||||
Environment = [ "XRAY_LOCATION_ASSET=${geodata.xray.assets}/share/v2ray" ];
|
||||
@@ -96,7 +111,7 @@ let
|
||||
execStart = scripts.startSocks;
|
||||
runtimeDirectory = serviceNames.socks;
|
||||
stateDirectory = "proxy-suite";
|
||||
extraServiceConfig = xrayAssetEnv;
|
||||
extraServiceConfig = xrayAssetEnv // spoolReaderSandbox [ ];
|
||||
};
|
||||
}
|
||||
{
|
||||
@@ -158,16 +173,23 @@ let
|
||||
{
|
||||
enable = killSwitchEnabled;
|
||||
name = serviceNames.killSwitch;
|
||||
value = mkOneshotService {
|
||||
description = "proxy-suite kill switch - reject traffic outside the global tunnel";
|
||||
after = [
|
||||
"${serviceNames.socks}.service"
|
||||
"${serviceNames.tun}.service"
|
||||
]
|
||||
++ map (name: "proxy-suite-awg-${name}.service") (builtins.attrNames awgGlobalProfiles);
|
||||
execStart = killSwitchUpScript;
|
||||
execStop = killSwitchDownScript;
|
||||
};
|
||||
value =
|
||||
mkOneshotService {
|
||||
description = "proxy-suite kill switch - reject traffic outside the global tunnel";
|
||||
after = [
|
||||
"${serviceNames.socks}.service"
|
||||
"${serviceNames.tun}.service"
|
||||
]
|
||||
++ map (name: "proxy-suite-awg-${name}.service") (builtins.attrNames awgGlobalProfiles);
|
||||
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;
|
||||
@@ -283,7 +305,10 @@ let
|
||||
execStart = scripts.subscriptionUpdateScript;
|
||||
stateDirectory = "proxy-suite";
|
||||
# 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";
|
||||
execStart = "${scripts.pinOutboundScript} %I";
|
||||
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";
|
||||
execStart = "${scripts.pinOutboundScript}";
|
||||
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";
|
||||
execStart = scripts.reloadOutboundsScript;
|
||||
stateDirectory = "proxy-suite";
|
||||
extraServiceConfig.RemainAfterExit = false;
|
||||
extraServiceConfig = {
|
||||
RemainAfterExit = false;
|
||||
}
|
||||
// spoolReaderSandbox [ ];
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
Reference in new issue
Block a user