diff --git a/README.md b/README.md index dd80e66..a5c8cbc 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ Inspired by [Throne](https://github.com/throneproj/Throne) (formerly NekoRay), [ - AmneziaWG 1.x–3.x tunnels from `.conf`, `vpn://`, or Nix - Telegram MTProto WebSocket proxy and SSH SOCKS5 tunnel - Cloudflare WARP from a `wgcf` profile, as an outbound or an AWG VPN profile +- Tor as an outbound, with `.onion` names routed to it automatically, bridges (obfs4, webtunnel, meek, snowflake), and an onion service in front of the server inbounds - Server inbounds (XRay protocols and multi-user AmneziaWG) with share links, QR codes, per-user subscriptions and traffic stats - Proxy Suite GUI (a desktop app with a tray icon), the `proxy-ctl` CLI, and the `proxy-tui` terminal UI @@ -97,6 +98,14 @@ services.proxy-suite = { # asAmneziaWg = true; # or a global profile instead: proxy-ctl awg on warp }; + # An outbound tagged "tor" for routing.rules; .onion names always go to it. + tor = { + enable = true; + asOutbound = true; + # bridges.file = "/run/secrets/tor-bridges"; # one obfs4/webtunnel/snowflake line each + # upstream = "proxy"; # reach Tor through the local proxy + }; + tgWsProxy = { enable = true; secretFile = "/run/secrets/tg-ws-proxy-secret"; @@ -116,7 +125,7 @@ The same options work outside NixOS. Pick the module for the host; everything th | Local SOCKS/HTTP proxy, subscriptions, selection, route modes | ✓ | ✓ | ✓ | ✓ | | Per-app proxychains | ✓ | ✓ | ✓ | ✓ | | Server inbounds, share links, stats | ✓ | ✓ | ports ≥ 1024 | ports ≥ 1024 | -| tg-ws-proxy, SSH proxy, WARP as a sing-box outbound | ✓ | ✓ | ✓ | ✓ | +| tg-ws-proxy, SSH proxy, WARP as a sing-box outbound, Tor | ✓ | ✓ | ✓ | ✓ | | AmneziaWG `asOutbound = "userspace"` | ✓ | ✓ | ✓ | ✓ | | Global TUN/TProxy, per-app TUN/TProxy/zapret, zapret, AmneziaWG interfaces and inbounds | ✓ | ✓ | ✗ | ✗ | | `userControl`, polkit | ✓ | ✓ | not needed | not needed | @@ -224,14 +233,17 @@ Secrets and changes need root, or the userControl group. ssh [status|on|off] SSH SOCKS5 tunnel warp [status|on|off] WARP tunnel behind the warp outbound + tor [status|on|off] Tor, behind the tor outbound and the onion service + tor newnym new circuits for new connections tg [status|on|off] Telegram WebSocket proxy apps [list] per-app routing profiles apps run -- [args] run a command through a profile inbounds [list] server inbounds - inbounds link [user] [--qr|--json] - client share link, or the client's outbound JSON + inbounds link [user] [--onion] [--qr|--json] + client share link, or the client's outbound JSON; + --onion: the one through the onion service inbounds link [user] --config [--qr] an AmneziaWG client's .conf, or its QR code inbounds link --server-json the server's inbound JSON diff --git a/deploy/server-module.nix b/deploy/server-module.nix index c646982..648487a 100644 --- a/deploy/server-module.nix +++ b/deploy/server-module.nix @@ -149,6 +149,16 @@ in example = "/3f9a1c07b2e4"; }; + onion.enable = mkOption { + type = types.bool; + default = false; + description = '' + Also serve the listeners as a Tor onion service, for clients that cannot reach + publicAddress. Its address is kept in /var/lib/proxy-suite/tor/onion; the links + to it come from `proxy-ctl inbounds link --onion`. + ''; + }; + ports = { reality = mkOption { type = types.port; @@ -261,6 +271,10 @@ in services.proxy-suite = { enable = true; proxy.enable = false; + tor = lib.mkIf cfg.onion.enable { + enable = true; + onionService.enable = true; + }; userControl = { enable = true; group = "wheel"; @@ -309,6 +323,9 @@ in proxy-suite server ''${certName}. Share links (as ''${cfg.adminUser}): proxy-ctl inbounds link vless-reality --qr (or vless-tls, vless-ws) + '' + + lib.optionalString cfg.onion.enable " proxy-ctl inbounds link vless-reality --onion --qr (through Tor)\n" + + '' Network down? Log in and run: sudo proxy-suite-net ''; diff --git a/docs/options/index.md b/docs/options/index.md index 7cd1d49..034eaf3 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -14,6 +14,7 @@ Update the module option docs there instead of editing these files by hand. - [proxy](./proxy.md) - [sshProxy](./sshProxy.md) - [tgWsProxy](./tgWsProxy.md) +- [tor](./tor.md) - [tui](./tui.md) - [userControl](./userControl.md) - [warp](./warp.md) @@ -256,6 +257,27 @@ services.proxy-suite = { secret = null; secretFile = null; }; + tor = { + asOutbound = false; + bridges = { + file = null; + lines = [ ]; + }; + clientOnly = true; + enable = false; + extraConfig = ""; + lyrebirdPackage = pkgs.lyrebird; + onionService = { + enable = false; + listeners = null; + secretKeyFile = null; + }; + package = pkgs.tor; + routeOnion = true; + snowflakePackage = pkgs.snowflake; + socksPort = 18530; + upstream = "direct"; + }; tui = { enable = true; }; diff --git a/docs/options/tor.md b/docs/options/tor.md new file mode 100644 index 0000000..0077982 --- /dev/null +++ b/docs/options/tor.md @@ -0,0 +1,302 @@ +# services.proxy-suite.tor + +Part of the [proxy-suite options reference](./index.md). + +## Options + +- tor + - [enable](#services-proxy-suite-tor-enable) + - [package](#services-proxy-suite-tor-package) + - [asOutbound](#services-proxy-suite-tor-asoutbound) + - bridges + - [file](#services-proxy-suite-tor-bridges-file) + - [lines](#services-proxy-suite-tor-bridges-lines) + - [clientOnly](#services-proxy-suite-tor-clientonly) + - [extraConfig](#services-proxy-suite-tor-extraconfig) + - [lyrebirdPackage](#services-proxy-suite-tor-lyrebirdpackage) + - onionService + - [enable](#services-proxy-suite-tor-onionservice-enable) + - [listeners](#services-proxy-suite-tor-onionservice-listeners) + - [secretKeyFile](#services-proxy-suite-tor-onionservice-secretkeyfile) + - [routeOnion](#services-proxy-suite-tor-routeonion) + - [snowflakePackage](#services-proxy-suite-tor-snowflakepackage) + - [socksPort](#services-proxy-suite-tor-socksport) + - [upstream](#services-proxy-suite-tor-upstream) + + +## services\.proxy-suite\.tor\.enable + +Whether to enable the Tor daemon (proxy-suite-tor)\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.tor\.package + +Tor package\. + +*Type:* +package + +*Default:* + +```nix +pkgs.tor +``` + + +## services\.proxy-suite\.tor\.asOutbound + +Add Tor as an outbound tagged “tor”: a SOCKS hop to proxy-suite-tor on 127\.0\.0\.1:socksPort, +which receives names unresolved\. proxy\.selection and autoProxy leave it alone unless it is the +only outbound; route to it with proxy\.routing\.rules or name it as a detour\. Requires proxy\.enable\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + + +## services\.proxy-suite\.tor\.bridges\.file + +Runtime path to more bridge lines, one per line; blank lines and \# comments are skipped\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/tor-bridges" +``` + + +## services\.proxy-suite\.tor\.bridges\.lines + +Bridge lines, as https://bridges\.torproject\.org hands them out, without the leading +“Bridge”\. Any given turns on UseBridges; obfs4, webtunnel, meek_lite and snowflake +transports are run as needed\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "obfs4 192.0.2.1:443 0123456789ABCDEF0123456789ABCDEF01234567 cert=... iat-mode=0" +] +``` + + +## services\.proxy-suite\.tor\.clientOnly + +Keep Tor a client (ClientOnly 1): never a relay, exit, bridge or directory server, even when +extraConfig sets an ORPort\. The onion service works either way\. Turn off only to run a relay +through extraConfig\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.tor\.extraConfig + +Lines appended to the generated torrc\. + +*Type:* +strings concatenated with “\\n” + +*Default:* + +```nix +"" +``` + +*Example:* + +```nix +'' + ExitNodes {de},{nl} + StrictNodes 1 +'' +``` + + +## services\.proxy-suite\.tor\.lyrebirdPackage + +Pluggable transport for obfs4, webtunnel and meek_lite bridges\. + +*Type:* +package + +*Default:* + +```nix +pkgs.lyrebird +``` + + +## services\.proxy-suite\.tor\.onionService\.enable + +Whether to enable an onion service in front of inbounds\.listeners\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.tor\.onionService\.listeners + +inbounds\.listeners served at the onion address, each on its share port\. Null takes every +listener a TCP-only onion can carry: not amneziawg, h3-only xhttp or raw JSON\. + +Share links for them (` proxy-ctl inbounds link TAG --onion `, and subscriptions) dial the +\.onion address and keep the listener’s TLS and REALITY names\. Clients reach XRay from +127\.0\.0\.1, so ` proxy-ctl inbounds online ` does not list them\. + +*Type:* +null or (list of string) + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +[ + "vless-reality" +] +``` + + +## services\.proxy-suite\.tor\.onionService\.secretKeyFile + +Runtime path to an hs_ed25519_secret_key, to keep an onion address\. Null lets Tor create +one in /var/lib/proxy-suite/tor/onion\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/tor-hs_ed25519_secret_key" +``` + + +## services\.proxy-suite\.tor\.routeOnion + +Send \.onion names to the “tor” outbound in every route mode, and keep them away from DNS: +in TUN and TProxy modes sing-box answers them with a fake address it maps back to the name, +and XRay drops the lookup\. Inbound clients’ \.onion names go the same way, through the local +proxy, whatever their listener’s via (except “block”)\. Applies with asOutbound\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.tor\.snowflakePackage + +Pluggable transport for snowflake bridges\. + +*Type:* +package + +*Default:* + +```nix +pkgs.snowflake +``` + + +## services\.proxy-suite\.tor\.socksPort + +Loopback SOCKS port of proxy-suite-tor, which the tor outbound dials\. + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + +*Default:* + +```nix +18530 +``` + + +## services\.proxy-suite\.tor\.upstream + +How Tor reaches its relays or bridges\. + + - “direct”: from the uplink, past TUN and TProxy (it runs as proxy-suite-daemon)\. + - “proxy”: through the local proxy listener (proxy\.listener, with its auth), for a network + that blocks Tor\. obfs4, webtunnel and meek_lite bridges follow it; snowflake cannot\. + +*Type:* +one of “direct”, “proxy” + +*Default:* + +```nix +"direct" +``` diff --git a/docs/options/userControl.md b/docs/options/userControl.md index 4b611cd..e9a91a3 100644 --- a/docs/options/userControl.md +++ b/docs/options/userControl.md @@ -48,7 +48,7 @@ string matching the pattern ^\[a-z_]\[a-z0-9_-]\*$ What userControl\.group may do; empty allows every scope\. - - “services”: turn the proxy-suite units on and off (proxy, tun, tproxy, zapret, ssh, warp, tg, awg, inbounds), and ` restart `\. + - “services”: turn the proxy-suite units on and off (proxy, tun, tproxy, zapret, ssh, warp, tor, tg, awg, inbounds), ` restart `, and ` tor status|newnym ` on Tor’s control socket\. - “perApp”: the per-app backend units used by ` proxy-ctl apps run `\. - “routing”: ` proxy pin `, ` proxy unpin ` and ` proxy mode `\. - “outbounds”: add and remove runtime outbounds and subscriptions, disable and enable outbounds, and update subscriptions\. diff --git a/flake.nix b/flake.nix index 23792cd..9aee9a5 100644 --- a/flake.nix +++ b/flake.nix @@ -1,5 +1,5 @@ { - description = "NixOS proxy suite - SingBox, XRay, AmneziaWG 3.1, zapret, tg-ws-proxy"; + description = "NixOS proxy suite - SingBox, XRay, AmneziaWG 3.1, zapret, tg-ws-proxy, Tor"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; diff --git a/modules/proxy-suite/config-templates/sing-box.nix b/modules/proxy-suite/config-templates/sing-box.nix index 44428b2..d1a6e5e 100644 --- a/modules/proxy-suite/config-templates/sing-box.nix +++ b/modules/proxy-suite/config-templates/sing-box.nix @@ -38,7 +38,12 @@ let localDetour ? null, useOutboundRoutingMark ? false, fakeIp ? false, + # Inbounds whose clients look names up in sing-box: .onion ones get a fake address there. + onionFakeIpInbounds ? [ ], }: + let + onionFakeIp = derived.torRouteOnion && onionFakeIpInbounds != [ ]; + in { servers = [ (mkDnsServer "remote" proxyCfg.dns.remote "proxy") @@ -52,7 +57,7 @@ let } // lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; } ) derived.awgInterfaceOutbounds - ++ lib.optional fakeIp { + ++ lib.optional (fakeIp || onionFakeIp) { tag = "fakeip"; type = "fakeip"; inet4_range = proxyCfg.dns.fakeIp.inet4Range; @@ -61,6 +66,26 @@ let # The route mode keeps the user's rules and fake IP, and may drop what sits between. rules = proxyCfg.dns.singBox.rules + # No resolver knows .onion, and asking one leaks the name. A transparent client gets a + # fake address that routes to Tor by name; everything else is told there is no such name. + ++ lib.optionals derived.torRouteOnion ( + lib.optional onionFakeIp { + inbound = onionFakeIpInbounds; + domain_suffix = [ "onion" ]; + query_type = [ + "A" + "AAAA" + ]; + server = "fakeip"; + } + ++ [ + { + domain_suffix = [ "onion" ]; + action = "predefined"; + rcode = "NXDOMAIN"; + } + ] + ) ++ rules.singBoxDnsRules # Only what apps ask through the TUN: the XRay sidecar's and sing-box's own lookups # need real addresses. @@ -126,6 +151,9 @@ let dns = mkDnsConfig { localDetour = if forceLocalDnsViaProxy then "proxy" else null; inherit useOutboundRoutingMark fakeIp; + onionFakeIpInbounds = + lib.optional enableTun "tun-in" + ++ lib.optionals enableTProxy ([ "tproxy-in" ] ++ lib.optional proxyCfg.ipv6 "tproxy-in6"); }; inbounds = diff --git a/modules/proxy-suite/config-templates/xray.nix b/modules/proxy-suite/config-templates/xray.nix index ff1dc85..5840e12 100644 --- a/modules/proxy-suite/config-templates/xray.nix +++ b/modules/proxy-suite/config-templates/xray.nix @@ -171,12 +171,30 @@ let tag = "dns-out"; settings = { userLevel = 0; - rules = [ - { - action = "direct"; - qType = "2-27,29-65535"; - } - ]; + # No resolver knows .onion, and asking one leaks the name. The TUN's fake DNS + # answers with an address that routes to Tor by name; anything else is told there + # is no such name. + rules = + lib.optionals derived.torRouteOnion ( + lib.optional enableTunFakeDns { + action = "hijack"; + qType = "1,28"; + domain = [ "domain:onion" ]; + } + ++ [ + { + action = "return"; + rCode = 3; + domain = [ "domain:onion" ]; + } + ] + ) + ++ [ + { + action = "direct"; + qType = "2-27,29-65535"; + } + ]; }; } ]; diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 79520f8..fa98266 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -26,7 +26,7 @@ let inboundRules = import ./rules/proxy-inbounds.nix { inherit lib; - inherit (derived) proxyInboundsCfg proxyInbounds; + inherit (derived) proxyInboundsCfg proxyInbounds proxyInboundsRouteOnion; inherit (rules) zapretDirectRules; }; @@ -40,6 +40,8 @@ let proxyInboundsSpec = { serverAddress = derived.proxyInboundsCfg.serverAddress; shareLinks = derived.proxyInboundsCfg.shareLinks; + # Listeners the onion service carries, which get a second set of links to it. + onionListeners = map (ib: ib.tag) derived.torOnionInbounds; listeners = map ( ib: { diff --git a/modules/proxy-suite/core.nix b/modules/proxy-suite/core.nix index cc1c2da..604dbc0 100644 --- a/modules/proxy-suite/core.nix +++ b/modules/proxy-suite/core.nix @@ -157,6 +157,17 @@ in } )) + (lib.mkIf cfg.tor.enable ( + import ./tor.nix { + inherit + lib + pkgs + cfg + derived + ; + } + )) + (lib.mkIf (derived.proxyInboundsEnabled && derived.proxyInboundsAwg != [ ]) ( import ./amnezia-wg-inbounds.nix { inherit diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index bb0c8d9..ed4687d 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -49,6 +49,14 @@ let warpOutboundTag = "warp"; # The sing-box tunnel; "userspace" and "interface" come in through the AmneziaWG profile list. warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound == "singBox"; + torCfg = cfg.tor // { + # tor's DataDirectory; the onion service keeps its keys and hostname under it. + dataDir = "${stateDir}/tor"; + onionDir = "${stateDir}/tor/onion"; + }; + torOutboundTag = "tor"; + torOutboundEnabled = torCfg.enable && torCfg.asOutbound; + torRouteOnion = torOutboundEnabled && torCfg.routeOnion && proxyEnabled; # Two ports per "singBox" or "userspace" AmneziaWG outbound, above the autoProxy prober's own # listeners (proxy.autoProxy.probeBasePort, 18540 by default, one per exit): @@ -87,10 +95,17 @@ let via = if listener.via == null then proxyInboundsCfg.routing.via else listener.via; }) proxyInboundsCfg.listeners; + # .onion names from clients go to the local proxy, whose rule hands them to Tor, whatever + # the listener's via. AmneziaWG listeners never pass XRay's routing. + proxyInboundsRouteOnion = + torRouteOnion + && lib.any (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds; + # Whether any listener or inbounds.routing.proxy exception relays through the local SOCKS # listener. proxyInboundsNeedLocalProxy = lib.any (ib: ib.via == "proxy") proxyInbounds + || proxyInboundsRouteOnion || lib.any (field: proxyInboundsCfg.routing.proxy.${field} != [ ]) [ "domains" "ips" @@ -170,6 +185,17 @@ let # h3-only xhttp listeners are UDP-only, leaving the TCP port to a web server. proxyInboundIsH3Only = l: l.type != null && l.transport.type == "xhttp" && l.tls.enable && l.tls.alpn == [ "h3" ]; + # What an onion service can carry: TCP to a listener with a known protocol. + proxyInboundOnionCapable = + ib: ib.listener.type != null && ib.listener.type != "amneziawg" && !proxyInboundIsH3Only ib.listener; + torOnionEnabled = torCfg.enable && torCfg.onionService.enable && proxyInboundsEnabled; + torOnionInbounds = + if !torOnionEnabled then + [ ] + else if torCfg.onionService.listeners == null then + builtins.filter proxyInboundOnionCapable proxyInbounds + else + builtins.filter (ib: builtins.elem ib.tag torCfg.onionService.listeners) proxyInbounds; proxyInboundFirewallPorts = lib.unique ( map (ib: ib.listener.port) ( builtins.filter ( @@ -200,6 +226,7 @@ let outboundTags ++ lib.optional sshProxyOutboundEnabled sshProxyOutboundTag ++ lib.optional warpOutboundEnabled warpOutboundTag + ++ lib.optional torOutboundEnabled torOutboundTag ++ map (ob: ob.tag) awgOutbounds; subscriptionTags = map (sub: sub.tag) proxyCfg.subscriptions; @@ -210,6 +237,7 @@ let || hasSubscriptions || sshProxyOutboundEnabled || warpOutboundEnabled + || torOutboundEnabled || awgOutbounds != [ ]; collapseNamedOutbounds = selectionMode == "first"; # Always on with sing-box: `proxy-ctl proxy outbounds test` needs it in every selection mode. @@ -318,6 +346,10 @@ let # Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches. outboundTestPort = 18537; inboundStatsFile = "${stateDir}/inbound-stats.json"; + # Written by proxy-suite-tor as it starts, before it reaches the network. + torOnionHostnameFile = "${stateDir}/tor/onion/hostname"; + # proxy-ctl tor status|newnym. + torControlSocket = "${runtimeDir}/proxy-suite-tor/control/socket"; # sing-box DNS server resolving through an "interface" AmneziaWG outbound. awgDnsServerTag = tag: "awg-dns-${tag}"; @@ -401,6 +433,13 @@ in warpCfg warpOutboundTag warpOutboundEnabled + torCfg + torOutboundTag + torOutboundEnabled + torRouteOnion + torOnionEnabled + torOnionInbounds + proxyInboundOnionCapable awgGlobalProfiles awgOutbounds awgInterfaceOutbounds @@ -409,6 +448,7 @@ in proxyInboundsEnabled proxyInbounds proxyInboundsAwg + proxyInboundsRouteOnion proxyInboundsNeedLocalProxy proxyInboundsResolveInSingBox proxyInboundsGuardPrivate diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index 5389043..ab3171b 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -15,6 +15,7 @@ ./amnezia-wg.nix ./ssh-proxy.nix ./warp.nix + ./tor.nix ./tg-ws-proxy.nix ./geodata.nix ./gui.nix diff --git a/modules/proxy-suite/options/tor.nix b/modules/proxy-suite/options/tor.nix new file mode 100644 index 0000000..b3e508b --- /dev/null +++ b/modules/proxy-suite/options/tor.nix @@ -0,0 +1,140 @@ +{ lib, pkgs, ... }: + +let + inherit (lib) + literalExpression + mkEnableOption + mkOption + types + ; + package = + name: description: + mkOption { + type = types.package; + default = pkgs.${name}; + defaultText = literalExpression "pkgs.${name}"; + inherit description; + }; +in +{ + options.services.proxy-suite.tor = { + enable = mkEnableOption "the Tor daemon (proxy-suite-tor)"; + + package = package "tor" "Tor package."; + + lyrebirdPackage = package "lyrebird" "Pluggable transport for obfs4, webtunnel and meek_lite bridges."; + + snowflakePackage = package "snowflake" "Pluggable transport for snowflake bridges."; + + asOutbound = mkOption { + type = types.bool; + default = false; + description = '' + Add Tor as an outbound tagged "tor": a SOCKS hop to proxy-suite-tor on 127.0.0.1:socksPort, + which receives names unresolved. proxy.selection and autoProxy leave it alone unless it is the + only outbound; route to it with proxy.routing.rules or name it as a detour. Requires proxy.enable. + ''; + }; + + routeOnion = mkOption { + type = types.bool; + default = true; + description = '' + Send .onion names to the "tor" outbound in every route mode, and keep them away from DNS: + in TUN and TProxy modes sing-box answers them with a fake address it maps back to the name, + and XRay drops the lookup. Inbound clients' .onion names go the same way, through the local + proxy, whatever their listener's via (except "block"). Applies with asOutbound. + ''; + }; + + clientOnly = mkOption { + type = types.bool; + default = true; + description = '' + Keep Tor a client (ClientOnly 1): never a relay, exit, bridge or directory server, even when + extraConfig sets an ORPort. The onion service works either way. Turn off only to run a relay + through extraConfig. + ''; + }; + + upstream = mkOption { + type = types.enum [ + "direct" + "proxy" + ]; + default = "direct"; + description = '' + How Tor reaches its relays or bridges. + - "direct": from the uplink, past TUN and TProxy (it runs as proxy-suite-daemon). + - "proxy": through the local proxy listener (proxy.listener, with its auth), for a network + that blocks Tor. obfs4, webtunnel and meek_lite bridges follow it; snowflake cannot. + ''; + }; + + socksPort = mkOption { + type = types.port; + default = 18530; + description = "Loopback SOCKS port of proxy-suite-tor, which the tor outbound dials."; + }; + + bridges = { + lines = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + Bridge lines, as https://bridges.torproject.org hands them out, without the leading + "Bridge". Any given turns on UseBridges; obfs4, webtunnel, meek_lite and snowflake + transports are run as needed. + ''; + example = [ + "obfs4 192.0.2.1:443 0123456789ABCDEF0123456789ABCDEF01234567 cert=... iat-mode=0" + ]; + }; + + file = mkOption { + type = types.nullOr types.str; + default = null; + description = "Runtime path to more bridge lines, one per line; blank lines and # comments are skipped."; + example = "/run/secrets/tor-bridges"; + }; + }; + + onionService = { + enable = mkEnableOption "an onion service in front of inbounds.listeners"; + + listeners = mkOption { + type = types.nullOr (types.listOf types.str); + default = null; + description = '' + inbounds.listeners served at the onion address, each on its share port. Null takes every + listener a TCP-only onion can carry: not amneziawg, h3-only xhttp or raw JSON. + + Share links for them (`proxy-ctl inbounds link TAG --onion`, and subscriptions) dial the + .onion address and keep the listener's TLS and REALITY names. Clients reach XRay from + 127.0.0.1, so `proxy-ctl inbounds online` does not list them. + ''; + example = [ "vless-reality" ]; + }; + + secretKeyFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to an hs_ed25519_secret_key, to keep an onion address. Null lets Tor create + one in /var/lib/proxy-suite/tor/onion. + ''; + example = "/run/secrets/tor-hs_ed25519_secret_key"; + }; + }; + + extraConfig = mkOption { + type = types.lines; + default = ""; + description = "Lines appended to the generated torrc."; + example = '' + ExitNodes {de},{nl} + StrictNodes 1 + ''; + }; + }; +} diff --git a/modules/proxy-suite/options/user-control.nix b/modules/proxy-suite/options/user-control.nix index 23016d2..0d6757b 100644 --- a/modules/proxy-suite/options/user-control.nix +++ b/modules/proxy-suite/options/user-control.nix @@ -29,7 +29,7 @@ in default = [ ]; description = '' What userControl.group may do; empty allows every scope. - - "services": turn the proxy-suite units on and off (proxy, tun, tproxy, zapret, ssh, warp, tg, awg, inbounds), and `restart`. + - "services": turn the proxy-suite units on and off (proxy, tun, tproxy, zapret, ssh, warp, tor, tg, awg, inbounds), `restart`, and `tor status|newnym` on Tor's control socket. - "perApp": the per-app backend units used by `proxy-ctl apps run`. - "routing": `proxy pin`, `proxy unpin` and `proxy mode`. - "outbounds": add and remove runtime outbounds and subscriptions, disable and enable outbounds, and update subscriptions. diff --git a/modules/proxy-suite/rules.nix b/modules/proxy-suite/rules.nix index e9b5dfe..27fa628 100644 --- a/modules/proxy-suite/rules.nix +++ b/modules/proxy-suite/rules.nix @@ -60,6 +60,9 @@ let } ) proxyCfg.outbounds; + # .onion names go to Tor in every route mode: nothing else can reach them. + onionOutbound = if derived.torRouteOnion then resolveTag derived.torOutboundTag else null; + # All custom rules in priority order: per-outbound first, then explicit routing.rules. customRules = perOutboundRules ++ map (rule: rule // { outbound = resolveTag rule.outbound; }) r.rules; @@ -72,6 +75,7 @@ let tgWsProxyCfg customRules customRuleCategory + onionOutbound ; inherit (cfg) geodata; }; @@ -91,6 +95,7 @@ let tgWsProxyCfg customRules customRuleCategory + onionOutbound ; inherit (derived) selectionMode; }; diff --git a/modules/proxy-suite/rules/proxy-inbounds.nix b/modules/proxy-suite/rules/proxy-inbounds.nix index 88e2fe5..fc48786 100644 --- a/modules/proxy-suite/rules/proxy-inbounds.nix +++ b/modules/proxy-suite/rules/proxy-inbounds.nix @@ -4,6 +4,7 @@ lib, proxyInboundsCfg, proxyInbounds, + proxyInboundsRouteOnion, zapretDirectRules, }: @@ -17,6 +18,18 @@ let # A blocked listener stays blocked: neither serverAddress nor the proxy exceptions open it. exceptionInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via != "block") proxyInbounds); + # Only Tor reaches .onion: to the local proxy, whose own rule sends it there. First, so no + # IP rule before it has XRay look the name up, which would leak it to a resolver. + onionRule = lib.optional proxyInboundsRouteOnion { + type = "field"; + ruleTag = "inbound-tor-onion"; + domain = [ "domain:onion" ]; + inboundTag = map (ib: ib.tag) ( + builtins.filter (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds + ); + outboundTag = "proxy"; + }; + blockPrivateRule = lib.optional proxyInboundsCfg.routing.blockPrivate { type = "field"; ruleTag = "inbound-block-private"; @@ -147,7 +160,8 @@ let # Explicit proxy exceptions beat blockRu: RU-geolocated ranges (Telegram's, # at times) would otherwise swallow them. xrayInboundRules = - blockPrivateRule + onionRule + ++ blockPrivateRule ++ serverAddressRule ++ proxyDomainRule ++ proxyIpRule diff --git a/modules/proxy-suite/rules/sing-box.nix b/modules/proxy-suite/rules/sing-box.nix index f02dc5d..d0c4c9b 100644 --- a/modules/proxy-suite/rules/sing-box.nix +++ b/modules/proxy-suite/rules/sing-box.nix @@ -6,6 +6,7 @@ tgWsProxyCfg, customRules, customRuleCategory, + onionOutbound, geodata, }: @@ -60,7 +61,11 @@ let action = "hijack-dns"; } { action = "sniff"; } - ]; + ] + ++ lib.optional (onionOutbound != null) { + domain_suffix = [ "onion" ]; + outbound = onionOutbound; + }; customRouteRules = map (rule: { category = customRuleCategory rule.outbound; diff --git a/modules/proxy-suite/rules/xray.nix b/modules/proxy-suite/rules/xray.nix index 3510597..c56eeb7 100644 --- a/modules/proxy-suite/rules/xray.nix +++ b/modules/proxy-suite/rules/xray.nix @@ -6,6 +6,7 @@ tgWsProxyCfg, customRules, customRuleCategory, + onionOutbound, selectionMode, }: @@ -116,8 +117,14 @@ let (xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips) ]; + # Kept by every route mode, like sing-box's common rules. + xrayCommonRules = lib.optional (onionOutbound != null) ( + mkXrayRule "tor-onion" { domain = [ "domain:onion" ]; } onionOutbound + ); + xrayRoutingRules = - lib.concatMap (item: item.entries) xrayCustomRouteRules + xrayCommonRules + ++ lib.concatMap (item: item.entries) xrayCustomRouteRules ++ xrayProxyPrimaryRules ++ xrayDirectRules ++ xraySafetyDirectRules @@ -125,7 +132,7 @@ let ++ xrayBlockRules; xrayRouteModeRules = { - common = [ ]; + common = xrayCommonRules; custom = xrayCustomRouteRules; proxyPrimary = xrayProxyPrimaryRules; direct = xrayDirectRules; diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index a5aef6b..332e277 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -72,6 +72,7 @@ let ob.tunnelPort ob.directPort ]) derived.awgTunnelOutbounds + ++ lib.optional derived.torOutboundEnabled derived.torCfg.socksPort ++ lib.optionals derived.proxyInboundsEnabled ( map (listener: listener.internalPort) derived.proxyInboundsAwg ); @@ -350,7 +351,7 @@ let proxyInboundAssertions = [ (mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ]) - "proxy-suite: inbounds via targets, or the hops they chain through, are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies, warp, ssh-proxy and AmneziaWG outbounds cannot be named here because the inbound service does not run them; use via = \"proxy\" to reach those." + "proxy-suite: inbounds via targets, or the hops they chain through, are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies, warp, tor, ssh-proxy and AmneziaWG outbounds cannot be named here because the inbound service does not run them; use via = \"proxy\" to reach those." ) (mkAssertion (!proxyInboundsEnabled || singBoxOnlyPinnedTags == [ ]) "proxy-suite: inbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson." @@ -928,9 +929,74 @@ let message = "proxy-suite: tgWsProxy.fwmark must not use per-app-zapret internal desync mark bits"; } ]; + + torCfg = cfg.tor; + torOnionListeners = if torCfg.onionService.listeners == null then [ ] else torCfg.onionService.listeners; + torOnionUnfit = map (ib: ib.tag) ( + builtins.filter (ib: !derived.proxyInboundOnionCapable ib) derived.torOnionInbounds + ); + torOnionVirtualPorts = map ( + ib: if ib.listener.sharePort != null then ib.listener.sharePort else ib.listener.port + ) derived.torOnionInbounds; + torSnowflake = lib.any (line: lib.hasPrefix "snowflake " line) torCfg.bridges.lines; + torAssertions = [ + (mkAssertion (!torCfg.enable || torCfg.asOutbound || torCfg.onionService.enable) + "proxy-suite: tor.enable = true needs tor.asOutbound or tor.onionService.enable" + ) + (requireEnabled (torCfg.enable && torCfg.asOutbound) proxyEnabled + "proxy-suite: tor.asOutbound requires proxy.enable = true" + ) + (requireEnabled (torCfg.enable && torCfg.upstream == "proxy") proxyEnabled + ''proxy-suite: tor.upstream = "proxy" requires proxy.enable = true'' + ) + (mkAssertion (!(torCfg.enable && torCfg.upstream == "proxy" && torSnowflake)) + ''proxy-suite: tor.bridges.lines has a snowflake bridge, which cannot follow tor.upstream = "proxy"; use obfs4, webtunnel or meek_lite bridges, or upstream = "direct"'' + ) + (mkAssertion (!(derived.torOutboundEnabled && builtins.elem derived.torOutboundTag outboundTags)) + "proxy-suite: the outbound tag \"tor\" belongs to tor.asOutbound; rename the proxy.outbounds entry" + ) + (requireEnabled (torCfg.enable && torCfg.onionService.enable) cfg.inbounds.enable + "proxy-suite: tor.onionService.enable requires inbounds.enable = true" + ) + (mkAssertion ( + !derived.torOnionEnabled + || builtins.all (tag: builtins.hasAttr tag cfg.inbounds.listeners) torOnionListeners + ) "proxy-suite: tor.onionService.listeners names listeners not in inbounds.listeners: ${ + lib.concatStringsSep ", " ( + builtins.filter (tag: !builtins.hasAttr tag cfg.inbounds.listeners) torOnionListeners + ) + }") + (mkAssertion (!derived.torOnionEnabled || derived.torOnionInbounds != [ ]) + "proxy-suite: tor.onionService has no listener to serve: amneziawg, h3-only xhttp and raw JSON listeners cannot go over an onion" + ) + (mkAssertion (!derived.torOnionEnabled || torOnionUnfit == [ ]) + "proxy-suite: tor.onionService.listeners cannot serve ${lib.concatStringsSep ", " torOnionUnfit}: an onion carries TCP only, so not amneziawg or h3-only xhttp, and raw JSON listeners have no known protocol" + ) + (uniqueValues derived.torOnionEnabled torOnionVirtualPorts + "proxy-suite: tor.onionService listeners must each share a distinct port (sharePort, or port)" + ) + (mkAssertion + ( + !derived.torOutboundEnabled + || !( + (proxyEnabled && proxyCfg.listener.port == torCfg.socksPort) + || (proxyInboundsEnabled && builtins.elem torCfg.socksPort derived.proxyInboundPorts) + || builtins.elem torCfg.socksPort ( + builtins.attrValues constants.xrayDnsBridgePorts + ++ [ + constants.inboundStatsApiPort + constants.outboundTestPort + ] + ) + ) + ) + "proxy-suite: tor.socksPort ${toString torCfg.socksPort} collides with another proxy-suite listener" + ) + ]; in rootlessAssertions ++ featureAssertions +++ torAssertions ++ perAppRoutingAssertions ++ localProxyAuthAssertions ++ secretAssertions diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index d04e304..508aafe 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -50,11 +50,13 @@ let sshProxyOutboundEnabled sshProxyUnitEnabled warpCfg + torCfg awgOutbounds proxyInboundsCfg proxyInboundsEnabled proxyInboundsAwg proxyInboundsNeedLocalProxy + torOnionEnabled proxyInboundsGuardPrivate proxyInboundViaOutbounds userControlAllows @@ -100,6 +102,7 @@ let proxyCfg sshProxyCfg warpCfg + torCfg awgOutbounds xrayEnabled hybridEnabled @@ -135,6 +138,7 @@ let proxyInboundsAwg awgBin proxyInboundsNeedLocalProxy + torOnionEnabled proxyInboundsGuardPrivate proxyInboundViaOutbounds userControlAllows diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 5e1cda1..9fc9cc2 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -63,6 +63,7 @@ if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl; autoProxyEnabled = if proxyCfg.autoProxy.enable then "1" else "0"; autoProxyStateDir = constants.autoProxyStateDir; + torControlSocket = constants.torControlSocket; inherit (constants) stateDir runtimeDir serviceManager; privileged = if constants.privileged then "1" else "0"; supervisorCtl = if constants.serviceManager == "supervisor" then constants.systemctl else ""; diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index c0fef14..d3dff99 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -66,6 +66,8 @@ let perAppZapretEnabled sshProxyOutboundEnabled sshProxyUnitEnabled + torOutboundEnabled + torOnionEnabled proxyInboundsEnabled proxyInboundsNeedLocalProxy proxyInboundFirewallPorts @@ -108,6 +110,8 @@ let perAppZapretEnabled sshProxyOutboundEnabled sshProxyUnitEnabled + torOutboundEnabled + torOnionEnabled proxyInboundsEnabled proxyInboundsNeedLocalProxy scripts diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index 6b74083..c8633ce 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -8,6 +8,7 @@ proxyInboundsAwg, awgBin, proxyInboundsNeedLocalProxy, + torOnionEnabled, proxyInboundViaOutbounds, userControlCfg, userControlAllows, @@ -53,6 +54,26 @@ let 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 = @@ -131,10 +152,12 @@ let mkdir -p "$RUNTIME_DIR" ${serverAddressBlock} + ${onionAddressBlock} RENDERED=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildInboundPy} \ --spec ${proxyInboundsSpecFile} \ - --server-address "$SERVER_ADDRESS") + --server-address "$SERVER_ADDRESS" \ + --onion-address "$ONION_ADDRESS") INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED") diff --git a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix index d1ff833..9affcdb 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -104,7 +104,7 @@ else | .dns.final = $dns_final | if $clear_dns_rules then .dns.rules = .dns.rules[:${toString (builtins.length userDnsRules)}] - + [.dns.rules[${toString (builtins.length userDnsRules)}:][] | select(.server? == "fakeip")] + + [.dns.rules[${toString (builtins.length userDnsRules)}:][] | select(.server? == "fakeip" or .domain_suffix? == ["onion"])] else . end else . end # autoProxy rules, after the route-mode replace so no mode drops them: pins first @@ -118,10 +118,13 @@ else # inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved. # Just before the first direct rule (or last, for a direct final), so names that the # proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local - # mixed-in clients lose names that resolve private. + # mixed-in clients lose names that resolve private. Rules for other inbounds do not count: + # autoProxy's direct probe pin would put the guard first, resolving every name, .onion too. | [{inbound: ["mixed-in"], action: "resolve"}, {inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard - | (.route.rules | map((.outbound? // "") == "direct") | index(true)) as $first_direct + | (.route.rules + | map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null) + | index(true)) as $first_direct | if $first_direct != null then .route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:] elif (.route.final // "direct") == "direct" then diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index 10f46c3..1c4c524 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -5,6 +5,7 @@ proxyCfg, sshProxyCfg, warpCfg, + torCfg, awgOutbounds, constants, pureXrayEnabled, @@ -27,6 +28,7 @@ let sshProxyTag = "ssh-proxy"; + torOutboundEnabled = torCfg != null && torCfg.enable && torCfg.asOutbound; # sing-box domain strategies in XRay's names (UseIPv4v6 = prefer IPv4). xrayDomainStrategies = { @@ -202,7 +204,7 @@ let tag="''${f##*/}" tag="''${tag%.*}" case "$tag" in - proxy | direct | block) + proxy | direct | block${lib.optionalString torOutboundEnabled " | tor"}) echo "proxy-suite: warning: ignoring runtime outbound '$tag': reserved name" >&2 continue ;; @@ -528,10 +530,11 @@ let # What selection may pick on its own: all but proxy.selectionExclude and disabled # outbounds. A pin still reaches the excluded ones, and a selector switched by hand both. + # Tor is only for what is routed to it, unless it is the one outbound there is. selectableBlock = '' SELECTABLE_TAGS_JSON=$(${jq} -c --argjson ex ${lib.escapeShellArg (builtins.toJSON proxyCfg.selectionExclude)} \ --argjson disabled "$DISABLED_TAGS_JSON" \ - 'map(select(. as $t | ($ex + $disabled) | index([$t]) | not))' <<< "$OUTBOUND_TAGS_JSON") + '${lib.optionalString torOutboundEnabled "(if length > 1 then [\"tor\"] else [] end) as $tor | "}map(select(. as $t | ($ex + $disabled${lib.optionalString torOutboundEnabled " + $tor"}) | index([$t]) | not))' <<< "$OUTBOUND_TAGS_JSON") if [ -z "$PINNED_OUTBOUND" ] && [ "$(${jq} 'length' <<< "$SELECTABLE_TAGS_JSON")" -eq 0 ]; then echo "proxy-suite: every outbound is in proxy.selectionExclude or disabled, so there is nothing to select; pin one, enable one (proxy-ctl proxy outbounds enable), or exclude fewer" >&2 exit 1 @@ -573,6 +576,9 @@ let warpBlock = lib.optionalString (warpCfg.enable && warpCfg.asOutbound == "singBox") ( mkTunnelOutboundBlock "proxy-suite-warp-tunnel" "warp" "warp" warpCfg.tunnelPort ); + torBlock = lib.optionalString torOutboundEnabled ( + mkTunnelOutboundBlock "proxy-suite-tor" "tor" "tor" torCfg.socksPort + ); awgBlocks = lib.concatMapStrings (mkAwgOutboundBlock routingMark) awgOutbounds; wrapperBlock = @@ -639,7 +645,9 @@ let # Real exits for autoProxy, taken after the wrapper may have renamed one to # "proxy". exitTagsBlock = '' - EXIT_TAGS_JSON=$(${jq} -c '[.[] | select(.type != "selector" and .type != "urltest") | .tag]' <<< "$OUTBOUNDS_JSON") + EXIT_TAGS_JSON=$(${jq} -c '[.[] | select(.type != "selector" and .type != "urltest"${ + lib.optionalString torOutboundEnabled " and (.tag | ltrimstr(\"proxy-suite-ob-\")) != \"tor\"" + }) | .tag]' <<< "$OUTBOUNDS_JSON") ''; in mkUrlOutboundHelpersBlock routingMark @@ -650,6 +658,7 @@ let + runtimeOutboundsBlock + sshProxyBlock + warpBlock + + torBlock + awgBlocks + detourBlock + requireOutboundsBlock diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 7c4687e..5d28615 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -6,6 +6,7 @@ proxyCfg, sshProxyCfg, warpCfg, + torCfg, awgOutbounds, xrayEnabled, hybridEnabled, @@ -32,6 +33,7 @@ proxyInboundsAwg, awgBin, proxyInboundsNeedLocalProxy, + torOnionEnabled, proxyInboundsGuardPrivate, proxyInboundViaOutbounds, userControlAllows, @@ -115,6 +117,7 @@ let proxyCfg sshProxyCfg warpCfg + torCfg awgOutbounds constants pureXrayEnabled @@ -202,6 +205,7 @@ let proxyInboundsAwg awgBin proxyInboundsNeedLocalProxy + torOnionEnabled proxyInboundViaOutbounds userControlCfg userControlAllows diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index d5ba1a5..fd5e97c 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -13,6 +13,8 @@ perAppZapretEnabled, sshProxyOutboundEnabled, sshProxyUnitEnabled, + torOutboundEnabled, + torOnionEnabled, proxyInboundsEnabled, proxyInboundsNeedLocalProxy, scripts, @@ -76,10 +78,12 @@ let "network-online.target" ] ++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service"; + # Not after Tor: it may reach its relays through this listener. wants = [ "network-online.target" ] - ++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service"; + ++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service" + ++ lib.optional torOutboundEnabled "proxy-suite-tor.service"; wantedBy = [ "multi-user.target" ]; execStart = scripts.startSocks; runtimeDirectory = serviceNames.socks; @@ -97,11 +101,14 @@ let ] # After the client stack, but not `requires`: direct listeners keep serving # without it. - ++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service"; + ++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service" + # For the onion address in the share links. + ++ lib.optional torOnionEnabled "proxy-suite-tor.service"; wants = [ "network-online.target" ] - ++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service"; + ++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service" + ++ lib.optional torOnionEnabled "proxy-suite-tor.service"; wantedBy = [ "multi-user.target" ]; execStart = scripts.startInbounds; runtimeDirectory = serviceNames.inbounds; diff --git a/modules/proxy-suite/tor.nix b/modules/proxy-suite/tor.nix new file mode 100644 index 0000000..3aae844 --- /dev/null +++ b/modules/proxy-suite/tor.nix @@ -0,0 +1,185 @@ +# The Tor daemon: the SOCKS listener behind the "tor" outbound, and the onion service in front +# of the inbounds. +{ + lib, + pkgs, + cfg, + derived, +}: + +let + t = derived.torCfg; + inherit (derived.constants) unprivilegedServiceConfig; + inherit (cfg.host) privileged; + + listener = cfg.proxy.listener; + auth = listener.auth; + # Tor dials the local proxy by address: a wildcard listener is reached on loopback. + proxyHost = + if + builtins.elem listener.address [ + "0.0.0.0" + "::" + ] + then + "127.0.0.1" + else + listener.address; + proxyHostPart = if lib.hasInfix ":" proxyHost then "[${proxyHost}]" else proxyHost; + passwordSource = + if auth.passwordFile != null then + auth.passwordFile + else if auth.password != null then + pkgs.writeText "proxy-suite-tor" auth.password + else + null; + viaProxy = t.upstream == "proxy"; + withProxyAuth = viaProxy && auth.username != null && passwordSource != null; + bridgesEnabled = t.bridges.lines != [ ] || t.bridges.file != null; + + # The control socket's directory: members of userControl.group may use it for + # `proxy-ctl tor status|newnym`, so it takes that group (setgid) on a system install. + controlGroup = privileged && derived.userControlAllows "services"; + + # An onion service port per listener: its share port, forwarded to where XRay listens. + onionTarget = + l: + let + addr = + if + builtins.elem l.address [ + "::" + "0.0.0.0" + "localhost" + ] + then + "127.0.0.1" + else + l.address; + in + "${if lib.hasInfix ":" addr then "[${addr}]" else addr}:${toString l.port}"; + onionPorts = map (ib: { + virtual = if ib.listener.sharePort != null then ib.listener.sharePort else ib.listener.port; + target = onionTarget ib.listener; + }) derived.torOnionInbounds; + + staticConfig = ( + lib.concatStringsSep "\n" ( + [ + "GeoIPFile ${t.package.geoip}/share/tor/geoip" + "GeoIPv6File ${t.package.geoip}/share/tor/geoip6" + "ClientUseIPv6 1" + "AvoidDiskWrites 1" + "Log notice stdout" + # Names come in over SOCKS unresolved; nothing here resolves for the host. + "AutomapHostsOnResolve 0" + "DNSPort 0" + "TransPort 0" + "NATDPort 0" + "CookieAuthentication 0" + "ControlSocketsGroupWritable 1" + ] + ++ lib.optional t.clientOnly "ClientOnly 1" + ++ ( + if t.asOutbound then + [ "SocksPort 127.0.0.1:${toString t.socksPort}" ] + else + [ "SocksPort 0" ] + ) + ++ lib.optionals bridgesEnabled [ + "UseBridges 1" + "ClientTransportPlugin obfs4,webtunnel,meek_lite exec ${t.lyrebirdPackage}/bin/lyrebird" + "ClientTransportPlugin snowflake exec ${t.snowflakePackage}/bin/client" + ] + ++ lib.optional viaProxy "Socks5Proxy ${proxyHostPart}:${toString listener.port}" + ++ map (line: "Bridge ${line}") t.bridges.lines + ) + ); + + # Group-owned and setgid, so the socket tor creates in it is the group's. + controlDirScript = pkgs.writeShellScript "proxy-suite-tor-control-dir" '' + set -euo pipefail + dir="$RUNTIME_DIRECTORY/control" + ${pkgs.coreutils}/bin/install -d -m 2750 -o ${derived.constants.serviceUser} \ + -g ${lib.escapeShellArg cfg.userControl.group} "$dir" + ''; + + startScript = pkgs.writeShellScript "proxy-suite-tor" '' + set -euo pipefail + umask 0077 + + torrc="$RUNTIME_DIRECTORY/torrc" + ${pkgs.coreutils}/bin/mkdir -p -m 0700 "$RUNTIME_DIRECTORY/control" + { + cat <<'TORRC' + ${staticConfig} + TORRC + echo "DataDirectory $STATE_DIRECTORY" + echo "ControlSocket unix:$RUNTIME_DIRECTORY/control/socket" + ${lib.optionalString withProxyAuth '' + echo "Socks5ProxyUsername "${lib.escapeShellArg auth.username} + printf 'Socks5ProxyPassword %s\n' "$(${pkgs.coreutils}/bin/head -n1 "$CREDENTIALS_DIRECTORY/proxy-password")" + ''} + ${lib.optionalString (t.bridges.file != null) '' + ${pkgs.gnused}/bin/sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e '/^$/d' -e '/^#/d' \ + -e 's/^\(Bridge[[:space:]]\+\)\?/Bridge /' "$CREDENTIALS_DIRECTORY/bridges" + ''} + ${lib.optionalString derived.torOnionEnabled '' + echo "HiddenServiceDir $STATE_DIRECTORY/onion" + ${lib.concatMapStrings (p: '' + echo ${lib.escapeShellArg "HiddenServicePort ${toString p.virtual} ${p.target}"} + '') onionPorts} + ''} + cat ${pkgs.writeText "proxy-suite-torrc-extra" t.extraConfig} + } > "$torrc" + + ${lib.optionalString (derived.torOnionEnabled && t.onionService.secretKeyFile != null) '' + # Tor wants the service directory private to it. + ${pkgs.coreutils}/bin/install -d -m 0700 "$STATE_DIRECTORY/onion" + if ! ${pkgs.diffutils}/bin/cmp -s "$CREDENTIALS_DIRECTORY/onion-secret-key" "$STATE_DIRECTORY/onion/hs_ed25519_secret_key"; then + # Another key: the old address and its public key must not be served with it. + ${pkgs.coreutils}/bin/rm -f "$STATE_DIRECTORY/onion/hs_ed25519_public_key" "$STATE_DIRECTORY/onion/hostname" + ${pkgs.coreutils}/bin/install -m 0600 "$CREDENTIALS_DIRECTORY/onion-secret-key" \ + "$STATE_DIRECTORY/onion/hs_ed25519_secret_key" + fi + ''} + + exec ${t.package}/bin/tor -f "$torrc" + ''; +in +{ + services.proxy-suite.internal.services.proxy-suite-tor = { + description = "proxy-suite - Tor"; + after = [ "network-online.target" ] ++ lib.optional viaProxy "proxy-suite-socks.service"; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + # Restart=always must not trip the start limit while the network is down. + startLimitIntervalSec = 0; + serviceConfig = + unprivilegedServiceConfig [ ] + // { + Type = "simple"; + ExecStart = startScript; + ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID"; + # The service user is excluded from TUN and TProxy capture, which is what keeps + # tor's own connections out of the proxy. + StateDirectory = "proxy-suite/tor"; + StateDirectoryMode = "0700"; + RuntimeDirectory = "proxy-suite-tor"; + RuntimeDirectoryMode = "0711"; + # Copies the service user can read, whoever owns the originals. + LoadCredential = + lib.optional withProxyAuth "proxy-password:${passwordSource}" + ++ lib.optional (t.bridges.file != null) "bridges:${t.bridges.file}" + ++ lib.optional ( + derived.torOnionEnabled && t.onionService.secretKeyFile != null + ) "onion-secret-key:${t.onionService.secretKeyFile}"; + Restart = "always"; + RestartSec = 5; + LimitNOFILE = 65536; + } + // lib.optionalAttrs controlGroup { + ExecStartPre = "+${controlDirScript}"; + }; + }; +} diff --git a/nix/checks/hosts.nix b/nix/checks/hosts.nix index 502fc5b..19e8d48 100644 --- a/nix/checks/hosts.nix +++ b/nix/checks/hosts.nix @@ -111,6 +111,11 @@ let enable = true; asOutbound = "singBox"; }; + tor = { + enable = true; + asOutbound = true; + onionService.enable = true; + }; perAppRouting = { enable = true; proxychains.enable = true; @@ -169,6 +174,12 @@ in assert lib.hasPrefix "/home/u/.local/state/" hmCfg.services.proxy-suite.host.stateDir; assert hmCfg.systemd.user.services ? proxy-suite-socks; assert hmCfg.systemd.user.services ? proxy-suite-inbounds; + assert hmCfg.systemd.user.services ? proxy-suite-tor; + # Rootless, there is no userControl group to hand the control socket to. + assert + !(lib.hasInfix "proxy-suite-tor-control-dir" ( + toString (hmCfg.systemd.user.services.proxy-suite-tor.Service.ExecStartPre or [ ]) + )); assert forced hmCfg.systemd.user.services; # No setpriv on a user manager: nothing to drop to. assert @@ -204,6 +215,7 @@ in assert lib.hasInfix "proxy-suitectl boot" nodCfg.build.activationAfter.proxySuite; assert lib.hasInfix "proxy-suitectl ensure" nodCfg.environment.etc.profile.text; assert forced nodCfg.build.activationAfter.proxySuite; + assert nodCfg.services.proxy-suite.internal.services.proxy-suite-tor.enable; # Android bans apps from netlink's route groups, which stock sing-box subscribes to. assert nodCfg.services.proxy-suite.proxy.singBox.package.passthru.rootlessNetlink or false; assert !(hmCfg.services.proxy-suite.proxy.singBox.package.passthru.rootlessNetlink or false); diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index 0d6c019..056adea 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -5,6 +5,7 @@ let inherit (checkLib) + mkRouting evalProxySuite mkRoutingRules mkRouteModeRules @@ -124,6 +125,21 @@ let ; }; + torChecks = import ./tor.nix { + inherit + pkgs + evalProxySuite + mkBadProxySuiteFixture + mkFailingAssertions + mkRouting + mkTunConfig + mkTProxyConfig + mkInboundsSpec + mkInboundsConfig + mkProxyCtlDerived + ; + }; + proxyInboundsChecks = import ./proxy-inbounds.nix { inherit pkgs @@ -276,6 +292,7 @@ let ++ localProxyAuthChecks.assertions ++ sshProxyChecks.assertions ++ warpChecks.assertions + ++ torChecks.assertions ++ proxyInboundsChecks.assertions ++ tgWsProxyChecks.assertions ++ xrayBackendChecks.assertions @@ -297,6 +314,7 @@ in proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok"); amneziawg-secret-manifest = amneziaWgChecks.manifest; xray-jq-filter-runtime = xrayBackendChecks.runtime; + tor-guard-runtime = torChecks.runtime; per-app-zapret-runtime = perAppRoutingChecks.runtime; zapret-hostlist-rules = zapretChecks.rules; zapret2-config = zapret2Checks.runtime; diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index e7496fc..d6228f4 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -372,6 +372,8 @@ has work awg on has torrent apps run has unpin proxy + has newnym tor + has --onion inbounds link has community-de proxy pin # Flags, and completion past the first of several arguments. @@ -785,6 +787,7 @@ singBoxCfg = null; sshProxyCfg = null; warpCfg = null; + torCfg = null; awgOutbounds = null; constants = null; pureXrayEnabled = null; diff --git a/nix/checks/server-module.nix b/nix/checks/server-module.nix index 65269e7..35cb13e 100644 --- a/nix/checks/server-module.nix +++ b/nix/checks/server-module.nix @@ -47,6 +47,7 @@ let }; ipServer = mkServer { }; + onionServer = mkServer { onion.enable = true; }; domainServer = mkServer { domain = "vpn.example.com"; network.dhcp = true; @@ -57,6 +58,7 @@ let listener = spec: tag: lib.head (builtins.filter (l: l.tag == tag) spec.listeners); ipSpec = mkInboundsSpec ipServer; + onionSpec = mkInboundsSpec onionServer; domainSpec = mkInboundsSpec domainServer; uplink = fixture: fixture.config.systemd.network.networks."10-uplink"; ipCert = ipServer.config.security.acme.certs."203.0.113.10"; @@ -159,5 +161,40 @@ in assert ipServer.config.services.openssh.settings.PermitRootLogin == "no"; true ) + + # onion.enable: every listener behind the onion service, and nothing opened for it. + ( + assert failedAssertions onionServer == [ ]; + true + ) + ( + assert + lib.sort (a: b: a < b) onionSpec.onionListeners == [ + "vless-reality" + "vless-tls" + "vless-ws" + ]; + true + ) + ( + assert !(ipServer.config.systemd.services ? proxy-suite-tor) && (ipSpec.onionListeners or [ ]) == [ ]; + true + ) + ( + assert builtins.elem "proxy-suite-tor.service" onionServer.config.systemd.services.proxy-suite-inbounds.after; + true + ) + ( + assert + onionServer.config.networking.firewall.allowedTCPPorts + == ipServer.config.networking.firewall.allowedTCPPorts; + true + ) + ( + assert + lib.hasInfix "--onion" onionServer.config.services.getty.helpLine + && !(lib.hasInfix "--onion" ipServer.config.services.getty.helpLine); + true + ) ]; } diff --git a/nix/checks/tor.nix b/nix/checks/tor.nix new file mode 100644 index 0000000..3b0414f --- /dev/null +++ b/nix/checks/tor.nix @@ -0,0 +1,497 @@ +{ + pkgs, + evalProxySuite, + mkBadProxySuiteFixture, + mkFailingAssertions, + mkRouting, + mkTunConfig, + mkTProxyConfig, + mkInboundsSpec, + mkInboundsConfig, + mkProxyCtlDerived, +}: + +let + generated = import ./read-generated.nix; + inherit (pkgs) lib; + inherit (lib) hasInfix; + + listener = { + type = "vless"; + port = 10443; + users = [ { uuidFile = "/run/secrets/uuid"; } ]; + }; + + mkFixture = + backend: settings: + evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = lib.recursiveUpdate { + enable = true; + tor = { + enable = true; + asOutbound = true; + }; + proxy = { + enable = true; + inherit backend; + tun.enable = true; + outbounds = [ + { + tag = "vps"; + url = "http://vps.example.com:8080"; + } + ]; + }; + } settings; + } + ]; + # Only proxy-suite's: these fixtures are not bootable systems. + failedAssertions = + fixture: + map (a: a.message) ( + builtins.filter (a: !a.assertion && lib.hasPrefix "proxy-suite" a.message) fixture.config.assertions + ); + services = fixture: fixture.config.systemd.services; + socksStartOf = fixture: generated.readDerivation (services fixture).proxy-suite-socks.serviceConfig.ExecStart; + torStartOf = fixture: generated.readDerivation (services fixture).proxy-suite-tor.serviceConfig.ExecStart; + dnsOut = config: (lib.head (builtins.filter (o: o.tag == "dns-out") config.outbounds)).settings.rules; + + singBox = mkFixture "sing-box" { }; + singBoxStart = socksStartOf singBox; + singBoxTorStart = torStartOf singBox; + singBoxTun = mkTunConfig singBox; + singBoxModes = (mkRouting singBox).singBoxRouteModeRules; + singBoxTorUnit = (services singBox).proxy-suite-tor; + singBoxTProxy = mkTProxyConfig (mkFixture "sing-box" { + proxy.tun.enable = false; + proxy.tproxy.enable = true; + }); + + xray = mkFixture "xray" { proxy.tproxy.enable = true; }; + xrayStart = socksStartOf xray; + xrayRouting = mkRouting xray; + + hybrid = mkFixture "hybrid" { }; + hybridStart = socksStartOf hybrid; + + controlled = mkFixture "sing-box" { userControl.enable = true; }; + + relayTorStart = torStartOf (mkFixture "sing-box" { tor.clientOnly = false; }); + + noOnion = mkFixture "sing-box" { tor.routeOnion = false; }; + noOnionTun = mkTunConfig noOnion; + + bridges = mkFixture "sing-box" { + tor = { + bridges.lines = [ "obfs4 192.0.2.1:443 0123456789ABCDEF0123456789ABCDEF01234567 cert=x iat-mode=0" ]; + bridges.file = "/run/secrets/tor-bridges"; + }; + }; + bridgesStart = torStartOf bridges; + + viaProxy = mkFixture "sing-box" { + tor.upstream = "proxy"; + proxy.listener.auth = { + username = "local-user"; + passwordFile = "/run/secrets/local-proxy-password"; + }; + }; + viaProxyStart = torStartOf viaProxy; + viaProxyTor = (services viaProxy).proxy-suite-tor; + + onion = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + tor = { + enable = true; + onionService = { + enable = true; + secretKeyFile = "/run/secrets/hs_ed25519_secret_key"; + }; + }; + inbounds = { + enable = true; + serverAddress = "vpn.example.com"; + routing.via = "direct"; + listeners.plain = listener; + listeners.shared = listener // { + port = 10444; + address = "127.0.0.1"; + sharePort = 443; + }; + }; + }; + } + ]; + # An exit node: its clients' .onion names still reach Tor, through the local proxy. + exitInbounds = { + inbounds = { + enable = true; + serverAddress = "vpn.example.com"; + routing.via = "direct"; + listeners.plain = listener; + listeners.closed = listener // { + port = 10445; + via = "block"; + }; + }; + }; + exitNode = mkFixture "sing-box" exitInbounds; + exitNodeConfig = mkInboundsConfig exitNode; + exitNodeRules = exitNodeConfig.routing.rules; + exitNodeNoOnion = mkInboundsConfig (mkFixture "sing-box" (exitInbounds // { tor.routeOnion = false; })); + + # inbounds.routing.blockPrivate's resolve guard must come after the .onion rule: resolving + # a .onion name fails, and the connection with it. autoProxy's probe pins sit first. + guardFilter = pkgs.writeText "proxy-suite-tor-guard-check.jq" ( + import ../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix { + inherit lib; + pureXrayEnabled = false; + proxyInboundsGuardPrivate = true; + selectionMode = "selector"; + } + ); + guardRouteRules = pkgs.writeText "proxy-suite-tor-guard-rules.json" ( + builtins.toJSON ( + (mkRouting exitNode).singBoxRouteModeRules.common + ++ [ + { + domain_suffix = [ "ru" ]; + outbound = "direct"; + } + ] + ) + ); + guardRuntime = + pkgs.runCommand "proxy-suite-tor-guard-check" { nativeBuildInputs = [ pkgs.jq ]; } + '' + echo '{"inbounds":[],"outbounds":[],"dns":{"rules":[]},"route":{"rules":[]}}' | + jq --argjson obs '[]' --argjson auth_enabled false --arg user "" --arg password "" \ + --argjson route_enabled true --argjson route_rules "$(cat ${guardRouteRules})" \ + --arg route_final proxy --arg dns_final remote --argjson clear_dns_rules false \ + --argjson probe_inbounds '[]' --argjson autoproxy_rule_sets '[]' --argjson autoproxy_rules '[]' \ + --argjson probe_pin_rules '[{"inbound":["probe-in-0"],"outbound":"direct"}]' \ + -f ${guardFilter} > rules.json + jq -e ' + .route.rules as $r + | ($r | map(.domain_suffix? == ["onion"]) | index(true)) as $onion + | ($r | map(.action? == "resolve") | index(true)) as $guard + | ($r | map(.domain_suffix? == ["ru"]) | index(true)) as $ru + | $onion != null and $guard > $onion and $guard < $ru + ' rules.json + touch $out + ''; + + onionStart = torStartOf onion; + onionSpec = mkInboundsSpec onion; + onionInbounds = (services onion).proxy-suite-inbounds; + + invalidAssertions = mkFailingAssertions mkBadProxySuiteFixture ( + map (case: { enable = true; } // case) [ + # Enabled but used for nothing. + { tor.enable = true; } + # An outbound without a backend. + { + tor = { + enable = true; + asOutbound = true; + }; + } + # "tor" is taken. + { + tor = { + enable = true; + asOutbound = true; + }; + proxy = { + enable = true; + outbounds = [ + { + tag = "tor"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + } + # Snowflake ignores Socks5Proxy. + { + tor = { + enable = true; + asOutbound = true; + upstream = "proxy"; + bridges.lines = [ "snowflake 192.0.2.3:80 2B280B23E1107BB62ABFC40DDCC8824814F80A72" ]; + }; + proxy.enable = true; + } + # The SOCKS port on the proxy's own. + { + tor = { + enable = true; + asOutbound = true; + socksPort = 1080; + }; + proxy = { + enable = true; + listener.port = 1080; + }; + } + # An onion service without inbounds, and one naming a listener that is not there. + { + tor = { + enable = true; + onionService.enable = true; + }; + } + { + tor = { + enable = true; + onionService = { + enable = true; + listeners = [ "missing" ]; + }; + }; + inbounds = { + enable = true; + routing.via = "direct"; + listeners.plain = listener; + }; + } + # Two listeners on one onion port. + { + tor = { + enable = true; + onionService.enable = true; + }; + inbounds = { + enable = true; + routing.via = "direct"; + listeners.a = listener // { + sharePort = 443; + }; + listeners.b = listener // { + port = 10444; + sharePort = 443; + }; + }; + } + ]); +in +{ + runtime = guardRuntime; + + assertions = [ + ( + assert failedAssertions exitNode == [ ]; + assert + lib.head exitNodeRules == { + type = "field"; + ruleTag = "inbound-tor-onion"; + domain = [ "domain:onion" ]; + inboundTag = [ "plain" ]; + outboundTag = "proxy"; + }; + assert lib.any (o: o.tag == "proxy") exitNodeConfig.outbounds; + assert builtins.elem "proxy-suite-socks.service" (services exitNode).proxy-suite-inbounds.wants; + assert !(lib.any (r: r.ruleTag or "" == "inbound-tor-onion") exitNodeNoOnion.routing.rules); + assert !(lib.any (r: r.ruleTag or "" == "inbound-tor-onion") (mkInboundsConfig onion).routing.rules); + true + ) + ( + assert lib.all (f: failedAssertions f == [ ]) [ + singBox + xray + hybrid + noOnion + bridges + viaProxy + onion + ]; + true + ) + + # Every backend dials Tor's SOCKS listener as the "tor" outbound. + ( + assert hasInfix ''{"server":"127.0.0.1","server_port":18530,"tag":"tor","type":"socks"}'' singBoxStart; + true + ) + ( + assert + hasInfix ''{"protocol":"socks","settings":{"address":"127.0.0.1","port":18530},"tag":"tor"}'' xrayStart; + true + ) + ( + assert hasInfix ''"tag":"tor","type":"socks"'' hybridStart; + true + ) + # Only rules and detours reach it: never selected, tested, or used as an autoProxy exit. + ( + assert + hasInfix ''(if length > 1 then ["tor"] else [] end) as $tor'' singBoxStart + && hasInfix ''(.tag | ltrimstr("proxy-suite-ob-")) != "tor"'' singBoxStart; + true + ) + # Not after Tor: with upstream = "proxy" that would be a cycle. + ( + assert + builtins.elem "proxy-suite-tor.service" (services singBox).proxy-suite-socks.wants + && !(builtins.elem "proxy-suite-tor.service" (services singBox).proxy-suite-socks.after) + && builtins.elem "proxy-suite-socks.service" viaProxyTor.after; + true + ) + + # .onion goes to Tor in every route mode, after DNS hijack and sniffing. + ( + assert + builtins.elemAt singBoxModes.common 2 == { + domain_suffix = [ "onion" ]; + outbound = "tor"; + }; + true + ) + ( + assert + xrayRouting.xrayRouteModeRules.common == [ + { + type = "field"; + ruleTag = "tor-onion"; + domain = [ "domain:onion" ]; + outboundTag = "tor"; + } + ] + && lib.head xrayRouting.xrayRoutingRules == lib.head xrayRouting.xrayRouteModeRules.common; + true + ) + ( + assert + !(lib.any (r: r ? domain_suffix) (mkRouting noOnion).singBoxRouteModeRules.common) + && !(lib.any (r: r ? domain_suffix) noOnionTun.dns.rules); + true + ) + # Onion names never reach a resolver: a fake address where traffic is captured, NXDOMAIN elsewhere. + ( + assert + lib.take 2 singBoxTun.dns.rules == [ + { + inbound = [ "tun-in" ]; + domain_suffix = [ "onion" ]; + query_type = [ + "A" + "AAAA" + ]; + server = "fakeip"; + } + { + domain_suffix = [ "onion" ]; + action = "predefined"; + rcode = "NXDOMAIN"; + } + ] + && lib.any (s: s.tag == "fakeip") singBoxTun.dns.servers; + true + ) + ( + assert + (lib.head singBoxTProxy.dns.rules).inbound == [ + "tproxy-in" + "tproxy-in6" + ] + && lib.any (s: s.tag == "fakeip") singBoxTProxy.dns.servers; + true + ) + ( + assert + lib.take 2 (dnsOut (mkTunConfig xray)) == [ + { + action = "hijack"; + qType = "1,28"; + domain = [ "domain:onion" ]; + } + { + action = "return"; + rCode = 3; + domain = [ "domain:onion" ]; + } + ] + && (lib.head (dnsOut (mkTProxyConfig xray))).action == "return"; + true + ) + + # Tor runs as the service user, which TUN and TProxy let through, and keeps its keys private. + ( + assert + singBoxTorUnit.serviceConfig.User == "proxy-suite-daemon" + && singBoxTorUnit.serviceConfig.StateDirectory == "proxy-suite/tor" + && singBoxTorUnit.serviceConfig.StateDirectoryMode == "0700"; + true + ) + ( + assert + hasInfix "SocksPort 127.0.0.1:18530" singBoxTorStart + && hasInfix "DNSPort 0" singBoxTorStart + && hasInfix "ClientOnly 1" singBoxTorStart + && !(hasInfix "ClientOnly" relayTorStart) + && hasInfix "ControlSocket unix:$RUNTIME_DIRECTORY/control/socket" singBoxTorStart + && !(hasInfix "UseBridges" singBoxTorStart) + && !(hasInfix "Socks5Proxy" singBoxTorStart) + && !(hasInfix "HiddenService" singBoxTorStart); + true + ) + # userControl's group can use the control socket: that is `proxy-ctl tor status|newnym`. + ( + assert + hasInfix "proxy-suite-tor-control-dir" (toString (services controlled).proxy-suite-tor.serviceConfig.ExecStartPre) + && !(singBoxTorUnit.serviceConfig ? ExecStartPre) + && (mkProxyCtlDerived singBox).wrapperEnv.TOR_CONTROL_SOCKET == "/run/proxy-suite-tor/control/socket"; + true + ) + ( + assert + hasInfix "UseBridges 1" bridgesStart + && hasInfix "/bin/lyrebird" bridgesStart + && hasInfix "ClientTransportPlugin snowflake exec" bridgesStart + && hasInfix "Bridge obfs4 192.0.2.1:443 " bridgesStart + && hasInfix ''"$CREDENTIALS_DIRECTORY/bridges"'' bridgesStart + && builtins.elem "bridges:/run/secrets/tor-bridges" (services bridges).proxy-suite-tor.serviceConfig.LoadCredential; + true + ) + # Through the local proxy, with its password read at start, never written to the store. + ( + assert + hasInfix "Socks5Proxy 127.0.0.1:1080" viaProxyStart + && hasInfix ''echo "Socks5ProxyUsername "local-user'' viaProxyStart + && hasInfix ''"$CREDENTIALS_DIRECTORY/proxy-password"'' viaProxyStart + && builtins.elem "proxy-password:/run/secrets/local-proxy-password" viaProxyTor.serviceConfig.LoadCredential; + true + ) + + # The onion service forwards each listener's share port to where it listens. + ( + assert + hasInfix "HiddenServiceDir $STATE_DIRECTORY/onion" onionStart + && hasInfix "HiddenServicePort 10443 127.0.0.1:10443" onionStart + && hasInfix "HiddenServicePort 443 127.0.0.1:10444" onionStart + && hasInfix "SocksPort 0" onionStart + && hasInfix "hs_ed25519_secret_key" onionStart; + true + ) + ( + assert + lib.sort (a: b: a < b) onionSpec.onionListeners == [ + "plain" + "shared" + ] + && builtins.elem "proxy-suite-tor.service" onionInbounds.after + && builtins.elem "proxy-suite-tor.service" onionInbounds.wants; + true + ) + ( + assert !(onion.config.systemd.services ? proxy-suite-socks); + true + ) + ] + ++ invalidAssertions; +} diff --git a/nix/checks/xray-backend-features/fixtures.nix b/nix/checks/xray-backend-features/fixtures.nix index c96441e..efde02b 100644 --- a/nix/checks/xray-backend-features/fixtures.nix +++ b/nix/checks/xray-backend-features/fixtures.nix @@ -17,6 +17,7 @@ let proxyCfg = null; sshProxyCfg = null; warpCfg = null; + torCfg = null; awgOutbounds = null; constants = null; hybridEnabled = null; diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index 9fb88e2..6a82a25 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -36,6 +36,7 @@ localProxyUrl, autoProxyEnabled, autoProxyStateDir, + torControlSocket ? "", singBox, stateDir ? "/var/lib/proxy-suite", runtimeDir ? "/run", @@ -84,6 +85,7 @@ let LOCAL_PROXY_URL = localProxyUrl; AUTOPROXY_ENABLED = autoProxyEnabled; AUTOPROXY_STATE_DIR = autoProxyStateDir; + TOR_CONTROL_SOCKET = torControlSocket; SING_BOX = singBox; STATE_DIR = stateDir; RUNTIME_DIR = runtimeDir; diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index ba3e60b..01a22c5 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -29,6 +29,7 @@ ALL_SERVICES = [ "proxy-suite-ssh-proxy", "proxy-suite-warp", "proxy-suite-warp-tunnel", + "proxy-suite-tor", "proxy-suite-tg-ws-proxy", "proxy-suite-zapret", "proxy-suite-zapret-vm-exempt", @@ -40,6 +41,7 @@ RESTART_SERVICES = [ "proxy-suite-inbounds", "proxy-suite-ssh-proxy", "proxy-suite-warp-tunnel", + "proxy-suite-tor", "proxy-suite-tg-ws-proxy", "proxy-suite-zapret", ] @@ -101,14 +103,17 @@ Secrets and changes need root, or the userControl group. ssh [status|on|off] SSH SOCKS5 tunnel warp [status|on|off] WARP tunnel behind the warp outbound + tor [status|on|off] Tor, behind the tor outbound and the onion service + tor newnym new circuits for new connections tg [status|on|off] Telegram WebSocket proxy apps [list] per-app routing profiles apps run -- [args] run a command through a profile inbounds [list] server inbounds - inbounds link [user] [--qr|--json] - client share link, or the client's outbound JSON + inbounds link [user] [--onion] [--qr|--json] + client share link, or the client's outbound JSON; + --onion: the one through the onion service inbounds link [user] --config [--qr] an AmneziaWG client's .conf, or its QR code inbounds link --server-json the server's inbound JSON @@ -313,6 +318,68 @@ def _warp_unit(): return "proxy-suite-warp-tunnel" +def _tor_control(*commands): + """Replies to commands on Tor's control socket, one list of lines per command. + + The socket authenticates by who can open it: root and the userControl group. + """ + path = env("TOR_CONTROL_SOCKET", f"{runtime_dir()}/proxy-suite-tor/control/socket") + replies = [] + try: + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock: + sock.settimeout(5) + sock.connect(path) + stream = sock.makefile("rwb") + for command in ("AUTHENTICATE", *commands): + stream.write(command.encode("ascii") + b"\r\n") + stream.flush() + lines = [] + while True: + line = stream.readline() + if not line: + die("Tor closed its control connection.") + line = line.decode("utf-8", "replace").rstrip("\r\n") + lines.append(line) + # "250-" and "250+" continue a reply; "250 " ends it. + if len(line) >= 4 and line[3] == " ": + break + if not lines[-1].startswith("250"): + die(f"Tor refused {command.split()[0]}: {lines[-1]}") + replies.append(lines) + except PermissionError: + denied(path, "open") + except (FileNotFoundError, ConnectionRefusedError): + die("Tor is not running: no control socket.") + except OSError as exc: + die(f"Cannot talk to Tor: {exc}") + return replies[1:] + + +def _tor_bootstrap(): + """Tor's bootstrap progress, as "100% (Done)".""" + line = _tor_control("GETINFO status/bootstrap-phase")[0][0] + progress = re.search(r"PROGRESS=(\d+)", line) + summary = re.search(r'SUMMARY="((?:[^"\\]|\\.)*)"', line) + if not progress: + return line + return f"{progress.group(1)}%" + (f" ({summary.group(1)})" if summary else "") + + +def cmd_tor(verb="status", *args): + unit = "proxy-suite-tor" + if verb == "newnym": + if not svc_exists(unit): + die("tor is not enabled in this configuration.") + _tor_control("SIGNAL NEWNYM") + print("New connections take new circuits (Tor allows this once every 10 seconds).") + return + if verb not in ("status", "on", "off"): + usage("tor [status|on|off|newnym]") + _toggle(unit, "tor", verb, *args) + if verb == "status" and svc_active(unit): + print(f"bootstrap {_tor_bootstrap()}") + + def _emit(text, qr): """Prints text, or its QR code.""" if not qr: @@ -379,6 +446,7 @@ COMPLETE = { "awg": "AmneziaWG profiles", "ssh": "SSH SOCKS5 tunnel", "warp": "WARP tunnel behind the warp outbound", + "tor": "Tor, behind the tor outbound and the onion service", "tg": "Telegram WebSocket proxy", "apps": "per-app routing profiles", "inbounds": "server inbounds", @@ -497,6 +565,7 @@ COMPLETE = { "awg restart": {"args": lambda: _names(_awg_profiles())}, "ssh": {"words": TOGGLE}, "warp": {"words": TOGGLE}, + "tor": {"words": {**TOGGLE, "newnym": "new circuits for new connections"}}, "tg": {"words": TOGGLE}, "apps": {"words": {"list": "per-app routing profiles", "run": "run a command through a profile"}}, "apps run": {"args": lambda: {_s(p["name"]): _s(p.get("route") or "") for p in read_json(env("PER_APP_ROUTING_PROFILES_FILE"))}}, @@ -514,6 +583,7 @@ COMPLETE = { "args": _inbound_link_choices, "flags": { "--qr": "print a QR code", + "--onion": "the link through the onion service", "--json": "the client's outbound JSON", "--config": "an AmneziaWG client's .conf", "--server-json": "the server's inbound JSON", @@ -2775,9 +2845,16 @@ def _inbound_server_json(tag): print(_json_text(inbound)) -def _inbound_link_for(tag, user="", *_, field="link"): - matches = [x for x in _inbound_links() if x.get("tag") == tag and (not user or x.get("user") == user)] +def _inbound_link_for(tag, user="", *_, field="link", variant=""): + """variant "onion": the link to the listener through the onion service.""" + matches = [ + x + for x in _inbound_links() + if x.get("tag") == tag and (not user or x.get("user") == user) and (x.get("variant") or "") == variant + ] if not matches: + if variant == "onion": + die(f"No onion link for {tag}: is it in tor.onionService.listeners, and has Tor written its address?") die(f"Unknown inbound, or no share link for it: {tag}") if len(matches) > 1: sys.stdout.flush() @@ -2973,20 +3050,22 @@ def cmd_inbounds(verb="list", *args): row = " {:<24} {:<16} {:<14} {:<8} {}" print(row.format("TAG", "USER", "TYPE", "PORT", "STATE")) for x in _inbound_links(): - print(row.format(*(_s(x.get(k)) for k in ("tag", "user", "type", "port")), state)) + kind = _s(x.get("type")) + (" (onion)" if x.get("variant") == "onion" else "") + print(row.format(_s(x.get("tag")), _s(x.get("user")), kind, _s(x.get("port")), state)) elif verb in ("link", "qr"): rest = [a for a in args if not a.startswith("--")] if not rest: - usage("inbounds link [user] [--qr|--json|--config|--server-json]") + usage("inbounds link [user] [--onion] [--qr|--json|--config|--server-json]") qr = verb == "qr" or "--qr" in args + variant = "onion" if "--onion" in args else "" if "--server-json" in args: _inbound_server_json(rest[0]) elif "--json" in args: - print(_json_text(_inbound_link_for(*rest, field="outbound"))) + print(_json_text(_inbound_link_for(*rest, field="outbound", variant=variant))) elif "--config" in args: - _emit(_inbound_link_for(*rest, field="config").rstrip("\n"), qr) + _emit(_inbound_link_for(*rest, field="config", variant=variant).rstrip("\n"), qr) else: - _emit(_inbound_link_for(*rest), qr) + _emit(_inbound_link_for(*rest, variant=variant), qr) elif verb == "stats": _inbound_stats(*args) elif verb == "online": @@ -3030,6 +3109,7 @@ COMMANDS = { "awg": cmd_awg, "ssh": lambda *args: _toggle("proxy-suite-ssh-proxy", "ssh", *args), "warp": lambda *args: _toggle(_warp_unit(), "warp", *args), + "tor": cmd_tor, "tg": lambda *args: _toggle("proxy-suite-tg-ws-proxy", "tg", *args), "apps": cmd_apps, "inbounds": cmd_inbounds, diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index b61263e..e35ba2e 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -135,6 +135,7 @@ TOGGLES = { # WARP as an AmneziaWG outbound: `proxy-ctl warp`, not `awg`, which only knows global profiles. "proxy-suite-awg-warp": ["warp"], "proxy-suite-tg-ws-proxy": ["tg"], + "proxy-suite-tor": ["tor"], "proxy-suite-zapret": ["zapret"], } AWG_PREFIX = ctl._awg_service("") @@ -303,8 +304,13 @@ def inbound_rows(_): # No presence column: XRay keys the online map by user alone (no inbound dimension), # so a per-listener row could only repeat the same verdict once per listener. The # "who is online" action shows it once per user, which is the shape the data has. + # A listener behind the onion service has a second row, for its .onion link. return [ - {"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}} + { + "key": "/".join(ctl._s(x.get(k) or "") for k in ("tag", "user", "variant")), + **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port", "variant")}, + **({"type": f"{ctl._s(x.get('type') or '')} (onion)"} if x.get("variant") == "onion" else {}), + } for x in ctl._inbound_links() ] @@ -360,7 +366,8 @@ def _natural(value): def _link(row, *extra): - return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *extra] + onion = ["--onion"] if row.get("variant") == "onion" else [] + return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *onion, *extra] def _amneziawg(row): diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index d9d63c3..65512b9 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -9,6 +9,7 @@ import shutil import socket import sys import tempfile +import threading import unittest from unittest import mock @@ -873,6 +874,26 @@ class ShareTest(EnvTest): self.assertNotEqual(status, 0) self.assertIn("only AmneziaWG", err) + def test_inbound_onion_link(self): + self.write( + "inbounds/links.json", + [ + {"tag": "in", "user": "u", "type": "vless", "link": "vless://x@h:443", "outbound": {"server": "h"}}, + {"tag": "in", "user": "u", "type": "vless", "port": 443, "link": "vless://x@o.onion:443", "outbound": {"server": "o.onion"}, + "variant": "onion"}, + {"tag": "plain", "user": "u", "type": "vless", "link": "vless://x@h:80", "outbound": None}, + ], + ) + # Same tag and user: the plain link unless --onion asks for the other. + self.assertEqual(ok(ctl.cmd_inbounds, "link", "in", "u"), "vless://x@h:443\n") + self.assertEqual(ok(ctl.cmd_inbounds, "link", "in", "--onion"), "vless://x@o.onion:443\n") + self.assertEqual(json.loads(ok(ctl.cmd_inbounds, "link", "in", "u", "--onion", "--json"))["server"], "o.onion") + status, _, err = run(ctl.cmd_inbounds, "link", "plain", "--onion") + self.assertNotEqual(status, 0) + self.assertIn("onionService.listeners", err) + self.patch("svc_state", lambda unit: "active") + self.assertRegex(ok(ctl.cmd_inbounds, "list"), r"(?m)^ in +u +vless \(onion\) +443 +active$") + @unittest.skipIf(os.geteuid() == 0, "root reads anything") def test_unreadable(self): os.chmod(self.share, 0) @@ -881,6 +902,61 @@ class ShareTest(EnvTest): self.assertIn("re-run with sudo", err) +class TorTest(EnvTest): + """proxy-ctl tor against a fake control socket that answers like Tor 0.4.9.""" + + def setUp(self): + super().setUp() + # A relative path: an absolute one under TMPDIR can outgrow sun_path. + cwd = os.getcwd() + os.chdir(self.dir) + self.addCleanup(os.chdir, cwd) + os.environ["TOR_CONTROL_SOCKET"] = "control" + self.received = [] + self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.server.bind("control") + self.server.listen(1) + self.addCleanup(self.server.close) + self.thread = threading.Thread(target=self.serve, daemon=True) + self.thread.start() + self.patch("systemctl", lambda *a, **kw: (0, "active\n") if kw.get("capture") else (0, None)) + + def serve(self): + replies = { + "AUTHENTICATE": "250 OK", + "GETINFO status/bootstrap-phase": '250-status/bootstrap-phase=NOTICE BOOTSTRAP PROGRESS=75 TAG=enough_dirinfo ' + 'SUMMARY="Loaded enough directory info to build circuits"\r\n250 OK', + "SIGNAL NEWNYM": "250 OK", + } + try: + conn, _ = self.server.accept() + except OSError: + return + with conn, conn.makefile("rwb") as stream: + for line in stream: + command = line.decode().rstrip("\r\n") + self.received.append(command) + stream.write((replies.get(command, '510 Unrecognized command "x"') + "\r\n").encode()) + stream.flush() + + def test_status_shows_bootstrap(self): + out = ok(ctl.cmd_tor) + self.assertIn("bootstrap 75% (Loaded enough directory info to build circuits)", out) + self.assertEqual(self.received, ["AUTHENTICATE", "GETINFO status/bootstrap-phase"]) + + def test_newnym(self): + ok(ctl.cmd_tor, "newnym") + self.thread.join(5) + self.assertEqual(self.received, ["AUTHENTICATE", "SIGNAL NEWNYM"]) + + def test_not_running(self): + os.environ["TOR_CONTROL_SOCKET"] = "missing" + status, _, err = run(ctl.cmd_tor, "newnym") + self.assertNotEqual(status, 0) + self.assertIn("not running", err) + self.assertNotEqual(run(ctl.cmd_tor, "bogus")[0], 0) + + class BadExitTest(EnvTest): def test_shown_from_state(self): os.environ.update( diff --git a/pkgs/proxy-ctl/test_proxy_model.py b/pkgs/proxy-ctl/test_proxy_model.py index a520b7e..9e6628c 100644 --- a/pkgs/proxy-ctl/test_proxy_model.py +++ b/pkgs/proxy-ctl/test_proxy_model.py @@ -107,6 +107,20 @@ class ModelTest(unittest.TestCase): self.assertEqual(called, []) self.assertNotIn("online", [c for c, _ in next(t for t in model.TABS if t.id == "inbounds").columns]) + def test_onion_rows_link_through_the_onion(self): + links = [ + {"tag": "ws", "user": "alice", "type": "vless", "port": 443}, + {"tag": "ws", "user": "alice", "type": "vless", "port": 443, "variant": "onion"}, + ] + with mock.patch.object(ctl, "_inbound_links", lambda: links): + plain, onion = model.inbound_rows({}) + self.assertNotEqual(plain["key"], onion["key"]) + self.assertEqual((plain["type"], onion["type"]), ("vless", "vless (onion)")) + self.assertEqual(model._link(plain, "--qr"), ["inbounds", "link", "ws", "alice", "--qr"]) + self.assertEqual(model._link(onion, "--qr"), ["inbounds", "link", "ws", "alice", "--onion", "--qr"]) + self.assertFalse(model._amneziawg(onion)) + self.assertEqual(model.TOGGLES["proxy-suite-tor"], ["tor"]) + def test_tray_menu(self): states = { "proxy-suite-socks": "active", diff --git a/scripts/build-inbound.py b/scripts/build-inbound.py index d44d3b3..864791a 100644 --- a/scripts/build-inbound.py +++ b/scripts/build-inbound.py @@ -19,6 +19,12 @@ def main() -> None: dest="server_address", help="public address used in generated share links", ) + ap.add_argument( + "--onion-address", + default="", + dest="onion_address", + help="the onion service's address, for a second set of links to its listeners", + ) args = ap.parse_args() with open(args.spec, encoding="utf-8") as handle: @@ -30,7 +36,7 @@ def main() -> None: sys.exit(1) try: - result = build_inbounds(spec, server_address) + result = build_inbounds(spec, server_address, args.onion_address) except (ValueError, OSError) as exc: print(f"error: {exc}", file=sys.stderr) sys.exit(1) diff --git a/scripts/proxy_inbound.py b/scripts/proxy_inbound.py index 3ac8132..988755b 100644 --- a/scripts/proxy_inbound.py +++ b/scripts/proxy_inbound.py @@ -243,14 +243,16 @@ def _link_security_params(listener: dict, server_address: str) -> dict: return {"security": "none"} -def _vmess_link(listener: dict, secret: str, server_address: str, label: str) -> str: +def _vmess_link( + listener: dict, secret: str, server_address: str, label: str, endpoint_address: str +) -> str: transport = listener["transport"] reality = listener["reality"] tls = listener["tls"] blob = { "v": "2", "ps": label, - "add": server_address, + "add": endpoint_address, "port": str(_share_port(listener)), "id": secret, "aid": "0", @@ -266,8 +268,14 @@ def _vmess_link(listener: dict, secret: str, server_address: str, label: str) -> return "vmess://" + _b64(json.dumps(blob, separators=(",", ":"))) -def build_share_link(listener: dict, server_address: str, user_index: int = 0) -> str: - """Build the client-facing share URL for a listener.""" +def build_share_link( + listener: dict, server_address: str, user_index: int = 0, onion_address: str = "" +) -> str: + """Build the client-facing share URL for a listener. + + With an onion address the link dials that instead, through the client's Tor; the TLS + and REALITY names stay those of server_address, which the listener still answers to. + """ tag = listener["tag"] listener_type = listener["type"] users = listener["users"] @@ -279,13 +287,14 @@ def build_share_link(listener: dict, server_address: str, user_index: int = 0) - user = users[user_index] secret = _user_secret(user, listener_type, tag) user_name = user.get("name") or f"{tag}-{user_index}" - label = f"{tag} ({user_name})" + label = f"{tag} ({user_name}, onion)" if onion_address else f"{tag} ({user_name})" fragment = urllib.parse.quote(label, safe="") - host = f"[{server_address}]" if ":" in server_address else server_address + endpoint_address = onion_address or server_address + host = f"[{endpoint_address}]" if ":" in endpoint_address else endpoint_address endpoint = f"{host}:{_share_port(listener)}" if listener_type == "vmess": - return _vmess_link(listener, secret, server_address, label) + return _vmess_link(listener, secret, server_address, label, endpoint_address) if listener_type == "shadowsocks": if len(users) > 1: @@ -335,7 +344,9 @@ def render_amneziawg_inbound(listener: dict) -> dict: } -def build_listener(listener: dict, server_address: str, share_links: bool) -> dict: +def build_listener( + listener: dict, server_address: str, share_links: bool, onion_address: str = "" +) -> dict: """Render one listener into its inbound object and, when possible, a link. Raw-JSON listeners are passed through untouched apart from the tag, and get @@ -372,7 +383,22 @@ def build_listener(listener: dict, server_address: str, share_links: bool) -> di if share_links else [] ) - return {"tag": tag, "type": listener["type"], "port": _share_port(listener), "inbound": inbound, "links": links} + onion_links = ( + [ + build_share_link(listener, server_address, index, onion_address) + for index in range(len(listener["users"])) + ] + if share_links and onion_address + else [] + ) + return { + "tag": tag, + "type": listener["type"], + "port": _share_port(listener), + "inbound": inbound, + "links": links, + "onionLinks": onion_links, + } def client_outbound(link: str, tag: str) -> dict | None: @@ -397,36 +423,43 @@ def subscription_token(name: str, secrets: list[str]) -> str: return hashlib.sha256(material.encode("utf-8")).hexdigest()[:32] -def build_inbounds(spec: dict, server_address: str) -> dict: +def build_inbounds(spec: dict, server_address: str, onion_address: str = "") -> dict: """Render a whole spec into {"inbounds": [...], "links": [...], "subscriptions": [...]}. A subscription gathers one user's links from every listener -- users are matched by name -- as base64 of the newline-joined links, which is what - v2rayNG, Hiddify and NekoBox import. + v2rayNG, Hiddify and NekoBox import. Listeners in spec["onionListeners"] get a + second link per user to onion_address, with "variant": "onion", in both. """ inbounds = [] links = [] by_user: dict[str, dict] = {} for listener in spec["listeners"]: - rendered = build_listener(listener, server_address, spec.get("shareLinks", True)) + onion = onion_address if listener["tag"] in spec.get("onionListeners", []) else "" + rendered = build_listener(listener, server_address, spec.get("shareLinks", True), onion) inbounds.append(rendered["inbound"]) - for index, link in enumerate(rendered["links"]): - user = listener["users"][index] - name = user.get("name") or f"{rendered['tag']}-{index}" - links.append( - { - "tag": rendered["tag"], - "user": name, - "type": rendered.get("type", ""), - "port": rendered.get("port", 0), - "link": link, - "outbound": client_outbound(link, rendered["tag"]), - } - ) - entry = by_user.setdefault(name, {"links": [], "secrets": []}) - entry["links"].append(link) - entry["secrets"].append(_user_secret(user, listener["type"], rendered["tag"])) + variants = [(rendered["links"], {})] + if rendered.get("onionLinks"): + variants.append((rendered["onionLinks"], {"variant": "onion"})) + for variant_links, extra in variants: + for index, link in enumerate(variant_links): + user = listener["users"][index] + name = user.get("name") or f"{rendered['tag']}-{index}" + links.append( + { + "tag": rendered["tag"], + "user": name, + "type": rendered.get("type", ""), + "port": rendered.get("port", 0), + "link": link, + "outbound": client_outbound(link, rendered["tag"]), + **extra, + } + ) + entry = by_user.setdefault(name, {"links": [], "secrets": []}) + entry["links"].append(link) + entry["secrets"].append(_user_secret(user, listener["type"], rendered["tag"])) # Not in subscriptions: the clients reading those do not speak vpn://. for entry in rendered.get("configs", []): links.append( diff --git a/scripts/test-build-inbound.py b/scripts/test-build-inbound.py index ffb45a8..ac3f795 100644 --- a/scripts/test-build-inbound.py +++ b/scripts/test-build-inbound.py @@ -576,6 +576,74 @@ class BuildInboundsTests(unittest.TestCase): self.assertEqual(result["inbounds"][0]["port"], 2053) self.assertEqual(result["links"], []) + def test_onion_links_dial_the_onion_and_keep_the_names(self): + onion = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion" + tls = {"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None} + users = [{"name": "alice", "uuid": "uuid-1", "uuidFile": None, "password": None, "passwordFile": None}] + spec = { + "serverAddress": "vpn.example.com", + "shareLinks": True, + "onionListeners": ["reality", "ws", "vmess"], + "listeners": [ + listener(tag="reality", users=users, reality=reality()), + listener( + tag="ws", + users=users, + port=10002, + sharePort=443, + tls=tls, + transport={"type": "ws", "path": "/ws", "host": "cdn.example.com", "serviceName": ""}, + ), + listener(tag="vmess", type="vmess", users=users, port=8443, tls=tls), + listener(tag="plain", users=users, port=8080), + ], + } + result = build_inbounds(spec, "vpn.example.com", onion) + by_variant = {(e["tag"], e.get("variant", "")): e for e in result["links"]} + self.assertEqual( + sorted(by_variant), + sorted( + [ + ("reality", ""), + ("reality", "onion"), + ("ws", ""), + ("ws", "onion"), + ("vmess", ""), + ("vmess", "onion"), + ("plain", ""), + ] + ), + ) + + real = by_variant[("reality", "onion")]["link"] + self.assertTrue(real.startswith(f"vless://uuid-1@{onion}:443?"), real) + self.assertEqual(link_params(real)["sni"], "www.microsoft.com") + self.assertIn("onion", urllib.parse.unquote(urllib.parse.urlsplit(real).fragment)) + + # The onion port is the share port, as the torrc maps it; TLS keeps the real name. + ws = by_variant[("ws", "onion")] + self.assertEqual(ws["port"], 443) + self.assertTrue(ws["link"].startswith(f"vless://uuid-1@{onion}:443?"), ws["link"]) + self.assertEqual(link_params(ws["link"])["sni"], "vpn.example.com") + self.assertEqual(link_params(ws["link"])["host"], "cdn.example.com") + self.assertEqual(ws["outbound"]["server"], onion) + + payload = by_variant[("vmess", "onion")]["link"][len("vmess://") :] + blob = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + self.assertEqual(blob["add"], onion) + self.assertEqual(blob["sni"], "vpn.example.com") + + # The plain links are untouched, and a subscription carries both. + self.assertTrue(by_variant[("reality", "")]["link"].startswith("vless://uuid-1@vpn.example.com:443?")) + body = base64.b64decode(result["subscriptions"][0]["body"]).decode().split("\n") + self.assertEqual(len(body), 7) + self.assertIn(real, body) + + # No address yet: no onion links, and nothing else changes. + without = build_inbounds(spec, "vpn.example.com") + self.assertEqual([e for e in without["links"] if e.get("variant")], []) + self.assertEqual(without["inbounds"], result["inbounds"]) + if __name__ == "__main__": unittest.main()