feat: add connectivity fix options + hardening
This commit is contained in:
41 files changed
+626
-111
No files matched your search
@@ -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" ];
|
||||
|
||||
Reference in new issue
Block a user