diff --git a/deploy/installer.nix b/deploy/installer.nix new file mode 100644 index 0000000..8db0eab --- /dev/null +++ b/deploy/installer.nix @@ -0,0 +1,63 @@ +# proxy-suite-install: the installer the ISO runs on tty1 (deploy/installer.sh). +{ + lib, + writeShellApplication, + xray, + flakeUrl, + flakeSource, + stateVersion, + coreutils, + curl, + dosfstools, + e2fsprogs, + gawk, + getent, + gnugrep, + gnused, + gptfdisk, + iproute2, + iputils, + mkpasswd, + nix, + nixos-install-tools, + openssl, + parted, + systemd, + util-linux, + xkcdpass, +}: + +writeShellApplication { + name = "proxy-suite-install"; + runtimeInputs = [ + coreutils + curl + dosfstools + e2fsprogs + gawk + getent + gnugrep + gnused + gptfdisk + iproute2 + iputils + mkpasswd + nix + nixos-install-tools + openssl + parted + systemd + util-linux + xkcdpass + xray + ]; + runtimeEnv = { + PSI_FLAKE_URL = flakeUrl; + PSI_FLAKE_SRC = "${flakeSource}"; + PSI_STATE_VERSION = stateVersion; + }; + text = lib.concatStringsSep "\n" [ + (builtins.readFile ./net-lib.sh) + (builtins.readFile ./installer.sh) + ]; +} diff --git a/deploy/installer.sh b/deploy/installer.sh new file mode 100644 index 0000000..161a012 --- /dev/null +++ b/deploy/installer.sh @@ -0,0 +1,380 @@ +# proxy-suite-install: turn a VPS booted from the installer ISO into a proxy-suite +# server. Everything asked here ends up in /etc/nixos/host.nix on the target. +# +# Baked in by deploy/installer.nix: PSI_FLAKE_URL (github ref at the ISO's commit, or +# empty), PSI_FLAKE_SRC (this flake's source in the store), PSI_STATE_VERSION. +# Unattended: PSI_UNATTENDED=1 plus PSI_ for every answer (see ask in net-lib.sh). + +: "${PSI_FLAKE_URL?}" "${PSI_FLAKE_SRC:?}" "${PSI_STATE_VERSION:?}" + +MNT=/mnt +SECRETS_DIR=/var/lib/proxy-suite-server + +if [[ $(id -u) != 0 ]]; then + echo "proxy-suite-install: run it as root (sudo -i)" >&2 + exit 1 +fi + +confirm() { + local reply + if [[ -n ${PSI_UNATTENDED-} ]]; then + return 0 + fi + read -r -p "$1 Type yes to continue: " reply || true + [[ $reply == yes ]] +} + +step() { printf '\n\033[1;36m== %s ==\033[0m\n' "$*"; } + +# nvme0n1 -> nvme0n1p1, vda -> vda1 +partition() { + if [[ $1 =~ [0-9]$ ]]; then + printf '%sp%s' "$1" "$2" + else + printf '%s%s' "$1" "$2" + fi +} + +# A stable name for GRUB, where the disk has one. +stable_disk_path() { + local link + for link in /dev/disk/by-id/*; do + [[ $link == *-part* || $link == */nvme-eui.* ]] && continue + if [[ $(readlink -f "$link") == "$1" ]]; then + printf '%s' "$link" + return 0 + fi + done + printf '%s' "$1" +} + +clear +bold "proxy-suite server installer" +say "Installs NixOS with VLESS REALITY, TLS and WS inbounds for one user, and SSH." +say "Every question has a default in [brackets]: press Enter to take it." +say "Ctrl+C aborts; run sudo proxy-suite-install to start over." + +# --- Network -------------------------------------------------------------------- +step "Network" +setup_network || exit 1 + +step "Public address" +if [[ $NET_DHCP == false ]]; then + local_ip=${NET_V4%/*} +else + local_ip=$(ip -4 route get 1.1.1.1 | awk '{ for (i = 1; i < NF; i++) if ($i == "src") { print $(i + 1); exit } }') +fi +seen_ip=$(curl -4 -s --max-time 10 https://api.ipify.org || true) +default_ip=$local_ip +if [[ -n $seen_ip && $seen_ip != "$local_ip" ]] && is_ipv4 "$seen_ip"; then + say "This server's address is $local_ip, but the internet sees it as $seen_ip (NAT)." + default_ip=$seen_ip +fi +while true; do + ask PUBLIC_IP "Public IPv4 clients connect to" "$default_ip" + is_ipv4 "$PUBLIC_IP" && break + reject "Not an IPv4 address." PUBLIC_IP +done +if ipv4_is_private "$PUBLIC_IP"; then + warn "$PUBLIC_IP is a private address: clients outside cannot reach it, and no certificate" + warn "can be issued for it. Use a domain, and forward the ports to this server." +fi + +# --- Server --------------------------------------------------------------------- +step "Server" +while true; do + ask HOST_NAME "Hostname" "proxy-$(openssl rand -hex 2)" + [[ $HOST_NAME =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$ ]] && break + reject "Lowercase letters, digits and dashes only." HOST_NAME +done +while true; do + ask ADMIN_USER "Admin user name (SSH login, sudo)" "admin" + [[ $ADMIN_USER =~ ^[a-z_][a-z0-9_-]{0,31}$ && $ADMIN_USER != root ]] && break + reject "Lowercase letters, digits, - and _; not root." ADMIN_USER +done +while true; do + ask SSH_PORT "SSH port" "22" + if [[ $SSH_PORT =~ ^[0-9]+$ ]] && ((SSH_PORT >= 1 && SSH_PORT <= 65535)) && + [[ ! " 80 443 2053 8443 18533 18534 18535 18536 " == *" $SSH_PORT "* ]]; then + break + fi + reject "A free port from 1 to 65535 (80, 443, 2053 and 8443 are taken)." SSH_PORT +done + +# --- Proxy ---------------------------------------------------------------------- +step "Proxy" +while true; do + ask PROXY_USER "Proxy user name (label of the share links)" "user" + [[ $PROXY_USER =~ ^[A-Za-z0-9_.-]{1,32}$ ]] && break + reject "Letters, digits, dot, dash and underscore." PROXY_USER +done + +say "" +say "The TLS and WS inbounds need a certificate from Let's Encrypt. With a domain" +say "(its A record pointing at $PUBLIC_IP) it is issued for the domain; without one," +say "for the IP itself (a six-day certificate, renewed automatically). Port 80 must be open." +while true; do + ask DOMAIN "Domain (empty: certificate for the IP)" "" + if [[ -z $DOMAIN ]]; then + break + fi + DOMAIN=${DOMAIN,,} + if [[ ! $DOMAIN =~ ^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$ ]]; then + reject "Not a domain name." DOMAIN + continue + fi + if getent ahostsv4 "$DOMAIN" | awk '{ print $1 }' | grep -qx "$PUBLIC_IP"; then + break + fi + warn "$DOMAIN does not resolve to $PUBLIC_IP (yet). The certificate order retries until it does." + ask_yes KEEP_DOMAIN "Keep $DOMAIN anyway" "y" + [[ $KEEP_DOMAIN == true ]] && break + unset PSI_DOMAIN PSI_KEEP_DOMAIN +done + +while true; do + ask ACME_EMAIL "Email for Let's Encrypt (optional)" "" + [[ -z $ACME_EMAIL || $ACME_EMAIL =~ ^[^[:space:]\"@]+@[^[:space:]\"@]+$ ]] && break + reject "Not an email address." ACME_EMAIL +done + +say "" +say "REALITY impersonates another site's TLS. Pick a big HTTPS site, ideally hosted" +say "near this server and not blocked where your clients are." +while true; do + ask REALITY_SNI "REALITY site" "www.microsoft.com" + if [[ ! $REALITY_SNI =~ ^([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z]{2,}$ ]]; then + reject "Not a domain name." REALITY_SNI + continue + fi + if curl -s -o /dev/null --max-time 10 --tlsv1.3 --http2 "https://$REALITY_SNI/"; then + break + fi + warn "$REALITY_SNI did not answer over TLS 1.3 from here; REALITY needs TLS 1.3 and HTTP/2." + ask_yes KEEP_SNI "Keep $REALITY_SNI anyway" "n" + [[ $KEEP_SNI == true ]] && break + unset PSI_REALITY_SNI PSI_KEEP_SNI +done + +# --- Disk ----------------------------------------------------------------------- +step "Disk" +mapfile -t disks < <(lsblk -dnpo NAME,TYPE,RO | awk '$2 == "disk" && $3 == 0 && $1 !~ /\/(zram|loop|sr|fd)[0-9]/ { print $1 }') +if ((${#disks[@]} == 0)); then + warn "No writable disk found." + exit 1 +fi +lsblk -dpo NAME,SIZE,MODEL "${disks[@]}" +while true; do + ask DISK "Disk to install on (ERASED)" "$(if ((${#disks[@]} == 1)); then printf '%s' "${disks[0]}"; fi)" + [[ -b $DISK && " ${disks[*]} " == *" $DISK "* ]] && break + reject "Not one of the disks above." DISK +done + +# --- Summary -------------------------------------------------------------------- +step "Summary" +if [[ $NET_DHCP == true ]]; then + net_summary="DHCP on $NET_IFACE ($NET_MAC)" +else + net_summary="$NET_V4 via $NET_V4_GW${NET_V6:+, $NET_V6 via $NET_V6_GW} on $NET_IFACE ($NET_MAC)" +fi +cat </dev/null || true +wipefs -af "$DISK" +sgdisk --zap-all "$DISK" +sgdisk \ + -n 1:0:+1M -t 1:EF02 -c 1:bios \ + -n 2:0:+512M -t 2:EF00 -c 2:ESP \ + -n 3:0:0 -t 3:8300 -c 3:nixos \ + "$DISK" +# sgdisk has the kernel reread the table; wait for udev to finish recreating the +# partition nodes, or mkfs can write to a node that is about to be replaced. +udevadm settle +esp=$(partition "$DISK" 2) +root=$(partition "$DISK" 3) +for _ in {1..20}; do + [[ -b $esp && -b $root ]] && break + sleep 0.5 +done +wipefs -aq "$esp" "$root" +mkfs.vfat -F 32 -n ESP "$esp" +mkfs.ext4 -qF -L nixos "$root" +sync +udevadm settle +mount -t ext4 "$root" "$MNT" +mkdir -p "$MNT/boot" +mount -t vfat -o umask=077 "$esp" "$MNT/boot" + +nixos-generate-config --root "$MNT" +rm -f "$MNT/etc/nixos/configuration.nix" + +# Evaluating NixOS takes more memory than the smallest VPS plans have. Added after +# nixos-generate-config, which would list it in swapDevices. +fallocate -l 2G "$MNT/.install-swap" +chmod 600 "$MNT/.install-swap" +mkswap "$MNT/.install-swap" >/dev/null +swapon "$MNT/.install-swap" + +# --- Secrets -------------------------------------------------------------------- +step "Generating keys" +install -d -m 0700 "$MNT$SECRETS_DIR" +keys=$(xray x25519) +# XRay prints "Private key:/Public key:", or from 25.x "PrivateKey:/Password (PublicKey):". +private_key=$(sed -n 's/^Private *[Kk]ey: *//p' <<<"$keys") +public_key=$(sed -n 's/^\(Public key\|Password (PublicKey)\|Password\): *//p' <<<"$keys" | head -n 1) +if [[ -z $private_key || -z $public_key ]]; then + warn "Could not read the output of xray x25519:" + printf '%s\n' "$keys" >&2 + exit 1 +fi +( + umask 077 + xray uuid >"$MNT$SECRETS_DIR/uuid" + printf '%s\n' "$private_key" >"$MNT$SECRETS_DIR/reality-key" +) +short_id=$(openssl rand -hex 8) +ws_path="/$(openssl rand -hex 6)" + +# --- Configuration -------------------------------------------------------------- +step "Writing /etc/nixos" +etc_nixos="$MNT/etc/nixos" + +cat >"$etc_nixos/host.nix" <"$etc_nixos/flake.nix" <.installer-iso). Boots to the +# console installer on tty1; everything per server is asked there, nothing is baked in. +{ self, serverModule }: + +{ + config, + lib, + pkgs, + modulesPath, + ... +}: + +let + inherit (pkgs.stdenv.hostPlatform) system; + + # The configuration the installer writes, with placeholders for what it asks. Its + # closure goes on the ISO, so installing downloads little and builds nothing big. + template = import "${modulesPath}/../lib/eval-config.nix" { + inherit system; + modules = [ + serverModule + { + networking.hostName = "proxy-template"; + system.stateVersion = config.system.nixos.release; + fileSystems."/" = { + device = "/dev/disk/by-label/nixos"; + fsType = "ext4"; + }; + fileSystems."/boot" = { + device = "/dev/disk/by-label/ESP"; + fsType = "vfat"; + options = [ "umask=077" ]; + }; + services.proxy-suite-server = { + enable = true; + bootDisk = "/dev/vda"; + network = { + mac = "52:54:00:00:00:01"; + ipv4 = { + address = "192.0.2.1/24"; + gateway = "192.0.2.254"; + }; + }; + publicAddress = "192.0.2.1"; + reality = { + publicKey = "template"; + shortId = "0123456789abcdef"; + }; + wsPath = "/template"; + }; + } + ]; + }; + + # The sources of this flake and of its inputs, so locking /etc/nixos finds them here. + inputSources = + flake: [ flake.outPath ] ++ lib.concatMap inputSources (lib.attrValues (flake.inputs or { })); + + installer = pkgs.callPackage ./installer.nix { + xray = import ../pkgs/xray.nix { inherit pkgs; }; + # A github ref only for a clean, committed tree; the installer falls back to the + # copy in PSI_FLAKE_SRC when it cannot be fetched (e.g. not pushed yet). + flakeUrl = lib.optionalString (self ? rev) "github:FUFSoB/proxy-suite-flake/${self.rev}"; + flakeSource = self.outPath; + stateVersion = config.system.nixos.release; + }; +in +{ + imports = [ "${modulesPath}/installer/cd-dvd/installation-cd-minimal.nix" ]; + + isoImage = { + edition = "proxy-suite"; + storeContents = [ template.config.system.build.toplevel ] ++ lib.unique (inputSources self); + }; + + # The same stack the installed system uses, so settings tested here carry over. + networking = { + hostName = "proxy-suite-installer"; + networkmanager.enable = lib.mkForce false; + wireless.enable = lib.mkForce false; + useNetworkd = true; + useDHCP = true; + }; + systemd.network.wait-online.enable = false; + services.openssh.enable = lib.mkForce false; + + nix.settings.experimental-features = [ + "nix-command" + "flakes" + ]; + + # VNC consoles are small and blurry. + console = { + earlySetup = true; + font = "${pkgs.terminus_font}/share/consolefonts/ter-v24n.psf.gz"; + packages = [ pkgs.terminus_font ]; + }; + + environment.systemPackages = [ + installer + (pkgs.callPackage ./net-rescue.nix { }) + ]; + + services.getty.helpLine = lib.mkForce '' + + Proxy-suite installer. It starts on tty1; to run it again: sudo proxy-suite-install + ''; + + # Once, on tty1 only: other consoles (Alt+F2) stay plain shells. The console logs in + # as nixos, which has passwordless sudo. + programs.bash.interactiveShellInit = '' + if [[ $(tty) == /dev/tty1 && ! -e /tmp/.proxy-suite-install-started ]]; then + touch /tmp/.proxy-suite-install-started + sudo proxy-suite-install + fi + ''; +} diff --git a/deploy/net-lib.sh b/deploy/net-lib.sh new file mode 100644 index 0000000..f02b3cb --- /dev/null +++ b/deploy/net-lib.sh @@ -0,0 +1,292 @@ +# Network prompts shared by proxy-suite-install and proxy-suite-net. The answers are +# applied through a systemd-networkd file in /run, the same way the installed system +# applies them from /etc, so settings that work here work after the reboot. +# +# Sets NET_IFACE NET_MAC NET_DHCP NET_V4 NET_V4_GW NET_V6 NET_V6_GW NET_DNS. Unattended +# runs (PSI_UNATTENDED=1) take every answer from PSI_ and fail instead of re-asking. + +NET_RUNTIME_FILE=/run/systemd/network/05-proxy-suite-net.network + +say() { printf '%s\n' "$*"; } +warn() { printf '\033[1;33m%s\033[0m\n' "$*" >&2; } +bold() { printf '\033[1m%s\033[0m\n' "$*"; } + +# ask VAR "Question" [default]. PSI_ in the environment answers it unattended. +ask() { + local __preset="PSI_$1" __reply + if [[ -n ${!__preset+x} ]]; then + __reply=${!__preset} + elif [[ -n ${3-} ]]; then + read -r -p "$2 [$3]: " __reply || true + else + read -r -p "$2: " __reply || true + fi + [[ -n $__reply ]] || __reply=${3-} + printf -v "$1" '%s' "$__reply" +} + +# ask_yes VAR "Question" y|n; sets VAR to true or false. +ask_yes() { + local __yn + ask "$1" "$2 (y/n)" "$3" + __yn=${!1} + case ${__yn,,} in + y | yes | true) printf -v "$1" '%s' true ;; + *) printf -v "$1" '%s' false ;; + esac +} + +# Drop a rejected answer so the next ask prompts; unattended, give up instead. +reject() { + warn "$1" + shift + if [[ -n ${PSI_UNATTENDED-} ]]; then + exit 1 + fi + local name + for name in "$@"; do unset "PSI_$name"; done +} + +is_ipv4() { + local IFS=. octet + [[ $1 =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || return 1 + for octet in $1; do ((octet <= 255)) || return 1; done +} + +is_ipv6() { [[ $1 == *:* && $1 =~ ^[0-9A-Fa-f:.]+$ ]]; } + +mask_to_prefix() { + local mask=$1 IFS=. octet bits=0 + if [[ $mask =~ ^[0-9]+$ ]]; then + ((mask <= 32)) && printf '%s' "$mask" && return 0 + return 1 + fi + is_ipv4 "$mask" || return 1 + for octet in $mask; do + case $octet in + 255) bits=$((bits + 8)) ;; + 254) bits=$((bits + 7)) ;; + 252) bits=$((bits + 6)) ;; + 248) bits=$((bits + 5)) ;; + 240) bits=$((bits + 4)) ;; + 224) bits=$((bits + 3)) ;; + 192) bits=$((bits + 2)) ;; + 128) bits=$((bits + 1)) ;; + 0) ;; + *) return 1 ;; + esac + done + printf '%s' "$bits" +} + +ipv4_to_int() { + local IFS=. a b c d + read -r a b c d <<<"$1" + printf '%s' $(((a << 24) | (b << 16) | (c << 8) | d)) +} + +# ipv4_in_subnet ADDR/PREFIX GATEWAY +ipv4_in_subnet() { + local addr=${1%/*} prefix=${1#*/} mask + mask=$(((0xffffffff << (32 - prefix)) & 0xffffffff)) + [[ $(($(ipv4_to_int "$addr") & mask)) == $(($(ipv4_to_int "$2") & mask)) ]] +} + +# Private, CGNAT or otherwise unroutable: clients cannot reach it, and no CA will +# issue a certificate for it. +ipv4_is_private() { + local n + n=$(ipv4_to_int "$1") + (((n >> 24) == 10)) || + (((n >> 24) == 127)) || + (((n >> 20) == (172 << 4 | 1))) || + (((n >> 16) == (192 << 8 | 168))) || + (((n >> 22) == (100 << 2 | 1))) || + (((n >> 16) == (169 << 8 | 254))) +} + +# Physical interfaces only: no lo, bridges or veths. +physical_ifaces() { + local path + for path in /sys/class/net/*; do + if [[ -e $path/device ]]; then + printf '%s\n' "${path##*/}" + fi + done +} + +list_ifaces() { + local name + bold "Network interfaces:" + while IFS= read -r name; do + printf ' %-12s mac %s state %s\n' "$name" "$(cat "/sys/class/net/$name/address")" \ + "$(cat "/sys/class/net/$name/operstate")" + ip -o addr show dev "$name" | awk '{ printf " %s %s%s\n", $3, $4, (/dynamic/ ? " (dhcp)" : "") }' + done < <(physical_ifaces) + ip route show default | sed 's/^/ route: /' + ip -6 route show default | sed 's/^/ route: /' +} + +ask_network() { + local ifaces default_iface has_lease NET_ADDR NET_MASK prefix NET_V6_IN + mapfile -t ifaces < <(physical_ifaces) + if ((${#ifaces[@]} == 0)); then + warn "No network interface found." + return 1 + fi + default_iface=$(ip route show default | awk '{ for (i = 1; i < NF; i++) if ($i == "dev") { print $(i + 1); exit } }') + [[ -n $default_iface ]] || default_iface=${ifaces[0]} + + list_ifaces + while true; do + ask NET_IFACE "Interface" "$default_iface" + [[ -e /sys/class/net/$NET_IFACE/address ]] && break + reject "No interface named '$NET_IFACE'." NET_IFACE + done + NET_MAC=$(cat "/sys/class/net/$NET_IFACE/address") + + has_lease=n + ip -4 -o addr show dev "$NET_IFACE" | grep -q dynamic && has_lease=y + say "" + say "Most VPS panels list a static IP, netmask (or prefix) and gateway: use those." + say "Answer y only if the provider says the server gets its address over DHCP." + ask_yes NET_DHCP "Use DHCP" "$has_lease" + + NET_V4="" NET_V4_GW="" NET_V6="" NET_V6_GW="" + if [[ $NET_DHCP == false ]]; then + while true; do + ask NET_ADDR "IPv4 address (203.0.113.10/24, or without /prefix)" + if [[ $NET_ADDR == */* ]]; then + prefix=${NET_ADDR#*/} NET_ADDR=${NET_ADDR%/*} + else + ask NET_MASK "Netmask or prefix length (255.255.255.0 or 24)" "24" + prefix=$(mask_to_prefix "$NET_MASK") || prefix="" + fi + if is_ipv4 "$NET_ADDR" && [[ $prefix =~ ^[0-9]+$ ]] && ((prefix >= 1 && prefix <= 32)); then + NET_V4="$NET_ADDR/$prefix" + break + fi + reject "Not an IPv4 address with a valid netmask." NET_ADDR NET_MASK + done + while true; do + ask NET_V4_GW "IPv4 gateway" + is_ipv4 "$NET_V4_GW" && break + reject "Not an IPv4 address." NET_V4_GW + done + if ! ipv4_in_subnet "$NET_V4" "$NET_V4_GW"; then + say "Gateway $NET_V4_GW is outside $NET_V4: it is routed on-link, as providers with /32 addresses expect." + fi + + ask NET_V6_IN "IPv6 address with prefix (empty to skip)" "" + if [[ -n $NET_V6_IN ]]; then + [[ $NET_V6_IN == */* ]] || NET_V6_IN="$NET_V6_IN/64" + if is_ipv6 "${NET_V6_IN%/*}"; then + NET_V6=$NET_V6_IN + ask NET_V6_GW "IPv6 gateway" "fe80::1" + else + warn "Not an IPv6 address; skipping IPv6." + fi + fi + fi + + ask NET_DNS "DNS servers (space-separated)" "1.1.1.1 8.8.8.8" +} + +# Mirrors the systemd.network config of deploy/server-module.nix. +write_networkd() { + local file=$1 dns gw + { + printf '[Match]\nMACAddress=%s\nType=ether\n\n' "$NET_MAC" + printf '[Link]\nRequiredForOnline=routable\n\n' + printf '[Network]\n' + if [[ $NET_DHCP == true ]]; then + printf 'DHCP=yes\n' + else + printf 'DHCP=no\n' + if [[ -n $NET_V6 ]]; then + printf 'IPv6AcceptRA=no\nAddress=%s\n' "$NET_V6" + fi + printf 'Address=%s\n' "$NET_V4" + fi + for dns in $NET_DNS; do printf 'DNS=%s\n' "$dns"; done + if [[ $NET_DHCP == false ]]; then + for gw in "$NET_V4_GW" "$NET_V6_GW"; do + if [[ -n $gw ]]; then + printf '\n[Route]\nGateway=%s\nGatewayOnLink=yes\n' "$gw" + fi + done + fi + } >"$file" +} + +apply_network() { + mkdir -p "$(dirname "$NET_RUNTIME_FILE")" + write_networkd "$NET_RUNTIME_FILE" + networkctl reload + networkctl reconfigure "$NET_IFACE" + for _ in {1..30}; do + ip -4 route show default dev "$NET_IFACE" | grep -q . && return 0 + sleep 1 + done + warn "No IPv4 default route on $NET_IFACE after 30 seconds." + return 1 +} + +# Each step names what failed, so a wrong gateway is told apart from a wrong DNS. +test_network() { + local gw + gw=$(ip -4 route show default dev "$NET_IFACE" | awk '{ print $3; exit }') + say "Testing the network..." + if [[ -n $gw ]] && ! ping -c 2 -W 2 "$gw" >/dev/null 2>&1; then + warn " gateway $gw does not answer ping (some providers block it; continuing)" + fi + if ! ping -c 2 -W 3 1.1.1.1 >/dev/null 2>&1 && ! curl -s -o /dev/null --max-time 8 http://1.1.1.1; then + warn " cannot reach the internet (1.1.1.1): check the address, netmask and gateway" + return 1 + fi + if ! getent ahosts cache.nixos.org >/dev/null; then + warn " internet works but DNS does not: check the DNS servers" + return 1 + fi + if ! curl -s -o /dev/null --max-time 15 https://cache.nixos.org/nix-cache-info; then + warn " cannot fetch https://cache.nixos.org" + return 1 + fi + say " network OK" +} + +setup_network() { + while true; do + ask_network || return 1 + if apply_network && test_network; then + return 0 + fi + reject "Network settings did not work; enter them again." \ + NET_IFACE NET_DHCP NET_ADDR NET_MASK NET_V4_GW NET_V6_IN NET_V6_GW NET_DNS + done +} + +# nix_str VALUE: VALUE as a Nix string literal. +nix_str() { + local s=${1//\\/\\\\} + s=${s//\"/\\\"} + s=${s//\$\{/\\\$\{} + printf '"%s"' "$s" +} + +# The services.proxy-suite-server.network block for host.nix, indented by $1. +print_network_nix() { + local pad=$1 dns list="" + for dns in $NET_DNS; do list+=" $(nix_str "$dns")"; done + printf '%snetwork = {\n' "$pad" + printf '%s mac = %s;\n' "$pad" "$(nix_str "$NET_MAC")" + printf '%s dhcp = %s;\n' "$pad" "$NET_DHCP" + if [[ $NET_DHCP == false && -n $NET_V4 ]]; then + printf '%s ipv4 = { address = %s; gateway = %s; };\n' "$pad" "$(nix_str "$NET_V4")" "$(nix_str "$NET_V4_GW")" + fi + if [[ $NET_DHCP == false && -n $NET_V6 ]]; then + printf '%s ipv6 = { address = %s; gateway = %s; };\n' "$pad" "$(nix_str "$NET_V6")" "$(nix_str "$NET_V6_GW")" + fi + printf '%s dns = [%s ];\n' "$pad" "$list" + printf '%s};\n' "$pad" +} diff --git a/deploy/net-rescue.nix b/deploy/net-rescue.nix new file mode 100644 index 0000000..3e4e1a5 --- /dev/null +++ b/deploy/net-rescue.nix @@ -0,0 +1,34 @@ +# proxy-suite-net: re-enter the uplink settings from the console of an installed server +# whose network does not come up. +{ + lib, + writeShellApplication, + coreutils, + curl, + gawk, + getent, + gnugrep, + gnused, + iproute2, + iputils, + systemd, +}: + +writeShellApplication { + name = "proxy-suite-net"; + runtimeInputs = [ + coreutils + curl + gawk + getent + gnugrep + gnused + iproute2 + iputils + systemd + ]; + text = lib.concatStringsSep "\n" [ + (builtins.readFile ./net-lib.sh) + (builtins.readFile ./net-rescue.sh) + ]; +} diff --git a/deploy/net-rescue.sh b/deploy/net-rescue.sh new file mode 100644 index 0000000..a3b684e --- /dev/null +++ b/deploy/net-rescue.sh @@ -0,0 +1,50 @@ +# proxy-suite-net: fix the network from the console when the installed settings do +# not work. The fix lives in /run until the next reboot; persist it in host.nix. + +usage() { + cat <&2 + exit 1 +fi + +case ${1-} in + -h | --help) + usage + ;; + --show) + list_ifaces + if [[ -e $NET_RUNTIME_FILE ]]; then + bold "Temporary settings ($NET_RUNTIME_FILE):" + cat "$NET_RUNTIME_FILE" + fi + ;; + --reset) + rm -f "$NET_RUNTIME_FILE" + networkctl reload + mapfile -t ifaces < <(physical_ifaces) + networkctl reconfigure "${ifaces[@]}" + say "Temporary settings dropped." + ;; + "") + setup_network + bold "Network works. These settings last until the next reboot." + say "To keep them, replace the network block in /etc/nixos/host.nix with:" + say "" + print_network_nix " " + say "" + say "then run: sudo nixos-rebuild switch --flake /etc/nixos && sudo proxy-suite-net --reset" + ;; + *) + usage >&2 + exit 1 + ;; +esac diff --git a/deploy/server-module.nix b/deploy/server-module.nix new file mode 100644 index 0000000..c646982 --- /dev/null +++ b/deploy/server-module.nix @@ -0,0 +1,320 @@ +# A single-user VLESS server on a VPS: REALITY, TLS and WS+TLS inbounds, ACME +# certificates (for the domain, or the bare IP), SSH, and networking pinned to the +# uplink's MAC. Written for the installer ISO (deploy/iso.nix), which fills in +# host.nix, but usable on its own. +{ proxySuiteModule }: + +{ + config, + lib, + pkgs, + modulesPath, + ... +}: + +let + inherit (lib) mkOption types; + cfg = config.services.proxy-suite-server; + net = cfg.network; + + certName = if cfg.domain != null then cfg.domain else cfg.publicAddress; + certDir = "/var/lib/acme/${certName}"; + + nullable = + type: description: + mkOption { + type = types.nullOr type; + default = null; + inherit description; + }; + + addressType = types.submodule { + options = { + address = mkOption { + type = types.str; + description = "Address with prefix length, e.g. 203.0.113.10/24."; + example = "203.0.113.10/24"; + }; + gateway = mkOption { + type = types.str; + description = "Default gateway. Reached on-link, so it may lie outside the subnet."; + example = "203.0.113.1"; + }; + }; + }; + + user = [ + { + name = cfg.user; + uuidFile = "${cfg.secretsDir}/uuid"; + } + ]; + tls = { + enable = true; + certificateFile = "${certDir}/fullchain.pem"; + keyFile = "${certDir}/key.pem"; + }; +in +{ + imports = [ + proxySuiteModule + "${modulesPath}/profiles/qemu-guest.nix" + ]; + + options.services.proxy-suite-server = { + enable = lib.mkEnableOption "the single-user VPS server profile"; + + adminUser = mkOption { + type = types.strMatching "[a-z_][a-z0-9_-]*"; + default = "admin"; + description = "Login user in wheel. Its password is set imperatively (passwd), not here."; + }; + + sshPort = mkOption { + type = types.port; + default = 22; + description = "SSH port."; + }; + + bootDisk = mkOption { + type = types.str; + description = "Disk GRUB installs its BIOS stage to."; + example = "/dev/vda"; + }; + + network = { + mac = mkOption { + type = types.strMatching "([0-9a-f]{2}:){5}[0-9a-f]{2}"; + description = "MAC address of the uplink; matched instead of a name, which can change between kernels."; + example = "52:54:00:12:34:56"; + }; + dhcp = mkOption { + type = types.bool; + default = false; + description = "Take IPv4 from DHCP (and IPv6 from RA) instead of ipv4/ipv6."; + }; + ipv4 = nullable addressType "Static IPv4."; + ipv6 = nullable addressType "Static IPv6."; + dns = mkOption { + type = types.listOf types.str; + default = [ + "1.1.1.1" + "8.8.8.8" + ]; + description = "DNS servers."; + }; + }; + + publicAddress = mkOption { + type = types.strMatching "([0-9]{1,3}\\.){3}[0-9]{1,3}"; + description = "Public IPv4 clients connect to; the certificate is issued for it when domain is null."; + example = "203.0.113.10"; + }; + + domain = nullable (types.strMatching "[A-Za-z0-9.-]+") "Domain pointing at publicAddress. Null gets a short-lived Let's Encrypt certificate for the IP itself."; + + acmeEmail = nullable types.str "ACME account email."; + + user = mkOption { + type = types.strMatching "[A-Za-z0-9_.-]+"; + default = "user"; + description = "Proxy user name: the label of its share links."; + }; + + secretsDir = mkOption { + type = types.str; + default = "/var/lib/proxy-suite-server"; + description = "Holds `uuid` and `reality-key` (the x25519 private key)."; + }; + + reality = { + sni = mkOption { + type = types.str; + default = "www.microsoft.com"; + description = "Site REALITY impersonates; must serve TLS 1.3 and HTTP/2 on 443."; + }; + publicKey = mkOption { + type = types.str; + description = "x25519 public key matching secretsDir/reality-key."; + }; + shortId = mkOption { + type = types.strMatching "[0-9a-f]{0,16}"; + description = "REALITY short id."; + }; + }; + + wsPath = mkOption { + type = types.strMatching "/[A-Za-z0-9/_-]*"; + description = "Path of the WS listener."; + example = "/3f9a1c07b2e4"; + }; + + ports = { + reality = mkOption { + type = types.port; + default = 443; + description = "VLESS REALITY port."; + }; + tls = mkOption { + type = types.port; + default = 8443; + description = "VLESS TLS port."; + }; + ws = mkOption { + type = types.port; + default = 2053; + description = "VLESS WS+TLS port (one Cloudflare proxies)."; + }; + }; + }; + + config = lib.mkIf cfg.enable { + boot.loader.grub = { + enable = true; + device = cfg.bootDisk; + # BIOS stage on the disk, EFI stage at the removable path: boots either way, + # and needs no NVRAM entry the VPS may not keep. + efiSupport = true; + efiInstallAsRemovable = true; + }; + boot.growPartition = true; + + networking = { + useDHCP = false; + useNetworkd = true; + firewall.enable = true; + firewall.allowedTCPPorts = [ 80 ]; + nameservers = net.dns; + }; + systemd.network = { + enable = true; + networks."10-uplink" = { + matchConfig.MACAddress = net.mac; + # Some drivers clone the MAC onto helper links; bind the real NIC only. + matchConfig.Type = "ether"; + networkConfig = { + DHCP = if net.dhcp then "yes" else "no"; + IPv6AcceptRA = net.dhcp || net.ipv6 == null; + }; + address = lib.optionals (!net.dhcp) ( + lib.optional (net.ipv4 != null) net.ipv4.address ++ lib.optional (net.ipv6 != null) net.ipv6.address + ); + routes = lib.optionals (!net.dhcp) ( + map (a: { + Gateway = a.gateway; + GatewayOnLink = true; + }) (lib.optional (net.ipv4 != null) net.ipv4 ++ lib.optional (net.ipv6 != null) net.ipv6) + ); + linkConfig.RequiredForOnline = "routable"; + }; + }; + + services.openssh = { + enable = true; + ports = [ cfg.sshPort ]; + settings = { + PasswordAuthentication = true; + KbdInteractiveAuthentication = false; + PermitRootLogin = "no"; + }; + }; + + users.mutableUsers = true; + users.users.${cfg.adminUser} = { + isNormalUser = true; + extraGroups = [ "wheel" ]; + }; + + boot.kernel.sysctl = { + "net.core.default_qdisc" = "fq"; + "net.ipv4.tcp_congestion_control" = "bbr"; + }; + zramSwap.enable = true; + nix.settings.experimental-features = [ + "nix-command" + "flakes" + ]; + + security.acme = { + acceptTerms = true; + defaults.email = cfg.acmeEmail; + certs.${certName} = { + domain = certName; + listenHTTP = ":80"; + group = "proxy-suite-daemon"; + reloadServices = [ "proxy-suite-inbounds" ]; + } + // lib.optionalAttrs (cfg.domain == null) { + # IP certificates come only from the six-day profile; check twice a day. + profile = "shortlived"; + renewInterval = "*-*-* 00,12:00:00"; + }; + }; + + # A self-signed placeholder is in place before the first order, so REALITY does + # not wait on ACME, and the order's success restarts the listeners. + systemd.services.proxy-suite-inbounds = { + wants = [ "acme-${certName}.service" ]; + after = [ "acme-${certName}.service" ]; + }; + + services.proxy-suite = { + enable = true; + proxy.enable = false; + userControl = { + enable = true; + group = "wheel"; + }; + inbounds = { + enable = true; + serverAddress = certName; + routing.via = "direct"; + listeners = { + vless-reality = { + type = "vless"; + port = cfg.ports.reality; + users = user; + flow = "xtls-rprx-vision"; + reality = { + enable = true; + dest = "${cfg.reality.sni}:443"; + serverNames = [ cfg.reality.sni ]; + privateKeyFile = "${cfg.secretsDir}/reality-key"; + inherit (cfg.reality) publicKey; + shortIds = [ cfg.reality.shortId ]; + }; + }; + vless-tls = { + type = "vless"; + port = cfg.ports.tls; + users = user; + flow = "xtls-rprx-vision"; + inherit tls; + }; + vless-ws = { + type = "vless"; + port = cfg.ports.ws; + users = user; + transport = { + type = "ws"; + path = cfg.wsPath; + }; + inherit tls; + }; + }; + }; + }; + + services.getty.helpLine = '' + + proxy-suite server ''${certName}. Share links (as ''${cfg.adminUser}): + proxy-ctl inbounds link vless-reality --qr (or vless-tls, vless-ws) + Network down? Log in and run: sudo proxy-suite-net + ''; + + environment.systemPackages = [ + pkgs.qrencode + (pkgs.callPackage ./net-rescue.nix { }) + ]; + }; +} diff --git a/flake.nix b/flake.nix index 57be1f4..13d60c5 100644 --- a/flake.nix +++ b/flake.nix @@ -56,6 +56,9 @@ # Main module – bakes in the zapret flake so consumers don't need it as a separate input. nixosModules.default = proxySuiteModule; + # A single-user VPS: VLESS REALITY, TLS and WS inbounds, ACME and SSH. Includes default. + nixosModules.server = import ./deploy/server-module.nix { inherit proxySuiteModule; }; + # Re-export zapret standalone for users who want just that. nixosModules.zapret = zapret.nixosModules.default; @@ -119,6 +122,17 @@ zapret2 ; xray = import ./pkgs/xray.nix { inherit pkgs; }; + # Console installer for a proxy-suite VPS (deploy/iso.nix). + installer-iso = + (nixpkgs.lib.nixosSystem { + modules = [ + (import ./deploy/iso.nix { + inherit self; + serverModule = self.nixosModules.server; + }) + { nixpkgs.hostPlatform = system; } + ]; + }).config.system.build.isoImage; optionsDoc = mkOptionsDoc system; readmeDoc = mkReadmeDoc system; update-docs = updateDocs; diff --git a/nix/checks/lib.nix b/nix/checks/lib.nix index 67ceb4a..a6a8fb2 100644 --- a/nix/checks/lib.nix +++ b/nix/checks/lib.nix @@ -264,5 +264,8 @@ in mkBadProxySuiteFixture mkFailingAssertions mkProxyCtlDerived + system + nixpkgs + proxySuiteModule ; } diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index b2bbe49..0d6c019 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -245,6 +245,11 @@ let zapretSyncService = zapretChecks.syncService; }; + serverModuleChecks = import ./server-module.nix { + inherit pkgs mkInboundsSpec; + inherit (checkLib) system nixpkgs proxySuiteModule; + }; + xrayBackendChecks = import ./xray-backends.nix { inherit pkgs @@ -285,6 +290,7 @@ let ++ subscriptionChecks.assertions ++ routeModeChecks.assertions ++ perAppRoutingChecks.assertions + ++ serverModuleChecks.assertions ); in { diff --git a/nix/checks/server-module.nix b/nix/checks/server-module.nix new file mode 100644 index 0000000..65269e7 --- /dev/null +++ b/nix/checks/server-module.nix @@ -0,0 +1,163 @@ +# nixosModules.server as the installer writes it: once for an IP certificate, once for +# a domain. +{ + pkgs, + system, + nixpkgs, + proxySuiteModule, + mkInboundsSpec, +}: + +let + inherit (pkgs) lib; + + serverModule = import ../../deploy/server-module.nix { inherit proxySuiteModule; }; + + mkServer = + extra: + import "${nixpkgs}/nixos/lib/eval-config.nix" { + inherit system; + modules = [ + serverModule + { + system.stateVersion = "26.05"; + fileSystems."/" = { + device = "/dev/disk/by-label/nixos"; + fsType = "ext4"; + }; + services.proxy-suite-server = lib.recursiveUpdate { + enable = true; + bootDisk = "/dev/vda"; + network = { + mac = "52:54:00:12:34:56"; + ipv4 = { + address = "203.0.113.10/32"; + gateway = "198.51.100.1"; + }; + }; + publicAddress = "203.0.113.10"; + reality = { + publicKey = "public-key"; + shortId = "0123456789abcdef"; + }; + wsPath = "/3f9a1c07b2e4"; + } extra; + } + ]; + }; + + ipServer = mkServer { }; + domainServer = mkServer { + domain = "vpn.example.com"; + network.dhcp = true; + }; + + failedAssertions = + fixture: map (a: a.message) (builtins.filter (a: !a.assertion) fixture.config.assertions); + listener = spec: tag: lib.head (builtins.filter (l: l.tag == tag) spec.listeners); + + ipSpec = mkInboundsSpec ipServer; + domainSpec = mkInboundsSpec domainServer; + uplink = fixture: fixture.config.systemd.network.networks."10-uplink"; + ipCert = ipServer.config.security.acme.certs."203.0.113.10"; + domainCert = domainServer.config.security.acme.certs."vpn.example.com"; +in +{ + assertions = [ + ( + assert failedAssertions ipServer == [ ]; + true + ) + ( + assert failedAssertions domainServer == [ ]; + true + ) + + ( + assert + lib.sort (a: b: a < b) (map (l: l.port) ipSpec.listeners) == [ + 443 + 2053 + 8443 + ]; + true + ) + ( + assert + (listener ipSpec "vless-reality").reality.privateKeyFile + == "/var/lib/proxy-suite-server/reality-key"; + true + ) + ( + assert + (listener ipSpec "vless-tls").tls.certificateFile == "/var/lib/acme/203.0.113.10/fullchain.pem"; + true + ) + ( + assert (listener domainSpec "vless-ws").tls.keyFile == "/var/lib/acme/vpn.example.com/key.pem"; + true + ) + ( + assert (listener ipSpec "vless-ws").transport.path == "/3f9a1c07b2e4"; + true + ) + ( + assert + (lib.head (listener ipSpec "vless-tls").users).uuidFile == "/var/lib/proxy-suite-server/uuid"; + true + ) + + # IP certificates exist only in the short-lived profile. + ( + assert ipCert.profile == "shortlived" && domainCert.profile == null; + true + ) + ( + assert ipCert.group == "proxy-suite-daemon"; + true + ) + ( + assert ipServer.config.services.proxy-suite.inbounds.serverAddress == "203.0.113.10"; + true + ) + ( + assert domainServer.config.services.proxy-suite.inbounds.serverAddress == "vpn.example.com"; + true + ) + + # A /32 with a gateway outside it only works on-link. + ( + assert (uplink ipServer).address == [ "203.0.113.10/32" ]; + true + ) + ( + assert + (uplink ipServer).routes == [ + { + Gateway = "198.51.100.1"; + GatewayOnLink = true; + } + ]; + true + ) + ( + assert (uplink domainServer).networkConfig.DHCP == "yes" && (uplink domainServer).address == [ ]; + true + ) + + ( + assert lib.all (p: builtins.elem p ipServer.config.networking.firewall.allowedTCPPorts) [ + 80 + 443 + 8443 + 2053 + 22 + ]; + true + ) + ( + assert ipServer.config.services.openssh.settings.PermitRootLogin == "no"; + true + ) + ]; +}