diff --git a/README.md b/README.md index ae8fc55..5f8d777 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github. - Local SOCKS5/HTTP proxy on `127.0.0.1:1080`, on sing-box, XRay, or both - System-wide TUN or TProxy mode, on demand or at boot - Kill switch: nothing leaks while a global tunnel restarts or after it fails -- Per-app routing: `proxy-ctl apps run -- ` +- Per-app routing: `proxy-ctl apps run -- `, or packages wrapped to always use the proxy - Outbounds from links, raw JSON or subscriptions, picked by hand or by latency - vless (REALITY, TLS), vmess, trojan, shadowsocks, hysteria2, socks, http; TUIC, AnyTLS and NaïveProxy on sing-box; XHTTP and ECH on XRay - Proxy chains: any outbound can connect through another @@ -135,7 +135,7 @@ services.proxy-suite = { ## Docs -- [Usage guides](./docs/usage/index.md): common setups, step by step. +- [Usage guides](./docs/usage/index.md): common setups, step by step, and complete examples. - [Options reference](./docs/options/index.md): every option. Regenerate it and the help below with `nix run .#update-docs`. ## `proxy-ctl help` diff --git a/docs/usage/client-basics.md b/docs/usage/client-basics.md index 04c678d..6a388f8 100644 --- a/docs/usage/client-basics.md +++ b/docs/usage/client-basics.md @@ -37,8 +37,8 @@ export all_proxy=socks5h://127.0.0.1:1080 export https_proxy=http://127.0.0.1:1080 ``` -To route apps without setting them up, see [Route the whole machine](./system-wide.md) or -[Route a single app](./per-app.md). +To route apps without setting them up, see [Route the whole machine](./system-wide.md), +[Route a single app](./per-app.md) or [Wrap programs with the proxy](./wrap-apps.md). ## Commands diff --git a/docs/usage/examples/multi-exit.md b/docs/usage/examples/multi-exit.md new file mode 100644 index 0000000..5f685cf --- /dev/null +++ b/docs/usage/examples/multi-exit.md @@ -0,0 +1,174 @@ +# Example: several exits, picked per site + +One host with four ways out: direct (with zapret2 for DPI), a VPS, WARP and an SSH server. +Each site goes to whichever works best for it, and autoProxy covers the sites nobody +listed. Everything runs in global TUN mode, so every app on the host follows these rules. + +```nix +{ ... }: +let + # Geosite "youtube" can miss the video and API hosts. + youtubeDomains = [ + "googlevideo.com" + "gvt1.com" + "ytimg.com" + "ggpht.com" + "youtubei.googleapis.com" + ]; + # Telegram apps dial their data centres by IP, so names alone do not catch them + # (https://core.telegram.org/resources/cidr.txt). + telegramIps = [ + "91.105.192.0/23" + "91.108.4.0/22" + "91.108.8.0/22" + "91.108.12.0/22" + "91.108.16.0/22" + "91.108.20.0/22" + "91.108.56.0/22" + "149.154.160.0/20" + "185.76.151.0/24" + "2001:67c:4e8::/48" + "2001:b28:f23c::/48" + "2001:b28:f23d::/48" + "2001:b28:f23f::/48" + "2a0a:f280::/32" + ]; +in +{ + services.proxy-suite = { + enable = true; + + proxy = { + enable = true; + outbounds = [ { tag = "primary"; urlFile = "/run/secrets/proxy-primary-url"; } ]; + tun.enable = true; + autostart = "tun"; + + routing = { + # Unlisted sites leave directly, where zapret2 unblocks what DPI blocks. + default = "direct"; + # Russian sites are routed by the last rule below instead. + directRu = false; + + # Checked in order; the first match wins. + rules = [ + # Sites that reject both this host's and the VPS's networks. + { + outbound = "ssh-proxy"; + geosites = [ "pixiv" "twitter" ]; + } + # Video throttled per connection by destination IP, which zapret cannot fix. + # One exit for the whole session: video URLs are bound to the IP that asked. + { + outbound = "warp"; + domains = youtubeDomains; + geosites = [ "youtube" ]; + } + # A CDN that stalls through WARP but runs at full speed directly. + { + outbound = "direct"; + domains = [ "video-cdn.example" ]; + } + # Russian services that refuse the VPS's foreign IP. + { + outbound = "warp"; + geosites = [ "category-ru" ]; + geoips = [ "ru" ]; + } + ]; + + # Through the selected outbound ("primary"). + proxy = { + geosites = [ "openai" "anthropic" "telegram" "netflix" ]; + ips = telegramIps; + # WARP registers through the proxy: its API is blocked directly. + domains = [ "api.cloudflareclient.com" ]; + }; + }; + + # For blocked sites no list names yet. YouTube is pinned to WARP above, so it + # is kept out of the probes. + autoProxy = { + enable = true; + exclude = [ "googlevideo.com" "gvt1.com" ]; + }; + }; + + warp = { + enable = true; + asOutbound = "singBox"; + }; + + sshProxy = { + enable = true; + asOutbound = true; + server = { + user = "me"; + host = "203.0.113.20"; + port = 2222; + }; + identityFile = "/run/secrets/proxy-ssh-key"; + hostKeyFile = "/run/secrets/proxy-ssh-known-hosts"; + }; + + # Tor through the proxy, since this network blocks Tor. + tor = { + enable = true; + asOutbound = true; + upstream = "proxy"; + }; + + zapret = { + enable = true; + engine = "zapret2"; + }; + }; + + # autoProxy probes in bursts (seconds of CPU, a few hundred MB). On a busy host, keep + # it from competing with real work. + systemd.services.proxy-suite-autoproxy.serviceConfig = { + CPUWeight = 10; + IOWeight = 10; + Nice = 19; + MemoryHigh = "200M"; + }; +} +``` + +## Checking the result + +```sh +proxy-ctl where youtube.com # -> warp, by the rule for youtube +proxy-ctl where chatgpt.com # -> proxy -> primary, by geosite openai +proxy-ctl proxy auto # what autoProxy routed, and through which exit +proxy-ctl zapret auto # what zapret2 learned +``` + +## With relay clients + +On a [relay server](./relay-server.md) with `inbounds.routing.via = "proxy"`, clients follow +these rules too, with two exceptions. Russian sites are blocked for them (`blockRu`), and +sites on zapret's list go straight out, so this host's zapret handles them (`zapretDirect`). +Sites listed in `inbounds.routing.proxy` skip both exceptions and go to the rules above: + +```nix no-check +services.proxy-suite.inbounds.routing = { + via = "proxy"; + blockRu = false; # clients may reach Russian sites, through WARP by the rule above + proxy = { + domains = youtubeDomains; # on zapret's list, but WARP works better here + geosites = [ "youtube" "category-ru" ]; + geoips = [ "ru" ]; + }; +}; +``` + +The same list applies to listeners with their own `via`, including `"direct"` ones. + +## Notes + +- Rules take effect in order. Put narrow ones (a single CDN) before broad ones (a whole + country). +- Rules can name any outbound tag: yours, `warp`, `ssh-proxy`, `tor`, or an AmneziaWG + outbound. +- `.onion` names go to Tor without a rule. diff --git a/docs/usage/examples/private-vpn.md b/docs/usage/examples/private-vpn.md new file mode 100644 index 0000000..069a1a8 --- /dev/null +++ b/docs/usage/examples/private-vpn.md @@ -0,0 +1,91 @@ +# Example: a private VPN for your own devices + +An AmneziaWG server for your laptop and phone. Unlike the proxy listeners, it also reaches +the server itself and its private services, like a home VPN. Internet traffic still follows +the server's routing (`inbounds.routing.via`), so the devices get the same exits and zapret +as the server. + +A small DNS server on the tunnel address answers for private names, such as a mail server +that is only reachable over the VPN. + +```nix +{ ... }: +let + interface = "awg0"; + serverAddress = "10.77.77.1"; + privateDomains = [ "mail.example.com" ]; +in +{ + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ { tag = "primary"; urlFile = "/run/secrets/proxy-primary-url"; } ]; + }; + + inbounds = { + enable = true; + routing.via = "proxy"; + listeners.vpn = { + type = "amneziawg"; + port = 51820; + # Fixed addresses, so firewall rules and DNS can name each device. Keys are + # generated on first start. + users = [ + { name = "laptop"; address = "10.77.77.2"; } + { name = "phone"; address = "10.77.77.3"; } + ]; + amneziaWg = { + # Devices also reach this host, its LAN and each other, directly. + mode = "lan"; + interfaceName = interface; + subnet = "10.77.77.0/24"; + subnet6 = "fd77:77:77::/64"; + mtu = 1400; + dns = [ serverAddress ]; + # Optional: a fixed server key, so client configs survive a reinstall. + privateKeyFile = "/run/secrets/awg-server-key"; + }; + }; + }; + }; + + # Private names for VPN clients; everything else is forwarded to 1.1.1.1. + services.dnsmasq = { + enable = true; + resolveLocalQueries = false; + settings = { + bind-dynamic = true; + interface = interface; + listen-address = serverAddress; + no-resolv = true; + server = [ "1.1.1.1" ]; + address = map (domain: "/${domain}/${serverAddress}") privateDomains; + }; + }; + # The interface comes and goes with the listener. + systemd.services.dnsmasq = { + after = [ "proxy-suite-inbounds-awg.service" ]; + wants = [ "proxy-suite-inbounds-awg.service" ]; + }; +} +``` + +## Adding a device + +```sh +proxy-ctl inbounds link vpn phone --config --qr # scan in the AmneziaWG app +proxy-ctl inbounds link vpn laptop --config > laptop.conf +proxy-ctl inbounds link vpn phone # a vpn:// link instead +``` + +On a laptop that also runs proxy-suite, the `.conf` becomes a profile: see +[Use an AmneziaWG config](../amneziawg.md). + +## Notes + +- `mode = "lan"` turns on IP forwarding. The default, `"proxy"`, gives devices the + internet only, like the other listeners. +- Only TCP and UDP reach the internet; ping and other protocols stop at the server. +- A device that keeps its own private key can be added with `users.*.publicKey` instead; + it gets no generated config. diff --git a/docs/usage/examples/relay-server.md b/docs/usage/examples/relay-server.md new file mode 100644 index 0000000..e5c3a09 --- /dev/null +++ b/docs/usage/examples/relay-server.md @@ -0,0 +1,200 @@ +# Example: a relay server behind nginx + +A VPS that already runs nginx for websites on port 443 also serves proxy clients: family +and friends, each with their own UUID and subscription. To a censor, the proxy traffic looks +like the site's own HTTPS. Clients get several transports, so each network can use +whichever one gets through. + +| Listener | Reached as | Why | +|---|---|---| +| `xhttp` | `https://vpn.example.com/media` through nginx | Looks like ordinary HTTPS to the site | +| `ws` | `/media-ws` through nginx | For clients without XHTTP | +| `xhttp-stream` | `/media-stream` through nginx, over gRPC | HTTP/2 end to end, for stream-one mode | +| `xhttp-h3` | UDP 443, directly | HTTP/3 next to nginx, which holds TCP 443 | +| `reality` | TCP 2053, directly | REALITY with Vision, no HTTP layer to stall | + +Client traffic exits through this host's own proxy (`routing.via = "proxy"`): here a single +upstream server, `primary`. With more exits, the server's routing decides where each site +goes; [Several exits, picked per site](./multi-exit.md) shows that. + +```nix +{ config, lib, ... }: +let + domain = "vpn.example.com"; + certDir = config.security.acme.certs.${domain}.directory; + + users = map (name: { inherit name; uuidFile = "/run/secrets/proxy-uuid-${name}"; }) [ + "alice" + "bob" + "carol" + ]; + + # The listeners terminate TLS themselves, so share links honestly say security=tls. + tls = { + enable = true; + certificateFile = "${certDir}/fullchain.pem"; + keyFile = "${certDir}/key.pem"; + serverName = domain; + }; + + # nginx on 443 hands a path to a loopback listener. + fronted = port: path: extra: { + type = "vless"; + inherit port users; + address = "127.0.0.1"; + sharePort = 443; # share links name nginx's port, not the listener's + transport = extra // { + inherit path; + # nginx sets this header, so XRay sees each client's real address (for + # `proxy-ctl inbounds online`). A client cannot forge it: nginx overwrites it. + trustedXForwardedFor = [ "X-Real-IP" ]; + }; + inherit tls; + }; + location = port: extra: { + proxyPass = "https://127.0.0.1:${toString port}"; + extraConfig = '' + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Real-IP $remote_addr; + proxy_ssl_server_name on; + proxy_ssl_name ${domain}; + # Tunnels idle along with their users; the 60s default would cut them. + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + '' + + extra; + }; +in +{ + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ { tag = "primary"; urlFile = "/run/secrets/proxy-primary-url"; } ]; + }; + + inbounds = { + enable = true; + serverAddress = domain; + routing.via = "proxy"; + + listeners = { + # nginx speaks HTTP/1.1 to the listener, which only packet-up mode crosses. + xhttp = fronted 10003 "/media" { + type = "xhttp"; + mode = "packet-up"; + }; + ws = fronted 10002 "/media-ws" { type = "ws"; }; + # stream-one needs HTTP/2 all the way: nginx's grpc_pass provides it. + xhttp-stream = lib.recursiveUpdate (fronted 10004 "/media-stream" { + type = "xhttp"; + mode = "stream-one"; + }) { tls.alpn = [ "h2" ]; }; + + # HTTP/3 takes UDP 443 only, beside nginx on TCP 443. No trustedXForwardedFor: + # nothing is in front, so it already sees the real client. + xhttp-h3 = { + type = "vless"; + port = 443; + inherit users; + transport = { type = "xhttp"; path = "/media-h3"; }; + tls = tls // { alpn = [ "h3" ]; }; + }; + + reality = { + type = "vless"; + port = 2053; + inherit users; + flow = "xtls-rprx-vision"; + reality = { + enable = true; + # Probes without the key land on a real TLS 1.3 + HTTP/2 site. + dest = "www.samsung.com:443"; + serverNames = [ "www.samsung.com" ]; + privateKeyFile = "/run/secrets/proxy-reality-key"; + publicKey = "jNXH…"; + shortIds = [ "0123abcd" ]; + }; + }; + }; + + subscriptions = { + enable = true; + baseUrl = "https://${domain}/sub"; + }; + }; + + userControl.enable = true; # passwordless proxy-ctl for the admin, see below + }; + + users.users.admin.extraGroups = [ "proxy-suite" ]; + + security.acme = { + acceptTerms = true; + defaults.email = "admin@example.com"; + # A renewed certificate restarts the listeners. + certs.${domain}.reloadServices = [ "proxy-suite-inbounds.service" ]; + }; + systemd.services.proxy-suite-inbounds = { + wants = [ "acme-${domain}.service" ]; + after = [ "acme-${domain}.service" ]; + }; + + services.nginx = { + enable = true; + virtualHosts.${domain} = { + forceSSL = true; + enableACME = true; + locations = { + # A prefix match: XHTTP appends //. + "/media" = location 10003 '' + proxy_http_version 1.1; + proxy_request_buffering off; + proxy_buffering off; + client_max_body_size 0; + ''; + "= /media-ws" = location 10002 "" // { proxyWebsockets = true; }; + "/media-stream".extraConfig = '' + grpc_pass grpcs://127.0.0.1:10004; + grpc_set_header X-Forwarded-For $remote_addr; + grpc_set_header X-Real-IP $remote_addr; + grpc_ssl_server_name on; + grpc_ssl_name ${domain}; + grpc_read_timeout 3600s; + grpc_send_timeout 3600s; + client_max_body_size 0; + ''; + # Subscriptions. Some clients show profile-title and follow profile-update-interval. + "/sub/".extraConfig = '' + alias /run/proxy-suite-inbounds/subscriptions/; + default_type text/plain; + autoindex off; + add_header profile-title "My VPN" always; + add_header profile-update-interval "12" always; + ''; + }; + }; + }; +} +``` + +## Handing out access + +```sh +proxy-ctl inbounds sub alice --qr # alice's subscription: every listener, kept current +proxy-ctl inbounds link reality alice --qr +proxy-ctl inbounds online # who is connected, by their real address +proxy-ctl inbounds stats 7 --by user # traffic over the last week +``` + +To add a user, add a name and a UUID file, and rebuild. Existing links stay valid. + +## Notes + +- `sharePort = 443` puts nginx's port into share links, while the listener stays on + loopback, closed in the firewall. +- `trustedXForwardedFor` is safe only behind a proxy that overwrites the header, as nginx + does here. On a listener open to the world, clients could set it themselves. +- The certificate belongs to nginx. If the listeners cannot read it, they use a copy, and + `reloadServices` restarts them with the renewed one. diff --git a/docs/usage/examples/workstation.md b/docs/usage/examples/workstation.md new file mode 100644 index 0000000..4b6d53e --- /dev/null +++ b/docs/usage/examples/workstation.md @@ -0,0 +1,90 @@ +# Example: a workstation using your own server + +The desktop side of the [relay server](./relay-server.md) and the +[private VPN](./private-vpn.md). Most apps go direct, with zapret for DPI. Blocked sites go +through the server. Some programs always use the proxy, and the private VPN is one +command away. + +```nix +{ config, pkgs, ... }: +let + proxySuite = config.lib.proxy-suite; +in +{ + services.proxy-suite = { + enable = true; + + proxy = { + enable = true; + # The server's subscription: every listener, each a separate outbound. + subscriptions = [ { tag = "home"; urlFile = "/run/secrets/proxy-home-sub"; } ]; + # The fastest listener that gets through the current network. + selection = "urltest"; + urlTest.url = "https://telegram.org"; # blocked here, so a pass means it works + + routing.default = "direct"; + autoProxy.enable = true; + tun.enable = true; # when everything should go through: proxy-ctl proxy tun on + }; + + zapret = { + enable = true; + engine = "zapret2"; + }; + + # The private VPN: `proxy-ctl awg on home`. + amneziaWg = { + enable = true; + profiles.home.configFile = "/run/secrets/home-vpn.conf"; + }; + killSwitch.enable = true; + + perAppRouting = { + enable = true; + createDefaultProfiles = true; + proxychains.enable = true; + tun.enable = true; + }; + + gui.enable = true; + userControl.enable = true; + }; + + users.users.me.extraGroups = [ "proxy-suite" ]; + + environment.systemPackages = [ + # CLIs that only work through the proxy, whatever the routing says. + (proxySuite.wrapEnv { protocol = "all"; } pkgs.codex) + (proxySuite.wrapEnv { } pkgs.claude-code) + # A browser for blocked sites, with its UDP (QUIC) too. + (proxySuite.wrapPerApp { profile = "tun"; } pkgs.chromium) + ]; + + # Nix downloads through the proxy. + systemd.services.nix-daemon.environment = proxySuite.envFor "http"; +} +``` + +## Day to day + +```sh +proxy-ctl status # what runs, and which outbound is picked +proxy-ctl proxy outbounds test # which listeners get through right now +proxy-ctl where some-site.com # direct, zapret or proxy, and why +proxy-ctl proxy tun on # everything through the server for a while +proxy-ctl awg on home # or through the private VPN (stops TUN) +``` + +The tray app shows the same, and switches with a click. + +## Notes + +- `wrapEnv` sets the proxy variables for one program only, so the rest of the system keeps + its direct routing. `protocol = "all"` sets both kinds, for a program whose choice you + do not know. +- The kill switch guards whichever global tunnel is on (TUN or the VPN), and does nothing + while both are off. +- Per-app `tun` profiles refuse to start while global TUN is on. Everything already goes + through the proxy then. +- See [Wrap programs with the proxy](../wrap-apps.md) for the helpers, and + [Keep secrets out of the Nix store](../secrets.md) for the files under `/run/secrets`. diff --git a/docs/usage/index.md b/docs/usage/index.md index 12a5e5a..500d051 100644 --- a/docs/usage/index.md +++ b/docs/usage/index.md @@ -1,7 +1,8 @@ # Usage guides Short guides for common setups. Each one has a minimal config, the commands you will use, -and links into the [options reference](../options/index.md) for the details. +and links into the [options reference](../options/index.md) for the details. Complete +examples follow below. | Guide | When to read it | |---|---| @@ -9,6 +10,7 @@ and links into the [options reference](../options/index.md) for the details. | [Route the whole machine](./system-wide.md) | Every app should use the proxy, not only those set to it | | [Choose what goes through the proxy](./routing.md) | Only blocked sites through the proxy, or everything but some | | [Route a single app](./per-app.md) | Only some apps should use the proxy | +| [Wrap programs with the proxy](./wrap-apps.md) | A package should always use the proxy, wherever it is started | | [Unblock sites without a server](./zapret.md) | YouTube, Discord or other sites are slowed or blocked by DPI | | [Run your own server](./server.md) | You have a VPS and want to connect your devices to it | | [Keep secrets out of the Nix store](./secrets.md) | Your config holds links, keys or passwords | @@ -17,3 +19,14 @@ and links into the [options reference](../options/index.md) for the details. | [Chain proxies and add exits](./chains.md) | WARP, Tor, SSH, or reaching a server through another one | | [Other Linux and Android](./other-hosts.md) | You are not on NixOS | | [Get past mobile whitelists](./whitelist-bypass.md) | Mobile internet lets only whitelisted services through | + +## Complete examples + +Whole configs that combine the guides, taken from real setups. + +| Example | What it shows | +|---|---| +| [A relay server behind nginx](./examples/relay-server.md) | Five transports on one VPS, fronted by nginx, with subscriptions for each user | +| [Several exits, picked per site](./examples/multi-exit.md) | Direct with zapret2, a VPS, WARP, SSH and Tor, each for the sites it suits | +| [A private VPN for your own devices](./examples/private-vpn.md) | An AmneziaWG server with fixed addresses and private DNS names | +| [A workstation using your own server](./examples/workstation.md) | Direct by default, wrapped programs, and TUN or the VPN on demand | diff --git a/docs/usage/per-app.md b/docs/usage/per-app.md index 26a6230..dc893c6 100644 --- a/docs/usage/per-app.md +++ b/docs/usage/per-app.md @@ -75,5 +75,6 @@ Then run `proxy-ctl apps run browser -- chromium`. ## See also +- [Wrap programs with the proxy](./wrap-apps.md): a package that always starts through a profile - [`perAppRouting.profiles`](../options/perAppRouting.md#services-proxy-suite-perapprouting-profiles) - [`perAppRouting.createDefaultProfiles`](../options/perAppRouting.md#services-proxy-suite-perapprouting-createdefaultprofiles) diff --git a/docs/usage/wrap-apps.md b/docs/usage/wrap-apps.md new file mode 100644 index 0000000..984dd16 --- /dev/null +++ b/docs/usage/wrap-apps.md @@ -0,0 +1,128 @@ +# Wrap programs with the proxy + +Build the proxy into a package, so a program uses it wherever and however it is started, +with no setup in the program. On NixOS and home-manager, the module provides the pieces as +`config.lib.proxy-suite`, built from your listener and per-app routing settings. + +| Helper | How the program is routed | Covers | +|---|---|---| +| `wrapEnv` | Proxy variables (`https_proxy`, `all_proxy`, …) | Programs that read them: most CLIs, Go, Python, curl, git | +| `wrapProxychains` | proxychains, for programs that ignore the variables | TCP; not static or Go programs | +| `wrapPerApp` | A [per-app routing](./per-app.md) profile, via `proxy-ctl apps run` | Everything, TCP and UDP (`tun` profile) | +| `env`, `envFor` | Just the variables, for services and shells | Whatever reads them | + +## On NixOS + +```nix +{ config, pkgs, ... }: +let + proxySuite = config.lib.proxy-suite; +in +{ + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ]; + }; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + proxychains.enable = true; + tun.enable = true; + }; + }; + + environment.systemPackages = [ + (proxySuite.wrapEnv { } pkgs.yt-dlp) + (proxySuite.wrapProxychains { } pkgs.telegram-desktop) + (proxySuite.wrapPerApp { profile = "tun"; } pkgs.firefox) + ]; + + # A service: here nix-daemon, so downloads go through the proxy. + systemd.services.nix-daemon.environment = proxySuite.envFor "http"; +} +``` + +The wrapped programs keep their names, and the package's `.desktop` files start them. + +## From home-manager + +A home-manager config inside NixOS reads the system's helpers through `osConfig`: + +```nix no-check +{ osConfig, pkgs, ... }: +let + proxySuite = osConfig.lib.proxy-suite; +in +{ + home.packages = [ + (proxySuite.wrapEnv { protocol = "all"; } pkgs.codex) + (proxySuite.wrapEnv { } pkgs.claude-code) + ]; +} +``` + +When proxy-suite itself runs under home-manager, use `config.lib.proxy-suite`. + +## Other hosts, or another host's proxy + +system-manager and Nix-on-Droid have no `config.lib`. There, or for a proxy that this config +does not run, the flake builds the URLs, the variables and `wrapEnv` from an address: + +```nix no-check +proxySuite = inputs.proxy-suite.lib.proxyHelpers { + inherit pkgs; + address = "192.168.1.10"; # default "127.0.0.1" + port = 1080; # default 1080 + # username and password, if the proxy asks for them +}; +``` + +## Reference + +- `urls.http`, `urls.socks`: the proxy's URLs. A listener on `0.0.0.0` or `::` is reached on + loopback. +- `env`: every proxy variable (`http_proxy`, `https_proxy`, `all_proxy`, their upper-case + forms, and `no_proxy`). `envFor "http"` or `envFor "socks"` gives one kind only. +- `wrapEnv { protocol ? "http"; programs ? null; } package`: the package, with its programs + run with the variables of `protocol`. +- `wrapProxychains { programs ? null; } package`: its programs run under proxychains. Needs + `perAppRouting.proxychains.enable`. +- `wrapPerApp { profile; programs ? null; } package`: its programs run with + `proxy-ctl apps run `. Needs the profile in `perAppRouting`. + +`programs = [ "…" ]` wraps only the named programs of the package; the rest stay as they +are. By default, every program in its `bin/` is wrapped. + +## Which variables + +`wrapEnv` sets one kind and unsets the other, so proxy variables in your shell cannot +send the program somewhere else: + +- `protocol = "http"` (the default): `http_proxy` and `https_proxy`, which nearly + everything reads. +- `protocol = "socks"`: `all_proxy` with `socks5h://`, so the proxy resolves names. For + programs that read only that one, or handle SOCKS better. +- `protocol = "all"`: both, when you are not sure which one a program reads. + +Local addresses (`localhost`, `127.0.0.0/8`, `::1`) always stay direct, through `no_proxy`. + +## Good to know + +- The variables need `proxy.enable`. They cannot hold a password from + `listener.auth.passwordFile`. Use `wrapProxychains` then, since it reads the password + at run time. +- `wrapPerApp` with a `tun`, `tproxy` or `zapret` profile has the same needs as + `proxy-ctl apps run`: an admin password, or the `perApp` scope in `userControl`. +- A helper that cannot work stops the build and says why, for example when a profile does + not exist. +- A wrapper does not inherit the package's license, so wrapping an unfree package needs + nothing beyond what the package itself needs. +- For every program on the machine, see [Route the whole machine](./system-wide.md) + instead. + +## See also + +- [Route a single app](./per-app.md): the profiles `wrapPerApp` uses +- [`perAppRouting.profiles`](../options/perAppRouting.md#services-proxy-suite-perapprouting-profiles) diff --git a/flake.nix b/flake.nix index f2ddb6a..e912ad7 100644 --- a/flake.nix +++ b/flake.nix @@ -72,6 +72,19 @@ # without the GUI. nixOnDroidModules.default = proxySuiteModules.nixOnDroid; + # Proxy variables and wrapEnv from an address alone: for a proxy this config does not + # run, or on system-manager and nix-on-droid, which have no config.lib. + # `proxy-suite.lib.proxyHelpers { inherit pkgs; port = 1080; }`. On NixOS and + # home-manager the module has the full set as config.lib.proxy-suite. + lib.proxyHelpers = + args: + import ./modules/proxy-suite/helpers.nix ( + { + inherit (args.pkgs) lib; + } + // args + ); + # Re-export zapret standalone for users who want just that. nixosModules.zapret = zapret.nixosModules.default; diff --git a/modules/proxy-suite/core.nix b/modules/proxy-suite/core.nix index 45ffe75..e2f35a2 100644 --- a/modules/proxy-suite/core.nix +++ b/modules/proxy-suite/core.nix @@ -36,6 +36,41 @@ in config = lib.mkMerge [ { + services.proxy-suite.internal.helpers = + let + inherit (cfg.proxy.listener) address port auth; + perAppRouting = assembly.context.perAppRouting; + perAppOn = cfg.enable && cfg.perAppRouting.enable; + in + import ./helpers.nix { + inherit + lib + pkgs + address + port + ; + inherit (auth) username password; + envUnavailable = + if !(cfg.enable && cfg.proxy.enable) then + "the proxy variables need services.proxy-suite.proxy.enable" + else if auth.passwordFile != null then + "the proxy variables cannot carry proxy.listener.auth.passwordFile; use wrapProxychains" + else + null; + proxychains = + if perAppOn && cfg.perAppRouting.proxychains.enable then + { args = "${perAppRouting.proxychainsQuietArg}-f ${toString perAppRouting.proxychainsConfigFile}"; } + else + "wrapProxychains needs perAppRouting.proxychains.enable"; + perApp = + if perAppOn then + { + inherit (assembly.context.control) proxyCtl; + profiles = perAppRouting.effectivePerAppRoutingProfileNames; + } + else + "wrapPerApp needs perAppRouting.enable"; + }; # xray and sing-box default to this flake's own nixpkgs (redirect it # with inputs.nixpkgs.follows), not the system's: a stable release lags # both by months, and current xray needs a newer Go than stable ships. diff --git a/modules/proxy-suite/helpers.nix b/modules/proxy-suite/helpers.nix new file mode 100644 index 0000000..28fdde4 --- /dev/null +++ b/modules/proxy-suite/helpers.nix @@ -0,0 +1,153 @@ +# Ways to point programs at the local proxy without touching their settings: proxy +# variables, a proxychains wrapper, or a per-app routing profile. The module exposes them +# as config.lib.proxy-suite on NixOS and home-manager; the flake's lib.proxyHelpers builds +# the variables alone, for a proxy this config does not run or a host without config.lib. +{ + lib, + pkgs, + address ? "127.0.0.1", + port ? 1080, + username ? null, + password ? null, + # Set when the variables cannot name the proxy (it is off, or its password is a file). + envUnavailable ? null, + # From the module only: { args } for proxychains4, and { proxyCtl, profiles } for + # per-app routing. A string instead says why the feature is unavailable. + proxychains ? "wrapProxychains needs the proxy-suite module", + perApp ? "wrapPerApp needs the proxy-suite module", +}: + +let + # A wildcard listener is reached on loopback. + host = + { + "0.0.0.0" = "127.0.0.1"; + "::" = "::1"; + } + .${address} or address; + hostPort = "${if lib.hasInfix ":" host then "[${host}]" else host}:${toString port}"; + credentials = lib.optionalString ( + username != null + ) "${lib.escapeURL username}:${lib.escapeURL password}@"; + checked = + value: if envUnavailable != null then throw "proxy-suite helpers: ${envUnavailable}" else value; + + urls = checked { + http = "http://${credentials}${hostPort}"; + # socks5h: names are resolved by the proxy, so they follow its routing. + socks = "socks5h://${credentials}${hostPort}"; + }; + + httpVars = [ + "http_proxy" + "https_proxy" + "HTTP_PROXY" + "HTTPS_PROXY" + ]; + socksVars = [ + "all_proxy" + "ALL_PROXY" + ]; + noProxy = { + no_proxy = "localhost,127.0.0.0/8,::1"; + NO_PROXY = "localhost,127.0.0.0/8,::1"; + }; + protocolVars = { + http = httpVars; + socks = socksVars; + all = httpVars ++ socksVars; + }; + varsOf = + protocol: + protocolVars.${protocol} + or (throw "proxy-suite helpers: protocol must be \"http\", \"socks\" or \"all\", not \"${protocol}\""); + envFor = + protocol: + lib.genAttrs (varsOf protocol) (name: if builtins.elem name httpVars then urls.http else urls.socks) + // noProxy; + + # A copy of `package` whose programs (all of bin/, or the named ones) are replaced by + # what `wrap` writes, given the original as "$target" and the wrapper as "$prog". + # .desktop files that start a program by its store path are pointed at the wrapper. + wrapPrograms = + suffix: programs: wrap: package: + pkgs.symlinkJoin { + name = "${lib.getName package}-${suffix}"; + paths = [ package ]; + nativeBuildInputs = [ pkgs.makeWrapper ]; + postBuild = '' + cd "$out/bin" + for prog in ${if programs == null then "*" else lib.escapeShellArgs programs}; do + target=$(readlink -f "$prog") + rm "$prog" + ${wrap} + done + for desktop in "$out"/share/applications/*.desktop; do + [ -e "$desktop" ] && grep -q ${package}/bin/ "$desktop" || continue + source=$(readlink -f "$desktop") + rm "$desktop" + sed "s|${package}/bin/|$out/bin/|g" "$source" > "$desktop" + done + ''; + passthru.unwrapped = package; + # Not the whole meta: its license would make an unfree package's wrapper unfree + # too, and refused unless the host allows unfree, which the package may not need. + meta = lib.filterAttrs (name: _: name == "mainProgram" || name == "description") ( + package.meta or { } + ); + }; + using = + feature: use: + if builtins.isString feature then throw "proxy-suite helpers: ${feature}" else use feature; +in +{ + inherit urls envFor; + env = envFor "all"; + + wrapEnv = + { + protocol ? "http", + programs ? null, + }: + let + vars = envFor protocol; + others = lib.subtractLists (varsOf protocol) (httpVars ++ socksVars); + in + # The others are unset, so a shell's own proxy variables cannot steer the program elsewhere. + wrapPrograms "proxied" programs '' + makeWrapper "$target" "$prog" ${ + lib.concatStringsSep " " ( + lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") vars + ++ map (name: "--unset ${name}") others + ) + } + ''; + + wrapProxychains = + { + programs ? null, + }: + using proxychains ( + { args }: + wrapPrograms "proxychains" programs '' + makeWrapper ${pkgs.proxychains-ng}/bin/proxychains4 "$prog" \ + --add-flags ${lib.escapeShellArg "${args} "}"$target" + '' + ); + + wrapPerApp = + { + profile, + programs ? null, + }: + using perApp ( + { proxyCtl, profiles }: + if !builtins.elem profile profiles then + throw "proxy-suite helpers: no per-app routing profile named \"${profile}\" (have: ${lib.concatStringsSep ", " profiles})" + else + wrapPrograms profile programs '' + makeWrapper ${proxyCtl}/bin/proxy-ctl "$prog" \ + --add-flags ${lib.escapeShellArg "apps run ${profile} -- "}"$target" + '' + ); +} diff --git a/modules/proxy-suite/hosts/home-manager.nix b/modules/proxy-suite/hosts/home-manager.nix index 2bdc921..a3880d3 100644 --- a/modules/proxy-suite/hosts/home-manager.nix +++ b/modules/proxy-suite/hosts/home-manager.nix @@ -35,6 +35,8 @@ in # have it cleared on reboot. runtimeDir = lib.mkDefault "${config.xdg.cacheHome}/proxy-suite/run"; }; + # home-manager's place for helper functions, as on NixOS. + lib.proxy-suite = cfg.internal.helpers; } (lib.mkIf cfg.enable ( diff --git a/modules/proxy-suite/hosts/nixos.nix b/modules/proxy-suite/hosts/nixos.nix index 19ba437..09180f1 100644 --- a/modules/proxy-suite/hosts/nixos.nix +++ b/modules/proxy-suite/hosts/nixos.nix @@ -32,6 +32,9 @@ in firewallPackage = config.networking.firewall.package; resolvconfPackage = config.networking.resolvconf.package; }; + # NixOS's place for helper functions; set even while disabled, so a config can + # refer to it unconditionally. + lib.proxy-suite = cfg.internal.helpers; } (lib.mkIf cfg.enable ( diff --git a/modules/proxy-suite/options/host.nix b/modules/proxy-suite/options/host.nix index b6ba41f..780a079 100644 --- a/modules/proxy-suite/options/host.nix +++ b/modules/proxy-suite/options/host.nix @@ -64,6 +64,9 @@ in rules = internalOption types.lines ""; }; nftables = internalOption types.bool false; + # ../helpers.nix, which the NixOS and home-manager adapters publish as + # config.lib.proxy-suite; the other hosts have no config.lib. + helpers = internalOption types.raw { }; firewall = { allowedTCPPorts = internalOption (types.listOf types.port) [ ]; allowedUDPPorts = internalOption (types.listOf types.port) [ ]; diff --git a/nix/checks.nix b/nix/checks.nix index 8122729..033a7cb 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -61,6 +61,10 @@ moduleSuiteChecks proxy-suite-hosts = builtins.seq (builtins.deepSeq hostChecks.assertions true) ( pkgs.writeText "proxy-suite-hosts-check" "ok" ); + proxy-helpers = import ./checks/proxy-helpers.nix { + inherit pkgs; + inherit (checkLib) evalProxySuite; + }; } // pkgs.lib.optionalAttrs (system == "x86_64-linux") { amneziawg-runtime = amneziaWgRuntime; diff --git a/nix/checks/hosts.nix b/nix/checks/hosts.nix index 137ee8d..561b7fd 100644 --- a/nix/checks/hosts.nix +++ b/nix/checks/hosts.nix @@ -33,6 +33,7 @@ let hostStubs = { homeManager.options = { + lib = stub (types.attrsOf types.attrs) { }; home.packages = packages; xdg.stateHome = stub types.str "/home/u/.local/state"; xdg.cacheHome = stub types.str "/home/u/.cache"; @@ -185,6 +186,8 @@ in assert hmCfg.services.proxy-suite.host.serviceManager == "systemd-user"; assert lib.hasPrefix "/home/u/.local/state/" hmCfg.services.proxy-suite.host.stateDir; assert hmCfg.systemd.user.services ? proxy-suite-socks; + # The helpers are published where home-manager keeps its own. + assert hmCfg.lib.proxy-suite.urls.http == "http://127.0.0.1:1080"; 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. diff --git a/nix/checks/lib.nix b/nix/checks/lib.nix index ffa2186..8fff05f 100644 --- a/nix/checks/lib.nix +++ b/nix/checks/lib.nix @@ -9,10 +9,12 @@ let generated = import ./read-generated.nix; + # Every fixture shares this one nixpkgs instead of importing its own: about 200 MB and + # 4 s less per evaluation. No fixture sets nixpkgs.* options, which this would ignore. evalProxySuite = modules: import "${nixpkgs}/nixos/lib/eval-config.nix" { - inherit system; + inherit system pkgs; modules = [ proxySuiteModule ] ++ modules; }; forceEval = value: builtins.tryEval (builtins.deepSeq value true); diff --git a/nix/checks/proxy-helpers.nix b/nix/checks/proxy-helpers.nix new file mode 100644 index 0000000..ac4f771 --- /dev/null +++ b/nix/checks/proxy-helpers.nix @@ -0,0 +1,98 @@ +# config.lib.proxy-suite: the wrappers are built for real and run, and each +# unavailable helper refuses with its reason instead of building something broken. +{ pkgs, evalProxySuite }: + +let + inherit (pkgs) lib; + helpersFor = + settings: + (evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ + { + tag = "a"; + url = "socks://127.0.0.1:9"; + } + ]; + }; + } + // settings; + } + ]).config.lib.proxy-suite; + helpers = helpersFor { + perAppRouting = { + enable = true; + createDefaultProfiles = true; + proxychains.enable = true; + tun.enable = true; + }; + }; + bare = helpersFor { }; + refuses = value: !(builtins.tryEval (builtins.deepSeq value value)).success; + + # Prints its environment; its .desktop file starts it by store path. Labelled unfree + # (built as free, since nixpkgs here refuses unfree), which the wrappers must not inherit. + fake = + (pkgs.runCommand "fake-app" { } '' + mkdir -p $out/bin $out/share/applications + printf '#!${pkgs.runtimeShell}\nexec ${pkgs.coreutils}/bin/env\n' > $out/bin/fake + printf '#!${pkgs.runtimeShell}\necho other\n' > $out/bin/other + chmod +x $out/bin/fake $out/bin/other + printf '[Desktop Entry]\nExec=%s/bin/fake %%U\n' "$out" > $out/share/applications/fake.desktop + '') + // { + meta.license = lib.licenses.unfree; + }; + viaHttp = helpers.wrapEnv { } fake; + viaSocks = helpers.wrapEnv { + protocol = "socks"; + programs = [ "fake" ]; + } fake; + viaChains = helpers.wrapProxychains { programs = [ "fake" ]; } fake; + viaTun = helpers.wrapPerApp { profile = "tun"; } fake; +in +assert helpers.urls.http == "http://127.0.0.1:1080"; +assert helpers.env.ALL_PROXY == "socks5h://127.0.0.1:1080"; +assert refuses (bare.wrapProxychains { } fake); +assert refuses (bare.wrapPerApp { profile = "tun"; } fake); +assert refuses (helpers.wrapPerApp { profile = "nope"; } fake); +assert refuses ( + (helpersFor { + proxy.listener.auth = { + username = "u"; + passwordFile = "/run/secrets/p"; + }; + }).env +); +pkgs.runCommand "proxy-suite-proxy-helpers-check" { } '' + set -eu + export ALL_PROXY=socks5h://elsewhere:1 HTTPS_PROXY=http://elsewhere:1 + + # http: its variables set, the shell's socks one dropped; every program wrapped. + ${viaHttp}/bin/fake > http.env + grep -qx 'HTTPS_PROXY=http://127.0.0.1:1080' http.env + grep -qx 'no_proxy=localhost,127.0.0.0/8,::1' http.env + ! grep -q '^ALL_PROXY=' http.env || exit 1 + grep -q 'HTTPS_PROXY' ${viaHttp}/bin/other + # The .desktop file starts the wrapper, not the original. + grep -qx "Exec=${viaHttp}/bin/fake %U" ${viaHttp}/share/applications/fake.desktop + + # socks: the reverse, and only the named program. + ${viaSocks}/bin/fake > socks.env + grep -qx 'ALL_PROXY=socks5h://127.0.0.1:1080' socks.env + ! grep -q '^HTTPS_PROXY=' socks.env || exit 1 + [ "$(readlink -f ${viaSocks}/bin/other)" = ${fake}/bin/other ] + + # proxychains preloads itself into the program. + ${viaChains}/bin/fake | grep -q '^LD_PRELOAD=.*libproxychains4' + + # Per-app routing goes through proxy-ctl. + grep -q 'proxy-ctl.* apps run tun -- ${fake}/bin/fake' ${viaTun}/bin/fake + + touch "$out" +'' diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index f41e19d..36593c0 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -59,14 +59,21 @@ in ''; # The usage guides are hand-written; what can go stale in them is checked here. Every - # ```nix block that sets services.proxy-suite (in the guides and the README) must - # evaluate, with no proxy-suite assertion or warning; a block fenced ```nix no-check is - # skipped. Every relative link must reach a file, and its #anchor an there. + # ```nix block that sets services.proxy-suite (in the guides, their examples/ and the + # README) must evaluate, with no proxy-suite assertion or warning; a block fenced + # ```nix no-check is skipped. A block is either module attributes or, when it starts + # with "{", a whole module. Every relative link must reach a file, and its #anchor an + # there. usage-docs = let inherit (pkgs) lib; usageDir = ../../docs/usage; - guides = builtins.filter (lib.hasSuffix ".md") (builtins.attrNames (builtins.readDir usageDir)); + markdownIn = + dir: + map (name: lib.removePrefix "./" "${dir}/${name}") ( + builtins.filter (lib.hasSuffix ".md") (builtins.attrNames (builtins.readDir (usageDir + "/${dir}"))) + ); + guides = markdownIn "." ++ markdownIn "examples"; readmeText = builtins.readFile ../../README.md; guideText = name: builtins.readFile (usageDir + "/${name}"); @@ -98,15 +105,22 @@ in where: snippet: let module = import ( - builtins.toFile "snippet.nix" '' - { config, lib, pkgs, ... }: - { - system.stateVersion = "26.05"; - ${snippet} - } - '' + builtins.toFile "snippet.nix" ( + if lib.hasPrefix "{" snippet then + snippet + else + '' + { config, lib, pkgs, ... }: + { + ${snippet} + } + '' + ) ); - eval = evalProxySuite [ module ]; + eval = evalProxySuite [ + module + { system.stateVersion = "26.05"; } + ]; inherit (eval) config; failed = map (a: a.message) (builtins.filter (a: !a.assertion) config.assertions); own = builtins.filter (lib.hasPrefix "proxy-suite:") (failed ++ config.warnings); @@ -135,7 +149,7 @@ in let target = builtins.head link; anchor = builtins.elemAt link 1; - path = if target == "" then usageDir + "/${name}" else usageDir + "/${target}"; + path = if target == "" then usageDir + "/${name}" else usageDir + "/${dirOf name}/${target}"; where = "docs/usage/${name}: ${target}${if anchor == null then "" else anchor}"; in if !builtins.pathExists path then