# Start script of the inbound service: renders the listeners with their secrets into the # template and runs XRay. { ctx }: let inherit (ctx) lib pkgs proxyCfg proxyInboundsCfg proxyInboundsAwg awgBin proxyInboundsNeedLocalProxy torOnionEnabled proxyInboundViaOutbounds userControlCfg userControlAllows userControlExtraGroupsFor localProxyAuth localProxyAuthEnabled localProxyAuthPasswordSource jq python3 parserScriptsPythonPath buildInboundPy buildOutboundPy proxyInboundsFile proxyInboundsSpecFile proxyInboundsSelfSources proxyInboundsRuntimeEnabled proxyInboundsManagerEnabled proxyInboundsManagerCfg proxyInboundsSpeedLimits proxySuiteScriptsDir builders constants cfg ; # A value in a shell comment, on that one line: a newline in a tag (types.str) would end # the comment and run the rest as root. oneLine = value: builtins.replaceStrings [ "\n" "\r" ] [ " " " " ] (toString value); runtimeDir = "${constants.runtimeDir}/proxy-suite-inbounds"; linksFile = "${runtimeDir}/links.json"; subscriptionsFile = "${runtimeDir}/subscriptions.json"; subsCfg = proxyInboundsCfg.subscriptions; xray = "${proxyInboundsCfg.package}/bin/xray"; # inbounds.routing.serverSource: the users' own addresses toward this host, on a dummy # interface. Reached through lo like any local address; nothing routes out from them. ip = "${pkgs.iproute2}/bin/ip"; selfInterface = lib.escapeShellArg proxyInboundsCfg.routing.serverSource.interface; selfInterfaceDown = "${ip} link del ${selfInterface} 2>/dev/null || true"; serverSource = proxyInboundsCfg.routing.serverSource; # With inbounds.runtime, runtime users may get addresses too, whatever the declared have. selfInterfaceWanted = proxyInboundsSelfSources != [ ] || (proxyInboundsRuntimeEnabled && (serverSource.ipv4 != null || serverSource.ipv6 != null)); selfInterfaceUp = lib.optionalString selfInterfaceWanted '' ${selfInterfaceDown} ${ip} link add ${selfInterface} type dummy ${ip} link set ${selfInterface} up ${lib.concatMapStrings ( s: lib.optionalString (s.ipv4 != null) "${ip} addr add ${s.ipv4}/32 dev ${selfInterface}\n" + lib.optionalString (s.ipv6 != null) "${ip} -6 addr add ${s.ipv6}/128 dev ${selfInterface} nodad\n" ) proxyInboundsSelfSources} ${lib.optionalString proxyInboundsRuntimeEnabled '' while IFS=$'\t' read -r family address; do case "$family" in 4) ${ip} addr add "$address/32" dev ${selfInterface} ;; 6) ${ip} -6 addr add "$address/128" dev ${selfInterface} nodad ;; esac done < <(${jq} -r '.selfAddresses[]? | (select(.ipv4) | "4\t\(.ipv4)"), (select(.ipv6) | "6\t\(.ipv6)")' <<< "$RENDERED") ''} ''; # Only listeners, and for AmneziaWG listeners transparent sockets (IP_TRANSPARENT). runXray = constants.runAsServiceUser pkgs ( [ "net_bind_service" ] ++ lib.optional (proxyInboundsAwg != [ ]) "net_admin" ); needsLocalProxyAuth = proxyInboundsNeedLocalProxy && localProxyAuthEnabled; serverAddressBlock = if proxyInboundsCfg.serverAddress != null then "SERVER_ADDRESS=${lib.escapeShellArg proxyInboundsCfg.serverAddress}" else if proxyInboundsCfg.shareLinks then '' ${builders.mkDefaultUplinkIPv4Source { ip = "${pkgs.iproute2}/bin/ip"; awk = "${pkgs.gawk}/bin/awk"; errorMessage = "proxy-suite: could not determine this host's uplink address for inbound share links; set inbounds.serverAddress"; }} SERVER_ADDRESS="$uplink_addr" '' else ''SERVER_ADDRESS=""''; # The onion service's address, for its share links. Tor writes it as it starts; a Tor # that is not up in time costs only the onion links, until the next restart. onionAddressBlock = if torOnionEnabled && proxyInboundsCfg.shareLinks then '' ONION_ADDRESS="" onion_hostname=${lib.escapeShellArg constants.torOnionHostnameFile} for _ in $(${pkgs.coreutils}/bin/seq 30); do [ -s "$onion_hostname" ] && break ${pkgs.coreutils}/bin/sleep 1 done if [ -s "$onion_hostname" ]; then ONION_ADDRESS=$(${pkgs.coreutils}/bin/tr -d '[:space:]' < "$onion_hostname") else echo "proxy-suite: proxy-suite-tor has not written $onion_hostname; no onion share links until a restart" >&2 fi '' else ''ONION_ADDRESS=""''; # Outbounds pinned with `via = ""`, rendered at start so urlFile contents stay # out of the store. mkViaOutboundBlock = ob: let # A chained one dials through its hop, which the chain put in this config too. dialerBlock = lib.optionalString (ob.detour != null) '' OB_JSON=$(${jq} -c --arg hop ${lib.escapeShellArg ob.detour} '.streamSettings.sockopt.dialerProxy = $hop' <<< "$OB_JSON") ''; urlSource = if ob.urlFile != null then ob.urlFile else if ob.url != null then pkgs.writeText "proxy-suite-inbounds" ob.url else null; in if urlSource == null then '' # via outbound: ${oneLine ob.tag} (static xray json) OB_JSON=$(cat ${ pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON (ob.xrayJson // { inherit (ob) tag; })) }) ${dialerBlock} OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON") '' else '' # via outbound: ${oneLine ob.tag} URL=$(cat ${lib.escapeShellArg urlSource}) OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \ --backend xray --tag ${lib.escapeShellArg ob.tag}) ${dialerBlock} OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON") ''; viaOutboundsBlock = lib.concatMapStrings mkViaOutboundBlock proxyInboundViaOutbounds; writeLinksBlock = lib.optionalString proxyInboundsCfg.shareLinks '' ${jq} -c '.links' <<< "$RENDERED" > "${linksFile}" ${lib.optionalString (userControlAllows "secrets") '' ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${linksFile}" ''} chmod ${if userControlAllows "secrets" then "640" else "600"} "${linksFile}" ${constants.grantFileAcl pkgs ''"${linksFile}"'' (userControlExtraGroupsFor "secrets") "r"} ''; # One file per user for the web server, plus a token index for proxy-ctl. Filled aside # and swapped in whole; a missing group leaves them root-only. writeSubscriptionsBlock = lib.optionalString (proxyInboundsCfg.shareLinks && subsCfg.enable) '' SUB_DIR="${runtimeDir}/subscriptions" rm -rf "$SUB_DIR.new" mkdir -m 0750 "$SUB_DIR.new" ${jq} -r '.subscriptions[] | "\(.token)\t\(.body)"' <<< "$RENDERED" | while IFS=$'\t' read -r token body; do printf '%s' "$body" > "$SUB_DIR.new/$token" done chmod -R u=rwX,g=rX,o= "$SUB_DIR.new" # Traverse-only for the group: the web server opens a token by name but can never # list them all (autoindex, a stray directory listing). chmod 0710 "$SUB_DIR.new" ${constants.ifPrivileged '' ${pkgs.coreutils}/bin/chgrp -R ${lib.escapeShellArg subsCfg.group} "$SUB_DIR.new" || echo "proxy-suite: group "${lib.escapeShellArg subsCfg.group}" cannot be given the subscriptions; they stay root-only" >&2''} rm -rf "$SUB_DIR" mv "$SUB_DIR.new" "$SUB_DIR" ${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}" ${lib.optionalString (userControlAllows "secrets") '' ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${subscriptionsFile}" ''} chmod ${if userControlAllows "secrets" then "640" else "600"} "${subscriptionsFile}" ${constants.grantFileAcl pkgs ''"${subscriptionsFile}"'' (userControlExtraGroupsFor "secrets") "r"} ''; startInbounds = pkgs.writeShellScript "proxy-suite-inbounds" '' set -euo pipefail umask 077 RUNTIME_DIR="${runtimeDir}" mkdir -p "$RUNTIME_DIR" ${serverAddressBlock} ${onionAddressBlock} RENDERED=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildInboundPy} \ --spec ${proxyInboundsSpecFile} \ --server-address "$SERVER_ADDRESS" \ --onion-address "$ONION_ADDRESS"${lib.optionalString proxyInboundsRuntimeEnabled " \\\n --template ${proxyInboundsFile}"}) # What runs, and from what: inbound_apply.py renders again with these and changes the # difference through XRay's API instead of restarting. printf '%s' "$RENDERED" > "$RUNTIME_DIR/rendered.json" ${jq} -n --arg server "$SERVER_ADDRESS" --arg onion "$ONION_ADDRESS" \ '{serverAddress: $server, onionAddress: $onion}' > "$RUNTIME_DIR/render-args.json" INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED") # Every address this host has now, for the direct outbound's fence (rules/proxy-inbounds.nix): # one it gains later is fenced from the next start. Where netlink is closed (Android), the # fence keeps what the configuration knows. if ! HOST_ADDRESSES=$(${ip} -j addr show | ${jq} -c '[.[].addr_info[]?.local | strings] | unique'); then echo "proxy-suite: cannot list this host's addresses; direct reaches any port of those not configured" >&2 HOST_ADDRESSES='[]' fi OUTBOUNDS_JSON='[]' ${viaOutboundsBlock} ${lib.optionalString needsLocalProxyAuth '' LOCAL_PROXY_PASSWORD="$(cat ${lib.escapeShellArg localProxyAuthPasswordSource})" ''} # With inbounds.runtime, the routing rules are build-inbound.py's: the template's with the # runtime listeners and users in. Their serverSource outbounds come with them. ${jq} \ --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 "''"} \ ${ if needsLocalProxyAuth then "--rawfile password <(printf '%s' \"$LOCAL_PROXY_PASSWORD\")" else "--arg password ''" } \ --argjson runtime ${if proxyInboundsRuntimeEnabled then "true" else "false"} \ --argjson exit_mark ${ if proxyInboundsSpeedLimits then toString constants.inboundExitMark else "null" } \ --slurpfile rendered <(printf '%s' "$RENDERED") \ --argjson host_addresses "$HOST_ADDRESSES" \ '.inbounds += $ibs[0] | (.outbounds[] | select(.tag == "direct") | .settings.finalRules[] | select(._hostAddresses)) |= (.ip += ($host_addresses - .ip) | del(._hostAddresses)) | .outbounds = $obs[0] + .outbounds # A via outbound that is freedom too (xrayJson, say, for its fragment settings) # dials from this host as "direct" does: the same fence, ahead of its own rules; # all of it but the closing allow of "direct", which would end them. | ([.outbounds[] | select(.tag == "direct") | .settings.finalRules // []] | first // []) as $fence | (.outbounds[] | select(.protocol == "freedom" and .tag != "direct" and ((.tag // "") | startswith("direct-self") | not))) |= (.settings = ((.settings // {}) | .finalRules = (($fence | map(select(. != {action: "allow"}))) + (.finalRules // [])))) | if $runtime then .routing.rules = $rendered[0].rules | .outbounds += $rendered[0].selfOutbounds else . end | if $auth_enabled then (.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users) = [{user:$user,pass:$password}] else . end # Speed limits: every exit marks the sockets of a limited user with their level (the # XRay patch), for nftables. Not the serverSource outbounds, nor one marked already. | if $exit_mark != null then (.outbounds[] | select(.protocol != "blackhole" and .tag != "api" and ((.tag // "") | startswith("direct-self") | not))) |= (.streamSettings.sockopt.mark //= $exit_mark) else . end' \ ${proxyInboundsFile} > "$RUNTIME_DIR/config.json.tmp" # XRay runs as ${constants.serviceUser}. A certificate or key it cannot read (an ACME # key, say) is copied in, which means a renewal needs a restart; give the user read # access to keep XRay's own reload. CERT_DIR="$RUNTIME_DIR/tls" rm -rf "$CERT_DIR" index=0 while IFS= read -r source; do [ -n "$source" ] || continue if ! ${runXray} ${pkgs.coreutils}/bin/test -r "$source"; then [ -d "$CERT_DIR" ] || install -d -m 0750 ${constants.ifPrivileged "-g ${constants.serviceUser} "}"$CERT_DIR" index=$((index + 1)) copy="$CERT_DIR/$index-$(basename "$source")" install -m 0640 ${constants.ifPrivileged "-g ${constants.serviceUser} "}"$source" "$copy" echo "proxy-suite: ${constants.serviceUser} cannot read $source; XRay uses a copy until the next restart" >&2 ${jq} --arg from "$source" --arg to "$copy" ' (.inbounds[].streamSettings.tlsSettings.certificates[]? | (.certificateFile, .keyFile) | select(. == $from)) = $to ' "$RUNTIME_DIR/config.json.tmp" > "$RUNTIME_DIR/config.json.next" mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json.tmp" fi done < <(${jq} -r '[.inbounds[].streamSettings.tlsSettings.certificates[]? | (.certificateFile, .keyFile) | strings] | unique[]' "$RUNTIME_DIR/config.json.tmp") # Read by XRay as ${constants.serviceUser}, and by the userControl group: the daemon # as owner then, since a file has one group. ${ if userControlAllows "secrets" then '' ${pkgs.coreutils}/bin/chown ${constants.serviceUser}:${lib.escapeShellArg userControlCfg.group} "$RUNTIME_DIR/config.json.tmp" chmod 440 "$RUNTIME_DIR/config.json.tmp" '' else '' ${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp"''} # Without root the group is the user's own primary one, which may be shared. chmod ${if constants.privileged then "640" else "600"} "$RUNTIME_DIR/config.json.tmp" '' } ${constants.grantFileAcl pkgs ''"$RUNTIME_DIR/config.json.tmp"'' (userControlExtraGroupsFor "secrets") "r" } mv "$RUNTIME_DIR/config.json.tmp" "$RUNTIME_DIR/config.json" # The stats API's socket: the daemon's and root's alone. Whoever reaches it can reset the # counters, wiping per-user traffic before the collector adds it up; the stats scope # reads the collector's file instead. API_DIR=$(dirname ${lib.escapeShellArg constants.inboundStatsApiSocket}) rm -rf "$API_DIR" ${ if !constants.privileged then ''mkdir -m 0700 "$API_DIR"'' else ''install -d -m 0700 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"'' } ${writeLinksBlock} ${writeSubscriptionsBlock} ${selfInterfaceUp} exec ${runXray} ${xray} run -c "$RUNTIME_DIR/config.json" ''; # Adds XRay's counters to the daily totals, read and reset in one call, and notes who # is online: .online, for `proxy-ctl inbounds online` without the API. Run by a timer, # and by the inbounds' ExecStop, so a restart loses nothing. collectInboundStats = pkgs.writeShellScript "proxy-suite-inbounds" '' set -euo pipefail file=${lib.escapeShellArg constants.inboundStatsFile} api=--server=unix://${constants.inboundStatsApiSocket} # A timer run and a stop can overlap: each reads and resets part, and both rewrite the file. exec 9> "$file.lock" ${pkgs.util-linux}/bin/flock 9 if ! reading=$(${xray} api statsquery "$api" -pattern "" -reset 2> /dev/null); then echo "the inbounds' stats API is not answering; nothing collected" exit 0 fi [ -n "$reading" ] || reading='{}' online=$(${xray} api statsonlineiplist "$api" -all 2> /dev/null) || online="" [ -n "$online" ] || online='{}' ${ if proxyInboundsAwg != [ ] then '' awg=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${parserScriptsPythonPath}/awg_inbound.py peers \ --spec ${proxyInboundsSpecFile} --awg ${awgBin}) || awg='[]' '' else "awg='[]'" } [ -s "$file" ] || echo '{}' > "$file" tmp=$(${pkgs.coreutils}/bin/mktemp "$file.XXXXXX") # Slurped, not --argjson: one argument holds at most 128 KiB, which a few hundred users' # counters outgrow, and the reading above already reset them. ${jq} --slurpfile q_ <(printf '%s' "$reading") --slurpfile online_ <(printf '%s' "$online") \ --slurpfile awg_ <(printf '%s' "$awg") \ --arg day "$(${pkgs.coreutils}/bin/date +%F)" \ --argjson now "$(${pkgs.coreutils}/bin/date +%s)" \ "\$q_[0] as \$q | \$online_[0] as \$online | \$awg_[0] as \$awg | $(< ${ builtins.path { name = "proxy-suite-inbounds"; path = ../inbound-stats-add.jq; } }) | .online = (\$online.users // [])" "$file" > "$tmp" ${lib.optionalString (userControlAllows "stats") '' ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$tmp" || echo "proxy-suite: group "${lib.escapeShellArg userControlCfg.group}" cannot read the stats; they stay root-only" >&2 ''} chmod ${if userControlAllows "stats" then "640" else "600"} "$tmp" ${constants.grantFileAcl pkgs ''"$tmp"'' (userControlExtraGroupsFor "stats") "r"} mv -f "$tmp" "$file" ''; # inbounds.runtime: after proxy-ctl changes the spool. The AmneziaWG interfaces only when # their peers changed: restarting them cuts off every one of their clients for a moment. # Users through XRay's API and AmneziaWG peers through `awg syncconf`, so the others keep # their connections; a restart only for what those cannot change (inbound_apply.py). reloadInbounds = pkgs.writeShellScript "proxy-suite-inbounds" '' set -euo pipefail PYTHONPATH="${parserScriptsPythonPath}" exec ${python3} ${parserScriptsPythonPath}/inbound_apply.py \ --config ${applyConfigFile} --spec ${proxyInboundsSpecFile} ''; # The links and subscriptions of a rendering saved by the start script, written as it # writes them: for inbound_apply.py, after users changed without a restart. writeInboundOutputs = pkgs.writeShellScript "proxy-suite-inbounds" '' set -euo pipefail umask 077 RENDERED=$(cat "$1") ${writeLinksBlock} ${writeSubscriptionsBlock} ''; # What inbound_apply.py works with: the binaries, units and names it may touch. applyConfig = { inherit runtimeDir; unit = "proxy-suite-inbounds.service"; template = "${proxyInboundsFile}"; inherit xray; api = "unix://${constants.inboundStatsApiSocket}"; ip = "${pkgs.iproute2}/bin/ip"; selfInterface = if selfInterfaceWanted then proxyInboundsCfg.routing.serverSource.interface else null; outputsScript = "${writeInboundOutputs}"; inherit (constants) systemctl; tmpDir = runtimeDir; env = lib.optionalAttrs (cfg.geodata.xray.assets != null) { XRAY_LOCATION_ASSET = "${cfg.geodata.xray.assets}/share/v2ray"; }; } # Killing a cut user's sockets, and the table their UDP is dropped in, take root. // lib.optionalAttrs constants.privileged { ss = "${pkgs.iproute2}/bin/ss"; } // lib.optionalAttrs (constants.privileged && proxyInboundsManagerEnabled) { nft = "${pkgs.nftables}/bin/nft"; nftTable = constants.inboundLimitsTable; } // lib.optionalAttrs (proxyInboundsAwg != [ ]) { awg = awgBin; awgRuntimeDir = "${constants.runtimeDir}/proxy-suite-inbounds-awg"; awgUnit = "proxy-suite-inbounds-awg.service"; }; applyConfigFile = pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON applyConfig); # The manager's own: where it keeps things, what it serves, whom it tells. mgr = proxyInboundsManagerCfg; managerApiGroup = if mgr.api.group != null then mgr.api.group else if userControlAllows "inbounds" then userControlCfg.group else null; managerConfig = { apply = applyConfig; policyFile = "${constants.inboundsManagerDir}/policy.json"; stateFile = "${constants.inboundsManagerDir}/state.json"; statsFile = constants.inboundStatsFile; collector = "${collectInboundStats}"; inherit (mgr) interval webhooks notify deleteExpiredAfter ; api = { socket = constants.inboundsManagerApiSocket; group = managerApiGroup; mode = if managerApiGroup == null then "0600" else "0660"; inherit (mgr.api) listen tokensFile; }; subscriptions = { socket = if mgr.subscriptions.enable then constants.inboundsManagerSubSocket else null; inherit (mgr.subscriptions) group listen profileTitle updateInterval supportUrl webPageUrl ; inherit (subsCfg) baseUrl; }; ipLimit.banSeconds = mgr.ipLimit.banTime; speedLimits = proxyInboundsSpeedLimits; inherit (mgr.speedLimits) slots; nft = if constants.privileged then "${pkgs.nftables}/bin/nft" else null; }; managerConfigFile = pkgs.writeText "proxy-suite-inbounds-manager" (builtins.toJSON managerConfig); runManager = pkgs.writeShellScript "proxy-suite-inbounds-manager" '' set -euo pipefail umask 077 mkdir -p ${lib.escapeShellArg constants.inboundsManagerDir} export PYTHONPATH=${proxySuiteScriptsDir} exec ${python3} ${proxySuiteScriptsDir}/inbound_manager.py \ --config ${managerConfigFile} --spec ${proxyInboundsSpecFile} serve ''; stopInboundsInterface = if !selfInterfaceWanted then null else pkgs.writeShellScript "proxy-suite-inbounds" selfInterfaceDown; in { inherit startInbounds stopInboundsInterface collectInboundStats reloadInbounds runManager linksFile subscriptionsFile ; }