From 825f3c77a5d20d2e2d1768de8f531c1753938ac6 Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Tue, 27 Oct 2026 05:55:21 +0330 Subject: [PATCH 1/9] feat(ssl): auto-detect IPv6 for IP certificates Discover eligible local IPv6 addresses with explicit interactive consent and preserve unattended IPv4 defaults. Embed shared helpers in both standalone scripts, verify dual-stack listeners and IP SAN/key identity, and preserve live certificates and prior panel state on failure. Add rootless regression coverage, CI checks, and SSL documentation. --- .github/workflows/ci.yml | 22 +- deploy/README.md | 23 +- .../docs/en/config/ssl-certificates.mdx | 49 +++ install.sh | 412 ++++++++++++++---- scripts/lib/ip-ssl.sh | 294 +++++++++++++ scripts/sync-ip-ssl-helpers.sh | 29 ++ scripts/test/README.md | 50 +++ scripts/test/ip-ssl-acme-listener-test.sh | 20 + scripts/test/ip-ssl-certificate-test.sh | 150 +++++++ scripts/test/ip-ssl-entrypoint-test.sh | 66 +++ scripts/test/ip-ssl-listener-test.sh | 32 ++ scripts/test/ip-ssl-test.sh | 70 +++ x-ui.sh | 368 +++++++++++++--- 13 files changed, 1434 insertions(+), 151 deletions(-) create mode 100644 scripts/lib/ip-ssl.sh create mode 100644 scripts/sync-ip-ssl-helpers.sh create mode 100644 scripts/test/README.md create mode 100644 scripts/test/ip-ssl-acme-listener-test.sh create mode 100644 scripts/test/ip-ssl-certificate-test.sh create mode 100644 scripts/test/ip-ssl-entrypoint-test.sh create mode 100644 scripts/test/ip-ssl-listener-test.sh create mode 100644 scripts/test/ip-ssl-test.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 350a85e74..80531c612 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,6 +10,11 @@ on: - ".nvmrc" - "Makefile" - ".github/workflows/ci.yml" + - "install.sh" + - "x-ui.sh" + - "scripts/lib/ip-ssl.sh" + - "scripts/sync-ip-ssl-helpers.sh" + - "scripts/test/**" push: branches: - main @@ -21,6 +26,11 @@ on: - ".nvmrc" - "Makefile" - ".github/workflows/ci.yml" + - "install.sh" + - "x-ui.sh" + - "scripts/lib/ip-ssl.sh" + - "scripts/sync-ip-ssl-helpers.sh" + - "scripts/test/**" permissions: contents: read @@ -311,11 +321,21 @@ jobs: # the panel ships are linted by the shellcheck step below. run: go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 -color -shellcheck= - name: Install shellcheck - run: sudo apt-get update && sudo apt-get install -y shellcheck + run: sudo apt-get update && sudo apt-get install -y shellcheck socat - name: shellcheck run: | shellcheck --severity=style DockerInit.sh DockerEntrypoint.sh deploy/test/smoke-noninteractive.sh shellcheck --severity=error install.sh update.sh x-ui.sh + shellcheck --severity=style -e SC1091 scripts/lib/ip-ssl.sh scripts/sync-ip-ssl-helpers.sh scripts/test/ip-ssl-*.sh + - name: IP certificate regressions (no ACME orders) + run: | + bash -n install.sh + bash -n x-ui.sh + bash scripts/sync-ip-ssl-helpers.sh --check + bash scripts/test/ip-ssl-test.sh + bash scripts/test/ip-ssl-entrypoint-test.sh + IP_SSL_LINUX_TEST=1 bash scripts/test/ip-ssl-listener-test.sh + bash scripts/test/ip-ssl-certificate-test.sh frontend: runs-on: ubuntu-latest diff --git a/deploy/README.md b/deploy/README.md index 25827285c..e86235a76 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -24,8 +24,29 @@ secure random / default): `XUI_USERNAME`, `XUI_PASSWORD`, `XUI_PANEL_PORT`, `XUI_WEB_BASE_PATH`, `XUI_SSL_MODE` (`none`|`ip`|`domain`, default `none`), `XUI_DOMAIN`, `XUI_ACME_EMAIL`, `XUI_ACME_HTTP_PORT` (ACME HTTP-01 listener port, default `80`), -`XUI_SSL_IPV6` (optional IPv6 address to add to an `ip`-mode cert), +`XUI_SSL_IPV6` (explicit public IPv6 literal to add to an `ip`-mode cert), `XUI_SERVER_IP` (fallback IP for the displayed access URL when auto-detection fails), `XUI_DB_TYPE` (`sqlite`|`postgres`), `XUI_DB_DSN`. The resulting credentials are written to `/etc/x-ui/install-result.env` (mode 600). + +### IPv6 in IP certificates + +Unattended installation never discovers or includes IPv6 unless you explicitly +set `XUI_SSL_IPV6` to one public IPv6 address. Unset or empty means IPv4 only; +`auto`, a subnet (`/64`), a zone ID (`%eth0`), and malformed or nonpublic addresses +are rejected. An invalid explicit value fails the SSL setup before stopping the +panel or requesting a certificate. + +Interactive installation discovers locally assigned global IPv6 addresses and +offers confirmation, numbered selection, manual entry, or skipping. Stable +addresses are preferred to temporary privacy addresses, and a default-route +source is labelled when available. A routed prefix is not a certificate address. + +Dual-stack issuance requires acme.sh **3.1.5+**, socat, and working local IPv4 and +IPv6 listeners. The installer checks both families on the chosen listener port +and sends both listen flags so acme.sh saves them for renewal. External port +**80 must reach that listener over both addresses**, including when +`XUI_ACME_HTTP_PORT` selects another internal port. A local probe cannot verify +the provider firewall or external forwarding; the CA validates each IP SAN. +Failure never silently drops the configured IPv6 or deletes the prior certificate. diff --git a/docs/content/docs/en/config/ssl-certificates.mdx b/docs/content/docs/en/config/ssl-certificates.mdx index fcea58be0..4f125e9b1 100644 --- a/docs/content/docs/en/config/ssl-certificates.mdx +++ b/docs/content/docs/en/config/ssl-certificates.mdx @@ -80,6 +80,55 @@ No domain? Choose **Get SSL for IP Address** to obtain a short-lived certificate (valid ~6 days, renewed automatically) bound to the server's IP. Useful for reaching the panel over HTTPS before you've set up a domain. +The menu and interactive installer detect locally assigned public IPv6 addresses +using `iproute2`. They prefer stable addresses, label the default-route source +when available, and ask **`Include … in the SSL certificate? [y/N]`**. Confirm with +`y`; rejecting the suggestion offers manual entry or skipping. Multiple candidates +are numbered so you can select just one, enter an address manually, or skip. +No IPv6 echo service is required, and an outgoing route does not prove which +address clients should connect to: confirm the server's actual incoming address. + +Only individual public IPv6 literals are accepted. A provider's routed `/64` +is a pool from which addresses can be assigned, not a certificate identifier. +Loopback, link-local, private, documentation, tentative, deprecated, and failed-DAD +addresses are not offered. Temporary privacy addresses are offered only when no +suitable stable address exists; their changing lifetime can prevent renewal. +Invalid manual input produces an error and another prompt. + +For unattended installation, set `XUI_SSL_IPV6` to a specific public IPv6 literal +to include it. Leaving it unset or empty keeps IPv4-only issuance with no new +prompts or automatic IPv6 inclusion. `auto` is not a supported override. Invalid +explicit values fail SSL setup. IP mode retains IPv4 as its primary identifier. + +Dual-stack orders require **acme.sh 3.1.5 or newer** and socat. Both +`--listen-v4` and `--listen-v6` are passed: these versions open separate IPv4 and +IPv6 sockets and persist both settings for cron renewal. Older clients fail +clearly rather than dropping a confirmed IPv6. The local preflight checks both +families on the selected HTTP listener port. External **port 80 must be reachable +over both addresses**; forward it to the selected internal port on both families +when using a custom port. In containers, enable IPv6 networking and publish the +validation port for both families. Local listener success cannot verify an +external firewall, NAT, or the provider's routing. + +The resulting certificate's IP SANs, validity, and matching private key are +checked before configuring the panel. Existing live certificate files are backed +up during installation and restored after a failed or invalid copy; failed +issuance does not remove certificates or ACME account data. Renewal still copies +to the usual `/root/cert/ip/` paths, with a persisted SAN/key check before the +panel reload command. The private key remains mode `600` and the chain `644`. +If IP setup fails in the installer, a previously running panel is started again; +an inactive panel is not started on failure. + +Inspect both IP SAN entries after issuance: + +```bash +openssl x509 -in /root/cert/ip/fullchain.pem -noout -ext subjectAltName +``` + +Use brackets around an IPv6 literal in an access URL, for example +`https://[2001:db8::10]:2053/`. This example uses a documentation prefix; issue a +certificate for your own assigned public address. + ## Cloudflare (DNS-01 wildcard) DNS validation proves you control the domain by creating a TXT record instead of diff --git a/install.sh b/install.sh index dd67e6c09..243fdcedf 100644 --- a/install.sh +++ b/install.sh @@ -54,9 +54,302 @@ export NONINTERACTIVE is_ipv4() { [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1 } -is_ipv6() { - [[ "$1" =~ : ]] && return 0 || return 1 +# BEGIN GENERATED IP SSL HELPERS +# shellcheck shell=bash +# Shared IP-certificate helpers, embedded into both standalone entry points. +# Keep this file free of top-level work and optional runtime dependencies. + +ip_ssl_ipv4() { + local value="$1" octet + local -a octets + [[ "$value" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1 + IFS=. read -r -a octets <<< "$value" + for octet in "${octets[@]}"; do + [[ "$octet" =~ ^(0|[1-9][0-9]{0,2})$ ]] && ((10#$octet <= 255)) || return 1 + done } + +ip_ssl_expand_ipv6() { + local value="$1" prefix tail group count missing i + local -a octets left=() right=() groups=() + if [[ "$value" == *.* ]]; then + tail="${value##*:}" + ip_ssl_ipv4 "$tail" || return 1 + [[ "$value" == *:* ]] || return 1 + IFS=. read -r -a octets <<< "$tail" + printf -v tail '%x:%x' "$((10#${octets[0]} * 256 + 10#${octets[1]}))" "$((10#${octets[2]} * 256 + 10#${octets[3]}))" + value="${value%:*}:$tail" + fi + [[ "$value" =~ ^[[:xdigit:]:]+$ && "$value" != *:::* ]] || return 1 + [[ "$value" != :* || "$value" == ::* ]] || return 1 + [[ "$value" != *: || "$value" == *:: ]] || return 1 + if [[ "$value" == *::* ]]; then + prefix="${value%%::*}" + tail="${value#*::}" + [[ "$tail" != *::* ]] || return 1 + [[ -z "$prefix" ]] || IFS=: read -r -a left <<< "$prefix" + [[ -z "$tail" ]] || IFS=: read -r -a right <<< "$tail" + count=$((${#left[@]} + ${#right[@]})) + ((count < 8)) || return 1 + missing=$((8 - count)) + groups=("${left[@]}") + for ((i = 0; i < missing; i++)); do groups+=(0); done + groups+=("${right[@]}") + else + [[ "$value" != :* && "$value" != *: ]] || return 1 + IFS=: read -r -a groups <<< "$value" + ((${#groups[@]} == 8)) || return 1 + fi + for group in "${groups[@]}"; do + [[ "$group" =~ ^[[:xdigit:]]{1,4}$ ]] || return 1 + done + for ((i = 0; i < 8; i++)); do + ((i == 0)) || printf ':' + printf '%04x' "$((16#${groups[i]}))" + done + printf '\n' +} + +is_ipv6() { ip_ssl_expand_ipv6 "$1" > /dev/null; } + +ip_ssl_public_ipv6() { + local expanded first second + expanded=$(ip_ssl_expand_ipv6 "$1") || return 1 + first="${expanded%%:*}" + second="${expanded#*:}"; second="${second%%:*}" + ((16#$first >= 0x2000 && 16#$first <= 0x3fff)) || return 1 + # Exclude protocol assignments, documentation and deprecated 6to4 space. + [[ "$first" != 2002 ]] || return 1 + [[ "$first:$second" != 2001:0db8 ]] || return 1 + [[ "$first" != 2001 ]] || ((16#$second >= 0x0200)) || return 1 + [[ "$first" != 3fff ]] || ((16#$second >= 0x1000)) || return 1 +} + +ip_ssl_detect_ipv6() { + command -v ip > /dev/null 2>&1 || return 0 + local source preferred='' line cidr address expanded label rank i + local -a fields stable=() privacy=() chosen=() + local -A seen=() + # This consults the kernel route table; it sends no packet to the target. + source=$(ip -6 route get 2606:4700:4700::1111 2> /dev/null | awk '{for(i=1;i /dev/null || true) + if ((${#stable[@]})); then chosen=("${stable[@]}"); else chosen=("${privacy[@]}"); fi + ((${#chosen[@]})) || return 0 + printf '%s\n' "${chosen[@]}" | LC_ALL=C sort -t $'\t' -k1,1n -k2,2 | cut -f2- +} + +ip_ssl_select_ipv6() { + local interactive="$1" configured="${2:-}" row address answer selection i + local -a candidates=() labels=() + if [[ -n "$configured" ]]; then + if ! ip_ssl_public_ipv6 "$configured"; then + printf 'Invalid public IPv6 in XUI_SSL_IPV6: %s\n' "$configured" >&2 + return 1 + fi + printf '%s\n' "$configured" + return 0 + fi + [[ "$interactive" == 1 ]] || return 0 + printf 'Detecting public IPv6 addresses...\n' >&2 + while IFS=$'\t' read -r address row; do + [[ -n "$address" ]] || continue + candidates+=("$address"); labels+=("$row") + done < <(ip_ssl_detect_ipv6) + address='' + if ((${#candidates[@]} == 1)); then + address="${candidates[0]}" + printf '\nDetected IPv6 (%s):\n%s\n' "${labels[0]}" "$address" >&2 + elif ((${#candidates[@]} > 1)); then + printf '\nDetected IPv6 candidates:\n' >&2 + for ((i=0;i<${#candidates[@]};i++)); do printf '%d) %s (%s)\n' "$((i+1))" "${candidates[i]}" "${labels[i]}" >&2; done + while true; do + printf 'Choose a number, m for manual entry, or Enter to skip: ' >&2 + IFS= read -r selection || selection='' + [[ -n "$selection" ]] || return 0 + [[ "$selection" != m && "$selection" != M ]] || break + if [[ "$selection" =~ ^[0-9]{1,5}$ ]] && ((10#$selection >= 1 && 10#$selection <= ${#candidates[@]})); then + address="${candidates[10#$selection-1]}"; break + fi + printf 'Invalid selection.\n' >&2 + done + else + printf 'No suitable public IPv6 address was detected.\n' >&2 + fi + if [[ -n "$address" ]]; then + if [[ "${labels[*]}" == *temporary* ]]; then + printf 'Temporary IPv6 addresses can change; renewal requires this address to remain reachable.\n' >&2 + fi + while true; do + printf 'Include %s in the SSL certificate? [y/N]: ' "$address" >&2 + IFS= read -r answer || answer='' + case "$answer" in + y|Y) printf '%s\n' "$address"; return 0 ;; + n|N|'') break ;; + *) printf 'Please answer y or n.\n' >&2 ;; + esac + done + fi + while true; do + printf 'Enter a public IPv6 address manually or press Enter to skip: ' >&2 + IFS= read -r address || address='' + address="${address#"${address%%[![:space:]]*}"}" + address="${address%"${address##*[![:space:]]}"}" + [[ -n "$address" ]] || return 0 + if ip_ssl_public_ipv6 "$address"; then printf '%s\n' "$address"; return 0; fi + printf 'Invalid public IPv6 address. Enter one address, without a subnet or zone ID.\n' >&2 + done +} + +ip_ssl_dual_stack_probe() ( + local port="$1" probe_dir pid4='' pid6='' attempt body4 body6 serve + local marker="xui-acme-$$-$RANDOM" + [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 + command -v socat > /dev/null 2>&1 && command -v curl > /dev/null 2>&1 || return 1 + probe_dir=$(mktemp -d) || return 1 + trap '[[ -z "$pid4" ]] || { kill "$pid4" 2>/dev/null || true; wait "$pid4" 2>/dev/null || true; }; [[ -z "$pid6" ]] || { kill "$pid6" 2>/dev/null || true; wait "$pid6" 2>/dev/null || true; }; rm -rf -- "$probe_dir"' EXIT + serve="sleep 0.1; echo 'HTTP/1.0 200 OK'; echo 'Content-Length\: ${#marker}'; echo ''; printf '%s' '$marker'" + socat "TCP4-LISTEN:$port,crlf,reuseaddr,fork" "SYSTEM:$serve" > /dev/null 2>"$probe_dir/v4.log" & + pid4=$! + socat "TCP6-LISTEN:$port,crlf,reuseaddr,fork,ipv6only=1" "SYSTEM:$serve" > /dev/null 2>"$probe_dir/v6.log" & + pid6=$! + for ((attempt=0;attempt<10;attempt++)); do + body4=$(curl --noproxy '*' -4 --silent --fail --connect-timeout 1 --max-time 2 "http://127.0.0.1:$port/" 2> /dev/null) || body4='' + body6=$(curl --noproxy '*' -6 --silent --fail -g --connect-timeout 1 --max-time 2 "http://[::1]:$port/" 2> /dev/null) || body6='' + [[ "$body4" != "$marker" || "$body6" != "$marker" ]] || return 0 + if ! kill -0 "$pid4" 2> /dev/null || ! kill -0 "$pid6" 2> /dev/null; then break; fi + sleep 0.1 + done + return 1 +) + +ip_ssl_prepare_listener() { + local acme="$1" port="$2" ipv6="${3:-}" line version='' major minor patch + IP_SSL_LISTEN_ARGS=(--listen-v4) + [[ -n "$ipv6" ]] || return 0 + while IFS= read -r line; do + if [[ "$line" =~ ^v?([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})($|[^0-9]) ]]; then + major="${BASH_REMATCH[1]}"; minor="${BASH_REMATCH[2]}"; patch="${BASH_REMATCH[3]}" + if ((10#$major > 3 || (10#$major == 3 && (10#$minor > 1 || (10#$minor == 1 && 10#$patch >= 5))))); then version=1; fi + break + fi + done < <("$acme" --version 2> /dev/null) + if [[ -z "$version" ]]; then + printf 'Dual-stack IP certificates require acme.sh 3.1.5 or newer. Upgrade acme.sh and retry; the confirmed IPv6 was not omitted.\n' >&2 + return 1 + fi + if ! ip_ssl_dual_stack_probe "$port"; then + printf 'Cannot serve HTTP-01 over both IPv4 and IPv6 on port %s. Check socat, IPv6 support and port conflicts. No certificate request was sent.\n' "$port" >&2 + return 1 + fi + # Consumed as an array by the standalone installer and menu entry points. + # shellcheck disable=SC2034 + IP_SSL_LISTEN_ARGS=(--listen-v4 --listen-v6) +} + +ip_ssl_shell_quote() { + local value="$1" + value="${value//\'/\'\\\'\'}" + printf "'%s'" "$value" +} + +ip_ssl_issue_and_install() ( + local acme="$1" ipv4="$2" ipv6="$3" port="$4" cert_dir="$5" reload="$6" + local stage='' attempted=0 installed=0 code=0 file restored + local quoted_cert quoted_key validation check_key reload_guard + local -a domain_args=(-d "$ipv4") + if ! ip_ssl_ipv4 "$ipv4" || { [[ -n "$ipv6" ]] && ! ip_ssl_public_ipv6 "$ipv6"; }; then + printf 'Invalid IP certificate identifier; no ACME request was sent.\n' >&2 + return 1 + fi + [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 + [[ -z "$ipv6" ]] || domain_args+=(-d "$ipv6") + ip_ssl_prepare_listener "$acme" "$port" "$ipv6" || return 1 + if ! "$acme" --issue "${domain_args[@]}" --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ + --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then + printf 'IP certificate issuance failed. Existing certificates and ACME data were preserved. Check external port 80 on every selected address.\n' >&2 + return 1 + fi + + umask 077 + mkdir -p "$cert_dir" || return 1 + stage=$(mktemp -d "$cert_dir/.xui-install.XXXXXX") || return 1 + # shellcheck disable=SC2329 + ip_ssl_install_cleanup() { + restored=1 + if ((attempted && !installed)); then + for file in fullchain.pem privkey.pem; do + if [[ -f "$stage/$file" ]]; then + cp -p -- "$stage/$file" "$cert_dir/$file" || restored=0 + else + rm -f -- "$cert_dir/$file" || restored=0 + fi + done + fi + if ((restored)); then + rm -rf -- "$stage" + else + printf 'Could not restore certificate files; recovery copies remain in %s\n' "$stage" >&2 + fi + } + trap ip_ssl_install_cleanup EXIT + for file in fullchain.pem privkey.pem; do + [[ ! -e "$cert_dir/$file" ]] || cp -p -- "$cert_dir/$file" "$stage/$file" || return 1 + done + quoted_cert=$(ip_ssl_shell_quote "$cert_dir/fullchain.pem") + quoted_key=$(ip_ssl_shell_quote "$cert_dir/privkey.pem") + # Trust the leaf only for local identity checks, not as a new system CA. + validation="openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv4' $quoted_cert" + [[ -z "$ipv6" ]] || validation+=" && openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv6' $quoted_cert" + # Expansion belongs to the later reload shell, including cron renewals. + # shellcheck disable=SC2016 + printf -v check_key 'xui_cert_pub=$(openssl x509 -in %s -pubkey -noout) && xui_key_pub=$(openssl pkey -in %s -passin pass: -pubout) && [ -n "$xui_cert_pub" ] && [ "$xui_cert_pub" = "$xui_key_pub" ]' "$quoted_cert" "$quoted_key" + validation+=" && $check_key" + # acme.sh persists this self-contained guard for later cron renewals too. + reload_guard="$validation && { $reload; }" + attempted=1 + "$acme" --installcert --force -d "$ipv4" --key-file "$cert_dir/privkey.pem" \ + --fullchain-file "$cert_dir/fullchain.pem" --reloadcmd "$reload_guard" || code=$? + if ! sh -c "$validation" > /dev/null 2>&1; then + printf 'Installed certificate failed IP SAN, validity or private-key checks; restoring previous files.\n' >&2 + return 1 + fi + if ((code != 0)) && [[ -f "$stage/fullchain.pem" ]] && [[ "$(cat "$stage/fullchain.pem")" == "$(cat "$cert_dir/fullchain.pem")" ]]; then + printf 'Certificate installation failed without replacing the previous certificate.\n' >&2 + return 1 + fi + chmod 600 "$cert_dir/privkey.pem" && chmod 644 "$cert_dir/fullchain.pem" || return 1 + installed=1 + if ((code != 0)); then printf 'Certificate files are valid, but the reload command reported an error.\n' >&2; fi +) +# END GENERATED IP SSL HELPERS is_ip() { is_ipv4 "$1" || is_ipv6 "$1" } @@ -498,7 +791,12 @@ setup_ssl_certificate() { # Requires acme.sh and port 80 open for HTTP-01 challenge setup_ip_certificate() { local ipv4="$1" - local ipv6="$2" # optional + local ipv6="${2:-}" + local certDir="${3:-/root/cert/ip}" + if ! ip_ssl_ipv4 "$ipv4" || { [[ -n "$ipv6" ]] && ! ip_ssl_public_ipv6 "$ipv6"; }; then + printf 'Invalid IP certificate identifier.\n' >&2 + return 1 + fi echo -e "${green}Setting up Let's Encrypt IP certificate (shortlived profile)...${plain}" echo -e "${yellow}Note: IP certificates are valid for ~6 days and will auto-renew.${plain}" @@ -513,28 +811,6 @@ setup_ip_certificate() { fi fi - # Validate IP address - if [[ -z "$ipv4" ]]; then - echo -e "${red}IPv4 address is required${plain}" - return 1 - fi - - if ! is_ipv4 "$ipv4"; then - echo -e "${red}Invalid IPv4 address: $ipv4${plain}" - return 1 - fi - - # Create certificate directory - local certDir="/root/cert/ip" - mkdir -p "$certDir" - - # Build domain arguments - local domain_args="-d ${ipv4}" - if [[ -n "$ipv6" ]] && is_ipv6 "$ipv6"; then - domain_args="${domain_args} -d ${ipv6}" - echo -e "${green}Including IPv6 address: ${ipv6}${plain}" - fi - # Set reload command for auto-renewal (add || true so it doesn't fail during first install) local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null || true" @@ -579,59 +855,15 @@ setup_ip_certificate() { fi done - # Issue certificate with shortlived profile - echo -e "${green}Issuing IP certificate for ${ipv4}...${plain}" - ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1 - [[ -n "${XUI_ACME_EMAIL:-}" ]] && ~/.acme.sh/acme.sh --register-account -m "${XUI_ACME_EMAIL}" > /dev/null 2>&1 - - ~/.acme.sh/acme.sh --issue \ - ${domain_args} \ - --standalone \ - --server letsencrypt \ - --certificate-profile shortlived \ - --days 6 \ - --httpport ${WebPort} \ - --force - - if [ $? -ne 0 ]; then - echo -e "${red}Failed to issue IP certificate${plain}" - echo -e "${yellow}Please ensure port ${WebPort} is reachable (or forwarded from external port 80)${plain}" - # Cleanup acme.sh data for both IPv4 and IPv6 if specified - rm -rf ~/.acme.sh/${ipv4} ~/.acme.sh/${ipv4}_ecc 2> /dev/null - [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} ~/.acme.sh/${ipv6}_ecc 2> /dev/null - rm -rf ${certDir} 2> /dev/null + if [[ -n "${XUI_ACME_EMAIL:-}" ]]; then + ~/.acme.sh/acme.sh --register-account --server letsencrypt -m "${XUI_ACME_EMAIL}" || return 1 + fi + if ! ip_ssl_issue_and_install "$HOME/.acme.sh/acme.sh" "$ipv4" "$ipv6" "$WebPort" "$certDir" "$reloadCmd"; then return 1 fi - - echo -e "${green}Certificate issued successfully, installing...${plain}" - - # Install certificate - # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails, - # but the cert files are still installed. We check for files instead of exit code. - ~/.acme.sh/acme.sh --installcert --force -d ${ipv4} \ - --key-file "${certDir}/privkey.pem" \ - --fullchain-file "${certDir}/fullchain.pem" \ - --reloadcmd "${reloadCmd}" 2>&1 || true - - # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero) - if [[ ! -f "${certDir}/fullchain.pem" || ! -f "${certDir}/privkey.pem" ]]; then - echo -e "${red}Certificate files not found after installation${plain}" - # Cleanup acme.sh data for both IPv4 and IPv6 if specified - rm -rf ~/.acme.sh/${ipv4} ~/.acme.sh/${ipv4}_ecc 2> /dev/null - [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} ~/.acme.sh/${ipv6}_ecc 2> /dev/null - rm -rf ${certDir} 2> /dev/null - return 1 - fi - - echo -e "${green}Certificate files installed successfully${plain}" - - # Enable auto-upgrade for acme.sh (ensures cron job runs) + echo -e "${green}Certificate files installed and verified successfully${plain}" ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1 - # Secure permissions: private key readable only by owner - chmod 600 ${certDir}/privkey.pem 2> /dev/null - chmod 644 ${certDir}/fullchain.pem 2> /dev/null - # Configure panel to use the certificate echo -e "${green}Setting certificate paths for the panel...${plain}" ${xui_folder}/x-ui cert -webCert "${certDir}/fullchain.pem" -webCertKey "${certDir}/privkey.pem" @@ -949,25 +1181,33 @@ prompt_and_setup_ssl() { fi fi - # Ask for optional IPv6 - local ipv6_addr="" - prompt_or_default ipv6_addr "Do you have an IPv6 address to include? (leave empty to skip): " "" XUI_SSL_IPV6 - ipv6_addr="${ipv6_addr// /}" # Trim whitespace + local ipv6_addr + ipv6_addr=$(ip_ssl_select_ipv6 "$((1 - NONINTERACTIVE))" "${XUI_SSL_IPV6:-}") || return 1 - # Stop panel if running (port 80 needed) + local panel_was_running=0 + # Remember the prior state so failed issuance does not leave it down. if [[ $release == "alpine" ]]; then + if rc-service x-ui status > /dev/null 2>&1; then panel_was_running=1; fi rc-service x-ui stop > /dev/null 2>&1 else + if systemctl is-active --quiet x-ui > /dev/null 2>&1; then panel_was_running=1; fi systemctl stop x-ui > /dev/null 2>&1 fi - setup_ip_certificate "${server_ip}" "${ipv6_addr}" - if [ $? -eq 0 ]; then + if setup_ip_certificate "${server_ip}" "${ipv6_addr}"; then SSL_HOST="${server_ip}" echo -e "${green}✓ Let's Encrypt IP certificate configured successfully${plain}" else - echo -e "${red}✗ IP certificate setup failed. Please check port 80 is open.${plain}" + echo -e "${red}✗ IP certificate setup failed. Please check port 80 on both selected addresses.${plain}" SSL_HOST="${server_ip}" + if ((panel_was_running)); then + if [[ $release == "alpine" ]]; then + rc-service x-ui start || echo -e "${red}Could not restore the previously running panel.${plain}" + else + systemctl start x-ui || echo -e "${red}Could not restore the previously running panel.${plain}" + fi + fi + return 1 fi ;; 3) @@ -1285,7 +1525,7 @@ EOF echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}" echo "" - prompt_and_setup_ssl "${config_port}" "${config_webBasePath}" "${server_ip}" + prompt_and_setup_ssl "${config_port}" "${config_webBasePath}" "${server_ip}" || return 1 # Retrieve the API token for display local config_apiToken=$(${xui_folder}/x-ui setting -getApiToken | grep -Eo 'apiToken: .+' | awk '{print $2}') @@ -1360,7 +1600,7 @@ EOF echo -e "${green}═══════════════════════════════════════════${plain}" echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}" echo "" - prompt_and_setup_ssl "${existing_port}" "${config_webBasePath}" "${server_ip}" + prompt_and_setup_ssl "${existing_port}" "${config_webBasePath}" "${server_ip}" || return 1 echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${existing_port}/${config_webBasePath}${plain}" else # If a cert already exists, just show the access URL @@ -1401,7 +1641,7 @@ EOF echo -e "${green}═══════════════════════════════════════════${plain}" echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}" echo "" - prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}" + prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}" || return 1 echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}" else echo -e "${green}SSL certificate already configured. No action needed.${plain}" @@ -1909,7 +2149,7 @@ install_x-ui() { fi chmod +x /usr/bin/x-ui mkdir -p /var/log/x-ui - config_after_install + config_after_install || return 1 # Etckeeper compatibility if [ -d "/etc/.git" ]; then diff --git a/scripts/lib/ip-ssl.sh b/scripts/lib/ip-ssl.sh new file mode 100644 index 000000000..1946639a7 --- /dev/null +++ b/scripts/lib/ip-ssl.sh @@ -0,0 +1,294 @@ +# shellcheck shell=bash +# Shared IP-certificate helpers, embedded into both standalone entry points. +# Keep this file free of top-level work and optional runtime dependencies. + +ip_ssl_ipv4() { + local value="$1" octet + local -a octets + [[ "$value" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1 + IFS=. read -r -a octets <<< "$value" + for octet in "${octets[@]}"; do + [[ "$octet" =~ ^(0|[1-9][0-9]{0,2})$ ]] && ((10#$octet <= 255)) || return 1 + done +} + +ip_ssl_expand_ipv6() { + local value="$1" prefix tail group count missing i + local -a octets left=() right=() groups=() + if [[ "$value" == *.* ]]; then + tail="${value##*:}" + ip_ssl_ipv4 "$tail" || return 1 + [[ "$value" == *:* ]] || return 1 + IFS=. read -r -a octets <<< "$tail" + printf -v tail '%x:%x' "$((10#${octets[0]} * 256 + 10#${octets[1]}))" "$((10#${octets[2]} * 256 + 10#${octets[3]}))" + value="${value%:*}:$tail" + fi + [[ "$value" =~ ^[[:xdigit:]:]+$ && "$value" != *:::* ]] || return 1 + [[ "$value" != :* || "$value" == ::* ]] || return 1 + [[ "$value" != *: || "$value" == *:: ]] || return 1 + if [[ "$value" == *::* ]]; then + prefix="${value%%::*}" + tail="${value#*::}" + [[ "$tail" != *::* ]] || return 1 + [[ -z "$prefix" ]] || IFS=: read -r -a left <<< "$prefix" + [[ -z "$tail" ]] || IFS=: read -r -a right <<< "$tail" + count=$((${#left[@]} + ${#right[@]})) + ((count < 8)) || return 1 + missing=$((8 - count)) + groups=("${left[@]}") + for ((i = 0; i < missing; i++)); do groups+=(0); done + groups+=("${right[@]}") + else + [[ "$value" != :* && "$value" != *: ]] || return 1 + IFS=: read -r -a groups <<< "$value" + ((${#groups[@]} == 8)) || return 1 + fi + for group in "${groups[@]}"; do + [[ "$group" =~ ^[[:xdigit:]]{1,4}$ ]] || return 1 + done + for ((i = 0; i < 8; i++)); do + ((i == 0)) || printf ':' + printf '%04x' "$((16#${groups[i]}))" + done + printf '\n' +} + +is_ipv6() { ip_ssl_expand_ipv6 "$1" > /dev/null; } + +ip_ssl_public_ipv6() { + local expanded first second + expanded=$(ip_ssl_expand_ipv6 "$1") || return 1 + first="${expanded%%:*}" + second="${expanded#*:}"; second="${second%%:*}" + ((16#$first >= 0x2000 && 16#$first <= 0x3fff)) || return 1 + # Exclude protocol assignments, documentation and deprecated 6to4 space. + [[ "$first" != 2002 ]] || return 1 + [[ "$first:$second" != 2001:0db8 ]] || return 1 + [[ "$first" != 2001 ]] || ((16#$second >= 0x0200)) || return 1 + [[ "$first" != 3fff ]] || ((16#$second >= 0x1000)) || return 1 +} + +ip_ssl_detect_ipv6() { + command -v ip > /dev/null 2>&1 || return 0 + local source preferred='' line cidr address expanded label rank i + local -a fields stable=() privacy=() chosen=() + local -A seen=() + # This consults the kernel route table; it sends no packet to the target. + source=$(ip -6 route get 2606:4700:4700::1111 2> /dev/null | awk '{for(i=1;i /dev/null || true) + if ((${#stable[@]})); then chosen=("${stable[@]}"); else chosen=("${privacy[@]}"); fi + ((${#chosen[@]})) || return 0 + printf '%s\n' "${chosen[@]}" | LC_ALL=C sort -t $'\t' -k1,1n -k2,2 | cut -f2- +} + +ip_ssl_select_ipv6() { + local interactive="$1" configured="${2:-}" row address answer selection i + local -a candidates=() labels=() + if [[ -n "$configured" ]]; then + if ! ip_ssl_public_ipv6 "$configured"; then + printf 'Invalid public IPv6 in XUI_SSL_IPV6: %s\n' "$configured" >&2 + return 1 + fi + printf '%s\n' "$configured" + return 0 + fi + [[ "$interactive" == 1 ]] || return 0 + printf 'Detecting public IPv6 addresses...\n' >&2 + while IFS=$'\t' read -r address row; do + [[ -n "$address" ]] || continue + candidates+=("$address"); labels+=("$row") + done < <(ip_ssl_detect_ipv6) + address='' + if ((${#candidates[@]} == 1)); then + address="${candidates[0]}" + printf '\nDetected IPv6 (%s):\n%s\n' "${labels[0]}" "$address" >&2 + elif ((${#candidates[@]} > 1)); then + printf '\nDetected IPv6 candidates:\n' >&2 + for ((i=0;i<${#candidates[@]};i++)); do printf '%d) %s (%s)\n' "$((i+1))" "${candidates[i]}" "${labels[i]}" >&2; done + while true; do + printf 'Choose a number, m for manual entry, or Enter to skip: ' >&2 + IFS= read -r selection || selection='' + [[ -n "$selection" ]] || return 0 + [[ "$selection" != m && "$selection" != M ]] || break + if [[ "$selection" =~ ^[0-9]{1,5}$ ]] && ((10#$selection >= 1 && 10#$selection <= ${#candidates[@]})); then + address="${candidates[10#$selection-1]}"; break + fi + printf 'Invalid selection.\n' >&2 + done + else + printf 'No suitable public IPv6 address was detected.\n' >&2 + fi + if [[ -n "$address" ]]; then + if [[ "${labels[*]}" == *temporary* ]]; then + printf 'Temporary IPv6 addresses can change; renewal requires this address to remain reachable.\n' >&2 + fi + while true; do + printf 'Include %s in the SSL certificate? [y/N]: ' "$address" >&2 + IFS= read -r answer || answer='' + case "$answer" in + y|Y) printf '%s\n' "$address"; return 0 ;; + n|N|'') break ;; + *) printf 'Please answer y or n.\n' >&2 ;; + esac + done + fi + while true; do + printf 'Enter a public IPv6 address manually or press Enter to skip: ' >&2 + IFS= read -r address || address='' + address="${address#"${address%%[![:space:]]*}"}" + address="${address%"${address##*[![:space:]]}"}" + [[ -n "$address" ]] || return 0 + if ip_ssl_public_ipv6 "$address"; then printf '%s\n' "$address"; return 0; fi + printf 'Invalid public IPv6 address. Enter one address, without a subnet or zone ID.\n' >&2 + done +} + +ip_ssl_dual_stack_probe() ( + local port="$1" probe_dir pid4='' pid6='' attempt body4 body6 serve + local marker="xui-acme-$$-$RANDOM" + [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 + command -v socat > /dev/null 2>&1 && command -v curl > /dev/null 2>&1 || return 1 + probe_dir=$(mktemp -d) || return 1 + trap '[[ -z "$pid4" ]] || { kill "$pid4" 2>/dev/null || true; wait "$pid4" 2>/dev/null || true; }; [[ -z "$pid6" ]] || { kill "$pid6" 2>/dev/null || true; wait "$pid6" 2>/dev/null || true; }; rm -rf -- "$probe_dir"' EXIT + serve="sleep 0.1; echo 'HTTP/1.0 200 OK'; echo 'Content-Length\: ${#marker}'; echo ''; printf '%s' '$marker'" + socat "TCP4-LISTEN:$port,crlf,reuseaddr,fork" "SYSTEM:$serve" > /dev/null 2>"$probe_dir/v4.log" & + pid4=$! + socat "TCP6-LISTEN:$port,crlf,reuseaddr,fork,ipv6only=1" "SYSTEM:$serve" > /dev/null 2>"$probe_dir/v6.log" & + pid6=$! + for ((attempt=0;attempt<10;attempt++)); do + body4=$(curl --noproxy '*' -4 --silent --fail --connect-timeout 1 --max-time 2 "http://127.0.0.1:$port/" 2> /dev/null) || body4='' + body6=$(curl --noproxy '*' -6 --silent --fail -g --connect-timeout 1 --max-time 2 "http://[::1]:$port/" 2> /dev/null) || body6='' + [[ "$body4" != "$marker" || "$body6" != "$marker" ]] || return 0 + if ! kill -0 "$pid4" 2> /dev/null || ! kill -0 "$pid6" 2> /dev/null; then break; fi + sleep 0.1 + done + return 1 +) + +ip_ssl_prepare_listener() { + local acme="$1" port="$2" ipv6="${3:-}" line version='' major minor patch + IP_SSL_LISTEN_ARGS=(--listen-v4) + [[ -n "$ipv6" ]] || return 0 + while IFS= read -r line; do + if [[ "$line" =~ ^v?([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})($|[^0-9]) ]]; then + major="${BASH_REMATCH[1]}"; minor="${BASH_REMATCH[2]}"; patch="${BASH_REMATCH[3]}" + if ((10#$major > 3 || (10#$major == 3 && (10#$minor > 1 || (10#$minor == 1 && 10#$patch >= 5))))); then version=1; fi + break + fi + done < <("$acme" --version 2> /dev/null) + if [[ -z "$version" ]]; then + printf 'Dual-stack IP certificates require acme.sh 3.1.5 or newer. Upgrade acme.sh and retry; the confirmed IPv6 was not omitted.\n' >&2 + return 1 + fi + if ! ip_ssl_dual_stack_probe "$port"; then + printf 'Cannot serve HTTP-01 over both IPv4 and IPv6 on port %s. Check socat, IPv6 support and port conflicts. No certificate request was sent.\n' "$port" >&2 + return 1 + fi + # Consumed as an array by the standalone installer and menu entry points. + # shellcheck disable=SC2034 + IP_SSL_LISTEN_ARGS=(--listen-v4 --listen-v6) +} + +ip_ssl_shell_quote() { + local value="$1" + value="${value//\'/\'\\\'\'}" + printf "'%s'" "$value" +} + +ip_ssl_issue_and_install() ( + local acme="$1" ipv4="$2" ipv6="$3" port="$4" cert_dir="$5" reload="$6" + local stage='' attempted=0 installed=0 code=0 file restored + local quoted_cert quoted_key validation check_key reload_guard + local -a domain_args=(-d "$ipv4") + if ! ip_ssl_ipv4 "$ipv4" || { [[ -n "$ipv6" ]] && ! ip_ssl_public_ipv6 "$ipv6"; }; then + printf 'Invalid IP certificate identifier; no ACME request was sent.\n' >&2 + return 1 + fi + [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 + [[ -z "$ipv6" ]] || domain_args+=(-d "$ipv6") + ip_ssl_prepare_listener "$acme" "$port" "$ipv6" || return 1 + if ! "$acme" --issue "${domain_args[@]}" --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ + --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then + printf 'IP certificate issuance failed. Existing certificates and ACME data were preserved. Check external port 80 on every selected address.\n' >&2 + return 1 + fi + + umask 077 + mkdir -p "$cert_dir" || return 1 + stage=$(mktemp -d "$cert_dir/.xui-install.XXXXXX") || return 1 + # shellcheck disable=SC2329 + ip_ssl_install_cleanup() { + restored=1 + if ((attempted && !installed)); then + for file in fullchain.pem privkey.pem; do + if [[ -f "$stage/$file" ]]; then + cp -p -- "$stage/$file" "$cert_dir/$file" || restored=0 + else + rm -f -- "$cert_dir/$file" || restored=0 + fi + done + fi + if ((restored)); then + rm -rf -- "$stage" + else + printf 'Could not restore certificate files; recovery copies remain in %s\n' "$stage" >&2 + fi + } + trap ip_ssl_install_cleanup EXIT + for file in fullchain.pem privkey.pem; do + [[ ! -e "$cert_dir/$file" ]] || cp -p -- "$cert_dir/$file" "$stage/$file" || return 1 + done + quoted_cert=$(ip_ssl_shell_quote "$cert_dir/fullchain.pem") + quoted_key=$(ip_ssl_shell_quote "$cert_dir/privkey.pem") + # Trust the leaf only for local identity checks, not as a new system CA. + validation="openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv4' $quoted_cert" + [[ -z "$ipv6" ]] || validation+=" && openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv6' $quoted_cert" + # Expansion belongs to the later reload shell, including cron renewals. + # shellcheck disable=SC2016 + printf -v check_key 'xui_cert_pub=$(openssl x509 -in %s -pubkey -noout) && xui_key_pub=$(openssl pkey -in %s -passin pass: -pubout) && [ -n "$xui_cert_pub" ] && [ "$xui_cert_pub" = "$xui_key_pub" ]' "$quoted_cert" "$quoted_key" + validation+=" && $check_key" + # acme.sh persists this self-contained guard for later cron renewals too. + reload_guard="$validation && { $reload; }" + attempted=1 + "$acme" --installcert --force -d "$ipv4" --key-file "$cert_dir/privkey.pem" \ + --fullchain-file "$cert_dir/fullchain.pem" --reloadcmd "$reload_guard" || code=$? + if ! sh -c "$validation" > /dev/null 2>&1; then + printf 'Installed certificate failed IP SAN, validity or private-key checks; restoring previous files.\n' >&2 + return 1 + fi + if ((code != 0)) && [[ -f "$stage/fullchain.pem" ]] && [[ "$(cat "$stage/fullchain.pem")" == "$(cat "$cert_dir/fullchain.pem")" ]]; then + printf 'Certificate installation failed without replacing the previous certificate.\n' >&2 + return 1 + fi + chmod 600 "$cert_dir/privkey.pem" && chmod 644 "$cert_dir/fullchain.pem" || return 1 + installed=1 + if ((code != 0)); then printf 'Certificate files are valid, but the reload command reported an error.\n' >&2; fi +) diff --git a/scripts/sync-ip-ssl-helpers.sh b/scripts/sync-ip-ssl-helpers.sh new file mode 100644 index 000000000..f8cf34faa --- /dev/null +++ b/scripts/sync-ip-ssl-helpers.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=$(cd "$(dirname "$0")/.." && pwd) +mode='write' +if [[ "${1:-}" == --check ]]; then mode=check; shift; fi +targets=("$@") +if (($# == 0)); then targets=(x-ui.sh install.sh); fi +temp=$(mktemp) +trap 'rm -f "$temp"' EXIT +for target in "${targets[@]}"; do + case "$target" in x-ui.sh|install.sh) ;; *) printf 'Unknown standalone script: %s\n' "$target" >&2; exit 1;; esac + awk -v helper="$ROOT/scripts/lib/ip-ssl.sh" ' + {sub(/\r$/, "")} + /^# BEGIN GENERATED IP SSL HELPERS$/ { + found++; print; while ((getline line < helper) > 0) print line; close(helper); block=1; next + } + /^# END GENERATED IP SSL HELPERS$/ {block=0} + !block {print} + END {if(found!=1 || block) exit 1} + ' "$ROOT/$target" > "$temp" + if [[ "$mode" == check ]]; then + if ! cmp -s "$temp" "$ROOT/$target"; then + printf 'Stale IP SSL helpers in %s; run bash scripts/sync-ip-ssl-helpers.sh\n' "$target" >&2 + exit 1 + fi + else + cat "$temp" > "$ROOT/$target" + fi +done diff --git a/scripts/test/README.md b/scripts/test/README.md new file mode 100644 index 000000000..191e61934 --- /dev/null +++ b/scripts/test/README.md @@ -0,0 +1,50 @@ +# IP certificate regression tests + +Run from the repository root in Bash. The suite uses temporary files, mocks ACME +orders and service commands, and generates local self-signed certificate fixtures. +It never requests a certificate from a CA or executes the complete installer. + +```bash +bash -n install.sh +bash -n x-ui.sh +bash scripts/sync-ip-ssl-helpers.sh --check +bash scripts/test/ip-ssl-test.sh +bash scripts/test/ip-ssl-entrypoint-test.sh +IP_SSL_LINUX_TEST=1 bash scripts/test/ip-ssl-listener-test.sh +bash scripts/test/ip-ssl-certificate-test.sh +``` + +Linux integration needs `socat`, `curl`, `openssl` (1.1.1+), and standard coreutils. +The listener tests bind unprivileged random ports on loopback. They need an IPv6 +loopback interface, but no public IPv6 address, root privileges, or working +external echo service. Run the same commands on Debian/Ubuntu and AlmaLinux/RHEL; +install test dependencies in a disposable container if they are missing locally. + +The tests cover real embedded installer/menu functions, discovery and consent, +unattended overrides, both socket families, actual IP SAN types and matching keys, +failed issuance/installation, rollback, permissions, and the persisted renewal +reload guard. Package installation, ACME orders, and panel/service operations are +mocked at their command boundaries. + +To check unchanged upstream acme.sh listener implementations separately: + +```bash +curl -fsSLo /tmp/acme-3.1.5.sh https://raw.githubusercontent.com/acmesh-official/acme.sh/3.1.5/acme.sh +bash scripts/test/ip-ssl-acme-listener-test.sh /tmp/acme-3.1.5.sh 28085 +curl -fsSLo /tmp/acme-3.1.6.sh https://raw.githubusercontent.com/acmesh-official/acme.sh/3.1.6/acme.sh +bash scripts/test/ip-ssl-acme-listener-test.sh /tmp/acme-3.1.6.sh 28085 +``` + +This invokes only the upstream listener dispatcher, sends independent loopback +HTTP requests with `curl -4` and `curl -6`, prints the sockets with `ss`, then +stops the listeners. It does not issue ACME orders or change an installed client. +Run it in a disposable Linux environment with `iproute2`/`iproute` installed. +Test both `net.ipv6.bindv6only=0` and `1` container configurations where available. + +Loopback success does not establish public reachability. Real CA validation, +external port 80 forwarding, provider firewalls, and scheduled cron execution on +a deployed server require separate deployment testing. + +After editing `scripts/lib/ip-ssl.sh`, run +`bash scripts/sync-ip-ssl-helpers.sh` to refresh both standalone scripts. CI checks +that the embedded helpers match the canonical source. diff --git a/scripts/test/ip-ssl-acme-listener-test.sh b/scripts/test/ip-ssl-acme-listener-test.sh new file mode 100644 index 000000000..5185ce281 --- /dev/null +++ b/scripts/test/ip-ssl-acme-listener-test.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -eo pipefail +acme_source="$1" +port="$2" +marker="xui-real-acme-$$" +serverproc='' +export Le_HTTPPort="$port" Le_Listen_V4=1 Le_Listen_V6=1 +trap '_stopserver "${serverproc:-}" >/dev/null 2>&1 || true; wait 2>/dev/null || true' EXIT +# The unchanged upstream dispatcher can call its listener without an ACME order. +set -- _startserver "$marker" '' +# shellcheck disable=SC1090 +source "$acme_source" +for family in 4 6; do + target=127.0.0.1 + [[ "$family" != 6 ]] || target='[::1]' + body=$(curl --noproxy '*' "-$family" -g --silent --show-error --fail --connect-timeout 2 --max-time 4 "http://$target:$port/.well-known/acme-challenge/probe") + [[ "$body" == "$marker" ]] || { printf 'Wrong ACME response over IPv%s\n' "$family" >&2; exit 1; } +done +ss -lnt | awk -v port=":$port" '$4 ~ port {print}' +printf 'PASS: unchanged upstream %s serves IPv4 and IPv6 with both listen flags\n' "$acme_source" diff --git a/scripts/test/ip-ssl-certificate-test.sh b/scripts/test/ip-ssl-certificate-test.sh new file mode 100644 index 000000000..85630d7a3 --- /dev/null +++ b/scripts/test/ip-ssl-certificate-test.sh @@ -0,0 +1,150 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +# shellcheck disable=SC1090 +source "${IP_SSL_TEST_HELPERS:-$ROOT/scripts/lib/ip-ssl.sh}" +TEMP=$(mktemp -d) +trap 'rm -rf "$TEMP"' EXIT +fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; } +export ACME_LOG="$TEMP/arguments" RELOAD_LOG="$TEMP/reloads" +export ISSUED_CERT="$TEMP/new.pem" ISSUED_KEY="$TEMP/new.key" +export ACME_ISSUE_FAIL=0 ACME_INSTALL_FAIL=0 ACME_RELOAD_FAIL=0 +for name in old new v4 dns; do + san='IP:198.51.100.8,IP:2001:4860::1' + [[ "$name" != v4 ]] || san='IP:198.51.100.8' + [[ "$name" != dns ]] || san='DNS:198.51.100.8,DNS:2001:4860::1' + openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 2 -subj /CN=ip-test -addext "subjectAltName=$san" -keyout "$TEMP/$name.key" -out "$TEMP/$name.pem" > /dev/null 2>&1 +done +mkdir "$TEMP/cert's directory" +cert_dir="$TEMP/cert's directory" +cp "$TEMP/old.pem" "$cert_dir/fullchain.pem" +cp "$TEMP/old.key" "$cert_dir/privkey.pem" +cat > "$TEMP/mock acme" <<'MOCK' +#!/usr/bin/env bash +set -euo pipefail +printf 'CALL\n' >> "$ACME_LOG" +printf 'arg=%s\n' "$@" >> "$ACME_LOG" +case "$1" in + --version) printf 'v3.1.5\n' ;; + --issue) [[ "$ACME_ISSUE_FAIL" != 1 ]] ;; + --upgrade|--register-account) : ;; + --installcert) + key=''; cert=''; reload='' + while (($#)); do + case "$1" in --key-file) key="$2"; shift;; --fullchain-file) cert="$2"; shift;; --reloadcmd) reload="$2"; shift;; esac + shift + done + if [[ "$ACME_INSTALL_FAIL" == 1 ]]; then printf 'broken certificate\n' > "$cert"; exit 1; fi + cp "$ISSUED_KEY" "$key"; cp "$ISSUED_CERT" "$cert" + printf '%s' "$reload" > "$RELOAD_LOG.command" + sh -c "$reload" + [[ "$ACME_RELOAD_FAIL" != 1 ]] + ;; + *) printf 'Unexpected ACME operation: %s\n' "$1" >&2; exit 1 ;; +esac +MOCK +chmod +x "$TEMP/mock acme" +acme="$TEMP/mock acme" +reload="printf 'reloaded\\n' >> '$RELOAD_LOG'" +port=$((20000+RANDOM)) + +ACME_ISSUE_FAIL=1 +if ip_ssl_issue_and_install "$acme" 198.51.100.8 '' "$port" "$cert_dir" "$reload"; then fail 'ACME failure reported success'; fi +cmp "$TEMP/old.pem" "$cert_dir/fullchain.pem" || fail 'issuance failure removed existing certificate' +cmp "$TEMP/old.key" "$cert_dir/privkey.pem" || fail 'issuance failure removed existing key' +[[ ! -f "$RELOAD_LOG" ]] || fail 'issuance failure reloaded panel' +printf 'PASS: ACME failure preserves existing certificate and key\n' +ACME_ISSUE_FAIL=0 + +ip_ssl_issue_and_install "$acme" 198.51.100.8 '2001:4860::1' "$port" "$cert_dir" "$reload" +cmp "$TEMP/new.pem" "$cert_dir/fullchain.pem" || fail 'new certificate not installed' +[[ "$(stat -c %a "$cert_dir/privkey.pem")" == 600 ]] || fail 'private key permissions changed' +[[ "$(stat -c %a "$cert_dir/fullchain.pem")" == 644 ]] || fail 'certificate permissions changed' +openssl verify -trusted "$cert_dir/fullchain.pem" -partial_chain -verify_ip 198.51.100.8 "$cert_dir/fullchain.pem" > /dev/null +openssl verify -trusted "$cert_dir/fullchain.pem" -partial_chain -verify_ip 2001:4860::1 "$cert_dir/fullchain.pem" > /dev/null +if ! grep -qx 'arg=--listen-v4' "$ACME_LOG" || ! grep -qx 'arg=--listen-v6' "$ACME_LOG"; then fail 'dual-stack flags absent'; fi +[[ "$(grep -cx 'arg=2001:4860::1' "$ACME_LOG")" == 1 ]] || fail 'IPv6 SAN duplicated or missing' +[[ "$(cat "$RELOAD_LOG")" == reloaded ]] || fail 'valid certificate did not reload' +sh -c "$(cat "$RELOAD_LOG.command")" +[[ "$(wc -l < "$RELOAD_LOG")" == 2 ]] || fail 'saved renewal reload command failed' +printf 'PASS: both IP SANs, quoting, install permissions and saved reload command\n' + +cp "$TEMP/v4.pem" "$cert_dir/fullchain.pem" +cp "$TEMP/v4.key" "$cert_dir/privkey.pem" +if sh -c "$(cat "$RELOAD_LOG.command")" > /dev/null 2>&1; then fail 'renewal guard accepted a missing IPv6 SAN'; fi +[[ "$(wc -l < "$RELOAD_LOG")" == 2 ]] || fail 'invalid renewed certificate reloaded the panel' +cp "$TEMP/new.pem" "$cert_dir/fullchain.pem" +cp "$TEMP/new.key" "$cert_dir/privkey.pem" +printf 'PASS: saved renewal guard blocks reload after a missing IPv6 SAN\n' + +for bad in v4 dns; do + ISSUED_CERT="$TEMP/$bad.pem"; ISSUED_KEY="$TEMP/$bad.key" + if ip_ssl_issue_and_install "$acme" 198.51.100.8 '2001:4860::1' "$port" "$cert_dir" "$reload"; then fail 'missing IP SAN accepted'; fi + cmp "$TEMP/new.pem" "$cert_dir/fullchain.pem" || fail 'bad SAN replaced working certificate' + cmp "$TEMP/new.key" "$cert_dir/privkey.pem" || fail 'bad SAN replaced working key' + [[ "$(wc -l < "$RELOAD_LOG")" == 2 ]] || fail 'invalid IP SAN reloaded panel' +done +ISSUED_CERT="$TEMP/new.pem"; ISSUED_KEY="$TEMP/old.key" +if ip_ssl_issue_and_install "$acme" 198.51.100.8 '' "$port" "$cert_dir" "$reload"; then fail 'mismatched private key accepted'; fi +cmp "$TEMP/new.key" "$cert_dir/privkey.pem" || fail 'mismatched key was not rolled back' +ACME_INSTALL_FAIL=1 +if ip_ssl_issue_and_install "$acme" 198.51.100.8 '' "$port" "$cert_dir" "$reload"; then fail 'partial installation accepted'; fi +cmp "$TEMP/new.pem" "$cert_dir/fullchain.pem" || fail 'partial install was not rolled back' +ACME_INSTALL_FAIL=0 +ISSUED_CERT="$TEMP/old.pem"; ISSUED_KEY="$TEMP/old.key"; ACME_RELOAD_FAIL=1 +ip_ssl_issue_and_install "$acme" 198.51.100.8 '' "$port" "$cert_dir" "$reload" +cmp "$TEMP/old.pem" "$cert_dir/fullchain.pem" || fail 'reload error discarded valid newly installed cert' +printf 'PASS: SAN/key mismatch and partial-install rollback; valid copy survives reload errors\n' + +before=$(wc -l < "$ACME_LOG") +if ip_ssl_issue_and_install "$acme" 198.51.100.8 "2001:4860::1;touch $TEMP/injected" "$port" "$cert_dir" "$reload"; then fail 'injection accepted'; fi +[[ ! -e "$TEMP/injected" && "$(wc -l < "$ACME_LOG")" == "$before" ]] || fail 'invalid IP reached shell or ACME' +printf 'PASS: invalid SAN never reaches ACME or a shell command\n' + +source_function() { + source /dev/stdin < <(awk -v name="$2" '$0==name"() {" {body=1} body {print} body && /^}/ {exit}' "$1") +} +export HOME="$TEMP/home" +mkdir -p "$HOME/.acme.sh" "$TEMP/panel" "$TEMP/mockbin" +cp "$acme" "$HOME/.acme.sh/acme.sh" +cat > "$TEMP/panel/x-ui" <<'PANEL' +#!/usr/bin/env bash +if [[ "$1" == setting ]]; then printf 'webBasePath: /test/\nport: 2053\n'; else printf 'configured\n' >> "$RELOAD_LOG.panel"; fi +PANEL +cat > "$TEMP/mockbin/systemctl" <<'SERVICE' +#!/usr/bin/env bash +printf 'reloaded\n' >> "$RELOAD_LOG" +SERVICE +chmod +x "$TEMP/panel/x-ui" "$TEMP/mockbin/systemctl" +export PATH="$TEMP/mockbin:$PATH" +export xui_folder="$TEMP/panel" release=ubuntu +export red='' green='' yellow='' blue='' plain='' +LOGI() { printf '%s\n' "$*"; } +LOGE() { printf '%s\n' "$*" >&2; } +apt-get() { :; } +restart() { printf 'restarted\n' >> "$RELOAD_LOG.panel"; } +curl() { + if [[ "$*" == *https://* ]]; then printf '198.51.100.8\n200'; else command curl "$@"; fi +} +ip() { + [[ "$*" != '-6 route get '* ]] || return 0 + printf '2: eth0 inet6 2001:4860::1/64 scope global valid_lft forever preferred_lft forever\n' +} +ACME_RELOAD_FAIL=0; ISSUED_CERT="$TEMP/new.pem"; ISSUED_KEY="$TEMP/new.key" +source_function "$ROOT/x-ui.sh" confirm +source_function "$ROOT/x-ui.sh" ssl_cert_issue_for_ip +if ! ssl_cert_issue_for_ip "$TEMP/menu-cert" <<< "$(printf 'y\ny\n%s\ny\n' "$port")" > "$TEMP/menu-output" 2>&1; then + cat "$TEMP/menu-output"; fail 'management menu issuance failed' +fi +grep -Fq 'https://[2001:4860::1]:2053/test/' "$TEMP/menu-output" || fail 'IPv6 access URL is not bracketed' +if ! grep -q configured "$RELOAD_LOG.panel" || ! grep -q restarted "$RELOAD_LOG.panel"; then fail 'menu did not configure and restart panel after consent'; fi +source_function "$ROOT/install.sh" prompt_or_default +source_function "$ROOT/install.sh" setup_ip_certificate +export NONINTERACTIVE=1 XUI_ACME_HTTP_PORT="$port" XUI_ACME_EMAIL=ssl-test@example.invalid +if ! setup_ip_certificate 198.51.100.8 '2001:4860::1' "$TEMP/installer-cert" "$TEMP/install-output" 2>&1; then + cat "$TEMP/install-output"; fail 'installer issuance failed' +fi +openssl verify -trusted "$TEMP/installer-cert/fullchain.pem" -partial_chain -verify_ip 2001:4860::1 "$TEMP/installer-cert/fullchain.pem" > /dev/null +grep -qx 'arg=--upgrade' "$ACME_LOG" || fail 'auto-upgrade registration lost' +grep -qx 'arg=--register-account' "$ACME_LOG" || fail 'configured account email ignored' +printf 'PASS: real menu and installer functions install both IP SANs, configure panel paths and retain renewal setup\n' diff --git a/scripts/test/ip-ssl-entrypoint-test.sh b/scripts/test/ip-ssl-entrypoint-test.sh new file mode 100644 index 000000000..f28a528fc --- /dev/null +++ b/scripts/test/ip-ssl-entrypoint-test.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="${IP_SSL_ENTRY_ROOT:-$(cd "$(dirname "$0")/../.." && pwd)}" +source_function() { + source /dev/stdin < <(awk -v name="$2" '$0==name"() {" {body=1} body {print} body && /^}/ {exit}' "$1") +} +fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; } +TEMP=$(mktemp -d) +trap 'rm -rf "$TEMP"' EXIT +export red='' green='' yellow='' blue='' plain='' release=ubuntu +source /dev/stdin < <(awk '/^# BEGIN GENERATED IP SSL HELPERS/ {block=1;next} /^# END GENERATED IP SSL HELPERS/ {block=0} block {print}' "$ROOT/install.sh") +source_function "$ROOT/install.sh" prompt_or_default +source_function "$ROOT/install.sh" prompt_and_setup_ssl +# Invoked by the real installer function loaded above, before the failure stubs. +# shellcheck disable=SC2329 +setup_ip_certificate() { captured="${2:-}"; called=1; } +# shellcheck disable=SC2329 +systemctl() { stopped=1; } +export NONINTERACTIVE=1 XUI_SSL_MODE=ip XUI_SSL_IPV6='not:ipv6' +called=0; stopped=0 +if prompt_and_setup_ssl 2053 / 198.51.100.8 > "$TEMP/invalid" 2>&1; then fail 'invalid environment IPv6 accepted by installer'; fi +[[ "$called" == 0 && "$stopped" == 0 ]] || fail 'invalid IPv6 stopped panel or reached issuance' +grep -q 'Invalid public IPv6' "$TEMP/invalid" || fail 'invalid environment value has no clear diagnostic' +unset XUI_SSL_IPV6 +called=0 +prompt_and_setup_ssl 2053 / 198.51.100.8 "$TEMP/unattended" 2>&1 +[[ "$called" == 1 && -z "$captured" ]] || fail 'unattended unset override did not retain IPv4-only issuance' +if grep -q 'Detecting public IPv6' "$TEMP/unattended"; then fail 'unattended installer detected IPv6 without opt-in'; fi +export XUI_SSL_IPV6='2001:4860::1'; called=0 +prompt_and_setup_ssl 2053 / 198.51.100.8 /dev/null +[[ "$called" == 1 && "$captured" == '2001:4860::1' ]] || fail 'explicit IPv6 override was lost' +unset XUI_SSL_IPV6 +ip() { + [[ "$*" != '-6 route get '* ]] || return 0 + printf '2: eth0 inet6 2001:4860::1/64 scope global valid_lft forever preferred_lft forever\n' +} +NONINTERACTIVE=0 +prompt_and_setup_ssl 2053 / 198.51.100.8 <<< $'\ny\ny' > "$TEMP/accepted" 2>&1 +[[ "$captured" == '2001:4860::1' ]] || fail 'interactive installer did not include confirmed detected address' +prompt_and_setup_ssl 2053 / 198.51.100.8 <<< $'\ny\nn\n' > "$TEMP/rejected" 2>&1 +[[ -z "$captured" ]] || fail 'interactive installer included a rejected address' +printf 'PASS: installer consent, explicit configuration, no unattended prompts, and validation before service stop\n' + +setup_ip_certificate() { return 1; } +systemctl() { + printf '%s\n' "$*" >> "$TEMP/service-calls" + [[ "$1" != is-active ]] || [[ "$was_running" == 1 ]] +} +rc-service() { + printf '%s\n' "$*" >> "$TEMP/service-calls" + [[ "$2" != status ]] || [[ "$was_running" == 1 ]] +} +NONINTERACTIVE=1 +export XUI_SSL_IPV6='2001:4860::1' +for release in ubuntu alpine; do + for was_running in 0 1; do + : > "$TEMP/service-calls" + if prompt_and_setup_ssl 2053 / 198.51.100.8 > /dev/null 2>&1; then fail 'failed IP setup reported success'; fi + if [[ "$was_running" == 1 ]]; then + grep -Eq '^(start x-ui|x-ui start)$' "$TEMP/service-calls" || fail "failed IP setup left the previous $release panel stopped" + elif grep -Eq '^(start x-ui|x-ui start)$' "$TEMP/service-calls"; then + fail "failed IP setup started an inactive $release panel" + fi + done +done +printf 'PASS: failed issuance restores only a previously running panel on systemd/OpenRC\n' diff --git a/scripts/test/ip-ssl-listener-test.sh b/scripts/test/ip-ssl-listener-test.sh new file mode 100644 index 000000000..c41c2e1f6 --- /dev/null +++ b/scripts/test/ip-ssl-listener-test.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +source "$ROOT/scripts/lib/ip-ssl.sh" +TEMP=$(mktemp -d) +trap 'rm -rf "$TEMP"' EXIT +fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; } +acme_version() { printf 'https://github.com/acmesh-official/acme.sh\nv%s\n' "${VERSION:-3.1.5}"; } +ip_ssl_prepare_listener acme_version 18080 '' +[[ "${IP_SSL_LISTEN_ARGS[*]}" == '--listen-v4' ]] || fail 'IPv4-only flags changed' +VERSION=3.1.4 +if ip_ssl_prepare_listener acme_version 18080 '2001:4860::1' 2>"$TEMP/old-version"; then fail 'old acme.sh accepted for dual-stack'; fi +grep -q '3.1.5' "$TEMP/old-version" || fail 'old-version error does not explain the minimum version' +printf 'PASS: IPv4-only and incompatible acme.sh behavior\n' + +[[ "${IP_SSL_LINUX_TEST:-0}" == 1 ]] || exit 0 +command -v socat > /dev/null || fail 'Linux listener test requires socat' +VERSION=3.1.5 +port=$((20000+RANDOM)) +ip_ssl_prepare_listener acme_version "$port" '2001:4860::1' +[[ "${IP_SSL_LISTEN_ARGS[*]}" == '--listen-v4 --listen-v6' ]] || fail 'dual-stack flags missing' +if curl --noproxy '*' --silent --fail --connect-timeout 1 --max-time 2 "http://127.0.0.1:$port" > /dev/null; then fail 'probe left its IPv4 listener running'; fi +if curl --noproxy '*' --silent --fail -g --connect-timeout 1 --max-time 2 "http://[::1]:$port" > /dev/null; then fail 'probe left its IPv6 listener running'; fi +printf 'PASS: both real loopback families answered, and probe listeners were cleaned up\n' + +socat() { + if [[ "$*" == *TCP6-LISTEN* ]]; then return 1; fi + command socat "$@" +} +if ip_ssl_prepare_listener acme_version "$port" '2001:4860::1' 2>"$TEMP/no-ipv6"; then fail 'unavailable IPv6 listener accepted'; fi +grep -q 'IPv4 and IPv6' "$TEMP/no-ipv6" || fail 'dual-stack failure has no clear diagnostic' +printf 'PASS: unavailable IPv6 does not silently fall back to IPv4\n' diff --git a/scripts/test/ip-ssl-test.sh b/scripts/test/ip-ssl-test.sh new file mode 100644 index 000000000..c056f1bda --- /dev/null +++ b/scripts/test/ip-ssl-test.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +source /dev/stdin < <(awk '/^# check root/ { exit } { print }' "$ROOT/x-ui.sh") +TEMP=$(mktemp -d) +trap 'rm -rf "$TEMP"' EXIT + +fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; } +same() { [[ "$1" == "$2" ]] || fail "$3: got [$1], want [$2]"; } +pass() { printf 'PASS: %s\n' "$1"; } + +for invalid in 'not:ipv6' ':::' '1::2:' ':1::2' '1:2:3:4:5:6:7' '1:2:3:4:5:6:7:8:9' '2606::4700::1' '2606:4700::12345' '2606:4700::1/64' 'fe80::1%eth0' 'example.org' '2606:4700::1;touch /tmp/injected' '::ffff:192.000.2.1' ''; do + if is_ipv6 "$invalid"; then fail "malformed IPv6 accepted: $invalid"; fi +done +for valid in '::' '::1' '2606:4700::1111' '2001:4860:4860:0:0:0:0:8888' '::ffff:192.0.2.1' '1:2:3:4:5:6:7::'; do + is_ipv6 "$valid" || fail "valid IPv6 rejected: $valid" +done +pass 'IPv6 parser rejects malformed literals, CIDRs, zones and injection' + +for unsuitable in '::1' '::' 'fe80::1' 'fd00::1' 'ff02::1' '2001:db8::1' '3fff::1' '2002:c000:201::1' '2001::1'; do + if ip_ssl_public_ipv6 "$unsuitable"; then fail "unsuitable public candidate: $unsuitable"; fi +done +ip_ssl_public_ipv6 '2001:4860::1' || fail 'global IPv6 rejected' +pass 'automatic candidates exclude nonpublic and special-purpose ranges' + +ip() { + if [[ "$*" == '-6 route get '* ]]; then printf '%s\n' "${ROUTE:-}"; return; fi + [[ "${IP_FAILURE:-0}" == 0 ]] || return 1 + printf '%s\n' "${ADDRESSES:-}" +} +curl() { printf 'unexpected external discovery request\n' >> "$TEMP/curl-calls"; return 7; } +row() { printf '2: eth0 inet6 %s/64 scope global %s valid_lft forever preferred_lft forever\n' "$1" "${2:-}"; } +ADDRESSES=$(row '2001:4860::1') +ROUTE='2606:4700::1111 via fe80::1 dev eth0 src 2001:4860::1 metric 100' +same "$(ip_ssl_detect_ipv6)" $'2001:4860::1\tdefault route' 'one default-route candidate' +ADDRESSES="$(row '2001:4860::1')"$'\n'"$(row '2606:4700::2')"$'\n'"$(row '2001:4860:0:0:0:0:0:1')" +ROUTE='2606:4700::1111 dev eth0 src 2606:4700::2 metric 100' +same "$(ip_ssl_detect_ipv6)" $'2606:4700::2\tdefault route\n2001:4860::1\tstable' 'route ordering and normalized deduplication' +ADDRESSES="$(row '2606:4700::1' temporary)"$'\n'"$(row '2001:4860::1')"$'\n'"$(row '2001:4860::2' deprecated)"$'\n'"$(row '2001:4860::3' tentative)"$'\n'"$(row '2001:4860::4' dadfailed)"$'\n'"$(row '2001:4860::5' optimistic)" +same "$(ip_ssl_detect_ipv6)" $'2001:4860::1\tstable' 'stable address wins over privacy and unusable addresses' +ADDRESSES=$(row '2606:4700::1' temporary) +same "$(ip_ssl_detect_ipv6)" $'2606:4700::1\ttemporary' 'privacy-only host is labelled' +ADDRESSES="$(row '2606:4700::1' temporary)"$'\n'"$(row '2606:4700:0:0:0:0:0:1')" +same "$(ip_ssl_detect_ipv6)" $'2606:4700:0:0:0:0:0:1\tstable' 'stable duplicate beats a temporary observation' +for ADDRESSES in '' "$(row 'fe80::1')" "$(row 'fd00::1')" 'broken output inet6 not:ipv6/64 scope global'; do + same "$(ip_ssl_detect_ipv6)" '' 'no eligible candidates' +done +IP_FAILURE=1 +same "$(ip_ssl_detect_ipv6)" '' 'ip command failure' +IP_FAILURE=0 +same "$(unset -f ip; PATH=/nonexistent ip_ssl_detect_ipv6)" '' 'missing ip command' +[[ ! -f "$TEMP/curl-calls" ]] || fail 'local discovery depended on an external echo service' +pass 'discovery handles route preference, deduplication, privacy, missing tools and invalid output' + +ADDRESSES=$(row '2001:4860::1') +ROUTE='' +same "$(ip_ssl_select_ipv6 1 '' <<< 'y')" '2001:4860::1' 'accept detected address' +same "$(ip_ssl_select_ipv6 1 '' <<< $'n\n')" '' 'reject and skip' +same "$(ip_ssl_select_ipv6 1 '' <<< $'n\n2606:4700::2')" '2606:4700::2' 'reject and enter manual address' +ADDRESSES="$(row '2001:4860::1')"$'\n'"$(row '2606:4700::2')" +same "$(ip_ssl_select_ipv6 1 '' <<< $'2\ny')" '2606:4700::2' 'select just one of multiple addresses' +ADDRESSES='' +same "$(ip_ssl_select_ipv6 1 '' <<< $'bad:ip\n2606:4700::2' 2>"$TEMP/manual-error")" '2606:4700::2' 'invalid manual input is retried' +grep -q 'Invalid public IPv6' "$TEMP/manual-error" || fail 'invalid manual input was silently skipped' +same "$(ip_ssl_select_ipv6 0 '' "$TEMP/env-error"; then fail 'invalid environment override accepted'; fi +grep -q 'Invalid public IPv6' "$TEMP/env-error" || fail 'invalid override has no clear error' +pass 'selection requires consent and retains manual, skip and unattended behavior' diff --git a/x-ui.sh b/x-ui.sh index 8e245c271..5ec286f47 100644 --- a/x-ui.sh +++ b/x-ui.sh @@ -40,9 +40,302 @@ is_port_in_use() { is_ipv4() { [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1 } -is_ipv6() { - [[ "$1" =~ : ]] && return 0 || return 1 +# BEGIN GENERATED IP SSL HELPERS +# shellcheck shell=bash +# Shared IP-certificate helpers, embedded into both standalone entry points. +# Keep this file free of top-level work and optional runtime dependencies. + +ip_ssl_ipv4() { + local value="$1" octet + local -a octets + [[ "$value" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1 + IFS=. read -r -a octets <<< "$value" + for octet in "${octets[@]}"; do + [[ "$octet" =~ ^(0|[1-9][0-9]{0,2})$ ]] && ((10#$octet <= 255)) || return 1 + done } + +ip_ssl_expand_ipv6() { + local value="$1" prefix tail group count missing i + local -a octets left=() right=() groups=() + if [[ "$value" == *.* ]]; then + tail="${value##*:}" + ip_ssl_ipv4 "$tail" || return 1 + [[ "$value" == *:* ]] || return 1 + IFS=. read -r -a octets <<< "$tail" + printf -v tail '%x:%x' "$((10#${octets[0]} * 256 + 10#${octets[1]}))" "$((10#${octets[2]} * 256 + 10#${octets[3]}))" + value="${value%:*}:$tail" + fi + [[ "$value" =~ ^[[:xdigit:]:]+$ && "$value" != *:::* ]] || return 1 + [[ "$value" != :* || "$value" == ::* ]] || return 1 + [[ "$value" != *: || "$value" == *:: ]] || return 1 + if [[ "$value" == *::* ]]; then + prefix="${value%%::*}" + tail="${value#*::}" + [[ "$tail" != *::* ]] || return 1 + [[ -z "$prefix" ]] || IFS=: read -r -a left <<< "$prefix" + [[ -z "$tail" ]] || IFS=: read -r -a right <<< "$tail" + count=$((${#left[@]} + ${#right[@]})) + ((count < 8)) || return 1 + missing=$((8 - count)) + groups=("${left[@]}") + for ((i = 0; i < missing; i++)); do groups+=(0); done + groups+=("${right[@]}") + else + [[ "$value" != :* && "$value" != *: ]] || return 1 + IFS=: read -r -a groups <<< "$value" + ((${#groups[@]} == 8)) || return 1 + fi + for group in "${groups[@]}"; do + [[ "$group" =~ ^[[:xdigit:]]{1,4}$ ]] || return 1 + done + for ((i = 0; i < 8; i++)); do + ((i == 0)) || printf ':' + printf '%04x' "$((16#${groups[i]}))" + done + printf '\n' +} + +is_ipv6() { ip_ssl_expand_ipv6 "$1" > /dev/null; } + +ip_ssl_public_ipv6() { + local expanded first second + expanded=$(ip_ssl_expand_ipv6 "$1") || return 1 + first="${expanded%%:*}" + second="${expanded#*:}"; second="${second%%:*}" + ((16#$first >= 0x2000 && 16#$first <= 0x3fff)) || return 1 + # Exclude protocol assignments, documentation and deprecated 6to4 space. + [[ "$first" != 2002 ]] || return 1 + [[ "$first:$second" != 2001:0db8 ]] || return 1 + [[ "$first" != 2001 ]] || ((16#$second >= 0x0200)) || return 1 + [[ "$first" != 3fff ]] || ((16#$second >= 0x1000)) || return 1 +} + +ip_ssl_detect_ipv6() { + command -v ip > /dev/null 2>&1 || return 0 + local source preferred='' line cidr address expanded label rank i + local -a fields stable=() privacy=() chosen=() + local -A seen=() + # This consults the kernel route table; it sends no packet to the target. + source=$(ip -6 route get 2606:4700:4700::1111 2> /dev/null | awk '{for(i=1;i /dev/null || true) + if ((${#stable[@]})); then chosen=("${stable[@]}"); else chosen=("${privacy[@]}"); fi + ((${#chosen[@]})) || return 0 + printf '%s\n' "${chosen[@]}" | LC_ALL=C sort -t $'\t' -k1,1n -k2,2 | cut -f2- +} + +ip_ssl_select_ipv6() { + local interactive="$1" configured="${2:-}" row address answer selection i + local -a candidates=() labels=() + if [[ -n "$configured" ]]; then + if ! ip_ssl_public_ipv6 "$configured"; then + printf 'Invalid public IPv6 in XUI_SSL_IPV6: %s\n' "$configured" >&2 + return 1 + fi + printf '%s\n' "$configured" + return 0 + fi + [[ "$interactive" == 1 ]] || return 0 + printf 'Detecting public IPv6 addresses...\n' >&2 + while IFS=$'\t' read -r address row; do + [[ -n "$address" ]] || continue + candidates+=("$address"); labels+=("$row") + done < <(ip_ssl_detect_ipv6) + address='' + if ((${#candidates[@]} == 1)); then + address="${candidates[0]}" + printf '\nDetected IPv6 (%s):\n%s\n' "${labels[0]}" "$address" >&2 + elif ((${#candidates[@]} > 1)); then + printf '\nDetected IPv6 candidates:\n' >&2 + for ((i=0;i<${#candidates[@]};i++)); do printf '%d) %s (%s)\n' "$((i+1))" "${candidates[i]}" "${labels[i]}" >&2; done + while true; do + printf 'Choose a number, m for manual entry, or Enter to skip: ' >&2 + IFS= read -r selection || selection='' + [[ -n "$selection" ]] || return 0 + [[ "$selection" != m && "$selection" != M ]] || break + if [[ "$selection" =~ ^[0-9]{1,5}$ ]] && ((10#$selection >= 1 && 10#$selection <= ${#candidates[@]})); then + address="${candidates[10#$selection-1]}"; break + fi + printf 'Invalid selection.\n' >&2 + done + else + printf 'No suitable public IPv6 address was detected.\n' >&2 + fi + if [[ -n "$address" ]]; then + if [[ "${labels[*]}" == *temporary* ]]; then + printf 'Temporary IPv6 addresses can change; renewal requires this address to remain reachable.\n' >&2 + fi + while true; do + printf 'Include %s in the SSL certificate? [y/N]: ' "$address" >&2 + IFS= read -r answer || answer='' + case "$answer" in + y|Y) printf '%s\n' "$address"; return 0 ;; + n|N|'') break ;; + *) printf 'Please answer y or n.\n' >&2 ;; + esac + done + fi + while true; do + printf 'Enter a public IPv6 address manually or press Enter to skip: ' >&2 + IFS= read -r address || address='' + address="${address#"${address%%[![:space:]]*}"}" + address="${address%"${address##*[![:space:]]}"}" + [[ -n "$address" ]] || return 0 + if ip_ssl_public_ipv6 "$address"; then printf '%s\n' "$address"; return 0; fi + printf 'Invalid public IPv6 address. Enter one address, without a subnet or zone ID.\n' >&2 + done +} + +ip_ssl_dual_stack_probe() ( + local port="$1" probe_dir pid4='' pid6='' attempt body4 body6 serve + local marker="xui-acme-$$-$RANDOM" + [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 + command -v socat > /dev/null 2>&1 && command -v curl > /dev/null 2>&1 || return 1 + probe_dir=$(mktemp -d) || return 1 + trap '[[ -z "$pid4" ]] || { kill "$pid4" 2>/dev/null || true; wait "$pid4" 2>/dev/null || true; }; [[ -z "$pid6" ]] || { kill "$pid6" 2>/dev/null || true; wait "$pid6" 2>/dev/null || true; }; rm -rf -- "$probe_dir"' EXIT + serve="sleep 0.1; echo 'HTTP/1.0 200 OK'; echo 'Content-Length\: ${#marker}'; echo ''; printf '%s' '$marker'" + socat "TCP4-LISTEN:$port,crlf,reuseaddr,fork" "SYSTEM:$serve" > /dev/null 2>"$probe_dir/v4.log" & + pid4=$! + socat "TCP6-LISTEN:$port,crlf,reuseaddr,fork,ipv6only=1" "SYSTEM:$serve" > /dev/null 2>"$probe_dir/v6.log" & + pid6=$! + for ((attempt=0;attempt<10;attempt++)); do + body4=$(curl --noproxy '*' -4 --silent --fail --connect-timeout 1 --max-time 2 "http://127.0.0.1:$port/" 2> /dev/null) || body4='' + body6=$(curl --noproxy '*' -6 --silent --fail -g --connect-timeout 1 --max-time 2 "http://[::1]:$port/" 2> /dev/null) || body6='' + [[ "$body4" != "$marker" || "$body6" != "$marker" ]] || return 0 + if ! kill -0 "$pid4" 2> /dev/null || ! kill -0 "$pid6" 2> /dev/null; then break; fi + sleep 0.1 + done + return 1 +) + +ip_ssl_prepare_listener() { + local acme="$1" port="$2" ipv6="${3:-}" line version='' major minor patch + IP_SSL_LISTEN_ARGS=(--listen-v4) + [[ -n "$ipv6" ]] || return 0 + while IFS= read -r line; do + if [[ "$line" =~ ^v?([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})($|[^0-9]) ]]; then + major="${BASH_REMATCH[1]}"; minor="${BASH_REMATCH[2]}"; patch="${BASH_REMATCH[3]}" + if ((10#$major > 3 || (10#$major == 3 && (10#$minor > 1 || (10#$minor == 1 && 10#$patch >= 5))))); then version=1; fi + break + fi + done < <("$acme" --version 2> /dev/null) + if [[ -z "$version" ]]; then + printf 'Dual-stack IP certificates require acme.sh 3.1.5 or newer. Upgrade acme.sh and retry; the confirmed IPv6 was not omitted.\n' >&2 + return 1 + fi + if ! ip_ssl_dual_stack_probe "$port"; then + printf 'Cannot serve HTTP-01 over both IPv4 and IPv6 on port %s. Check socat, IPv6 support and port conflicts. No certificate request was sent.\n' "$port" >&2 + return 1 + fi + # Consumed as an array by the standalone installer and menu entry points. + # shellcheck disable=SC2034 + IP_SSL_LISTEN_ARGS=(--listen-v4 --listen-v6) +} + +ip_ssl_shell_quote() { + local value="$1" + value="${value//\'/\'\\\'\'}" + printf "'%s'" "$value" +} + +ip_ssl_issue_and_install() ( + local acme="$1" ipv4="$2" ipv6="$3" port="$4" cert_dir="$5" reload="$6" + local stage='' attempted=0 installed=0 code=0 file restored + local quoted_cert quoted_key validation check_key reload_guard + local -a domain_args=(-d "$ipv4") + if ! ip_ssl_ipv4 "$ipv4" || { [[ -n "$ipv6" ]] && ! ip_ssl_public_ipv6 "$ipv6"; }; then + printf 'Invalid IP certificate identifier; no ACME request was sent.\n' >&2 + return 1 + fi + [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 + [[ -z "$ipv6" ]] || domain_args+=(-d "$ipv6") + ip_ssl_prepare_listener "$acme" "$port" "$ipv6" || return 1 + if ! "$acme" --issue "${domain_args[@]}" --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ + --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then + printf 'IP certificate issuance failed. Existing certificates and ACME data were preserved. Check external port 80 on every selected address.\n' >&2 + return 1 + fi + + umask 077 + mkdir -p "$cert_dir" || return 1 + stage=$(mktemp -d "$cert_dir/.xui-install.XXXXXX") || return 1 + # shellcheck disable=SC2329 + ip_ssl_install_cleanup() { + restored=1 + if ((attempted && !installed)); then + for file in fullchain.pem privkey.pem; do + if [[ -f "$stage/$file" ]]; then + cp -p -- "$stage/$file" "$cert_dir/$file" || restored=0 + else + rm -f -- "$cert_dir/$file" || restored=0 + fi + done + fi + if ((restored)); then + rm -rf -- "$stage" + else + printf 'Could not restore certificate files; recovery copies remain in %s\n' "$stage" >&2 + fi + } + trap ip_ssl_install_cleanup EXIT + for file in fullchain.pem privkey.pem; do + [[ ! -e "$cert_dir/$file" ]] || cp -p -- "$cert_dir/$file" "$stage/$file" || return 1 + done + quoted_cert=$(ip_ssl_shell_quote "$cert_dir/fullchain.pem") + quoted_key=$(ip_ssl_shell_quote "$cert_dir/privkey.pem") + # Trust the leaf only for local identity checks, not as a new system CA. + validation="openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv4' $quoted_cert" + [[ -z "$ipv6" ]] || validation+=" && openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv6' $quoted_cert" + # Expansion belongs to the later reload shell, including cron renewals. + # shellcheck disable=SC2016 + printf -v check_key 'xui_cert_pub=$(openssl x509 -in %s -pubkey -noout) && xui_key_pub=$(openssl pkey -in %s -passin pass: -pubout) && [ -n "$xui_cert_pub" ] && [ "$xui_cert_pub" = "$xui_key_pub" ]' "$quoted_cert" "$quoted_key" + validation+=" && $check_key" + # acme.sh persists this self-contained guard for later cron renewals too. + reload_guard="$validation && { $reload; }" + attempted=1 + "$acme" --installcert --force -d "$ipv4" --key-file "$cert_dir/privkey.pem" \ + --fullchain-file "$cert_dir/fullchain.pem" --reloadcmd "$reload_guard" || code=$? + if ! sh -c "$validation" > /dev/null 2>&1; then + printf 'Installed certificate failed IP SAN, validity or private-key checks; restoring previous files.\n' >&2 + return 1 + fi + if ((code != 0)) && [[ -f "$stage/fullchain.pem" ]] && [[ "$(cat "$stage/fullchain.pem")" == "$(cat "$cert_dir/fullchain.pem")" ]]; then + printf 'Certificate installation failed without replacing the previous certificate.\n' >&2 + return 1 + fi + chmod 600 "$cert_dir/privkey.pem" && chmod 644 "$cert_dir/fullchain.pem" || return 1 + installed=1 + if ((code != 0)); then printf 'Certificate files are valid, but the reload command reported an error.\n' >&2; fi +) +# END GENERATED IP SSL HELPERS is_ip() { is_ipv4 "$1" || is_ipv6 "$1" } @@ -1542,6 +1835,7 @@ ssl_cert_issue_main() { } ssl_cert_issue_for_ip() { + local certPath="${1:-/root/cert/ip}" LOGI "Starting automatic SSL certificate generation for server IP..." LOGI "Using Let's Encrypt shortlived profile (~6 days validity, auto-renews)" @@ -1562,7 +1856,7 @@ ssl_cert_issue_for_ip() { local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null) local http_code=$(echo "$response" | tail -n1) local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"') - if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + if [[ "${http_code}" == "200" ]] && ip_ssl_ipv4 "$ip_result"; then server_ip="${ip_result}" break fi @@ -1580,7 +1874,7 @@ ssl_cert_issue_for_ip() { while [[ -z "$server_ip" ]]; do read -rp "Please enter your server's public IPv4 address: " server_ip server_ip="${server_ip// /}" - if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + if ! ip_ssl_ipv4 "$server_ip"; then LOGE "Invalid IPv4 address. Please try again." server_ip="" fi @@ -1588,10 +1882,8 @@ ssl_cert_issue_for_ip() { LOGI "Issuing certificate for server IP: ${server_ip}" - # Ask for optional IPv6 - local ipv6_addr="" - read -rp "Do you have an IPv6 address to include? (leave empty to skip): " ipv6_addr - ipv6_addr="${ipv6_addr// /}" # Trim whitespace + local ipv6_addr + ipv6_addr=$(ip_ssl_select_ipv6 1) || return 1 # check for acme.sh first if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then @@ -1632,17 +1924,6 @@ ssl_cert_issue_for_ip() { ;; esac - # Create certificate directory - certPath="/root/cert/ip" - mkdir -p "$certPath" - - # Build domain arguments - local domain_args="-d ${server_ip}" - if [[ -n "$ipv6_addr" ]] && is_ipv6 "$ipv6_addr"; then - domain_args="${domain_args} -d ${ipv6_addr}" - LOGI "Including IPv6 address: ${ipv6_addr}" - fi - # Choose port for HTTP-01 listener (default 80, allow override) local WebPort="" read -rp "Port to use for ACME HTTP-01 listener (default 80): " WebPort @@ -1682,53 +1963,11 @@ ssl_cert_issue_for_ip() { # Reload command - restarts panel after renewal local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null" - # issue the certificate for IP with shortlived profile - ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force - ~/.acme.sh/acme.sh --issue \ - ${domain_args} \ - --standalone \ - --server letsencrypt \ - --certificate-profile shortlived \ - --days 6 \ - --httpport ${WebPort} \ - --force - - if [ $? -ne 0 ]; then - LOGE "Failed to issue certificate for IP: ${server_ip}" - LOGE "Make sure port ${WebPort} is open and the server is accessible from the internet" - # Cleanup acme.sh data for both IPv4 and IPv6 if specified - rm -rf ~/.acme.sh/${server_ip} ~/.acme.sh/${server_ip}_ecc 2> /dev/null - [[ -n "$ipv6_addr" ]] && rm -rf ~/.acme.sh/${ipv6_addr} ~/.acme.sh/${ipv6_addr}_ecc 2> /dev/null - rm -rf ${certPath} 2> /dev/null - return 1 - else - LOGI "Certificate issued successfully for IP: ${server_ip}" - fi - - # Install the certificate - # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails, - # but the cert files are still installed. We check for files instead of exit code. - ~/.acme.sh/acme.sh --installcert --force -d ${server_ip} \ - --key-file "${certPath}/privkey.pem" \ - --fullchain-file "${certPath}/fullchain.pem" \ - --reloadcmd "${reloadCmd}" 2>&1 || true - - # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero) - if [[ ! -f "${certPath}/fullchain.pem" || ! -f "${certPath}/privkey.pem" ]]; then - LOGE "Certificate files not found after installation" - # Cleanup acme.sh data for both IPv4 and IPv6 if specified - rm -rf ~/.acme.sh/${server_ip} ~/.acme.sh/${server_ip}_ecc 2> /dev/null - [[ -n "$ipv6_addr" ]] && rm -rf ~/.acme.sh/${ipv6_addr} ~/.acme.sh/${ipv6_addr}_ecc 2> /dev/null - rm -rf ${certPath} 2> /dev/null + if ! ip_ssl_issue_and_install "$HOME/.acme.sh/acme.sh" "$server_ip" "$ipv6_addr" "$WebPort" "$certPath" "$reloadCmd"; then return 1 fi - - LOGI "Certificate files installed successfully" - - # enable auto-renew + LOGI "Certificate files installed and verified successfully" ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1 - chmod 600 $certPath/privkey.pem 2> /dev/null - chmod 644 $certPath/fullchain.pem 2> /dev/null # Prompt user to set panel paths after successful certificate installation local webCertFile="${certPath}/fullchain.pem" @@ -1743,6 +1982,9 @@ ssl_cert_issue_for_ip() { LOGI " - Private Key File: $webKeyFile" LOGI " - Validity: ~6 days (auto-renews via acme.sh cron)" echo -e "${green}Access URL: https://${server_ip}:${existing_port}${existing_webBasePath}${plain}" + if [[ -n "$ipv6_addr" ]]; then + echo -e "${green}IPv6 access URL: https://[${ipv6_addr}]:${existing_port}${existing_webBasePath}${plain}" + fi LOGI "Panel will restart to apply SSL certificate..." restart else From 51997927f2642f5198ae820462ec9de8e6cfe016 Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Tue, 27 Oct 2026 10:32:47 +0330 Subject: [PATCH 2/9] fix(ci): support runner ShellCheck diagnostics for indirect calls Ubuntu 24.04 ships ShellCheck 0.9.0, which reports SC2317 for the EXIT cleanup and dynamically loaded installer test stubs. Scope both old and new diagnostic annotations to those indirect functions and regenerate both standalone scripts. Verified all shell checks and rootless regressions on the runner version as well as ShellCheck 0.11.0. --- install.sh | 3 ++- scripts/lib/ip-ssl.sh | 3 ++- scripts/test/ip-ssl-entrypoint-test.sh | 4 ++-- x-ui.sh | 3 ++- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/install.sh b/install.sh index 243fdcedf..386283f09 100644 --- a/install.sh +++ b/install.sh @@ -301,7 +301,8 @@ ip_ssl_issue_and_install() ( umask 077 mkdir -p "$cert_dir" || return 1 stage=$(mktemp -d "$cert_dir/.xui-install.XXXXXX") || return 1 - # shellcheck disable=SC2329 + # Invoked indirectly by the EXIT trap; older ShellCheck reports SC2317. + # shellcheck disable=SC2317,SC2329 ip_ssl_install_cleanup() { restored=1 if ((attempted && !installed)); then diff --git a/scripts/lib/ip-ssl.sh b/scripts/lib/ip-ssl.sh index 1946639a7..5d3635036 100644 --- a/scripts/lib/ip-ssl.sh +++ b/scripts/lib/ip-ssl.sh @@ -244,7 +244,8 @@ ip_ssl_issue_and_install() ( umask 077 mkdir -p "$cert_dir" || return 1 stage=$(mktemp -d "$cert_dir/.xui-install.XXXXXX") || return 1 - # shellcheck disable=SC2329 + # Invoked indirectly by the EXIT trap; older ShellCheck reports SC2317. + # shellcheck disable=SC2317,SC2329 ip_ssl_install_cleanup() { restored=1 if ((attempted && !installed)); then diff --git a/scripts/test/ip-ssl-entrypoint-test.sh b/scripts/test/ip-ssl-entrypoint-test.sh index f28a528fc..895c0409e 100644 --- a/scripts/test/ip-ssl-entrypoint-test.sh +++ b/scripts/test/ip-ssl-entrypoint-test.sh @@ -12,9 +12,9 @@ source /dev/stdin < <(awk '/^# BEGIN GENERATED IP SSL HELPERS/ {block=1;next} /^ source_function "$ROOT/install.sh" prompt_or_default source_function "$ROOT/install.sh" prompt_and_setup_ssl # Invoked by the real installer function loaded above, before the failure stubs. -# shellcheck disable=SC2329 +# shellcheck disable=SC2317,SC2329 setup_ip_certificate() { captured="${2:-}"; called=1; } -# shellcheck disable=SC2329 +# shellcheck disable=SC2317,SC2329 systemctl() { stopped=1; } export NONINTERACTIVE=1 XUI_SSL_MODE=ip XUI_SSL_IPV6='not:ipv6' called=0; stopped=0 diff --git a/x-ui.sh b/x-ui.sh index 5ec286f47..c9d084f79 100644 --- a/x-ui.sh +++ b/x-ui.sh @@ -287,7 +287,8 @@ ip_ssl_issue_and_install() ( umask 077 mkdir -p "$cert_dir" || return 1 stage=$(mktemp -d "$cert_dir/.xui-install.XXXXXX") || return 1 - # shellcheck disable=SC2329 + # Invoked indirectly by the EXIT trap; older ShellCheck reports SC2317. + # shellcheck disable=SC2317,SC2329 ip_ssl_install_cleanup() { restored=1 if ((attempted && !installed)); then From 95f09d6f1e28d92635bb8489a4b72ea0c47ebb65 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 17:29:16 +0330 Subject: [PATCH 3/9] fix(ssl): keep installing when the IP certificate fails, and keep its renewal entry A failed IP certificate made the installer return early. A fresh install was left with no service, no result file and its generated login never shown; an upgrade was left with the panel stopped. Failing issuance is ordinary: IP mode is the interactive default and it fails whenever port 80 is closed. Report the failure and carry on over HTTP, as the installer did before. An invalid XUI_SSL_IPV6 is treated the same way: the certificate is skipped, not issued for fewer names than were asked for. A failed account registration is a warning again. acme.sh records the requested names before it places the order, so a failed attempt to add IPv6 rewrote the renewal entry of the working IPv4 certificate and cron then kept renewing it with the names that had just failed. Restore the entry after a failed order, and remove the one a failed first order leaves behind. --- scripts/lib/ip-ssl.sh | 16 ++++++++++++++ scripts/test/ip-ssl-certificate-test.sh | 19 +++++++++++++++- scripts/test/ip-ssl-entrypoint-test.sh | 29 +++++++++---------------- x-ui.sh | 16 ++++++++++++++ 4 files changed, 60 insertions(+), 20 deletions(-) diff --git a/scripts/lib/ip-ssl.sh b/scripts/lib/ip-ssl.sh index 5d3635036..d536a74fe 100644 --- a/scripts/lib/ip-ssl.sh +++ b/scripts/lib/ip-ssl.sh @@ -226,6 +226,7 @@ ip_ssl_shell_quote() { ip_ssl_issue_and_install() ( local acme="$1" ipv4="$2" ipv6="$3" port="$4" cert_dir="$5" reload="$6" local stage='' attempted=0 installed=0 code=0 file restored + local acme_home="${acme%/*}" renewal_backup entry local quoted_cert quoted_key validation check_key reload_guard local -a domain_args=(-d "$ipv4") if ! ip_ssl_ipv4 "$ipv4" || { [[ -n "$ipv6" ]] && ! ip_ssl_public_ipv6 "$ipv6"; }; then @@ -235,11 +236,26 @@ ip_ssl_issue_and_install() ( [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 [[ -z "$ipv6" ]] || domain_args+=(-d "$ipv6") ip_ssl_prepare_listener "$acme" "$port" "$ipv6" || return 1 + renewal_backup=$(mktemp -d "$acme_home/.xui-acme.XXXXXX") || return 1 + for entry in "$ipv4" "${ipv4}_ecc"; do + [[ ! -d "$acme_home/$entry" ]] || cp -a -- "$acme_home/$entry" "$renewal_backup/$entry" || { + rm -rf -- "$renewal_backup" + return 1 + } + done if ! "$acme" --issue "${domain_args[@]}" --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then + # acme.sh saves the requested names before it places the order, so a failed one would + # make cron renew the working certificate with the names that just failed. + for entry in "$ipv4" "${ipv4}_ecc"; do + rm -rf -- "${acme_home:?}/$entry" + [[ ! -d "$renewal_backup/$entry" ]] || mv -- "$renewal_backup/$entry" "$acme_home/$entry" + done + rm -rf -- "$renewal_backup" printf 'IP certificate issuance failed. Existing certificates and ACME data were preserved. Check external port 80 on every selected address.\n' >&2 return 1 fi + rm -rf -- "$renewal_backup" umask 077 mkdir -p "$cert_dir" || return 1 diff --git a/scripts/test/ip-ssl-certificate-test.sh b/scripts/test/ip-ssl-certificate-test.sh index 85630d7a3..d6eb13a02 100644 --- a/scripts/test/ip-ssl-certificate-test.sh +++ b/scripts/test/ip-ssl-certificate-test.sh @@ -26,7 +26,12 @@ printf 'CALL\n' >> "$ACME_LOG" printf 'arg=%s\n' "$@" >> "$ACME_LOG" case "$1" in --version) printf 'v3.1.5\n' ;; - --issue) [[ "$ACME_ISSUE_FAIL" != 1 ]] ;; + --issue) + # Like acme.sh, record the requested SAN set before the order can fail. + mkdir -p "$ACME_HOME/198.51.100.8_ecc" + printf "Le_Alt='%s'\n" "$*" > "$ACME_HOME/198.51.100.8_ecc/198.51.100.8.conf" + [[ "$ACME_ISSUE_FAIL" != 1 ]] + ;; --upgrade|--register-account) : ;; --installcert) key=''; cert=''; reload='' @@ -45,6 +50,7 @@ esac MOCK chmod +x "$TEMP/mock acme" acme="$TEMP/mock acme" +export ACME_HOME="$TEMP" reload="printf 'reloaded\\n' >> '$RELOAD_LOG'" port=$((20000+RANDOM)) @@ -53,7 +59,18 @@ if ip_ssl_issue_and_install "$acme" 198.51.100.8 '' "$port" "$cert_dir" "$reload cmp "$TEMP/old.pem" "$cert_dir/fullchain.pem" || fail 'issuance failure removed existing certificate' cmp "$TEMP/old.key" "$cert_dir/privkey.pem" || fail 'issuance failure removed existing key' [[ ! -f "$RELOAD_LOG" ]] || fail 'issuance failure reloaded panel' +[[ ! -e "$ACME_HOME/198.51.100.8_ecc" ]] || fail 'a failed first order left a renewal entry that cron would retry every day' printf 'PASS: ACME failure preserves existing certificate and key\n' + +mkdir -p "$ACME_HOME/198.51.100.8_ecc" +printf "Le_Alt='no'\nLe_NextRenewTime='1'\n" > "$ACME_HOME/198.51.100.8_ecc/198.51.100.8.conf" +cp "$ACME_HOME/198.51.100.8_ecc/198.51.100.8.conf" "$TEMP/working.conf" +if ip_ssl_issue_and_install "$acme" 198.51.100.8 '2001:4860::1' "$port" "$cert_dir" "$reload"; then fail 'ACME failure reported success'; fi +cmp "$TEMP/working.conf" "$ACME_HOME/198.51.100.8_ecc/198.51.100.8.conf" || fail 'a failed IPv6 attempt rewrote the working certificate renewal entry' +[[ -z "$(find "$ACME_HOME" -maxdepth 1 -name '.xui-acme.*')" ]] || fail 'the renewal entry backup was left behind' +printf 'PASS: a failed order restores the renewal entry of the working certificate\n' +rm -rf "$ACME_HOME/198.51.100.8_ecc" +: > "$ACME_LOG" ACME_ISSUE_FAIL=0 ip_ssl_issue_and_install "$acme" 198.51.100.8 '2001:4860::1' "$port" "$cert_dir" "$reload" diff --git a/scripts/test/ip-ssl-entrypoint-test.sh b/scripts/test/ip-ssl-entrypoint-test.sh index 895c0409e..259529f51 100644 --- a/scripts/test/ip-ssl-entrypoint-test.sh +++ b/scripts/test/ip-ssl-entrypoint-test.sh @@ -18,9 +18,11 @@ setup_ip_certificate() { captured="${2:-}"; called=1; } systemctl() { stopped=1; } export NONINTERACTIVE=1 XUI_SSL_MODE=ip XUI_SSL_IPV6='not:ipv6' called=0; stopped=0 -if prompt_and_setup_ssl 2053 / 198.51.100.8 > "$TEMP/invalid" 2>&1; then fail 'invalid environment IPv6 accepted by installer'; fi +SSL_HOST='' +prompt_and_setup_ssl 2053 / 198.51.100.8 > "$TEMP/invalid" 2>&1 || fail 'an invalid XUI_SSL_IPV6 aborted the installer instead of skipping the certificate' [[ "$called" == 0 && "$stopped" == 0 ]] || fail 'invalid IPv6 stopped panel or reached issuance' grep -q 'Invalid public IPv6' "$TEMP/invalid" || fail 'invalid environment value has no clear diagnostic' +[[ "$SSL_HOST" == 198.51.100.8 ]] || fail 'the installer lost its access host after skipping the certificate' unset XUI_SSL_IPV6 called=0 prompt_and_setup_ssl 2053 / 198.51.100.8 "$TEMP/unattended" 2>&1 @@ -42,25 +44,14 @@ prompt_and_setup_ssl 2053 / 198.51.100.8 <<< $'\ny\nn\n' > "$TEMP/rejected" 2>&1 printf 'PASS: installer consent, explicit configuration, no unattended prompts, and validation before service stop\n' setup_ip_certificate() { return 1; } -systemctl() { - printf '%s\n' "$*" >> "$TEMP/service-calls" - [[ "$1" != is-active ]] || [[ "$was_running" == 1 ]] -} -rc-service() { - printf '%s\n' "$*" >> "$TEMP/service-calls" - [[ "$2" != status ]] || [[ "$was_running" == 1 ]] -} +systemctl() { :; } +rc-service() { :; } NONINTERACTIVE=1 export XUI_SSL_IPV6='2001:4860::1' for release in ubuntu alpine; do - for was_running in 0 1; do - : > "$TEMP/service-calls" - if prompt_and_setup_ssl 2053 / 198.51.100.8 > /dev/null 2>&1; then fail 'failed IP setup reported success'; fi - if [[ "$was_running" == 1 ]]; then - grep -Eq '^(start x-ui|x-ui start)$' "$TEMP/service-calls" || fail "failed IP setup left the previous $release panel stopped" - elif grep -Eq '^(start x-ui|x-ui start)$' "$TEMP/service-calls"; then - fail "failed IP setup started an inactive $release panel" - fi - done + SSL_HOST='' + prompt_and_setup_ssl 2053 / 198.51.100.8 > "$TEMP/failed" 2>&1 || fail "a failed IP certificate aborted the $release installer: the panel must still be installed over HTTP" + grep -q 'IP certificate setup failed' "$TEMP/failed" || fail 'failed issuance was not reported' + [[ "$SSL_HOST" == 198.51.100.8 ]] || fail 'the installer lost its access host after a failed certificate' done -printf 'PASS: failed issuance restores only a previously running panel on systemd/OpenRC\n' +printf 'PASS: a failed IP certificate is reported and the installer carries on on systemd/OpenRC\n' diff --git a/x-ui.sh b/x-ui.sh index 5d6af4202..b9d5d70a4 100644 --- a/x-ui.sh +++ b/x-ui.sh @@ -269,6 +269,7 @@ ip_ssl_shell_quote() { ip_ssl_issue_and_install() ( local acme="$1" ipv4="$2" ipv6="$3" port="$4" cert_dir="$5" reload="$6" local stage='' attempted=0 installed=0 code=0 file restored + local acme_home="${acme%/*}" renewal_backup entry local quoted_cert quoted_key validation check_key reload_guard local -a domain_args=(-d "$ipv4") if ! ip_ssl_ipv4 "$ipv4" || { [[ -n "$ipv6" ]] && ! ip_ssl_public_ipv6 "$ipv6"; }; then @@ -278,11 +279,26 @@ ip_ssl_issue_and_install() ( [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 [[ -z "$ipv6" ]] || domain_args+=(-d "$ipv6") ip_ssl_prepare_listener "$acme" "$port" "$ipv6" || return 1 + renewal_backup=$(mktemp -d "$acme_home/.xui-acme.XXXXXX") || return 1 + for entry in "$ipv4" "${ipv4}_ecc"; do + [[ ! -d "$acme_home/$entry" ]] || cp -a -- "$acme_home/$entry" "$renewal_backup/$entry" || { + rm -rf -- "$renewal_backup" + return 1 + } + done if ! "$acme" --issue "${domain_args[@]}" --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then + # acme.sh saves the requested names before it places the order, so a failed one would + # make cron renew the working certificate with the names that just failed. + for entry in "$ipv4" "${ipv4}_ecc"; do + rm -rf -- "${acme_home:?}/$entry" + [[ ! -d "$renewal_backup/$entry" ]] || mv -- "$renewal_backup/$entry" "$acme_home/$entry" + done + rm -rf -- "$renewal_backup" printf 'IP certificate issuance failed. Existing certificates and ACME data were preserved. Check external port 80 on every selected address.\n' >&2 return 1 fi + rm -rf -- "$renewal_backup" umask 077 mkdir -p "$cert_dir" || return 1 From 83199a770f74b43a156c3db8b8639393a50bdce2 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 17:29:35 +0330 Subject: [PATCH 4/9] docs(ssl): describe what a failed IP certificate leaves behind The page still said the installer restarts a previously running panel and stops; it now carries on over HTTP and a failed order restores the renewal entry of the certificate already in place. --- deploy/README.md | 2 +- docs/content/docs/en/config/ssl-certificates.mdx | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/deploy/README.md b/deploy/README.md index e86235a76..15be5b873 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -36,7 +36,7 @@ Unattended installation never discovers or includes IPv6 unless you explicitly set `XUI_SSL_IPV6` to one public IPv6 address. Unset or empty means IPv4 only; `auto`, a subnet (`/64`), a zone ID (`%eth0`), and malformed or nonpublic addresses are rejected. An invalid explicit value fails the SSL setup before stopping the -panel or requesting a certificate. +panel or requesting a certificate; the install itself continues over plain HTTP. Interactive installation discovers locally assigned global IPv6 addresses and offers confirmation, numbered selection, manual entry, or skipping. Stable diff --git a/docs/content/docs/en/config/ssl-certificates.mdx b/docs/content/docs/en/config/ssl-certificates.mdx index 4f125e9b1..5dc05db36 100644 --- a/docs/content/docs/en/config/ssl-certificates.mdx +++ b/docs/content/docs/en/config/ssl-certificates.mdx @@ -116,8 +116,11 @@ up during installation and restored after a failed or invalid copy; failed issuance does not remove certificates or ACME account data. Renewal still copies to the usual `/root/cert/ip/` paths, with a persisted SAN/key check before the panel reload command. The private key remains mode `600` and the chain `644`. -If IP setup fails in the installer, a previously running panel is started again; -an inactive panel is not started on failure. +A failed order also restores the acme.sh renewal entry of the certificate that +was already in place, so cron keeps renewing it for its original addresses. +If IP setup fails in the installer, the failure is reported and the installation +continues: the panel is installed and reachable over plain HTTP, and the +certificate can be issued later from the `x-ui` menu. Inspect both IP SAN entries after issuance: From 26e1cd0f3ed397f2b58059a808401bb1d23f2337 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 17:55:28 +0330 Subject: [PATCH 5/9] test(install): expect the installer to finish after a failed certificate The Go regression still asserted that a failed SSL setup stops the install before the service is set up, the behaviour this branch no longer has. --- scripts_base_path_test.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/scripts_base_path_test.go b/scripts_base_path_test.go index 516971147..13910021b 100644 --- a/scripts_base_path_test.go +++ b/scripts_base_path_test.go @@ -299,17 +299,19 @@ func TestScriptConfigReadFailureKeepsServiceSetup(t *testing.T) { } } -func TestInstallerSSLFailureStopsServiceSetup(t *testing.T) { +func TestInstallerSSLFailureKeepsServiceSetup(t *testing.T) { dir, out, err := runScriptConfig(t, "install.sh", "/a/", true, "ssl_failure", 1, true) - if err == nil { - t.Fatalf("SSL failure should abort installation before service setup:\n%s", out) + if err != nil { + t.Fatalf("a failed certificate must not abort the install: %v\n%s", err, out) } if _, err := os.Stat(filepath.Join(dir, "ssl")); err != nil { t.Fatalf("SSL setup was not attempted: %v\n%s", err, out) } - for _, name := range []string{"lifecycle", "restarts"} { - if actual := readScriptState(t, dir, name); actual != "" { - t.Errorf("failed SSL setup continued %s: %q", name, actual) + for name, want := range map[string]string{ + "lifecycle": "fail2ban\nunit\n", "restarts": "daemon-reload\nenable x-ui\nrestart x-ui\n", + } { + if actual := readScriptState(t, dir, name); actual != want { + t.Errorf("%s after a failed certificate = %q, want %q: the panel must still be installed and started", name, actual, want) } } } From 85a8dd672544b1f4a2215de7f9e1976aaa5d0113 Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Wed, 2 Dec 2026 21:17:30 +0330 Subject: [PATCH 6/9] fix(ssl): preserve live certificates and renewal state across failed deployments --- .github/workflows/ci.yml | 5 + .../docs/en/config/ssl-certificates.mdx | 43 +- install.sh | 478 ++++++++++++++--- scripts/lib/ip-ssl.sh | 463 ++++++++++++++--- scripts/test/README.md | 20 +- scripts/test/ip-ssl-acme-lifecycle-test.sh | 132 +++++ scripts/test/ip-ssl-certificate-test.sh | 428 +++++++++++---- scripts/test/ip-ssl-entrypoint-test.sh | 3 + x-ui.sh | 491 +++++++++++++++--- 9 files changed, 1709 insertions(+), 354 deletions(-) create mode 100644 scripts/test/ip-ssl-acme-lifecycle-test.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc3c73742..5b659a53b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -509,6 +509,11 @@ jobs: bash scripts/test/ip-ssl-entrypoint-test.sh IP_SSL_LINUX_TEST=1 bash scripts/test/ip-ssl-listener-test.sh bash scripts/test/ip-ssl-certificate-test.sh + - name: IP certificate lifecycle with upstream acme.sh (offline orders) + run: | + curl -fsSLo "$RUNNER_TEMP/acme-3.1.5.sh" https://raw.githubusercontent.com/acmesh-official/acme.sh/d5fc938d80e266dba3239f54cf4665432f17c00b/acme.sh + curl -fsSLo "$RUNNER_TEMP/acme-3.1.6.sh" https://raw.githubusercontent.com/acmesh-official/acme.sh/807da6498377ee5e0cf43a78091f46f12dc59a89/acme.sh + bash scripts/test/ip-ssl-acme-lifecycle-test.sh "$RUNNER_TEMP/acme-3.1.5.sh" "$RUNNER_TEMP/acme-3.1.6.sh" - name: Installer panel port regression tests run: bash deploy/test/installer-panel-port.sh diff --git a/docs/content/docs/en/config/ssl-certificates.mdx b/docs/content/docs/en/config/ssl-certificates.mdx index 5dc05db36..dd8027656 100644 --- a/docs/content/docs/en/config/ssl-certificates.mdx +++ b/docs/content/docs/en/config/ssl-certificates.mdx @@ -110,17 +110,38 @@ when using a custom port. In containers, enable IPv6 networking and publish the validation port for both families. Local listener success cannot verify an external firewall, NAT, or the provider's routing. -The resulting certificate's IP SANs, validity, and matching private key are -checked before configuring the panel. Existing live certificate files are backed -up during installation and restored after a failed or invalid copy; failed -issuance does not remove certificates or ACME account data. Renewal still copies -to the usual `/root/cert/ip/` paths, with a persisted SAN/key check before the -panel reload command. The private key remains mode `600` and the chain `644`. -A failed order also restores the acme.sh renewal entry of the certificate that -was already in place, so cron keeps renewing it for its original addresses. -If IP setup fails in the installer, the failure is reported and the installation -continues: the panel is installed and reachable over plain HTTP, and the -certificate can be issued later from the `x-ui` menu. +Issuance and renewal work in a private directory under `/root/cert/ip/.xui-ip-ssl/`. +The helper checks the chain, validity dates, every requested IP SAN, and the +matching key before activating a new generation. One symlink switch activates +the certificate, key, and their ACME renewal state together. The panel still +uses `/root/cert/ip/fullchain.pem` (mode `644`) and `/root/cert/ip/privkey.pem` +(mode `600`). A failed order, copy, validation, or promotion preserves the +previous generation and its renewal schedule. If reloading the panel fails +after activation, the valid certificate stays installed and reload is retried. + +The root crontab checks the versioned local renewal helper hourly. Manual setup +and cron share a file lock for the same panel paths, even when the primary IP +changes. The first successful setup retires legacy acme.sh renewal entries for +those paths. Existing domain certificates and the ACME account are retained. +Renew managed IP certificates from the `x-ui` menu. Standard acme.sh cron +continues to handle its other certificates. + +After an interrupted attempt, the next run recovers the pending transaction +before making another ACME request. If recovery reports an error, keep the +reported journal and any listed `.xui-retired-*` directories. Fix the reported +filesystem problem and rerun IP certificate setup from `x-ui` to retry recovery. +The installer reports certificate setup failures and continues, so you can issue +the certificate from the `x-ui` menu later. + +In acme.sh 3.1.5 and 3.1.6, an explicit issue uses the destinations and hooks +passed on its command line. Renewing can replay saved destinations and hooks. +The client records the next renewal time before copying files and runs the +reload command after the copy. x-ui supplies private staging paths and commits +the modified renewal state once the candidate passes validation. The test suite +exercises the upstream copy and install-retry behavior with local certificates. +Public issuance and renewal require a separate test with port 80 reachable over +both address families. [acme.sh issuance and renewal](https://github.com/acmesh-official/acme.sh/blob/3.1.5/acme.sh#L5289-L6742) +· [acme.sh install and retry](https://github.com/acmesh-official/acme.sh/blob/3.1.6/acme.sh#L7205-L7380) Inspect both IP SAN entries after issuance: diff --git a/install.sh b/install.sh index 9d11a4b8e..59edfc4bb 100644 --- a/install.sh +++ b/install.sh @@ -280,91 +280,396 @@ ip_ssl_shell_quote() { printf "'%s'" "$value" } +# The public paths always resolve through one generation pointer after migration. +ip_ssl_link() { + local state="$1" target="$2" link="$3" + rm -f -- "$state/pending/link" && + ln -s -- "$target" "$state/pending/link" && + mv -Tf -- "$state/pending/link" "$link" +} + +ip_ssl_lock() { + local dir="$1" state="$1/.xui-ip-ssl" + command -v flock >/dev/null || { printf 'IP certificates require flock. Install it and retry.\n' >&2; return 1; } + umask 077 + mkdir -p -- "$dir" || return 1 + [[ -d "$dir" && ! -L "$dir" && -O "$dir" ]] || return 1 + chmod go-w -- "$dir" || return 1 + [[ ! -L "$state" ]] && mkdir -p -- "$state" && [[ -O "$state" ]] && chmod 700 -- "$state" || return 1 + exec 9>>"$state/lock" || return 1 + flock -x 9 +} + +# An old cron can have sourced a legacy config already. Check on both sides +# of retiring its entries. Managed renewals always take the destination lock. +ip_ssl_legacy_busy() { + local acme="$1" cmdline arg found action + for cmdline in /proc/[0-9]*/cmdline; do + [[ -r "$cmdline" ]] || continue + found=0 action=0 + { + while IFS= read -r -d '' arg; do + if [[ "$arg" == "$acme" ]]; then + found=1 + elif ((found)); then + case "$arg" in + --cron|--renew|--renew-all|--renewAll|--renewall|--issue|--install-cert|--installcert|--deploy) action=1 ;; + esac + fi + done + } < "$cmdline" 2>/dev/null || continue + if ((found && action)); then return 0; fi + done + return 1 +} + +ip_ssl_retire_legacy() { + local state="$1" acme="$2" ipv4="$3" dir="$4" gen="$5" home="$6" + local entry name conf value destination destinations + local -a retire=() + for entry in "$home"/*; do + [[ -d "$entry" && ! -L "$entry" ]] || continue + name="${entry##*/}" + ip_ssl_ipv4 "${name%_ecc}" || continue + conf="$entry/${name%_ecc}.conf" + [[ -f "$conf" ]] || continue + # Retire every legacy IP entry sharing this destination, including an older primary IP. + destinations=$(sed -n "s/^Le_Real\(FullChain\|Cert\|Key\|CACert\)Path='\(.*\)'$/\2/p" "$conf") || return 1 + while IFS= read -r value; do + case "${value##*/}" in fullchain.pem|privkey.pem) ;; *) continue ;; esac + destination=$(cd -P -- "${value%/*}" 2>/dev/null && pwd -P) || continue + if [[ "$destination" == "$dir" ]]; then + retire+=("$name") + break + fi + done <<< "$destinations" + done + # The requested entries can also be unfinished orders with no destinations. + for name in "$ipv4" "${ipv4}_ecc"; do + entry="$home/$name" + conf="$entry/$ipv4.conf" + [[ -d "$entry" && ! -L "$entry" ]] || continue + if [[ ! -f "$conf" ]] || ! grep -Eq "^Le_(Real(Cert|Key|CACert|FullChain)Path|ReloadCmd|DeployHook)='[^']+" "$conf"; then + retire+=("$name") + fi + done + ((${#retire[@]})) || return 0 + if ip_ssl_legacy_busy "$acme"; then + printf 'Wait for the existing acme.sh command to finish, then retry IP certificate setup.\n' >&2 + return 1 + fi + for name in "${retire[@]}"; do + [[ -d "$home/$name" ]] || continue + # Journal before the same-directory rename so a crash can restore it. + printf '%s\n' "$name" >> "$state/pending/legacy" && + mv -T -- "$home/$name" "$home/.xui-retired-$gen-$name" || return 1 + done + if ip_ssl_legacy_busy "$acme"; then + printf 'An existing acme.sh command started during migration. Retry IP certificate setup after it exits.\n' >&2 + return 1 + fi +} + +ip_ssl_recover() { + local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending" + local gen='' home='' current='' entry held file name failed=0 previous='' + [[ -d "$pending" ]] || return 0 + if [[ -f "$pending/generation" ]]; then + if ! IFS= read -r gen < "$pending/generation" || [[ ! "$gen" =~ ^gen\.[a-zA-Z0-9]+$ ]]; then + printf 'Invalid IP certificate generation journal. Keep recovery files at %s.\n' "$pending" >&2 + return 1 + fi + fi + current=$(readlink -- "$state/current") || current='' + if [[ -f "$pending/home" ]] && ! IFS= read -r home < "$pending/home"; then + printf 'Invalid ACME home in the IP certificate journal. Keep recovery files at %s.\n' "$pending" >&2 + return 1 + fi + + if [[ -n "$gen" && "$current" == "$gen" ]]; then + # Commit is the pointer swap. Never roll back a committed generation. + if [[ -f "$pending/legacy" ]]; then + while IFS= read -r entry; do + ip_ssl_ipv4 "${entry%_ecc}" && [[ -n "$home" ]] && + rm -rf -- "$home/.xui-retired-$gen-$entry" || failed=1 + done < "$pending/legacy" + fi + if [[ -f "$state/$gen/previous" ]]; then IFS= read -r previous < "$state/$gen/previous" || failed=1; fi + for entry in "$state"/gen.*; do + name="${entry##*/}" + [[ "$name" != "$gen" && "$name" != "$previous" ]] || continue + rm -rf -- "$entry" || failed=1 + done + else + if [[ -f "$pending/live-changing" ]]; then + for file in fullchain.pem privkey.pem; do + if [[ -e "$pending/live/$file" || -L "$pending/live/$file" ]]; then + rm -f -- "$pending/restore" && + cp -a -- "$pending/live/$file" "$pending/restore" && + mv -Tf -- "$pending/restore" "$dir/$file" || failed=1 + else + rm -f -- "$dir/$file" || failed=1 + fi + done + fi + # Keep stock cron away from the public paths until the original file + # types are restored. A failed restore may still leave a live alias. + if ((!failed)) && [[ -f "$pending/legacy" ]]; then + while IFS= read -r entry; do + if ! ip_ssl_ipv4 "${entry%_ecc}" || [[ -z "$home" || -z "$gen" ]]; then failed=1; continue; fi + held="$home/.xui-retired-$gen-$entry" + if [[ -e "$held" ]]; then + if [[ -e "$home/$entry" || -L "$home/$entry" ]] || + ! mv -T -- "$held" "$home/$entry"; then + printf 'ACME recovery copy remains at %s\n' "$held" >&2 + failed=1 + fi + elif [[ ! -d "$home/$entry" ]]; then + failed=1 + fi + done < "$pending/legacy" + fi + if ((!failed)) && [[ -n "$gen" ]]; then rm -rf -- "${state:?}/${gen:?}" || failed=1; fi + fi + if ((failed)); then + printf 'IP certificate recovery could not complete. Keep recovery files at %s and retry after resolving the error.\n' "$pending" >&2 + return 1 + fi + if ! rm -f -- "$state/staging/fullchain.pem" "$state/staging/privkey.pem" || ! rm -rf -- "$pending"; then + printf 'Could not remove the IP certificate journal at %s\n' "$pending" >&2 + return 1 + fi +} + +ip_ssl_aliases() { + local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending" + local file seed + if [[ -f "$state/current/config" ]]; then + for file in fullchain.pem privkey.pem; do + [[ "$(readlink -- "$dir/$file")" == ".xui-ip-ssl/current/$file" ]] || return 1 + done + return 0 + fi + # The seed contains the original bytes, so converting either alias first + # still exposes the same pair. The journal keeps the original file types. + seed=$(mktemp -d "$state/gen.XXXXXX") || return 1 + for file in fullchain.pem privkey.pem; do + if [[ -e "$pending/live/$file" || -L "$pending/live/$file" ]]; then + # Follow the original live symlink relative to its own directory. + cp -pL -- "$dir/$file" "$seed/$file" || return 1 + fi + done + ip_ssl_link "$state" "${seed##*/}" "$state/current" && + touch "$pending/live-changing" || return 1 + for file in fullchain.pem privkey.pem; do + ip_ssl_link "$state" ".xui-ip-ssl/current/$file" "$dir/$file" || return 1 + done +} + +ip_ssl_validate_pair() { + local chain="$1" key="$2" ipv4="$3" ipv6="$4" cert_pub key_pub + [[ -s "$chain" && -s "$key" ]] && + openssl crl2pkcs7 -nocrl -certfile "$chain" -out /dev/null && + openssl verify -purpose sslserver -untrusted "$chain" -verify_ip "$ipv4" "$chain" >/dev/null || return 1 + [[ -z "$ipv6" ]] || openssl verify -purpose sslserver -untrusted "$chain" -verify_ip "$ipv6" "$chain" >/dev/null || return 1 + cert_pub=$(openssl x509 -in "$chain" -pubkey -noout) && + key_pub=$(openssl pkey -in "$key" -passin pass: -pubout) && + [[ -n "$cert_pub" && "$cert_pub" == "$key_pub" ]] +} + +ip_ssl_reload() { + local gen="$1" reload="$2" + if sh -c "$reload" 9>&-; then + rm -f -- "$gen/reload-pending" || + printf 'Could not clear the IP certificate reload marker.\n' >&2 + else + printf 'A valid certificate is installed. Panel reload failed and will be retried by the IP certificate job.\n' >&2 + fi +} + +ip_ssl_schedule() ( + local state="$1" home="$2" command line existing + [[ "$state" != *[$'\n\r%']* ]] || return 1 + # Different destinations share the user's crontab, but can order and stage in parallel. + exec 8>>"$home/.xui-ip-crontab.lock" && flock -x 8 || return 1 + command=$(ip_ssl_shell_quote "$state/renew-v1") + line="19 * * * * $command # x-ui managed IP certificate" + if ! existing=$(LC_ALL=C crontab -l 2>&1); then + case "$existing" in + *"no crontab for "*|*"No such file or directory"*) existing='' ;; + *) printf 'Could not read crontab: %s\n' "$existing" >&2; return 1 ;; + esac + fi + if grep -Fxq -- "$line" <<< "$existing"; then return 0; fi + { printf '%s\n' "$existing"; printf '%s\n' "$line"; } | crontab - +) + +ip_ssl_account_config() ( + local home="$1" cert_home="$2" ACCOUNT_CONF_PATH='' + # acme.sh sources account.conf after parsing --cert-home, so a saved + # CERT_HOME overrides the command line. Keep this override private. + if [[ -f "$home/account.conf" ]]; then + # shellcheck disable=SC1091 + source "$home/account.conf" || return 1 + fi + local original="${ACCOUNT_CONF_PATH:-$home/account.conf}" + if [[ -f "$original" ]]; then cat -- "$original" || return 1; fi + printf '\nCERT_HOME=%s\n' "$(ip_ssl_shell_quote "$cert_home")" +) + +ip_ssl_legacy_home() ( + local home="$1" ACCOUNT_CONF_PATH='' CERT_HOME='' + if [[ -f "$home/account.conf" ]]; then + # shellcheck disable=SC1091 + source "$home/account.conf" || return 1 + fi + if [[ -n "$ACCOUNT_CONF_PATH" && -f "$ACCOUNT_CONF_PATH" ]]; then + # shellcheck disable=SC1090 + source "$ACCOUNT_CONF_PATH" || return 1 + fi + printf '%s\n' "${CERT_HOME:-$home}" +) + +ip_ssl_transaction() ( + local action="$1" acme="$2" ipv4="$3" ipv6="$4" port="$5" dir="$6" reload="$7" + local state="$dir/.xui-ip-ssl" pending="$dir/.xui-ip-ssl/pending" home="${acme%/*}" + local work gen file previous rc legacy_home stage="$dir/.xui-ip-ssl/staging" + local -a scope domains=(-d "$ipv4") + mkdir -- "$pending" || return 1 + # Recovery runs under the caller's flock, including on normal exit. + trap 'rc=$?; ip_ssl_recover "$dir" || rc=1; exit "$rc"' EXIT + trap 'exit 130' INT + trap 'exit 143' TERM + trap 'exit 129' HUP + + work=$(mktemp -d "$state/gen.XXXXXX") || return 1 + gen="${work##*/}" + printf '%s\n' "$gen" > "$pending/generation" && mkdir -- "$work/acme" "$pending/live" || return 1 + if [[ "$action" == issue ]]; then + legacy_home=$(ip_ssl_legacy_home "$home") || return 1 + [[ "$legacy_home" == /* && "$legacy_home" != *[$'\n\r']* ]] || return 1 + printf '%s\n' "$legacy_home" > "$pending/home" && + ip_ssl_retire_legacy "$state" "$acme" "$ipv4" "$dir" "$gen" "$legacy_home" || return 1 + fi + for file in fullchain.pem privkey.pem; do + [[ ! -e "$dir/$file" && ! -L "$dir/$file" ]] || + cp -a -- "$dir/$file" "$pending/live/$file" || return 1 + done + if [[ -f "$state/current/config" ]]; then + previous=$(readlink -- "$state/current") && + printf '%s\n' "$previous" > "$work/previous" || return 1 + fi + if [[ "$action" != issue ]]; then + cp -a -- "$state/current/acme/." "$work/acme/" || return 1 + fi + [[ ! -L "$stage" ]] && mkdir -p -- "$stage" && chmod 700 -- "$stage" && + rm -f -- "$stage/fullchain.pem" "$stage/privkey.pem" || return 1 + ip_ssl_account_config "$home" "$work/acme" > "$pending/account.conf" || return 1 + scope=(--home "$home" --cert-home "$work/acme" --accountconf "$pending/account.conf") + # acme.sh saves destinations in single quotes. A fixed private working + # directory makes relative install paths safe even with a quoted parent. + cd -- "$state" || return 1 + if [[ "$action" == issue ]]; then + [[ -z "$ipv6" ]] || domains+=(-d "$ipv6") + if ! "$acme" --issue "${scope[@]}" "${domains[@]}" --keylength ec-256 --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ + --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then + printf 'IP certificate issuance failed. Check external port 80 on each selected address.\n' >&2 + return 1 + fi + else + rc=0 + local -a force=() + [[ "$action" != renew-force ]] || force=(--force) + "$acme" --renew "${scope[@]}" -d "$ipv4" --ecc "${force[@]}" || rc=$? + # acme.sh uses 2 when a certificate is not due for renewal. + if ((rc == 2)); then return 0; fi + ((rc == 0)) || return "$rc" + fi + # A renewal may already have copied to staging. Require both outputs from + # this explicit install so an incomplete copy cannot reuse an older file. + rm -f -- "$stage/fullchain.pem" "$stage/privkey.pem" || return 1 + if ! "$acme" --installcert "${scope[@]}" --ecc -d "$ipv4" --key-file staging/privkey.pem \ + --fullchain-file staging/fullchain.pem --reloadcmd ""; then + printf 'Could not stage the IP certificate and key.\n' >&2 + return 1 + fi + if ! ip_ssl_validate_pair "$stage/fullchain.pem" "$stage/privkey.pem" "$ipv4" "$ipv6"; then + printf 'Staged IP certificate failed SAN, validity or private-key checks.\n' >&2 + return 1 + fi + cp -- "$stage/privkey.pem" "$work/privkey.pem" && + cp -- "$stage/fullchain.pem" "$work/fullchain.pem" && + chmod 600 -- "$work/privkey.pem" && chmod 644 -- "$work/fullchain.pem" && + printf 'managed_acme=%q\nmanaged_ipv4=%q\nmanaged_ipv6=%q\nmanaged_reload=%q\n' "$acme" "$ipv4" "$ipv6" "$reload" > "$work/config" && + touch "$work/reload-pending" || return 1 + if [[ "$action" == issue ]]; then ip_ssl_schedule "$state" "$home" || return 1; fi + ip_ssl_aliases "$dir" && + ip_ssl_link "$state" "$gen" "$state/current" || return 1 + ip_ssl_reload "$work" "$reload" +) + +ip_ssl_scheduled() ( + local dir="$1" state="$1/.xui-ip-ssl" action="${2:-renew}" + local managed_acme managed_ipv4 managed_ipv6 managed_reload + ip_ssl_lock "$dir" && ip_ssl_recover "$dir" || return 1 + [[ -f "$state/current/config" ]] || return 0 + # This file is generated with Bash quoting under the private state directory. + # shellcheck disable=SC1091 + source "$state/current/config" || return 1 + if [[ -f "$state/current/reload-pending" ]]; then ip_ssl_reload "$state/current" "$managed_reload"; fi + ip_ssl_transaction "$action" "$managed_acme" "$managed_ipv4" "$managed_ipv6" '' "$dir" "$managed_reload" +) + +ip_ssl_revoke_managed() ( + local dir="$1" state="$1/.xui-ip-ssl" managed_acme managed_ipv4 gen account + ip_ssl_lock "$dir" && ip_ssl_recover "$dir" || return 1 + [[ -f "$state/current/config" ]] || return 1 + # shellcheck disable=SC1091 + source "$state/current/config" || return 1 + account=$(mktemp "$state/.account.XXXXXX") || return 1 + trap 'rm -f -- "$account"' EXIT + ip_ssl_account_config "${managed_acme%/*}" "$state/current/acme" > "$account" || return 1 + "$managed_acme" --revoke --home "${managed_acme%/*}" --cert-home "$state/current/acme" --accountconf "$account" -d "$managed_ipv4" --ecc || + printf 'CA revocation failed. Removing local renewal state and files.\n' >&2 + # Keep the lock inode and inert scheduled runner for later issuance. + rm -f -- "$state/current" "$dir/fullchain.pem" "$dir/privkey.pem" || return 1 + for gen in "$state"/gen.*; do rm -rf -- "$gen" || return 1; done +) + +ip_ssl_write_runner() { + local state="$1" temp + temp=$(mktemp "$state/.runner.XXXXXX") || return 1 + if { + printf '#!/bin/bash\n# x-ui managed IP certificate deployment v1\n' + # The OpenRC service commands live in /sbin on Alpine. + # shellcheck disable=SC2016 + printf 'export PATH="${PATH:+$PATH:}/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"\n' + declare -f ip_ssl_ipv4 ip_ssl_shell_quote ip_ssl_link ip_ssl_lock ip_ssl_legacy_busy \ + ip_ssl_retire_legacy ip_ssl_recover ip_ssl_aliases ip_ssl_validate_pair ip_ssl_reload \ + ip_ssl_schedule ip_ssl_account_config ip_ssl_legacy_home ip_ssl_transaction ip_ssl_scheduled + # shellcheck disable=SC2016 + printf '\nip_ssl_scheduled "$(cd -- "$(dirname -- "$0")/.." && pwd -P)"\n' + } > "$temp" && chmod 700 -- "$temp" && mv -Tf -- "$temp" "$state/renew-v1"; then + return 0 + fi + rm -f -- "$temp" || printf 'Could not remove incomplete renewal helper %s\n' "$temp" >&2 + return 1 +} + ip_ssl_issue_and_install() ( - local acme="$1" ipv4="$2" ipv6="$3" port="$4" cert_dir="$5" reload="$6" - local stage='' attempted=0 installed=0 code=0 file restored - local acme_home="${acme%/*}" renewal_backup entry - local quoted_cert quoted_key validation check_key reload_guard - local -a domain_args=(-d "$ipv4") + local acme="$1" ipv4="$2" ipv6="$3" port="$4" dir="$5" reload="$6" if ! ip_ssl_ipv4 "$ipv4" || { [[ -n "$ipv6" ]] && ! ip_ssl_public_ipv6 "$ipv6"; }; then printf 'Invalid IP certificate identifier; no ACME request was sent.\n' >&2 return 1 fi [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 - [[ -z "$ipv6" ]] || domain_args+=(-d "$ipv6") - ip_ssl_prepare_listener "$acme" "$port" "$ipv6" || return 1 - renewal_backup=$(mktemp -d "$acme_home/.xui-acme.XXXXXX") || return 1 - for entry in "$ipv4" "${ipv4}_ecc"; do - [[ ! -d "$acme_home/$entry" ]] || cp -a -- "$acme_home/$entry" "$renewal_backup/$entry" || { - rm -rf -- "$renewal_backup" - return 1 - } - done - if ! "$acme" --issue "${domain_args[@]}" --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ - --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then - # acme.sh saves the requested names before it places the order, so a failed one would - # make cron renew the working certificate with the names that just failed. - for entry in "$ipv4" "${ipv4}_ecc"; do - rm -rf -- "${acme_home:?}/$entry" - [[ ! -d "$renewal_backup/$entry" ]] || mv -- "$renewal_backup/$entry" "$acme_home/$entry" - done - rm -rf -- "$renewal_backup" - printf 'IP certificate issuance failed. Existing certificates and ACME data were preserved. Check external port 80 on every selected address.\n' >&2 - return 1 - fi - rm -rf -- "$renewal_backup" - - umask 077 - mkdir -p "$cert_dir" || return 1 - stage=$(mktemp -d "$cert_dir/.xui-install.XXXXXX") || return 1 - # Invoked indirectly by the EXIT trap; older ShellCheck reports SC2317. - # shellcheck disable=SC2317,SC2329 - ip_ssl_install_cleanup() { - restored=1 - if ((attempted && !installed)); then - for file in fullchain.pem privkey.pem; do - if [[ -f "$stage/$file" ]]; then - cp -p -- "$stage/$file" "$cert_dir/$file" || restored=0 - else - rm -f -- "$cert_dir/$file" || restored=0 - fi - done - fi - if ((restored)); then - rm -rf -- "$stage" - else - printf 'Could not restore certificate files; recovery copies remain in %s\n' "$stage" >&2 - fi - } - trap ip_ssl_install_cleanup EXIT - for file in fullchain.pem privkey.pem; do - [[ ! -e "$cert_dir/$file" ]] || cp -p -- "$cert_dir/$file" "$stage/$file" || return 1 - done - quoted_cert=$(ip_ssl_shell_quote "$cert_dir/fullchain.pem") - quoted_key=$(ip_ssl_shell_quote "$cert_dir/privkey.pem") - # Trust the leaf only for local identity checks, not as a new system CA. - validation="openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv4' $quoted_cert" - [[ -z "$ipv6" ]] || validation+=" && openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv6' $quoted_cert" - # Expansion belongs to the later reload shell, including cron renewals. - # shellcheck disable=SC2016 - printf -v check_key 'xui_cert_pub=$(openssl x509 -in %s -pubkey -noout) && xui_key_pub=$(openssl pkey -in %s -passin pass: -pubout) && [ -n "$xui_cert_pub" ] && [ "$xui_cert_pub" = "$xui_key_pub" ]' "$quoted_cert" "$quoted_key" - validation+=" && $check_key" - # acme.sh persists this self-contained guard for later cron renewals too. - reload_guard="$validation && { $reload; }" - attempted=1 - "$acme" --installcert --force -d "$ipv4" --key-file "$cert_dir/privkey.pem" \ - --fullchain-file "$cert_dir/fullchain.pem" --reloadcmd "$reload_guard" || code=$? - if ! sh -c "$validation" > /dev/null 2>&1; then - printf 'Installed certificate failed IP SAN, validity or private-key checks; restoring previous files.\n' >&2 - return 1 - fi - if ((code != 0)) && [[ -f "$stage/fullchain.pem" ]] && [[ "$(cat "$stage/fullchain.pem")" == "$(cat "$cert_dir/fullchain.pem")" ]]; then - printf 'Certificate installation failed without replacing the previous certificate.\n' >&2 - return 1 - fi - chmod 600 "$cert_dir/privkey.pem" && chmod 644 "$cert_dir/fullchain.pem" || return 1 - installed=1 - if ((code != 0)); then printf 'Certificate files are valid, but the reload command reported an error.\n' >&2; fi + [[ "$acme" == /* && "$acme" != *[$'\n\r']* && "$dir" == /* && "$dir" != *[$'\n\r%']* ]] || return 1 + command -v crontab >/dev/null || { printf 'IP certificate renewal requires crontab.\n' >&2; return 1; } + ip_ssl_lock "$dir" && dir=$(cd -- "$dir" && pwd -P) && acme=$(readlink -f -- "$acme") && + ip_ssl_recover "$dir" || return 1 + ip_ssl_prepare_listener "$acme" "$port" "$ipv6" && + ip_ssl_write_runner "$dir/.xui-ip-ssl" && + ip_ssl_transaction issue "$acme" "$ipv4" "$ipv6" "$port" "$dir" "$reload" ) # END GENERATED IP SSL HELPERS is_ip() { @@ -493,7 +798,7 @@ install_base() { zypper refresh && zypper -q install -y cron curl tar timezone socat ca-certificates openssl ;; alpine) - apk update && apk add dcron curl tar tzdata socat ca-certificates openssl + apk update && apk add dcron curl tar tzdata socat ca-certificates openssl flock ;; *) apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl @@ -896,8 +1201,7 @@ setup_ip_certificate() { fi fi - # Set reload command for auto-renewal (add || true so it doesn't fail during first install) - local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null || true" + local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null" # Choose port for HTTP-01 listener (default 80, prompt override) local WebPort="" @@ -964,8 +1268,7 @@ setup_ip_certificate() { fi echo -e "${green}IP certificate installed and configured successfully!${plain}" - echo -e "${green}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}" - echo -e "${yellow}acme.sh will automatically renew and reload x-ui before expiry.${plain}" + echo -e "${green}Certificate valid for ~6 days, auto-renews via the x-ui IP certificate job.${plain}" return 0 } @@ -1259,7 +1562,7 @@ prompt_and_setup_ssl() { while [[ -z "$server_ip" ]]; do read -rp "Please enter your server's public IPv4 address: " server_ip server_ip="${server_ip// /}" - if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + if ! ip_ssl_ipv4 "$server_ip"; then echo -e "${red}Invalid IPv4 address. Please try again.${plain}" server_ip="" fi @@ -1268,7 +1571,10 @@ prompt_and_setup_ssl() { fi local ipv6_addr - if ! ipv6_addr=$(ip_ssl_select_ipv6 "$((1 - NONINTERACTIVE))" "${XUI_SSL_IPV6:-}"); then + if ! ip_ssl_ipv4 "$server_ip"; then + echo -e "${red}✗ IP certificate setup failed. Provide a valid public IPv4 address in the x-ui menu.${plain}" + SSL_HOST="${server_ip}" + elif ! ipv6_addr=$(ip_ssl_select_ipv6 "$((1 - NONINTERACTIVE))" "${XUI_SSL_IPV6:-}"); then # A refused address neither shrinks the requested certificate nor aborts the install. echo -e "${red}✗ IP certificate setup failed. Correct XUI_SSL_IPV6, then issue it from the x-ui menu.${plain}" SSL_HOST="${server_ip}" diff --git a/scripts/lib/ip-ssl.sh b/scripts/lib/ip-ssl.sh index d536a74fe..dddddb058 100644 --- a/scripts/lib/ip-ssl.sh +++ b/scripts/lib/ip-ssl.sh @@ -223,89 +223,394 @@ ip_ssl_shell_quote() { printf "'%s'" "$value" } +# The public paths always resolve through one generation pointer after migration. +ip_ssl_link() { + local state="$1" target="$2" link="$3" + rm -f -- "$state/pending/link" && + ln -s -- "$target" "$state/pending/link" && + mv -Tf -- "$state/pending/link" "$link" +} + +ip_ssl_lock() { + local dir="$1" state="$1/.xui-ip-ssl" + command -v flock >/dev/null || { printf 'IP certificates require flock. Install it and retry.\n' >&2; return 1; } + umask 077 + mkdir -p -- "$dir" || return 1 + [[ -d "$dir" && ! -L "$dir" && -O "$dir" ]] || return 1 + chmod go-w -- "$dir" || return 1 + [[ ! -L "$state" ]] && mkdir -p -- "$state" && [[ -O "$state" ]] && chmod 700 -- "$state" || return 1 + exec 9>>"$state/lock" || return 1 + flock -x 9 +} + +# An old cron can have sourced a legacy config already. Check on both sides +# of retiring its entries. Managed renewals always take the destination lock. +ip_ssl_legacy_busy() { + local acme="$1" cmdline arg found action + for cmdline in /proc/[0-9]*/cmdline; do + [[ -r "$cmdline" ]] || continue + found=0 action=0 + { + while IFS= read -r -d '' arg; do + if [[ "$arg" == "$acme" ]]; then + found=1 + elif ((found)); then + case "$arg" in + --cron|--renew|--renew-all|--renewAll|--renewall|--issue|--install-cert|--installcert|--deploy) action=1 ;; + esac + fi + done + } < "$cmdline" 2>/dev/null || continue + if ((found && action)); then return 0; fi + done + return 1 +} + +ip_ssl_retire_legacy() { + local state="$1" acme="$2" ipv4="$3" dir="$4" gen="$5" home="$6" + local entry name conf value destination destinations + local -a retire=() + for entry in "$home"/*; do + [[ -d "$entry" && ! -L "$entry" ]] || continue + name="${entry##*/}" + ip_ssl_ipv4 "${name%_ecc}" || continue + conf="$entry/${name%_ecc}.conf" + [[ -f "$conf" ]] || continue + # Retire every legacy IP entry sharing this destination, including an older primary IP. + destinations=$(sed -n "s/^Le_Real\(FullChain\|Cert\|Key\|CACert\)Path='\(.*\)'$/\2/p" "$conf") || return 1 + while IFS= read -r value; do + case "${value##*/}" in fullchain.pem|privkey.pem) ;; *) continue ;; esac + destination=$(cd -P -- "${value%/*}" 2>/dev/null && pwd -P) || continue + if [[ "$destination" == "$dir" ]]; then + retire+=("$name") + break + fi + done <<< "$destinations" + done + # The requested entries can also be unfinished orders with no destinations. + for name in "$ipv4" "${ipv4}_ecc"; do + entry="$home/$name" + conf="$entry/$ipv4.conf" + [[ -d "$entry" && ! -L "$entry" ]] || continue + if [[ ! -f "$conf" ]] || ! grep -Eq "^Le_(Real(Cert|Key|CACert|FullChain)Path|ReloadCmd|DeployHook)='[^']+" "$conf"; then + retire+=("$name") + fi + done + ((${#retire[@]})) || return 0 + if ip_ssl_legacy_busy "$acme"; then + printf 'Wait for the existing acme.sh command to finish, then retry IP certificate setup.\n' >&2 + return 1 + fi + for name in "${retire[@]}"; do + [[ -d "$home/$name" ]] || continue + # Journal before the same-directory rename so a crash can restore it. + printf '%s\n' "$name" >> "$state/pending/legacy" && + mv -T -- "$home/$name" "$home/.xui-retired-$gen-$name" || return 1 + done + if ip_ssl_legacy_busy "$acme"; then + printf 'An existing acme.sh command started during migration. Retry IP certificate setup after it exits.\n' >&2 + return 1 + fi +} + +ip_ssl_recover() { + local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending" + local gen='' home='' current='' entry held file name failed=0 previous='' + [[ -d "$pending" ]] || return 0 + if [[ -f "$pending/generation" ]]; then + if ! IFS= read -r gen < "$pending/generation" || [[ ! "$gen" =~ ^gen\.[a-zA-Z0-9]+$ ]]; then + printf 'Invalid IP certificate generation journal. Keep recovery files at %s.\n' "$pending" >&2 + return 1 + fi + fi + current=$(readlink -- "$state/current") || current='' + if [[ -f "$pending/home" ]] && ! IFS= read -r home < "$pending/home"; then + printf 'Invalid ACME home in the IP certificate journal. Keep recovery files at %s.\n' "$pending" >&2 + return 1 + fi + + if [[ -n "$gen" && "$current" == "$gen" ]]; then + # Commit is the pointer swap. Never roll back a committed generation. + if [[ -f "$pending/legacy" ]]; then + while IFS= read -r entry; do + ip_ssl_ipv4 "${entry%_ecc}" && [[ -n "$home" ]] && + rm -rf -- "$home/.xui-retired-$gen-$entry" || failed=1 + done < "$pending/legacy" + fi + if [[ -f "$state/$gen/previous" ]]; then IFS= read -r previous < "$state/$gen/previous" || failed=1; fi + for entry in "$state"/gen.*; do + name="${entry##*/}" + [[ "$name" != "$gen" && "$name" != "$previous" ]] || continue + rm -rf -- "$entry" || failed=1 + done + else + if [[ -f "$pending/live-changing" ]]; then + for file in fullchain.pem privkey.pem; do + if [[ -e "$pending/live/$file" || -L "$pending/live/$file" ]]; then + rm -f -- "$pending/restore" && + cp -a -- "$pending/live/$file" "$pending/restore" && + mv -Tf -- "$pending/restore" "$dir/$file" || failed=1 + else + rm -f -- "$dir/$file" || failed=1 + fi + done + fi + # Keep stock cron away from the public paths until the original file + # types are restored. A failed restore may still leave a live alias. + if ((!failed)) && [[ -f "$pending/legacy" ]]; then + while IFS= read -r entry; do + if ! ip_ssl_ipv4 "${entry%_ecc}" || [[ -z "$home" || -z "$gen" ]]; then failed=1; continue; fi + held="$home/.xui-retired-$gen-$entry" + if [[ -e "$held" ]]; then + if [[ -e "$home/$entry" || -L "$home/$entry" ]] || + ! mv -T -- "$held" "$home/$entry"; then + printf 'ACME recovery copy remains at %s\n' "$held" >&2 + failed=1 + fi + elif [[ ! -d "$home/$entry" ]]; then + failed=1 + fi + done < "$pending/legacy" + fi + if ((!failed)) && [[ -n "$gen" ]]; then rm -rf -- "${state:?}/${gen:?}" || failed=1; fi + fi + if ((failed)); then + printf 'IP certificate recovery could not complete. Keep recovery files at %s and retry after resolving the error.\n' "$pending" >&2 + return 1 + fi + if ! rm -f -- "$state/staging/fullchain.pem" "$state/staging/privkey.pem" || ! rm -rf -- "$pending"; then + printf 'Could not remove the IP certificate journal at %s\n' "$pending" >&2 + return 1 + fi +} + +ip_ssl_aliases() { + local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending" + local file seed + if [[ -f "$state/current/config" ]]; then + for file in fullchain.pem privkey.pem; do + [[ "$(readlink -- "$dir/$file")" == ".xui-ip-ssl/current/$file" ]] || return 1 + done + return 0 + fi + # The seed contains the original bytes, so converting either alias first + # still exposes the same pair. The journal keeps the original file types. + seed=$(mktemp -d "$state/gen.XXXXXX") || return 1 + for file in fullchain.pem privkey.pem; do + if [[ -e "$pending/live/$file" || -L "$pending/live/$file" ]]; then + # Follow the original live symlink relative to its own directory. + cp -pL -- "$dir/$file" "$seed/$file" || return 1 + fi + done + ip_ssl_link "$state" "${seed##*/}" "$state/current" && + touch "$pending/live-changing" || return 1 + for file in fullchain.pem privkey.pem; do + ip_ssl_link "$state" ".xui-ip-ssl/current/$file" "$dir/$file" || return 1 + done +} + +ip_ssl_validate_pair() { + local chain="$1" key="$2" ipv4="$3" ipv6="$4" cert_pub key_pub + [[ -s "$chain" && -s "$key" ]] && + openssl crl2pkcs7 -nocrl -certfile "$chain" -out /dev/null && + openssl verify -purpose sslserver -untrusted "$chain" -verify_ip "$ipv4" "$chain" >/dev/null || return 1 + [[ -z "$ipv6" ]] || openssl verify -purpose sslserver -untrusted "$chain" -verify_ip "$ipv6" "$chain" >/dev/null || return 1 + cert_pub=$(openssl x509 -in "$chain" -pubkey -noout) && + key_pub=$(openssl pkey -in "$key" -passin pass: -pubout) && + [[ -n "$cert_pub" && "$cert_pub" == "$key_pub" ]] +} + +ip_ssl_reload() { + local gen="$1" reload="$2" + if sh -c "$reload" 9>&-; then + rm -f -- "$gen/reload-pending" || + printf 'Could not clear the IP certificate reload marker.\n' >&2 + else + printf 'A valid certificate is installed. Panel reload failed and will be retried by the IP certificate job.\n' >&2 + fi +} + +ip_ssl_schedule() ( + local state="$1" home="$2" command line existing + [[ "$state" != *[$'\n\r%']* ]] || return 1 + # Different destinations share the user's crontab, but can order and stage in parallel. + exec 8>>"$home/.xui-ip-crontab.lock" && flock -x 8 || return 1 + command=$(ip_ssl_shell_quote "$state/renew-v1") + line="19 * * * * $command # x-ui managed IP certificate" + if ! existing=$(LC_ALL=C crontab -l 2>&1); then + case "$existing" in + *"no crontab for "*|*"No such file or directory"*) existing='' ;; + *) printf 'Could not read crontab: %s\n' "$existing" >&2; return 1 ;; + esac + fi + if grep -Fxq -- "$line" <<< "$existing"; then return 0; fi + { printf '%s\n' "$existing"; printf '%s\n' "$line"; } | crontab - +) + +ip_ssl_account_config() ( + local home="$1" cert_home="$2" ACCOUNT_CONF_PATH='' + # acme.sh sources account.conf after parsing --cert-home, so a saved + # CERT_HOME overrides the command line. Keep this override private. + if [[ -f "$home/account.conf" ]]; then + # shellcheck disable=SC1091 + source "$home/account.conf" || return 1 + fi + local original="${ACCOUNT_CONF_PATH:-$home/account.conf}" + if [[ -f "$original" ]]; then cat -- "$original" || return 1; fi + printf '\nCERT_HOME=%s\n' "$(ip_ssl_shell_quote "$cert_home")" +) + +ip_ssl_legacy_home() ( + local home="$1" ACCOUNT_CONF_PATH='' CERT_HOME='' + if [[ -f "$home/account.conf" ]]; then + # shellcheck disable=SC1091 + source "$home/account.conf" || return 1 + fi + if [[ -n "$ACCOUNT_CONF_PATH" && -f "$ACCOUNT_CONF_PATH" ]]; then + # shellcheck disable=SC1090 + source "$ACCOUNT_CONF_PATH" || return 1 + fi + printf '%s\n' "${CERT_HOME:-$home}" +) + +ip_ssl_transaction() ( + local action="$1" acme="$2" ipv4="$3" ipv6="$4" port="$5" dir="$6" reload="$7" + local state="$dir/.xui-ip-ssl" pending="$dir/.xui-ip-ssl/pending" home="${acme%/*}" + local work gen file previous rc legacy_home stage="$dir/.xui-ip-ssl/staging" + local -a scope domains=(-d "$ipv4") + mkdir -- "$pending" || return 1 + # Recovery runs under the caller's flock, including on normal exit. + trap 'rc=$?; ip_ssl_recover "$dir" || rc=1; exit "$rc"' EXIT + trap 'exit 130' INT + trap 'exit 143' TERM + trap 'exit 129' HUP + + work=$(mktemp -d "$state/gen.XXXXXX") || return 1 + gen="${work##*/}" + printf '%s\n' "$gen" > "$pending/generation" && mkdir -- "$work/acme" "$pending/live" || return 1 + if [[ "$action" == issue ]]; then + legacy_home=$(ip_ssl_legacy_home "$home") || return 1 + [[ "$legacy_home" == /* && "$legacy_home" != *[$'\n\r']* ]] || return 1 + printf '%s\n' "$legacy_home" > "$pending/home" && + ip_ssl_retire_legacy "$state" "$acme" "$ipv4" "$dir" "$gen" "$legacy_home" || return 1 + fi + for file in fullchain.pem privkey.pem; do + [[ ! -e "$dir/$file" && ! -L "$dir/$file" ]] || + cp -a -- "$dir/$file" "$pending/live/$file" || return 1 + done + if [[ -f "$state/current/config" ]]; then + previous=$(readlink -- "$state/current") && + printf '%s\n' "$previous" > "$work/previous" || return 1 + fi + if [[ "$action" != issue ]]; then + cp -a -- "$state/current/acme/." "$work/acme/" || return 1 + fi + [[ ! -L "$stage" ]] && mkdir -p -- "$stage" && chmod 700 -- "$stage" && + rm -f -- "$stage/fullchain.pem" "$stage/privkey.pem" || return 1 + ip_ssl_account_config "$home" "$work/acme" > "$pending/account.conf" || return 1 + scope=(--home "$home" --cert-home "$work/acme" --accountconf "$pending/account.conf") + # acme.sh saves destinations in single quotes. A fixed private working + # directory makes relative install paths safe even with a quoted parent. + cd -- "$state" || return 1 + if [[ "$action" == issue ]]; then + [[ -z "$ipv6" ]] || domains+=(-d "$ipv6") + if ! "$acme" --issue "${scope[@]}" "${domains[@]}" --keylength ec-256 --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ + --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then + printf 'IP certificate issuance failed. Check external port 80 on each selected address.\n' >&2 + return 1 + fi + else + rc=0 + local -a force=() + [[ "$action" != renew-force ]] || force=(--force) + "$acme" --renew "${scope[@]}" -d "$ipv4" --ecc "${force[@]}" || rc=$? + # acme.sh uses 2 when a certificate is not due for renewal. + if ((rc == 2)); then return 0; fi + ((rc == 0)) || return "$rc" + fi + # A renewal may already have copied to staging. Require both outputs from + # this explicit install so an incomplete copy cannot reuse an older file. + rm -f -- "$stage/fullchain.pem" "$stage/privkey.pem" || return 1 + if ! "$acme" --installcert "${scope[@]}" --ecc -d "$ipv4" --key-file staging/privkey.pem \ + --fullchain-file staging/fullchain.pem --reloadcmd ""; then + printf 'Could not stage the IP certificate and key.\n' >&2 + return 1 + fi + if ! ip_ssl_validate_pair "$stage/fullchain.pem" "$stage/privkey.pem" "$ipv4" "$ipv6"; then + printf 'Staged IP certificate failed SAN, validity or private-key checks.\n' >&2 + return 1 + fi + cp -- "$stage/privkey.pem" "$work/privkey.pem" && + cp -- "$stage/fullchain.pem" "$work/fullchain.pem" && + chmod 600 -- "$work/privkey.pem" && chmod 644 -- "$work/fullchain.pem" && + printf 'managed_acme=%q\nmanaged_ipv4=%q\nmanaged_ipv6=%q\nmanaged_reload=%q\n' "$acme" "$ipv4" "$ipv6" "$reload" > "$work/config" && + touch "$work/reload-pending" || return 1 + if [[ "$action" == issue ]]; then ip_ssl_schedule "$state" "$home" || return 1; fi + ip_ssl_aliases "$dir" && + ip_ssl_link "$state" "$gen" "$state/current" || return 1 + ip_ssl_reload "$work" "$reload" +) + +ip_ssl_scheduled() ( + local dir="$1" state="$1/.xui-ip-ssl" action="${2:-renew}" + local managed_acme managed_ipv4 managed_ipv6 managed_reload + ip_ssl_lock "$dir" && ip_ssl_recover "$dir" || return 1 + [[ -f "$state/current/config" ]] || return 0 + # This file is generated with Bash quoting under the private state directory. + # shellcheck disable=SC1091 + source "$state/current/config" || return 1 + if [[ -f "$state/current/reload-pending" ]]; then ip_ssl_reload "$state/current" "$managed_reload"; fi + ip_ssl_transaction "$action" "$managed_acme" "$managed_ipv4" "$managed_ipv6" '' "$dir" "$managed_reload" +) + +ip_ssl_revoke_managed() ( + local dir="$1" state="$1/.xui-ip-ssl" managed_acme managed_ipv4 gen account + ip_ssl_lock "$dir" && ip_ssl_recover "$dir" || return 1 + [[ -f "$state/current/config" ]] || return 1 + # shellcheck disable=SC1091 + source "$state/current/config" || return 1 + account=$(mktemp "$state/.account.XXXXXX") || return 1 + trap 'rm -f -- "$account"' EXIT + ip_ssl_account_config "${managed_acme%/*}" "$state/current/acme" > "$account" || return 1 + "$managed_acme" --revoke --home "${managed_acme%/*}" --cert-home "$state/current/acme" --accountconf "$account" -d "$managed_ipv4" --ecc || + printf 'CA revocation failed. Removing local renewal state and files.\n' >&2 + # Keep the lock inode and inert scheduled runner for later issuance. + rm -f -- "$state/current" "$dir/fullchain.pem" "$dir/privkey.pem" || return 1 + for gen in "$state"/gen.*; do rm -rf -- "$gen" || return 1; done +) + +ip_ssl_write_runner() { + local state="$1" temp + temp=$(mktemp "$state/.runner.XXXXXX") || return 1 + if { + printf '#!/bin/bash\n# x-ui managed IP certificate deployment v1\n' + # The OpenRC service commands live in /sbin on Alpine. + # shellcheck disable=SC2016 + printf 'export PATH="${PATH:+$PATH:}/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"\n' + declare -f ip_ssl_ipv4 ip_ssl_shell_quote ip_ssl_link ip_ssl_lock ip_ssl_legacy_busy \ + ip_ssl_retire_legacy ip_ssl_recover ip_ssl_aliases ip_ssl_validate_pair ip_ssl_reload \ + ip_ssl_schedule ip_ssl_account_config ip_ssl_legacy_home ip_ssl_transaction ip_ssl_scheduled + # shellcheck disable=SC2016 + printf '\nip_ssl_scheduled "$(cd -- "$(dirname -- "$0")/.." && pwd -P)"\n' + } > "$temp" && chmod 700 -- "$temp" && mv -Tf -- "$temp" "$state/renew-v1"; then + return 0 + fi + rm -f -- "$temp" || printf 'Could not remove incomplete renewal helper %s\n' "$temp" >&2 + return 1 +} + ip_ssl_issue_and_install() ( - local acme="$1" ipv4="$2" ipv6="$3" port="$4" cert_dir="$5" reload="$6" - local stage='' attempted=0 installed=0 code=0 file restored - local acme_home="${acme%/*}" renewal_backup entry - local quoted_cert quoted_key validation check_key reload_guard - local -a domain_args=(-d "$ipv4") + local acme="$1" ipv4="$2" ipv6="$3" port="$4" dir="$5" reload="$6" if ! ip_ssl_ipv4 "$ipv4" || { [[ -n "$ipv6" ]] && ! ip_ssl_public_ipv6 "$ipv6"; }; then printf 'Invalid IP certificate identifier; no ACME request was sent.\n' >&2 return 1 fi [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 - [[ -z "$ipv6" ]] || domain_args+=(-d "$ipv6") - ip_ssl_prepare_listener "$acme" "$port" "$ipv6" || return 1 - renewal_backup=$(mktemp -d "$acme_home/.xui-acme.XXXXXX") || return 1 - for entry in "$ipv4" "${ipv4}_ecc"; do - [[ ! -d "$acme_home/$entry" ]] || cp -a -- "$acme_home/$entry" "$renewal_backup/$entry" || { - rm -rf -- "$renewal_backup" - return 1 - } - done - if ! "$acme" --issue "${domain_args[@]}" --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ - --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then - # acme.sh saves the requested names before it places the order, so a failed one would - # make cron renew the working certificate with the names that just failed. - for entry in "$ipv4" "${ipv4}_ecc"; do - rm -rf -- "${acme_home:?}/$entry" - [[ ! -d "$renewal_backup/$entry" ]] || mv -- "$renewal_backup/$entry" "$acme_home/$entry" - done - rm -rf -- "$renewal_backup" - printf 'IP certificate issuance failed. Existing certificates and ACME data were preserved. Check external port 80 on every selected address.\n' >&2 - return 1 - fi - rm -rf -- "$renewal_backup" - - umask 077 - mkdir -p "$cert_dir" || return 1 - stage=$(mktemp -d "$cert_dir/.xui-install.XXXXXX") || return 1 - # Invoked indirectly by the EXIT trap; older ShellCheck reports SC2317. - # shellcheck disable=SC2317,SC2329 - ip_ssl_install_cleanup() { - restored=1 - if ((attempted && !installed)); then - for file in fullchain.pem privkey.pem; do - if [[ -f "$stage/$file" ]]; then - cp -p -- "$stage/$file" "$cert_dir/$file" || restored=0 - else - rm -f -- "$cert_dir/$file" || restored=0 - fi - done - fi - if ((restored)); then - rm -rf -- "$stage" - else - printf 'Could not restore certificate files; recovery copies remain in %s\n' "$stage" >&2 - fi - } - trap ip_ssl_install_cleanup EXIT - for file in fullchain.pem privkey.pem; do - [[ ! -e "$cert_dir/$file" ]] || cp -p -- "$cert_dir/$file" "$stage/$file" || return 1 - done - quoted_cert=$(ip_ssl_shell_quote "$cert_dir/fullchain.pem") - quoted_key=$(ip_ssl_shell_quote "$cert_dir/privkey.pem") - # Trust the leaf only for local identity checks, not as a new system CA. - validation="openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv4' $quoted_cert" - [[ -z "$ipv6" ]] || validation+=" && openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv6' $quoted_cert" - # Expansion belongs to the later reload shell, including cron renewals. - # shellcheck disable=SC2016 - printf -v check_key 'xui_cert_pub=$(openssl x509 -in %s -pubkey -noout) && xui_key_pub=$(openssl pkey -in %s -passin pass: -pubout) && [ -n "$xui_cert_pub" ] && [ "$xui_cert_pub" = "$xui_key_pub" ]' "$quoted_cert" "$quoted_key" - validation+=" && $check_key" - # acme.sh persists this self-contained guard for later cron renewals too. - reload_guard="$validation && { $reload; }" - attempted=1 - "$acme" --installcert --force -d "$ipv4" --key-file "$cert_dir/privkey.pem" \ - --fullchain-file "$cert_dir/fullchain.pem" --reloadcmd "$reload_guard" || code=$? - if ! sh -c "$validation" > /dev/null 2>&1; then - printf 'Installed certificate failed IP SAN, validity or private-key checks; restoring previous files.\n' >&2 - return 1 - fi - if ((code != 0)) && [[ -f "$stage/fullchain.pem" ]] && [[ "$(cat "$stage/fullchain.pem")" == "$(cat "$cert_dir/fullchain.pem")" ]]; then - printf 'Certificate installation failed without replacing the previous certificate.\n' >&2 - return 1 - fi - chmod 600 "$cert_dir/privkey.pem" && chmod 644 "$cert_dir/fullchain.pem" || return 1 - installed=1 - if ((code != 0)); then printf 'Certificate files are valid, but the reload command reported an error.\n' >&2; fi + [[ "$acme" == /* && "$acme" != *[$'\n\r']* && "$dir" == /* && "$dir" != *[$'\n\r%']* ]] || return 1 + command -v crontab >/dev/null || { printf 'IP certificate renewal requires crontab.\n' >&2; return 1; } + ip_ssl_lock "$dir" && dir=$(cd -- "$dir" && pwd -P) && acme=$(readlink -f -- "$acme") && + ip_ssl_recover "$dir" || return 1 + ip_ssl_prepare_listener "$acme" "$port" "$ipv6" && + ip_ssl_write_runner "$dir/.xui-ip-ssl" && + ip_ssl_transaction issue "$acme" "$ipv4" "$ipv6" "$port" "$dir" "$reload" ) diff --git a/scripts/test/README.md b/scripts/test/README.md index 191e61934..e6fc4455e 100644 --- a/scripts/test/README.md +++ b/scripts/test/README.md @@ -1,7 +1,7 @@ # IP certificate regression tests Run from the repository root in Bash. The suite uses temporary files, mocks ACME -orders and service commands, and generates local self-signed certificate fixtures. +orders and service commands, and generates certificate fixtures from a local CA. It never requests a certificate from a CA or executes the complete installer. ```bash @@ -14,7 +14,7 @@ IP_SSL_LINUX_TEST=1 bash scripts/test/ip-ssl-listener-test.sh bash scripts/test/ip-ssl-certificate-test.sh ``` -Linux integration needs `socat`, `curl`, `openssl` (1.1.1+), and standard coreutils. +Linux integration needs `socat`, `curl`, `flock`, `openssl` (1.1.1+), and standard coreutils. The listener tests bind unprivileged random ports on loopback. They need an IPv6 loopback interface, but no public IPv6 address, root privileges, or working external echo service. Run the same commands on Debian/Ubuntu and AlmaLinux/RHEL; @@ -22,9 +22,10 @@ install test dependencies in a disposable container if they are missing locally. The tests cover real embedded installer/menu functions, discovery and consent, unattended overrides, both socket families, actual IP SAN types and matching keys, -failed issuance/installation, rollback, permissions, and the persisted renewal -reload guard. Package installation, ACME orders, and panel/service operations are -mocked at their command boundaries. +failed issuance and installation, failed restoration, interruption, shared-path +locking, rejected automatic renewals, and the persisted renewal runner. Package +installation, ACME orders, and panel/service operations are mocked at their command +boundaries. To check unchanged upstream acme.sh listener implementations separately: @@ -33,14 +34,21 @@ curl -fsSLo /tmp/acme-3.1.5.sh https://raw.githubusercontent.com/acmesh-official bash scripts/test/ip-ssl-acme-listener-test.sh /tmp/acme-3.1.5.sh 28085 curl -fsSLo /tmp/acme-3.1.6.sh https://raw.githubusercontent.com/acmesh-official/acme.sh/3.1.6/acme.sh bash scripts/test/ip-ssl-acme-listener-test.sh /tmp/acme-3.1.6.sh 28085 +bash scripts/test/ip-ssl-acme-lifecycle-test.sh /tmp/acme-3.1.5.sh /tmp/acme-3.1.6.sh ``` -This invokes only the upstream listener dispatcher, sends independent loopback +The listener test invokes the upstream dispatcher, sends independent loopback HTTP requests with `curl -4` and `curl -6`, prints the sockets with `ss`, then stops the listeners. It does not issue ACME orders or change an installed client. Run it in a disposable Linux environment with `iproute2`/`iproute` installed. Test both `net.ipv6.bindv6only=0` and `1` container configurations where available. +The lifecycle test exercises stock `--installcert` and the retry path of stock +`--renew`. It reproduces the live-file overwrite on a failed upstream reload, +then checks the x-ui runner against the same behavior using isolated ACME state, +fixture certificates, and no CA requests. CI fetches the two upstream versions +by commit and runs this test alongside the lifecycle and concurrency regressions. + Loopback success does not establish public reachability. Real CA validation, external port 80 forwarding, provider firewalls, and scheduled cron execution on a deployed server require separate deployment testing. diff --git a/scripts/test/ip-ssl-acme-lifecycle-test.sh b/scripts/test/ip-ssl-acme-lifecycle-test.sh new file mode 100644 index 000000000..d521527d4 --- /dev/null +++ b/scripts/test/ip-ssl-acme-lifecycle-test.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# Exercise the actual upstream install and renewal-retry commands without a CA. +set -euo pipefail +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +# shellcheck disable=SC1091 +source "$ROOT/scripts/lib/ip-ssl.sh" + +test_acme() ( + source_file="$1" + temp=$(mktemp -d) + trap 'rm -rf "$temp"' EXIT + ipv4=198.51.100.8 + ipv6=2001:4860::1 + export HOME="$temp/home" NO_ARI=1 SSL_CERT_FILE="$temp/ca.pem" + export CRON_FILE="$temp/crontab" + export PATH="$temp/bin:$PATH" + acme_home="$HOME/.acme.sh" + global="$temp/global-certs" + legacy="$temp/legacy-live" + managed="$temp/managed's live" + mkdir -p "$acme_home" "$global/${ipv4}_ecc" "$legacy" "$temp/bin" + cp "$source_file" "$acme_home/upstream.sh" + printf "CERT_HOME='%s'\n" "$global" > "$acme_home/account.conf" + cp "$acme_home/account.conf" "$temp/account.conf" + touch "$CRON_FILE" + cat > "$temp/bin/crontab" <<'CRON' +#!/usr/bin/env bash +case "$1" in -l) cat "$CRON_FILE";; -) cat > "$CRON_FILE";; *) exit 1;; esac +CRON + chmod +x "$temp/bin/crontab" + + openssl req -new -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \ + -days 3 -subj /CN=offline-ACME-CA -keyout "$temp/ca.key" -out "$SSL_CERT_FILE" >/dev/null 2>&1 + serial=0 + for name in good invalid renewed; do + san="IP:$ipv4,IP:$ipv6" + [[ "$name" != invalid ]] || san="IP:$ipv4" + printf 'subjectAltName=%s\n' "$san" > "$temp/ext" + openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \ + -subj "/CN=$name" -keyout "$temp/$name.key" -out "$temp/$name.csr" >/dev/null 2>&1 + openssl x509 -req -in "$temp/$name.csr" -CA "$SSL_CERT_FILE" -CAkey "$temp/ca.key" \ + -set_serial "$((++serial))" -days 2 -extfile "$temp/ext" -out "$temp/$name.cer" >/dev/null 2>&1 + cat "$temp/$name.cer" "$SSL_CERT_FILE" > "$temp/$name.fullchain" + done + + seed_order() { + local entry="$1" fixture="$2" + mkdir -p "$entry" + cp "$temp/$fixture.cer" "$entry/$ipv4.cer" + cp "$temp/$fixture.key" "$entry/$ipv4.key" + cp "$temp/$fixture.fullchain" "$entry/fullchain.cer" + cp "$SSL_CERT_FILE" "$entry/ca.cer" + } + + version=$(sh "$acme_home/upstream.sh" --version | tail -n1) + entry="$global/${ipv4}_ecc" + seed_order "$entry" invalid + printf "Le_Domain='%s'\nLe_NextRenewTime='4000000000'\nLe_CertCreateTime='2'\nLe_InstallCertSuccessTime='1'\n" "$ipv4" > "$entry/$ipv4.conf" + cp "$temp/good.fullchain" "$legacy/fullchain.pem" + cp "$temp/good.key" "$legacy/privkey.pem" + # Old design: the guard fails after installcert has copied both files. + if sh "$acme_home/upstream.sh" --installcert --home "$acme_home" -d "$ipv4" --ecc \ + --key-file "$legacy/privkey.pem" --fullchain-file "$legacy/fullchain.pem" --reloadcmd false > "$temp/legacy.log" 2>&1; then + printf 'FAIL: upstream accepted a failing reload command (%s)\n' "$version" >&2 + return 1 + fi + cmp "$temp/invalid.fullchain" "$legacy/fullchain.pem" + cmp "$temp/invalid.key" "$legacy/privkey.pem" + grep -q "^Le_NextRenewTime='4000000000'" "$entry/$ipv4.conf" + grep -q "^Le_InstallCertSuccessTime='1'" "$entry/$ipv4.conf" + grep -Fq "Le_RealKeyPath='$legacy/privkey.pem'" "$entry/$ipv4.conf" + cp "$temp/good.fullchain" "$legacy/fullchain.pem" + if sh "$acme_home/upstream.sh" --renew --home "$acme_home" -d "$ipv4" --ecc > "$temp/legacy-retry.log" 2>&1; then + printf 'FAIL: upstream accepted a failing install retry (%s)\n' "$version" >&2 + return 1 + fi + grep -q 'retrying install cert' "$temp/legacy-retry.log" + cmp "$temp/invalid.fullchain" "$legacy/fullchain.pem" + printf 'PASS: upstream %s reproduces live overwrite on failed reload, including a saved-path retry\n' "$version" + + # Only the order is replaced by local fixtures. Stock installcert and + # renew execute through the actual persistent runner with the original home. + export TEST_ACME_DIR="$temp" TEST_ACME_IP="$ipv4" TEST_ACME_ORIGINAL="$acme_home/upstream.sh" + wrapper="$acme_home/acme.sh" + cat > "$wrapper" <<'WRAPPER' +#!/usr/bin/env bash +set -euo pipefail +if [[ "$1" != --issue ]]; then exec sh "$TEST_ACME_ORIGINAL" "$@"; fi +while [[ "$1" != --cert-home ]]; do shift; done +domain="$TEST_ACME_IP" +entry="$2/${domain}_ecc" +mkdir -p "$entry" +cp "$TEST_ACME_DIR/good.cer" "$entry/$domain.cer" +cp "$TEST_ACME_DIR/good.key" "$entry/$domain.key" +cp "$TEST_ACME_DIR/good.fullchain" "$entry/fullchain.cer" +cp "$SSL_CERT_FILE" "$entry/ca.cer" +printf "Le_Domain='%s'\nLe_CertCreateTime='1'\nLe_NextRenewTime='4000000000'\n" "$domain" > "$entry/$domain.conf" +WRAPPER + chmod +x "$wrapper" + ip_ssl_issue_and_install "$wrapper" "$ipv4" "$ipv6" "$((20000+RANDOM))" "$managed" true + cmp "$temp/good.fullchain" "$managed/fullchain.pem" + cmp "$temp/good.key" "$managed/privkey.pem" + cmp "$temp/account.conf" "$acme_home/account.conf" + cmp "$temp/invalid.fullchain" "$legacy/fullchain.pem" + state="$managed/.xui-ip-ssl" + entry="$state/current/acme/${ipv4}_ecc" + grep -Fxq "Le_RealKeyPath='staging/privkey.pem'" "$entry/$ipv4.conf" + seed_order "$entry" invalid + # Simulate an already-created certificate with a pending upstream install + # retry. NO_ARI and a future timestamp keep stock --renew entirely offline. + sed -i '/^Le_InstallCertSuccessTime=/d; /^Le_CertCreateTime=/d' "$entry/$ipv4.conf" + printf "Le_InstallCertSuccessTime='1'\nLe_CertCreateTime='2'\n" >> "$entry/$ipv4.conf" + cp "$entry/$ipv4.conf" "$temp/before-retry.conf" + if "$state/renew-v1" > "$temp/retry.log" 2>&1; then + printf 'FAIL: managed retry accepted candidate without IPv6 SAN (%s)\n' "$version" >&2 + return 1 + fi + grep -q 'retrying install cert' "$temp/retry.log" + grep -q 'Staged IP certificate failed' "$temp/retry.log" + cmp "$temp/good.fullchain" "$managed/fullchain.pem" + cmp "$temp/good.key" "$managed/privkey.pem" + cmp "$temp/before-retry.conf" "$entry/$ipv4.conf" + seed_order "$entry" renewed + "$state/renew-v1" > "$temp/valid-retry.log" 2>&1 + cmp "$temp/renewed.fullchain" "$managed/fullchain.pem" + cmp "$temp/renewed.key" "$managed/privkey.pem" + cmp "$temp/account.conf" "$acme_home/account.conf" + printf 'PASS: managed upstream %s installs privately, rejects failed retry, and promotes valid retry\n' "$version" +) + +if (($# == 0)); then printf 'Pass verified upstream acme.sh source paths as arguments.\n' >&2; exit 2; fi +for acme_source in "$@"; do test_acme "$acme_source"; done diff --git a/scripts/test/ip-ssl-certificate-test.sh b/scripts/test/ip-ssl-certificate-test.sh index d6eb13a02..346a69d50 100644 --- a/scripts/test/ip-ssl-certificate-test.sh +++ b/scripts/test/ip-ssl-certificate-test.sh @@ -6,115 +6,369 @@ source "${IP_SSL_TEST_HELPERS:-$ROOT/scripts/lib/ip-ssl.sh}" TEMP=$(mktemp -d) trap 'rm -rf "$TEMP"' EXIT fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; } -export ACME_LOG="$TEMP/arguments" RELOAD_LOG="$TEMP/reloads" -export ISSUED_CERT="$TEMP/new.pem" ISSUED_KEY="$TEMP/new.key" -export ACME_ISSUE_FAIL=0 ACME_INSTALL_FAIL=0 ACME_RELOAD_FAIL=0 -for name in old new v4 dns; do - san='IP:198.51.100.8,IP:2001:4860::1' - [[ "$name" != v4 ]] || san='IP:198.51.100.8' - [[ "$name" != dns ]] || san='DNS:198.51.100.8,DNS:2001:4860::1' - openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 2 -subj /CN=ip-test -addext "subjectAltName=$san" -keyout "$TEMP/$name.key" -out "$TEMP/$name.pem" > /dev/null 2>&1 +export ACME_LOG="$TEMP/arguments" RELOAD_LOG="$TEMP/reloads" CRON_FILE="$TEMP/crontab" +export ISSUE_MODE=ok RENEW_MODE=ok INSTALL_MODE=ok RELOAD_FAIL=0 +export SSL_CERT_FILE="$TEMP/ca.pem" +ipv4=198.51.100.8 +ipv6=2001:4860::1 +port=$((20000+RANDOM)) +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3 \ + -subj /CN=IP-fixture-CA -keyout "$TEMP/ca.key" -out "$SSL_CERT_FILE" >/dev/null 2>&1 +serial=0 +touch "$TEMP/ca-index" +printf '01\n' > "$TEMP/ca-serial" +cat > "$TEMP/ca.conf" </dev/null 2>&1 + printf 'subjectAltName=%s\n' "$san" > "$TEMP/ext" + if [[ "$name" == expired ]]; then + openssl ca -config "$TEMP/ca.conf" -in "$TEMP/$name.csr" -cert "$SSL_CERT_FILE" -keyfile "$TEMP/ca.key" \ + -startdate 20200101000000Z -enddate 20200102000000Z -batch -notext \ + -extfile "$TEMP/ext" -out "$TEMP/$name.pem" >/dev/null 2>&1 + else + openssl x509 -req -in "$TEMP/$name.csr" -CA "$SSL_CERT_FILE" -CAkey "$TEMP/ca.key" \ + -set_serial "$((++serial))" -days 2 -extfile "$TEMP/ext" -out "$TEMP/$name.pem" >/dev/null 2>&1 + fi + cat "$SSL_CERT_FILE" >> "$TEMP/$name.pem" done -mkdir "$TEMP/cert's directory" + +mkdir "$TEMP/mockbin" "$TEMP/acme home" "$TEMP/legacy certificates" +export PATH="$TEMP/mockbin:$PATH" +printf '13 0 * * * /unrelated-cron\n' > "$CRON_FILE" +acme="$TEMP/acme home/acme.sh" +legacy="$TEMP/legacy certificates" cert_dir="$TEMP/cert's directory" +state="$cert_dir/.xui-ip-ssl" +runner="$state/renew-v1" +mkdir -p "$cert_dir" "$legacy/$ipv4" "$legacy/${ipv4}_ecc" "$legacy/example.net_ecc" +printf "CERT_HOME='%s'\n" "$legacy" > "${acme%/*}/account.conf" +printf 'unrelated certificate\n' > "$legacy/example.net_ecc/marker" +for suffix in '' _ecc; do + printf "Le_Alt='no'\nLe_NextRenewTime='1'\nLe_RealKeyPath='%s/privkey.pem'\nLe_RealFullChainPath='%s/fullchain.pem'\n" \ + "$cert_dir" "$cert_dir" > "$legacy/$ipv4$suffix/$ipv4.conf" +done +cp "$legacy/${ipv4}_ecc/$ipv4.conf" "$TEMP/legacy.conf" +cp "${acme%/*}/account.conf" "$TEMP/account.conf" cp "$TEMP/old.pem" "$cert_dir/fullchain.pem" cp "$TEMP/old.key" "$cert_dir/privkey.pem" -cat > "$TEMP/mock acme" <<'MOCK' + +cat > "$TEMP/mockbin/crontab" <<'MOCK' +#!/usr/bin/env bash +case "$1" in + -l) cat "$CRON_FILE" ;; + -) cat > "$CRON_FILE" ;; + *) exit 1 ;; +esac +MOCK +cat > "$acme" <<'MOCK' #!/usr/bin/env bash set -euo pipefail +action=$1 printf 'CALL\n' >> "$ACME_LOG" printf 'arg=%s\n' "$@" >> "$ACME_LOG" -case "$1" in +shift +home='' cert_home='' account='' domain='' san='' key='' chain='' reload='' +while (($#)); do + case "$1" in + --home) home=$2; shift ;; + --cert-home) cert_home=$2; shift ;; + --accountconf) account=$2; shift ;; + -d) + if [[ -z "$domain" ]]; then domain=$2; else san=$2; fi + shift ;; + --key-file) key=$2; shift ;; + --fullchain-file) chain=$2; shift ;; + --reloadcmd) reload=$2; shift ;; + esac + shift +done +# Like upstream, load the account config after applying command-line arguments. +CERT_HOME=${cert_home:-${home:-${0%/*}}} +if [[ -z "$account" ]]; then account="${home:-${0%/*}}/account.conf"; fi +# shellcheck disable=SC1090 +if [[ -f "$account" ]]; then source "$account"; fi +entry="$CERT_HOME/${domain}_ecc" +conf="$entry/$domain.conf" +case "$action" in --version) printf 'v3.1.5\n' ;; - --issue) - # Like acme.sh, record the requested SAN set before the order can fail. - mkdir -p "$ACME_HOME/198.51.100.8_ecc" - printf "Le_Alt='%s'\n" "$*" > "$ACME_HOME/198.51.100.8_ecc/198.51.100.8.conf" - [[ "$ACME_ISSUE_FAIL" != 1 ]] + --issue|--renew) + mkdir -p "$entry" + if [[ "$action" == --issue ]]; then + printf "Le_Alt='%s'\n" "${san:-no}" > "$conf" + if [[ "$ISSUE_MODE" == fail ]]; then exit 1; fi + else + if [[ "$RENEW_MODE" == skip ]]; then exit 2; fi + if [[ -n "${RENEW_BARRIER:-}" ]]; then + : > "$RENEW_BARRIER.ready" + read -r _ < "$RENEW_BARRIER" + fi + # Renew reuses stored destinations and advances the schedule before copying. + # shellcheck disable=SC1090 + source "$conf" + printf "Le_NextRenewTime='advanced'\n" >> "$conf" + cp "$ISSUED_KEY" "$Le_RealKeyPath" + cp "$ISSUED_CERT" "$Le_RealFullChainPath" + if [[ "$RENEW_MODE" == fail ]]; then exit 1; fi + exit 0 + fi + printf "Le_NextRenewTime='issued'\n" >> "$conf" ;; --upgrade|--register-account) : ;; --installcert) - key=''; cert=''; reload='' - while (($#)); do - case "$1" in --key-file) key="$2"; shift;; --fullchain-file) cert="$2"; shift;; --reloadcmd) reload="$2"; shift;; esac - shift - done - if [[ "$ACME_INSTALL_FAIL" == 1 ]]; then printf 'broken certificate\n' > "$cert"; exit 1; fi - cp "$ISSUED_KEY" "$key"; cp "$ISSUED_CERT" "$cert" - printf '%s' "$reload" > "$RELOAD_LOG.command" - sh -c "$reload" - [[ "$ACME_RELOAD_FAIL" != 1 ]] + printf 'Le_RealKeyPath=%q\nLe_RealFullChainPath=%q\n' "$key" "$chain" >> "$conf" + [[ -z "$account" || "$account" == */pending/account.conf ]] || exit 1 + if [[ "$INSTALL_MODE" == fail ]]; then printf 'broken chain\n' > "$chain"; exit 1; fi + if [[ "$INSTALL_MODE" != no-key ]]; then cp "$ISSUED_KEY" "$key"; fi + if [[ "$INSTALL_MODE" != no-chain ]]; then cp "$ISSUED_CERT" "$chain"; fi + if [[ -n "$reload" ]]; then sh -c "$reload"; fi ;; - *) printf 'Unexpected ACME operation: %s\n' "$1" >&2; exit 1 ;; + *) printf 'Unexpected ACME operation: %s\n' "$action" >&2; exit 1 ;; esac MOCK -chmod +x "$TEMP/mock acme" -acme="$TEMP/mock acme" -export ACME_HOME="$TEMP" -reload="printf 'reloaded\\n' >> '$RELOAD_LOG'" -port=$((20000+RANDOM)) +env chmod +x "$acme" "$TEMP/mockbin/crontab" +reload="test \"\$RELOAD_FAIL\" = 0 && printf 'reloaded\\n' >> '$RELOAD_LOG'" -ACME_ISSUE_FAIL=1 -if ip_ssl_issue_and_install "$acme" 198.51.100.8 '' "$port" "$cert_dir" "$reload"; then fail 'ACME failure reported success'; fi -cmp "$TEMP/old.pem" "$cert_dir/fullchain.pem" || fail 'issuance failure removed existing certificate' -cmp "$TEMP/old.key" "$cert_dir/privkey.pem" || fail 'issuance failure removed existing key' -[[ ! -f "$RELOAD_LOG" ]] || fail 'issuance failure reloaded panel' -[[ ! -e "$ACME_HOME/198.51.100.8_ecc" ]] || fail 'a failed first order left a renewal entry that cron would retry every day' -printf 'PASS: ACME failure preserves existing certificate and key\n' +fixture() { + export ISSUED_CERT="$TEMP/$1.pem" ISSUED_KEY="$TEMP/${2:-$1}.key" +} -mkdir -p "$ACME_HOME/198.51.100.8_ecc" -printf "Le_Alt='no'\nLe_NextRenewTime='1'\n" > "$ACME_HOME/198.51.100.8_ecc/198.51.100.8.conf" -cp "$ACME_HOME/198.51.100.8_ecc/198.51.100.8.conf" "$TEMP/working.conf" -if ip_ssl_issue_and_install "$acme" 198.51.100.8 '2001:4860::1' "$port" "$cert_dir" "$reload"; then fail 'ACME failure reported success'; fi -cmp "$TEMP/working.conf" "$ACME_HOME/198.51.100.8_ecc/198.51.100.8.conf" || fail 'a failed IPv6 attempt rewrote the working certificate renewal entry' -[[ -z "$(find "$ACME_HOME" -maxdepth 1 -name '.xui-acme.*')" ]] || fail 'the renewal entry backup was left behind' -printf 'PASS: a failed order restores the renewal entry of the working certificate\n' -rm -rf "$ACME_HOME/198.51.100.8_ecc" -: > "$ACME_LOG" -ACME_ISSUE_FAIL=0 +issue() { + ip_ssl_issue_and_install "$acme" "${1:-$ipv4}" "$ipv6" "$port" "${2:-$cert_dir}" "$reload" +} -ip_ssl_issue_and_install "$acme" 198.51.100.8 '2001:4860::1' "$port" "$cert_dir" "$reload" -cmp "$TEMP/new.pem" "$cert_dir/fullchain.pem" || fail 'new certificate not installed' -[[ "$(stat -c %a "$cert_dir/privkey.pem")" == 600 ]] || fail 'private key permissions changed' -[[ "$(stat -c %a "$cert_dir/fullchain.pem")" == 644 ]] || fail 'certificate permissions changed' -openssl verify -trusted "$cert_dir/fullchain.pem" -partial_chain -verify_ip 198.51.100.8 "$cert_dir/fullchain.pem" > /dev/null -openssl verify -trusted "$cert_dir/fullchain.pem" -partial_chain -verify_ip 2001:4860::1 "$cert_dir/fullchain.pem" > /dev/null -if ! grep -qx 'arg=--listen-v4' "$ACME_LOG" || ! grep -qx 'arg=--listen-v6' "$ACME_LOG"; then fail 'dual-stack flags absent'; fi -[[ "$(grep -cx 'arg=2001:4860::1' "$ACME_LOG")" == 1 ]] || fail 'IPv6 SAN duplicated or missing' -[[ "$(cat "$RELOAD_LOG")" == reloaded ]] || fail 'valid certificate did not reload' -sh -c "$(cat "$RELOAD_LOG.command")" -[[ "$(wc -l < "$RELOAD_LOG")" == 2 ]] || fail 'saved renewal reload command failed' -printf 'PASS: both IP SANs, quoting, install permissions and saved reload command\n' +live_is() { + cmp "$TEMP/$1.pem" "$cert_dir/fullchain.pem" && cmp "$TEMP/$1.key" "$cert_dir/privkey.pem" +} -cp "$TEMP/v4.pem" "$cert_dir/fullchain.pem" -cp "$TEMP/v4.key" "$cert_dir/privkey.pem" -if sh -c "$(cat "$RELOAD_LOG.command")" > /dev/null 2>&1; then fail 'renewal guard accepted a missing IPv6 SAN'; fi -[[ "$(wc -l < "$RELOAD_LOG")" == 2 ]] || fail 'invalid renewed certificate reloaded the panel' -cp "$TEMP/new.pem" "$cert_dir/fullchain.pem" -cp "$TEMP/new.key" "$cert_dir/privkey.pem" -printf 'PASS: saved renewal guard blocks reload after a missing IPv6 SAN\n' +legacy_is_intact() { + cmp "$TEMP/legacy.conf" "$legacy/$ipv4/$ipv4.conf" && + cmp "$TEMP/legacy.conf" "$legacy/${ipv4}_ecc/$ipv4.conf" && + cmp "$TEMP/account.conf" "${acme%/*}/account.conf" && + grep -qx 'unrelated certificate' "$legacy/example.net_ecc/marker" +} -for bad in v4 dns; do - ISSUED_CERT="$TEMP/$bad.pem"; ISSUED_KEY="$TEMP/$bad.key" - if ip_ssl_issue_and_install "$acme" 198.51.100.8 '2001:4860::1' "$port" "$cert_dir" "$reload"; then fail 'missing IP SAN accepted'; fi - cmp "$TEMP/new.pem" "$cert_dir/fullchain.pem" || fail 'bad SAN replaced working certificate' - cmp "$TEMP/new.key" "$cert_dir/privkey.pem" || fail 'bad SAN replaced working key' - [[ "$(wc -l < "$RELOAD_LOG")" == 2 ]] || fail 'invalid IP SAN reloaded panel' +reject() { + if "$@" > "$TEMP/rejected" 2>&1; then fail "unexpected success: $*"; fi +} + +fixture new +ISSUE_MODE=fail +reject issue +if ! live_is old || ! legacy_is_intact; then fail 'failed dual-stack order changed prior certificate or ACME state'; fi +reject issue 198.51.100.9 "$TEMP/first" +[[ ! -e "$legacy/198.51.100.9_ecc" && ! -e "$TEMP/first/fullchain.pem" ]] || fail 'failed first order left public files or a renewable entry' +ISSUE_MODE=ok +for mode in fail no-key no-chain; do + INSTALL_MODE="$mode" + reject issue + if ! live_is old || ! legacy_is_intact; then fail "$mode installation changed prior certificate or ACME state"; fi done -ISSUED_CERT="$TEMP/new.pem"; ISSUED_KEY="$TEMP/old.key" -if ip_ssl_issue_and_install "$acme" 198.51.100.8 '' "$port" "$cert_dir" "$reload"; then fail 'mismatched private key accepted'; fi -cmp "$TEMP/new.key" "$cert_dir/privkey.pem" || fail 'mismatched key was not rolled back' -ACME_INSTALL_FAIL=1 -if ip_ssl_issue_and_install "$acme" 198.51.100.8 '' "$port" "$cert_dir" "$reload"; then fail 'partial installation accepted'; fi -cmp "$TEMP/new.pem" "$cert_dir/fullchain.pem" || fail 'partial install was not rolled back' -ACME_INSTALL_FAIL=0 -ISSUED_CERT="$TEMP/old.pem"; ISSUED_KEY="$TEMP/old.key"; ACME_RELOAD_FAIL=1 -ip_ssl_issue_and_install "$acme" 198.51.100.8 '' "$port" "$cert_dir" "$reload" -cmp "$TEMP/old.pem" "$cert_dir/fullchain.pem" || fail 'reload error discarded valid newly installed cert' -printf 'PASS: SAN/key mismatch and partial-install rollback; valid copy survives reload errors\n' +INSTALL_MODE=ok +for invalid in v4 dns; do + fixture "$invalid" + reject issue + if ! live_is old || ! legacy_is_intact; then fail 'missing IP SAN changed prior certificate or ACME state'; fi +done +fixture new old +reject issue +if ! live_is old || ! legacy_is_intact; then fail 'wrong key changed prior certificate or ACME state'; fi + +fixture new +# Fault hooks are called indirectly by the sourced lifecycle functions. +# shellcheck disable=SC2317 +chmod() { + if [[ "$1" == 600 && "$*" == *'/gen.'* ]]; then return 1; fi + command chmod "$@" +} +reject issue +unset -f chmod +if ! live_is old || ! legacy_is_intact; then fail 'chmod failure changed prior certificate or ACME state'; fi +printf 'PASS: issuance, installation, SAN, key, partial and permission failures preserve prior state\n' + +# shellcheck disable=SC2317 +mv() { + if [[ "$*" == *'.xui-retired-'* && "${!#}" == "$legacy/${ipv4}_ecc" ]]; then return 1; fi + command mv "$@" +} +ISSUE_MODE=fail +reject issue +grep -Fq "$state/pending" "$TEMP/rejected" || fail 'journal location missing from recovery error' +compgen -G "$legacy/.xui-retired-*-${ipv4}_ecc" >/dev/null || fail 'only renewal recovery copy was discarded' +unset -f mv +reject issue +legacy_is_intact || fail 'subsequent attempt did not finish ACME recovery' +ISSUE_MODE=ok + +# shellcheck disable=SC2317 +mv() { + if [[ "${!#}" == "$cert_dir/privkey.pem" || ( "$*" == *'/pending/restore '* && "${!#}" == "$cert_dir/fullchain.pem" ) ]]; then + return 1 + fi + command mv "$@" +} +reject issue +grep -Fq "$state/pending" "$TEMP/rejected" || fail 'live recovery error omitted journal location' +cmp "$TEMP/old.pem" "$state/pending/live/fullchain.pem" || fail 'live recovery copy was lost' +unset -f mv +ISSUE_MODE=fail +reject issue +if ! live_is old || ! legacy_is_intact; then fail 'subsequent attempt did not finish live restoration'; fi +[[ ! -L "$cert_dir/fullchain.pem" ]] || fail 'original regular file type was not recovered' +ISSUE_MODE=ok + +# shellcheck disable=SC2317 +mv() { + command mv "$@" || return + if [[ "${!#}" == "$cert_dir/fullchain.pem" && "$*" == *'/pending/link '* ]]; then kill -KILL "$BASHPID"; fi +} +reject issue +unset -f mv +if [[ ! -d "$state/pending" ]] || ! live_is old; then fail 'interrupted transition exposed a mixed pair'; fi +ISSUE_MODE=fail +reject issue +if ! live_is old || ! legacy_is_intact; then fail 'interrupted transition failed to recover'; fi +ISSUE_MODE=ok +printf 'PASS: restoration failures retain backups and interruptions recover on next run\n' + +: > "$ACME_LOG" +RELOAD_FAIL=1 +issue +if ! live_is new || [[ ! -f "$state/current/reload-pending" ]]; then fail 'reload failure discarded valid deployment'; fi +[[ "$(stat -Lc %a "$cert_dir/privkey.pem")" == 600 ]] || fail 'private key permissions changed' +[[ "$(stat -Lc %a "$cert_dir/fullchain.pem")" == 644 ]] || fail 'certificate permissions changed' +[[ ! -e "$legacy/$ipv4" && ! -e "$legacy/${ipv4}_ecc" ]] || fail 'old cron can still target live paths' +[[ "$(grep -cx 'arg=--listen-v4' "$ACME_LOG")" == 1 && "$(grep -cx 'arg=--listen-v6' "$ACME_LOG")" == 1 ]] || fail 'dual-stack flags absent' +[[ "$(grep -cx "arg=$ipv6" "$ACME_LOG")" == 1 ]] || fail 'IPv6 SAN duplicated or missing' +grep -Fq '/unrelated-cron' "$CRON_FILE" || fail 'crontab lost an unrelated entry' +[[ "$(grep -c 'x-ui managed IP certificate' "$CRON_FILE")" == 1 ]] || fail 'persistent cron missing or duplicated' +cmp "$TEMP/account.conf" "${acme%/*}/account.conf" || fail 'global account config changed' +grep -qx 'unrelated certificate' "$legacy/example.net_ecc/marker" +export RELOAD_FAIL=0 RENEW_MODE=skip +"$runner" +[[ ! -f "$state/current/reload-pending" && "$(cat "$RELOAD_LOG")" == reloaded ]] || fail 'fresh-shell reload retry failed' +printf 'PASS: validated commit preserves modes, retires old live destinations and retries panel reload\n' + +working=$(readlink "$state/current") +working_conf="$state/current/acme/${ipv4}_ecc/$ipv4.conf" +cp "$working_conf" "$TEMP/working.conf" +RENEW_MODE=ok +for invalid in v4 expired; do fixture "$invalid"; reject "$runner"; live_is new || fail "$invalid renewal exposed invalid files"; done +fixture later old +reject "$runner" +live_is new || fail 'wrong renewal key replaced live pair' +fixture later +for mode in no-key no-chain; do INSTALL_MODE="$mode"; reject "$runner"; done +INSTALL_MODE=ok +if ! live_is new || ! cmp "$TEMP/working.conf" "$working_conf"; then fail 'rejected renewal committed advanced ACME state'; fi +[[ "$(readlink "$state/current")" == "$working" ]] || fail 'rejected renewal changed generation' +# Start a fresh TLS process using the unchanged panel paths after rejecting a renewal. +( + openssl s_server -quiet -www -accept "127.0.0.1:$port" -cert "$cert_dir/fullchain.pem" \ + -key "$cert_dir/privkey.pem" > "$TEMP/tls.log" 2>&1 & + tls_pid=$! + trap 'if kill -0 "$tls_pid" 2>/dev/null; then kill "$tls_pid"; fi; wait "$tls_pid" 2>/dev/null || [[ $? == 143 ]]' EXIT + for ((attempt=0; attempt<100; attempt++)); do + kill -0 "$tls_pid" || break + if curl --noproxy '*' --silent --fail --cacert "$SSL_CERT_FILE" --connect-timeout 1 --max-time 3 \ + --connect-to "$ipv4:$port:127.0.0.1:$port" "https://$ipv4:$port/" >/dev/null; then exit 0; fi + sleep .01 + done + cat "$TEMP/tls.log" >&2 + fail 'TLS restart could not load the last known-good certificate' +) +# shellcheck disable=SC2317 +mv() { + if [[ "${!#}" == "$state/current" ]]; then return 1; fi + command mv "$@" +} +reject ip_ssl_scheduled "$cert_dir" +unset -f mv +if ! live_is new || ! cmp "$TEMP/working.conf" "$working_conf"; then fail 'promotion failure damaged the previous generation'; fi +"$runner" +if ! live_is later || ! grep -q advanced "$working_conf"; then fail 'valid persistent renewal did not commit files and ACME state'; fi +printf 'PASS: actual TLS startup can read last known-good pair after rejected renewals; valid renewal promotes both files\n' + +# Pause renewal while it holds the destination lock. An unrelated destination +# completes during the wait, while two competing manual requests share the lock. +export RENEW_BARRIER="$TEMP/renewal" +mkfifo "$RENEW_BARRIER" +fixture v4 +"$runner" > "$TEMP/concurrent-renewal" 2>&1 & +renew_pid=$! +for ((attempt=0; attempt<500; attempt++)); do + [[ ! -f "$RENEW_BARRIER.ready" ]] || break + sleep .01 +done +[[ -f "$RENEW_BARRIER.ready" ]] || fail 'renewal did not reach the deterministic barrier' +if flock -n "$state/lock" true; then fail 'renewal was not holding the destination lock'; fi +fixture old +issue "$ipv4" > "$TEMP/concurrent-manual" 2>&1 & +manual_pid=$! +fixture new +issue 198.51.100.9 > "$TEMP/concurrent-invalid" 2>&1 & +invalid_pid=$! +issue "$ipv4" "$TEMP/independent" +live_is later || fail 'a competing request changed live files while renewal held the lock' +printf 'continue\n' > "$RENEW_BARRIER" +if wait "$renew_pid"; then fail 'invalid concurrent renewal succeeded'; fi +wait "$manual_pid" || { cat "$TEMP/concurrent-manual"; fail 'concurrent manual issuance failed'; } +if wait "$invalid_pid"; then fail 'wrong identifier unexpectedly committed'; fi +live_is old || fail 'failed operation rolled back newer successful deployment' +unset RENEW_BARRIER +printf 'PASS: manual, renewal and shared-destination promotion serialize; unrelated destination progresses\n' + +# Fail the first pointer swap while a second valid operation is waiting to +# promote. Its new state must survive cleanup of the earlier transaction. +promotion="$TEMP/promotion" +mkfifo "$promotion" +# shellcheck disable=SC2317 +mv() { + if [[ "${!#}" == "$state/current" && "${FAIL_PROMOTION:-0}" == 1 ]]; then + : > "$promotion.ready" + read -r _ < "$promotion" + return 1 + fi + command mv "$@" +} +fixture new +FAIL_PROMOTION=1 issue > "$TEMP/failed-promotion" 2>&1 & +failed_pid=$! +for ((attempt=0; attempt<500; attempt++)); do + [[ ! -f "$promotion.ready" ]] || break + sleep .01 +done +[[ -f "$promotion.ready" ]] || fail 'first operation did not reach promotion' +fixture later +issue > "$TEMP/waiting-promotion" 2>&1 & +waiting_pid=$! +if flock -n "$state/lock" true; then fail 'promotion was not holding the destination lock'; fi +live_is old || fail 'uncommitted promotion changed live files' +printf 'continue\n' > "$promotion" +if wait "$failed_pid"; then fail 'injected promotion failure reported success'; fi +wait "$waiting_pid" || { cat "$TEMP/waiting-promotion"; fail 'second promotion failed'; } +unset -f mv +live_is later || fail 'rollback overwrote a newer promotion' +printf 'PASS: a failed promotion cannot roll back another operation on the same paths\n' before=$(wc -l < "$ACME_LOG") -if ip_ssl_issue_and_install "$acme" 198.51.100.8 "2001:4860::1;touch $TEMP/injected" "$port" "$cert_dir" "$reload"; then fail 'injection accepted'; fi +reject ip_ssl_issue_and_install "$acme" "$ipv4" "$ipv6;touch $TEMP/injected" "$port" "$cert_dir" "$reload" [[ ! -e "$TEMP/injected" && "$(wc -l < "$ACME_LOG")" == "$before" ]] || fail 'invalid IP reached shell or ACME' printf 'PASS: invalid SAN never reaches ACME or a shell command\n' @@ -147,7 +401,7 @@ ip() { [[ "$*" != '-6 route get '* ]] || return 0 printf '2: eth0 inet6 2001:4860::1/64 scope global valid_lft forever preferred_lft forever\n' } -ACME_RELOAD_FAIL=0; ISSUED_CERT="$TEMP/new.pem"; ISSUED_KEY="$TEMP/new.key" +fixture new source_function "$ROOT/x-ui.sh" confirm source_function "$ROOT/x-ui.sh" ssl_cert_issue_for_ip if ! ssl_cert_issue_for_ip "$TEMP/menu-cert" <<< "$(printf 'y\ny\n%s\ny\n' "$port")" > "$TEMP/menu-output" 2>&1; then diff --git a/scripts/test/ip-ssl-entrypoint-test.sh b/scripts/test/ip-ssl-entrypoint-test.sh index 259529f51..b21d0b839 100644 --- a/scripts/test/ip-ssl-entrypoint-test.sh +++ b/scripts/test/ip-ssl-entrypoint-test.sh @@ -24,6 +24,9 @@ prompt_and_setup_ssl 2053 / 198.51.100.8 > "$TEMP/invalid" 2>&1 || fail 'an inva grep -q 'Invalid public IPv6' "$TEMP/invalid" || fail 'invalid environment value has no clear diagnostic' [[ "$SSL_HOST" == 198.51.100.8 ]] || fail 'the installer lost its access host after skipping the certificate' unset XUI_SSL_IPV6 +called=0; stopped=0 +prompt_and_setup_ssl 2053 / 198.51.100.900 > "$TEMP/invalid-v4" 2>&1 || fail 'an invalid IPv4 aborted the installer' +[[ "$called" == 0 && "$stopped" == 0 ]] || fail 'invalid IPv4 stopped panel or reached issuance' called=0 prompt_and_setup_ssl 2053 / 198.51.100.8 "$TEMP/unattended" 2>&1 [[ "$called" == 1 && -z "$captured" ]] || fail 'unattended unset override did not retain IPv4-only issuance' diff --git a/x-ui.sh b/x-ui.sh index b64258aab..04b4e41a9 100644 --- a/x-ui.sh +++ b/x-ui.sh @@ -266,91 +266,396 @@ ip_ssl_shell_quote() { printf "'%s'" "$value" } +# The public paths always resolve through one generation pointer after migration. +ip_ssl_link() { + local state="$1" target="$2" link="$3" + rm -f -- "$state/pending/link" && + ln -s -- "$target" "$state/pending/link" && + mv -Tf -- "$state/pending/link" "$link" +} + +ip_ssl_lock() { + local dir="$1" state="$1/.xui-ip-ssl" + command -v flock >/dev/null || { printf 'IP certificates require flock. Install it and retry.\n' >&2; return 1; } + umask 077 + mkdir -p -- "$dir" || return 1 + [[ -d "$dir" && ! -L "$dir" && -O "$dir" ]] || return 1 + chmod go-w -- "$dir" || return 1 + [[ ! -L "$state" ]] && mkdir -p -- "$state" && [[ -O "$state" ]] && chmod 700 -- "$state" || return 1 + exec 9>>"$state/lock" || return 1 + flock -x 9 +} + +# An old cron can have sourced a legacy config already. Check on both sides +# of retiring its entries. Managed renewals always take the destination lock. +ip_ssl_legacy_busy() { + local acme="$1" cmdline arg found action + for cmdline in /proc/[0-9]*/cmdline; do + [[ -r "$cmdline" ]] || continue + found=0 action=0 + { + while IFS= read -r -d '' arg; do + if [[ "$arg" == "$acme" ]]; then + found=1 + elif ((found)); then + case "$arg" in + --cron|--renew|--renew-all|--renewAll|--renewall|--issue|--install-cert|--installcert|--deploy) action=1 ;; + esac + fi + done + } < "$cmdline" 2>/dev/null || continue + if ((found && action)); then return 0; fi + done + return 1 +} + +ip_ssl_retire_legacy() { + local state="$1" acme="$2" ipv4="$3" dir="$4" gen="$5" home="$6" + local entry name conf value destination destinations + local -a retire=() + for entry in "$home"/*; do + [[ -d "$entry" && ! -L "$entry" ]] || continue + name="${entry##*/}" + ip_ssl_ipv4 "${name%_ecc}" || continue + conf="$entry/${name%_ecc}.conf" + [[ -f "$conf" ]] || continue + # Retire every legacy IP entry sharing this destination, including an older primary IP. + destinations=$(sed -n "s/^Le_Real\(FullChain\|Cert\|Key\|CACert\)Path='\(.*\)'$/\2/p" "$conf") || return 1 + while IFS= read -r value; do + case "${value##*/}" in fullchain.pem|privkey.pem) ;; *) continue ;; esac + destination=$(cd -P -- "${value%/*}" 2>/dev/null && pwd -P) || continue + if [[ "$destination" == "$dir" ]]; then + retire+=("$name") + break + fi + done <<< "$destinations" + done + # The requested entries can also be unfinished orders with no destinations. + for name in "$ipv4" "${ipv4}_ecc"; do + entry="$home/$name" + conf="$entry/$ipv4.conf" + [[ -d "$entry" && ! -L "$entry" ]] || continue + if [[ ! -f "$conf" ]] || ! grep -Eq "^Le_(Real(Cert|Key|CACert|FullChain)Path|ReloadCmd|DeployHook)='[^']+" "$conf"; then + retire+=("$name") + fi + done + ((${#retire[@]})) || return 0 + if ip_ssl_legacy_busy "$acme"; then + printf 'Wait for the existing acme.sh command to finish, then retry IP certificate setup.\n' >&2 + return 1 + fi + for name in "${retire[@]}"; do + [[ -d "$home/$name" ]] || continue + # Journal before the same-directory rename so a crash can restore it. + printf '%s\n' "$name" >> "$state/pending/legacy" && + mv -T -- "$home/$name" "$home/.xui-retired-$gen-$name" || return 1 + done + if ip_ssl_legacy_busy "$acme"; then + printf 'An existing acme.sh command started during migration. Retry IP certificate setup after it exits.\n' >&2 + return 1 + fi +} + +ip_ssl_recover() { + local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending" + local gen='' home='' current='' entry held file name failed=0 previous='' + [[ -d "$pending" ]] || return 0 + if [[ -f "$pending/generation" ]]; then + if ! IFS= read -r gen < "$pending/generation" || [[ ! "$gen" =~ ^gen\.[a-zA-Z0-9]+$ ]]; then + printf 'Invalid IP certificate generation journal. Keep recovery files at %s.\n' "$pending" >&2 + return 1 + fi + fi + current=$(readlink -- "$state/current") || current='' + if [[ -f "$pending/home" ]] && ! IFS= read -r home < "$pending/home"; then + printf 'Invalid ACME home in the IP certificate journal. Keep recovery files at %s.\n' "$pending" >&2 + return 1 + fi + + if [[ -n "$gen" && "$current" == "$gen" ]]; then + # Commit is the pointer swap. Never roll back a committed generation. + if [[ -f "$pending/legacy" ]]; then + while IFS= read -r entry; do + ip_ssl_ipv4 "${entry%_ecc}" && [[ -n "$home" ]] && + rm -rf -- "$home/.xui-retired-$gen-$entry" || failed=1 + done < "$pending/legacy" + fi + if [[ -f "$state/$gen/previous" ]]; then IFS= read -r previous < "$state/$gen/previous" || failed=1; fi + for entry in "$state"/gen.*; do + name="${entry##*/}" + [[ "$name" != "$gen" && "$name" != "$previous" ]] || continue + rm -rf -- "$entry" || failed=1 + done + else + if [[ -f "$pending/live-changing" ]]; then + for file in fullchain.pem privkey.pem; do + if [[ -e "$pending/live/$file" || -L "$pending/live/$file" ]]; then + rm -f -- "$pending/restore" && + cp -a -- "$pending/live/$file" "$pending/restore" && + mv -Tf -- "$pending/restore" "$dir/$file" || failed=1 + else + rm -f -- "$dir/$file" || failed=1 + fi + done + fi + # Keep stock cron away from the public paths until the original file + # types are restored. A failed restore may still leave a live alias. + if ((!failed)) && [[ -f "$pending/legacy" ]]; then + while IFS= read -r entry; do + if ! ip_ssl_ipv4 "${entry%_ecc}" || [[ -z "$home" || -z "$gen" ]]; then failed=1; continue; fi + held="$home/.xui-retired-$gen-$entry" + if [[ -e "$held" ]]; then + if [[ -e "$home/$entry" || -L "$home/$entry" ]] || + ! mv -T -- "$held" "$home/$entry"; then + printf 'ACME recovery copy remains at %s\n' "$held" >&2 + failed=1 + fi + elif [[ ! -d "$home/$entry" ]]; then + failed=1 + fi + done < "$pending/legacy" + fi + if ((!failed)) && [[ -n "$gen" ]]; then rm -rf -- "${state:?}/${gen:?}" || failed=1; fi + fi + if ((failed)); then + printf 'IP certificate recovery could not complete. Keep recovery files at %s and retry after resolving the error.\n' "$pending" >&2 + return 1 + fi + if ! rm -f -- "$state/staging/fullchain.pem" "$state/staging/privkey.pem" || ! rm -rf -- "$pending"; then + printf 'Could not remove the IP certificate journal at %s\n' "$pending" >&2 + return 1 + fi +} + +ip_ssl_aliases() { + local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending" + local file seed + if [[ -f "$state/current/config" ]]; then + for file in fullchain.pem privkey.pem; do + [[ "$(readlink -- "$dir/$file")" == ".xui-ip-ssl/current/$file" ]] || return 1 + done + return 0 + fi + # The seed contains the original bytes, so converting either alias first + # still exposes the same pair. The journal keeps the original file types. + seed=$(mktemp -d "$state/gen.XXXXXX") || return 1 + for file in fullchain.pem privkey.pem; do + if [[ -e "$pending/live/$file" || -L "$pending/live/$file" ]]; then + # Follow the original live symlink relative to its own directory. + cp -pL -- "$dir/$file" "$seed/$file" || return 1 + fi + done + ip_ssl_link "$state" "${seed##*/}" "$state/current" && + touch "$pending/live-changing" || return 1 + for file in fullchain.pem privkey.pem; do + ip_ssl_link "$state" ".xui-ip-ssl/current/$file" "$dir/$file" || return 1 + done +} + +ip_ssl_validate_pair() { + local chain="$1" key="$2" ipv4="$3" ipv6="$4" cert_pub key_pub + [[ -s "$chain" && -s "$key" ]] && + openssl crl2pkcs7 -nocrl -certfile "$chain" -out /dev/null && + openssl verify -purpose sslserver -untrusted "$chain" -verify_ip "$ipv4" "$chain" >/dev/null || return 1 + [[ -z "$ipv6" ]] || openssl verify -purpose sslserver -untrusted "$chain" -verify_ip "$ipv6" "$chain" >/dev/null || return 1 + cert_pub=$(openssl x509 -in "$chain" -pubkey -noout) && + key_pub=$(openssl pkey -in "$key" -passin pass: -pubout) && + [[ -n "$cert_pub" && "$cert_pub" == "$key_pub" ]] +} + +ip_ssl_reload() { + local gen="$1" reload="$2" + if sh -c "$reload" 9>&-; then + rm -f -- "$gen/reload-pending" || + printf 'Could not clear the IP certificate reload marker.\n' >&2 + else + printf 'A valid certificate is installed. Panel reload failed and will be retried by the IP certificate job.\n' >&2 + fi +} + +ip_ssl_schedule() ( + local state="$1" home="$2" command line existing + [[ "$state" != *[$'\n\r%']* ]] || return 1 + # Different destinations share the user's crontab, but can order and stage in parallel. + exec 8>>"$home/.xui-ip-crontab.lock" && flock -x 8 || return 1 + command=$(ip_ssl_shell_quote "$state/renew-v1") + line="19 * * * * $command # x-ui managed IP certificate" + if ! existing=$(LC_ALL=C crontab -l 2>&1); then + case "$existing" in + *"no crontab for "*|*"No such file or directory"*) existing='' ;; + *) printf 'Could not read crontab: %s\n' "$existing" >&2; return 1 ;; + esac + fi + if grep -Fxq -- "$line" <<< "$existing"; then return 0; fi + { printf '%s\n' "$existing"; printf '%s\n' "$line"; } | crontab - +) + +ip_ssl_account_config() ( + local home="$1" cert_home="$2" ACCOUNT_CONF_PATH='' + # acme.sh sources account.conf after parsing --cert-home, so a saved + # CERT_HOME overrides the command line. Keep this override private. + if [[ -f "$home/account.conf" ]]; then + # shellcheck disable=SC1091 + source "$home/account.conf" || return 1 + fi + local original="${ACCOUNT_CONF_PATH:-$home/account.conf}" + if [[ -f "$original" ]]; then cat -- "$original" || return 1; fi + printf '\nCERT_HOME=%s\n' "$(ip_ssl_shell_quote "$cert_home")" +) + +ip_ssl_legacy_home() ( + local home="$1" ACCOUNT_CONF_PATH='' CERT_HOME='' + if [[ -f "$home/account.conf" ]]; then + # shellcheck disable=SC1091 + source "$home/account.conf" || return 1 + fi + if [[ -n "$ACCOUNT_CONF_PATH" && -f "$ACCOUNT_CONF_PATH" ]]; then + # shellcheck disable=SC1090 + source "$ACCOUNT_CONF_PATH" || return 1 + fi + printf '%s\n' "${CERT_HOME:-$home}" +) + +ip_ssl_transaction() ( + local action="$1" acme="$2" ipv4="$3" ipv6="$4" port="$5" dir="$6" reload="$7" + local state="$dir/.xui-ip-ssl" pending="$dir/.xui-ip-ssl/pending" home="${acme%/*}" + local work gen file previous rc legacy_home stage="$dir/.xui-ip-ssl/staging" + local -a scope domains=(-d "$ipv4") + mkdir -- "$pending" || return 1 + # Recovery runs under the caller's flock, including on normal exit. + trap 'rc=$?; ip_ssl_recover "$dir" || rc=1; exit "$rc"' EXIT + trap 'exit 130' INT + trap 'exit 143' TERM + trap 'exit 129' HUP + + work=$(mktemp -d "$state/gen.XXXXXX") || return 1 + gen="${work##*/}" + printf '%s\n' "$gen" > "$pending/generation" && mkdir -- "$work/acme" "$pending/live" || return 1 + if [[ "$action" == issue ]]; then + legacy_home=$(ip_ssl_legacy_home "$home") || return 1 + [[ "$legacy_home" == /* && "$legacy_home" != *[$'\n\r']* ]] || return 1 + printf '%s\n' "$legacy_home" > "$pending/home" && + ip_ssl_retire_legacy "$state" "$acme" "$ipv4" "$dir" "$gen" "$legacy_home" || return 1 + fi + for file in fullchain.pem privkey.pem; do + [[ ! -e "$dir/$file" && ! -L "$dir/$file" ]] || + cp -a -- "$dir/$file" "$pending/live/$file" || return 1 + done + if [[ -f "$state/current/config" ]]; then + previous=$(readlink -- "$state/current") && + printf '%s\n' "$previous" > "$work/previous" || return 1 + fi + if [[ "$action" != issue ]]; then + cp -a -- "$state/current/acme/." "$work/acme/" || return 1 + fi + [[ ! -L "$stage" ]] && mkdir -p -- "$stage" && chmod 700 -- "$stage" && + rm -f -- "$stage/fullchain.pem" "$stage/privkey.pem" || return 1 + ip_ssl_account_config "$home" "$work/acme" > "$pending/account.conf" || return 1 + scope=(--home "$home" --cert-home "$work/acme" --accountconf "$pending/account.conf") + # acme.sh saves destinations in single quotes. A fixed private working + # directory makes relative install paths safe even with a quoted parent. + cd -- "$state" || return 1 + if [[ "$action" == issue ]]; then + [[ -z "$ipv6" ]] || domains+=(-d "$ipv6") + if ! "$acme" --issue "${scope[@]}" "${domains[@]}" --keylength ec-256 --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ + --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then + printf 'IP certificate issuance failed. Check external port 80 on each selected address.\n' >&2 + return 1 + fi + else + rc=0 + local -a force=() + [[ "$action" != renew-force ]] || force=(--force) + "$acme" --renew "${scope[@]}" -d "$ipv4" --ecc "${force[@]}" || rc=$? + # acme.sh uses 2 when a certificate is not due for renewal. + if ((rc == 2)); then return 0; fi + ((rc == 0)) || return "$rc" + fi + # A renewal may already have copied to staging. Require both outputs from + # this explicit install so an incomplete copy cannot reuse an older file. + rm -f -- "$stage/fullchain.pem" "$stage/privkey.pem" || return 1 + if ! "$acme" --installcert "${scope[@]}" --ecc -d "$ipv4" --key-file staging/privkey.pem \ + --fullchain-file staging/fullchain.pem --reloadcmd ""; then + printf 'Could not stage the IP certificate and key.\n' >&2 + return 1 + fi + if ! ip_ssl_validate_pair "$stage/fullchain.pem" "$stage/privkey.pem" "$ipv4" "$ipv6"; then + printf 'Staged IP certificate failed SAN, validity or private-key checks.\n' >&2 + return 1 + fi + cp -- "$stage/privkey.pem" "$work/privkey.pem" && + cp -- "$stage/fullchain.pem" "$work/fullchain.pem" && + chmod 600 -- "$work/privkey.pem" && chmod 644 -- "$work/fullchain.pem" && + printf 'managed_acme=%q\nmanaged_ipv4=%q\nmanaged_ipv6=%q\nmanaged_reload=%q\n' "$acme" "$ipv4" "$ipv6" "$reload" > "$work/config" && + touch "$work/reload-pending" || return 1 + if [[ "$action" == issue ]]; then ip_ssl_schedule "$state" "$home" || return 1; fi + ip_ssl_aliases "$dir" && + ip_ssl_link "$state" "$gen" "$state/current" || return 1 + ip_ssl_reload "$work" "$reload" +) + +ip_ssl_scheduled() ( + local dir="$1" state="$1/.xui-ip-ssl" action="${2:-renew}" + local managed_acme managed_ipv4 managed_ipv6 managed_reload + ip_ssl_lock "$dir" && ip_ssl_recover "$dir" || return 1 + [[ -f "$state/current/config" ]] || return 0 + # This file is generated with Bash quoting under the private state directory. + # shellcheck disable=SC1091 + source "$state/current/config" || return 1 + if [[ -f "$state/current/reload-pending" ]]; then ip_ssl_reload "$state/current" "$managed_reload"; fi + ip_ssl_transaction "$action" "$managed_acme" "$managed_ipv4" "$managed_ipv6" '' "$dir" "$managed_reload" +) + +ip_ssl_revoke_managed() ( + local dir="$1" state="$1/.xui-ip-ssl" managed_acme managed_ipv4 gen account + ip_ssl_lock "$dir" && ip_ssl_recover "$dir" || return 1 + [[ -f "$state/current/config" ]] || return 1 + # shellcheck disable=SC1091 + source "$state/current/config" || return 1 + account=$(mktemp "$state/.account.XXXXXX") || return 1 + trap 'rm -f -- "$account"' EXIT + ip_ssl_account_config "${managed_acme%/*}" "$state/current/acme" > "$account" || return 1 + "$managed_acme" --revoke --home "${managed_acme%/*}" --cert-home "$state/current/acme" --accountconf "$account" -d "$managed_ipv4" --ecc || + printf 'CA revocation failed. Removing local renewal state and files.\n' >&2 + # Keep the lock inode and inert scheduled runner for later issuance. + rm -f -- "$state/current" "$dir/fullchain.pem" "$dir/privkey.pem" || return 1 + for gen in "$state"/gen.*; do rm -rf -- "$gen" || return 1; done +) + +ip_ssl_write_runner() { + local state="$1" temp + temp=$(mktemp "$state/.runner.XXXXXX") || return 1 + if { + printf '#!/bin/bash\n# x-ui managed IP certificate deployment v1\n' + # The OpenRC service commands live in /sbin on Alpine. + # shellcheck disable=SC2016 + printf 'export PATH="${PATH:+$PATH:}/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"\n' + declare -f ip_ssl_ipv4 ip_ssl_shell_quote ip_ssl_link ip_ssl_lock ip_ssl_legacy_busy \ + ip_ssl_retire_legacy ip_ssl_recover ip_ssl_aliases ip_ssl_validate_pair ip_ssl_reload \ + ip_ssl_schedule ip_ssl_account_config ip_ssl_legacy_home ip_ssl_transaction ip_ssl_scheduled + # shellcheck disable=SC2016 + printf '\nip_ssl_scheduled "$(cd -- "$(dirname -- "$0")/.." && pwd -P)"\n' + } > "$temp" && chmod 700 -- "$temp" && mv -Tf -- "$temp" "$state/renew-v1"; then + return 0 + fi + rm -f -- "$temp" || printf 'Could not remove incomplete renewal helper %s\n' "$temp" >&2 + return 1 +} + ip_ssl_issue_and_install() ( - local acme="$1" ipv4="$2" ipv6="$3" port="$4" cert_dir="$5" reload="$6" - local stage='' attempted=0 installed=0 code=0 file restored - local acme_home="${acme%/*}" renewal_backup entry - local quoted_cert quoted_key validation check_key reload_guard - local -a domain_args=(-d "$ipv4") + local acme="$1" ipv4="$2" ipv6="$3" port="$4" dir="$5" reload="$6" if ! ip_ssl_ipv4 "$ipv4" || { [[ -n "$ipv6" ]] && ! ip_ssl_public_ipv6 "$ipv6"; }; then printf 'Invalid IP certificate identifier; no ACME request was sent.\n' >&2 return 1 fi [[ "$port" =~ ^[0-9]{1,5}$ ]] && ((10#$port >= 1 && 10#$port <= 65535)) || return 1 - [[ -z "$ipv6" ]] || domain_args+=(-d "$ipv6") - ip_ssl_prepare_listener "$acme" "$port" "$ipv6" || return 1 - renewal_backup=$(mktemp -d "$acme_home/.xui-acme.XXXXXX") || return 1 - for entry in "$ipv4" "${ipv4}_ecc"; do - [[ ! -d "$acme_home/$entry" ]] || cp -a -- "$acme_home/$entry" "$renewal_backup/$entry" || { - rm -rf -- "$renewal_backup" - return 1 - } - done - if ! "$acme" --issue "${domain_args[@]}" --standalone "${IP_SSL_LISTEN_ARGS[@]}" \ - --server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then - # acme.sh saves the requested names before it places the order, so a failed one would - # make cron renew the working certificate with the names that just failed. - for entry in "$ipv4" "${ipv4}_ecc"; do - rm -rf -- "${acme_home:?}/$entry" - [[ ! -d "$renewal_backup/$entry" ]] || mv -- "$renewal_backup/$entry" "$acme_home/$entry" - done - rm -rf -- "$renewal_backup" - printf 'IP certificate issuance failed. Existing certificates and ACME data were preserved. Check external port 80 on every selected address.\n' >&2 - return 1 - fi - rm -rf -- "$renewal_backup" - - umask 077 - mkdir -p "$cert_dir" || return 1 - stage=$(mktemp -d "$cert_dir/.xui-install.XXXXXX") || return 1 - # Invoked indirectly by the EXIT trap; older ShellCheck reports SC2317. - # shellcheck disable=SC2317,SC2329 - ip_ssl_install_cleanup() { - restored=1 - if ((attempted && !installed)); then - for file in fullchain.pem privkey.pem; do - if [[ -f "$stage/$file" ]]; then - cp -p -- "$stage/$file" "$cert_dir/$file" || restored=0 - else - rm -f -- "$cert_dir/$file" || restored=0 - fi - done - fi - if ((restored)); then - rm -rf -- "$stage" - else - printf 'Could not restore certificate files; recovery copies remain in %s\n' "$stage" >&2 - fi - } - trap ip_ssl_install_cleanup EXIT - for file in fullchain.pem privkey.pem; do - [[ ! -e "$cert_dir/$file" ]] || cp -p -- "$cert_dir/$file" "$stage/$file" || return 1 - done - quoted_cert=$(ip_ssl_shell_quote "$cert_dir/fullchain.pem") - quoted_key=$(ip_ssl_shell_quote "$cert_dir/privkey.pem") - # Trust the leaf only for local identity checks, not as a new system CA. - validation="openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv4' $quoted_cert" - [[ -z "$ipv6" ]] || validation+=" && openssl verify -trusted $quoted_cert -partial_chain -verify_ip '$ipv6' $quoted_cert" - # Expansion belongs to the later reload shell, including cron renewals. - # shellcheck disable=SC2016 - printf -v check_key 'xui_cert_pub=$(openssl x509 -in %s -pubkey -noout) && xui_key_pub=$(openssl pkey -in %s -passin pass: -pubout) && [ -n "$xui_cert_pub" ] && [ "$xui_cert_pub" = "$xui_key_pub" ]' "$quoted_cert" "$quoted_key" - validation+=" && $check_key" - # acme.sh persists this self-contained guard for later cron renewals too. - reload_guard="$validation && { $reload; }" - attempted=1 - "$acme" --installcert --force -d "$ipv4" --key-file "$cert_dir/privkey.pem" \ - --fullchain-file "$cert_dir/fullchain.pem" --reloadcmd "$reload_guard" || code=$? - if ! sh -c "$validation" > /dev/null 2>&1; then - printf 'Installed certificate failed IP SAN, validity or private-key checks; restoring previous files.\n' >&2 - return 1 - fi - if ((code != 0)) && [[ -f "$stage/fullchain.pem" ]] && [[ "$(cat "$stage/fullchain.pem")" == "$(cat "$cert_dir/fullchain.pem")" ]]; then - printf 'Certificate installation failed without replacing the previous certificate.\n' >&2 - return 1 - fi - chmod 600 "$cert_dir/privkey.pem" && chmod 644 "$cert_dir/fullchain.pem" || return 1 - installed=1 - if ((code != 0)); then printf 'Certificate files are valid, but the reload command reported an error.\n' >&2; fi + [[ "$acme" == /* && "$acme" != *[$'\n\r']* && "$dir" == /* && "$dir" != *[$'\n\r%']* ]] || return 1 + command -v crontab >/dev/null || { printf 'IP certificate renewal requires crontab.\n' >&2; return 1; } + ip_ssl_lock "$dir" && dir=$(cd -- "$dir" && pwd -P) && acme=$(readlink -f -- "$acme") && + ip_ssl_recover "$dir" || return 1 + ip_ssl_prepare_listener "$acme" "$port" "$ipv6" && + ip_ssl_write_runner "$dir/.xui-ip-ssl" && + ip_ssl_transaction issue "$acme" "$ipv4" "$ipv6" "$port" "$dir" "$reload" ) # END GENERATED IP SSL HELPERS is_ip() { @@ -1797,7 +2102,13 @@ ssl_cert_issue_main() { # tracks the cert under the actual IP address(es). Resolve those so renewal # state is torn down too; otherwise the acme.sh cron re-creates the deleted cert. local acme_ids="${domain}" - if [[ "${domain}" == "ip" ]]; then + if [[ "${domain}" == "ip" && -f /root/cert/ip/.xui-ip-ssl/current/config ]]; then + if ! ip_ssl_revoke_managed /root/cert/ip; then + LOGE "Could not remove the managed IP certificate." + return 1 + fi + acme_ids='' + elif [[ "${domain}" == "ip" ]]; then acme_ids=$(~/.acme.sh/acme.sh --list 2> /dev/null | awk 'NR>1 {print $1}' | grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3}$|:') fi for id in ${acme_ids}; do @@ -1808,7 +2119,9 @@ ssl_cert_issue_main() { rm -rf ~/.acme.sh/"${id}" ~/.acme.sh/"${id}_ecc" done # Delete the local certificate files for this domain. - rm -rf "/root/cert/${domain}" + if [[ "${domain}" != "ip" || ! -d /root/cert/ip/.xui-ip-ssl ]]; then + rm -rf "/root/cert/${domain}" + fi LOGI "Certificate revoked and removed for domain: ${domain}" # If the panel currently serves this domain's cert, clear the stored paths @@ -1834,8 +2147,16 @@ ssl_cert_issue_main() { echo "$domains" read -rp "Please enter a domain from the list to renew the SSL certificate: " domain if echo "$domains" | grep -qw "$domain"; then - ~/.acme.sh/acme.sh --renew -d ${domain} --force - LOGI "Certificate forcefully renewed for domain: $domain" + if [[ "$domain" == ip && -f /root/cert/ip/.xui-ip-ssl/current/config ]]; then + if ip_ssl_scheduled /root/cert/ip renew-force; then + LOGI "IP certificate renewed." + else + LOGE "IP certificate renewal failed." + fi + else + ~/.acme.sh/acme.sh --renew -d ${domain} --force + LOGI "Certificate forcefully renewed for domain: $domain" + fi else echo "Invalid domain entered." fi @@ -2031,7 +2352,7 @@ ssl_cert_issue_for_ip() { zypper refresh > /dev/null 2>&1 && zypper -q install -y socat > /dev/null 2>&1 ;; alpine) - apk add socat curl openssl > /dev/null 2>&1 + apk add socat curl openssl flock > /dev/null 2>&1 ;; *) LOGW "Unsupported OS for automatic socat installation" @@ -2094,7 +2415,7 @@ ssl_cert_issue_for_ip() { LOGI "Panel paths set for IP: $server_ip" LOGI " - Certificate File: $webCertFile" LOGI " - Private Key File: $webKeyFile" - LOGI " - Validity: ~6 days (auto-renews via acme.sh cron)" + LOGI " - Validity: ~6 days (auto-renews via the x-ui IP certificate job)" echo -e "${green}Access URL: https://${server_ip}:${existing_port}${existing_webBasePath}${plain}" if [[ -n "$ipv6_addr" ]]; then echo -e "${green}IPv6 access URL: https://[${ipv6_addr}]:${existing_port}${existing_webBasePath}${plain}" From 6ad00e3149fbca4363de81d424f6ee5a9033ecc0 Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Wed, 2 Dec 2026 21:25:30 +0330 Subject: [PATCH 7/9] fix(ssl): preserve independent IP certificates and enable Alpine renewal --- .../docs/en/config/ssl-certificates.mdx | 5 +++-- install.sh | 16 ++++++++++++++-- scripts/lib/ip-ssl.sh | 15 +++++++++++++-- scripts/test/ip-ssl-certificate-test.sh | 4 ++++ scripts/test/ip-ssl-entrypoint-test.sh | 17 ++++++++++++++++- x-ui.sh | 18 +++++++++++++++--- 6 files changed, 65 insertions(+), 10 deletions(-) diff --git a/docs/content/docs/en/config/ssl-certificates.mdx b/docs/content/docs/en/config/ssl-certificates.mdx index dd8027656..f7cd90a88 100644 --- a/docs/content/docs/en/config/ssl-certificates.mdx +++ b/docs/content/docs/en/config/ssl-certificates.mdx @@ -119,8 +119,9 @@ uses `/root/cert/ip/fullchain.pem` (mode `644`) and `/root/cert/ip/privkey.pem` previous generation and its renewal schedule. If reloading the panel fails after activation, the valid certificate stays installed and reload is retried. -The root crontab checks the versioned local renewal helper hourly. Manual setup -and cron share a file lock for the same panel paths, even when the primary IP +The root crontab checks the versioned local renewal helper hourly. On Alpine, +IP setup enables the OpenRC cron service when no `crond` service is running. +Manual setup and cron share a file lock for the same panel paths, even when the primary IP changes. The first successful setup retires legacy acme.sh renewal entries for those paths. Existing domain certificates and the ACME account are retained. Renew managed IP certificates from the `x-ui` menu. Standard acme.sh cron diff --git a/install.sh b/install.sh index 59edfc4bb..89f2a1967 100644 --- a/install.sh +++ b/install.sh @@ -280,6 +280,15 @@ ip_ssl_shell_quote() { printf "'%s'" "$value" } +ip_ssl_enable_openrc_cron() { + [[ "$1" == alpine ]] || return 0 + if rc-service crond status >/dev/null 2>&1; then return 0; fi + if ! rc-update add dcron default || ! rc-service dcron start; then + printf 'Could not enable the OpenRC cron service for IP certificate renewal.\n' >&2 + return 1 + fi +} + # The public paths always resolve through one generation pointer after migration. ip_ssl_link() { local state="$1" target="$2" link="$3" @@ -344,12 +353,14 @@ ip_ssl_retire_legacy() { fi done <<< "$destinations" done - # The requested entries can also be unfinished orders with no destinations. + # Retire unfinished orders for this IP. A completed cert without saved + # destinations may be in use directly by another service. for name in "$ipv4" "${ipv4}_ecc"; do entry="$home/$name" conf="$entry/$ipv4.conf" [[ -d "$entry" && ! -L "$entry" ]] || continue - if [[ ! -f "$conf" ]] || ! grep -Eq "^Le_(Real(Cert|Key|CACert|FullChain)Path|ReloadCmd|DeployHook)='[^']+" "$conf"; then + [[ ! -s "$entry/fullchain.cer" && ! -s "$entry/$ipv4.cer" ]] || continue + if [[ ! -f "$conf" ]] || ! grep -Eq "^Le_(Real(Cert|Key|CACert|FullChain)Path|(Pre|Post|Renew|Deploy)Hook|ReloadCmd)='[^']+" "$conf"; then retire+=("$name") fi done @@ -1244,6 +1255,7 @@ setup_ip_certificate() { fi done + ip_ssl_enable_openrc_cron "$release" || return 1 if [[ -n "${XUI_ACME_EMAIL:-}" ]]; then ~/.acme.sh/acme.sh --register-account --server letsencrypt -m "${XUI_ACME_EMAIL}" \ || echo -e "${yellow}Could not register ${XUI_ACME_EMAIL} with Let's Encrypt; continuing without it.${plain}" diff --git a/scripts/lib/ip-ssl.sh b/scripts/lib/ip-ssl.sh index dddddb058..7fdd6b00e 100644 --- a/scripts/lib/ip-ssl.sh +++ b/scripts/lib/ip-ssl.sh @@ -223,6 +223,15 @@ ip_ssl_shell_quote() { printf "'%s'" "$value" } +ip_ssl_enable_openrc_cron() { + [[ "$1" == alpine ]] || return 0 + if rc-service crond status >/dev/null 2>&1; then return 0; fi + if ! rc-update add dcron default || ! rc-service dcron start; then + printf 'Could not enable the OpenRC cron service for IP certificate renewal.\n' >&2 + return 1 + fi +} + # The public paths always resolve through one generation pointer after migration. ip_ssl_link() { local state="$1" target="$2" link="$3" @@ -287,12 +296,14 @@ ip_ssl_retire_legacy() { fi done <<< "$destinations" done - # The requested entries can also be unfinished orders with no destinations. + # Retire unfinished orders for this IP. A completed cert without saved + # destinations may be in use directly by another service. for name in "$ipv4" "${ipv4}_ecc"; do entry="$home/$name" conf="$entry/$ipv4.conf" [[ -d "$entry" && ! -L "$entry" ]] || continue - if [[ ! -f "$conf" ]] || ! grep -Eq "^Le_(Real(Cert|Key|CACert|FullChain)Path|ReloadCmd|DeployHook)='[^']+" "$conf"; then + [[ ! -s "$entry/fullchain.cer" && ! -s "$entry/$ipv4.cer" ]] || continue + if [[ ! -f "$conf" ]] || ! grep -Eq "^Le_(Real(Cert|Key|CACert|FullChain)Path|(Pre|Post|Renew|Deploy)Hook|ReloadCmd)='[^']+" "$conf"; then retire+=("$name") fi done diff --git a/scripts/test/ip-ssl-certificate-test.sh b/scripts/test/ip-ssl-certificate-test.sh index 346a69d50..6aacedaff 100644 --- a/scripts/test/ip-ssl-certificate-test.sh +++ b/scripts/test/ip-ssl-certificate-test.sh @@ -254,6 +254,9 @@ if ! live_is new || [[ ! -f "$state/current/reload-pending" ]]; then fail 'reloa [[ "$(stat -Lc %a "$cert_dir/privkey.pem")" == 600 ]] || fail 'private key permissions changed' [[ "$(stat -Lc %a "$cert_dir/fullchain.pem")" == 644 ]] || fail 'certificate permissions changed' [[ ! -e "$legacy/$ipv4" && ! -e "$legacy/${ipv4}_ecc" ]] || fail 'old cron can still target live paths' +mkdir "$legacy/$ipv4" +cp "$TEMP/old.pem" "$legacy/$ipv4/fullchain.cer" +printf "Le_Alt='no'\n" > "$legacy/$ipv4/$ipv4.conf" [[ "$(grep -cx 'arg=--listen-v4' "$ACME_LOG")" == 1 && "$(grep -cx 'arg=--listen-v6' "$ACME_LOG")" == 1 ]] || fail 'dual-stack flags absent' [[ "$(grep -cx "arg=$ipv6" "$ACME_LOG")" == 1 ]] || fail 'IPv6 SAN duplicated or missing' grep -Fq '/unrelated-cron' "$CRON_FILE" || fail 'crontab lost an unrelated entry' @@ -365,6 +368,7 @@ if wait "$failed_pid"; then fail 'injected promotion failure reported success'; wait "$waiting_pid" || { cat "$TEMP/waiting-promotion"; fail 'second promotion failed'; } unset -f mv live_is later || fail 'rollback overwrote a newer promotion' +cmp "$TEMP/old.pem" "$legacy/$ipv4/fullchain.cer" || fail 'an unrelated certificate using the same IP was retired' printf 'PASS: a failed promotion cannot roll back another operation on the same paths\n' before=$(wc -l < "$ACME_LOG") diff --git a/scripts/test/ip-ssl-entrypoint-test.sh b/scripts/test/ip-ssl-entrypoint-test.sh index b21d0b839..9881f21a3 100644 --- a/scripts/test/ip-ssl-entrypoint-test.sh +++ b/scripts/test/ip-ssl-entrypoint-test.sh @@ -48,7 +48,14 @@ printf 'PASS: installer consent, explicit configuration, no unattended prompts, setup_ip_certificate() { return 1; } systemctl() { :; } -rc-service() { :; } +rc-service() { + case "$*" in + 'x-ui stop') : ;; + 'crond status') [[ "${CROND_RUNNING:-0}" == 1 ]] ;; + 'dcron start') printf 'rc-service %s\n' "$*" >> "$TEMP/cron" ;; + *) return 1 ;; + esac +} NONINTERACTIVE=1 export XUI_SSL_IPV6='2001:4860::1' for release in ubuntu alpine; do @@ -58,3 +65,11 @@ for release in ubuntu alpine; do [[ "$SSL_HOST" == 198.51.100.8 ]] || fail 'the installer lost its access host after a failed certificate' done printf 'PASS: a failed IP certificate is reported and the installer carries on on systemd/OpenRC\n' + +rc-update() { printf 'rc-update %s\n' "$*" >> "$TEMP/cron"; } +ip_ssl_enable_openrc_cron ubuntu +CROND_RUNNING=1 ip_ssl_enable_openrc_cron alpine +[[ ! -e "$TEMP/cron" ]] || fail 'an existing cron service was disturbed' +ip_ssl_enable_openrc_cron alpine +[[ "$(cat "$TEMP/cron")" == $'rc-update add dcron default\nrc-service dcron start' ]] || fail 'Alpine cron was not enabled and started' +printf 'PASS: IP setup keeps an existing daemon and enables Alpine cron when needed\n' diff --git a/x-ui.sh b/x-ui.sh index 04b4e41a9..46cc67c50 100644 --- a/x-ui.sh +++ b/x-ui.sh @@ -266,6 +266,15 @@ ip_ssl_shell_quote() { printf "'%s'" "$value" } +ip_ssl_enable_openrc_cron() { + [[ "$1" == alpine ]] || return 0 + if rc-service crond status >/dev/null 2>&1; then return 0; fi + if ! rc-update add dcron default || ! rc-service dcron start; then + printf 'Could not enable the OpenRC cron service for IP certificate renewal.\n' >&2 + return 1 + fi +} + # The public paths always resolve through one generation pointer after migration. ip_ssl_link() { local state="$1" target="$2" link="$3" @@ -330,12 +339,14 @@ ip_ssl_retire_legacy() { fi done <<< "$destinations" done - # The requested entries can also be unfinished orders with no destinations. + # Retire unfinished orders for this IP. A completed cert without saved + # destinations may be in use directly by another service. for name in "$ipv4" "${ipv4}_ecc"; do entry="$home/$name" conf="$entry/$ipv4.conf" [[ -d "$entry" && ! -L "$entry" ]] || continue - if [[ ! -f "$conf" ]] || ! grep -Eq "^Le_(Real(Cert|Key|CACert|FullChain)Path|ReloadCmd|DeployHook)='[^']+" "$conf"; then + [[ ! -s "$entry/fullchain.cer" && ! -s "$entry/$ipv4.cer" ]] || continue + if [[ ! -f "$conf" ]] || ! grep -Eq "^Le_(Real(Cert|Key|CACert|FullChain)Path|(Pre|Post|Renew|Deploy)Hook|ReloadCmd)='[^']+" "$conf"; then retire+=("$name") fi done @@ -2352,7 +2363,7 @@ ssl_cert_issue_for_ip() { zypper refresh > /dev/null 2>&1 && zypper -q install -y socat > /dev/null 2>&1 ;; alpine) - apk add socat curl openssl flock > /dev/null 2>&1 + apk add socat curl openssl flock dcron > /dev/null 2>&1 ;; *) LOGW "Unsupported OS for automatic socat installation" @@ -2398,6 +2409,7 @@ ssl_cert_issue_for_ip() { # Reload command - restarts panel after renewal local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null" + ip_ssl_enable_openrc_cron "$release" || return 1 if ! ip_ssl_issue_and_install "$HOME/.acme.sh/acme.sh" "$server_ip" "$ipv6_addr" "$WebPort" "$certPath" "$reloadCmd"; then return 1 fi From e0ee0965d66e5042453b6015c45ca2a4e9024b18 Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Wed, 2 Dec 2026 23:43:17 +0330 Subject: [PATCH 8/9] test(ssl): handle ShellCheck diagnostics for fault hooks --- scripts/test/ip-ssl-certificate-test.sh | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/scripts/test/ip-ssl-certificate-test.sh b/scripts/test/ip-ssl-certificate-test.sh index 6aacedaff..eb49812d6 100644 --- a/scripts/test/ip-ssl-certificate-test.sh +++ b/scripts/test/ip-ssl-certificate-test.sh @@ -191,8 +191,9 @@ reject issue if ! live_is old || ! legacy_is_intact; then fail 'wrong key changed prior certificate or ACME state'; fi fixture new -# Fault hooks are called indirectly by the sourced lifecycle functions. -# shellcheck disable=SC2317 +# The chmod and mv overrides in this suite are called by the sourced lifecycle functions. +# Older ShellCheck reports SC2317 for these calls, and newer versions report SC2329. +# shellcheck disable=SC2317,SC2329 chmod() { if [[ "$1" == 600 && "$*" == *'/gen.'* ]]; then return 1; fi command chmod "$@" @@ -202,7 +203,7 @@ unset -f chmod if ! live_is old || ! legacy_is_intact; then fail 'chmod failure changed prior certificate or ACME state'; fi printf 'PASS: issuance, installation, SAN, key, partial and permission failures preserve prior state\n' -# shellcheck disable=SC2317 +# shellcheck disable=SC2317,SC2329 mv() { if [[ "$*" == *'.xui-retired-'* && "${!#}" == "$legacy/${ipv4}_ecc" ]]; then return 1; fi command mv "$@" @@ -216,7 +217,7 @@ reject issue legacy_is_intact || fail 'subsequent attempt did not finish ACME recovery' ISSUE_MODE=ok -# shellcheck disable=SC2317 +# shellcheck disable=SC2317,SC2329 mv() { if [[ "${!#}" == "$cert_dir/privkey.pem" || ( "$*" == *'/pending/restore '* && "${!#}" == "$cert_dir/fullchain.pem" ) ]]; then return 1 @@ -233,7 +234,7 @@ if ! live_is old || ! legacy_is_intact; then fail 'subsequent attempt did not fi [[ ! -L "$cert_dir/fullchain.pem" ]] || fail 'original regular file type was not recovered' ISSUE_MODE=ok -# shellcheck disable=SC2317 +# shellcheck disable=SC2317,SC2329 mv() { command mv "$@" || return if [[ "${!#}" == "$cert_dir/fullchain.pem" && "$*" == *'/pending/link '* ]]; then kill -KILL "$BASHPID"; fi @@ -296,7 +297,7 @@ if ! live_is new || ! cmp "$TEMP/working.conf" "$working_conf"; then fail 'rejec cat "$TEMP/tls.log" >&2 fail 'TLS restart could not load the last known-good certificate' ) -# shellcheck disable=SC2317 +# shellcheck disable=SC2317,SC2329 mv() { if [[ "${!#}" == "$state/current" ]]; then return 1; fi command mv "$@" @@ -341,7 +342,7 @@ printf 'PASS: manual, renewal and shared-destination promotion serialize; unrela # promote. Its new state must survive cleanup of the earlier transaction. promotion="$TEMP/promotion" mkfifo "$promotion" -# shellcheck disable=SC2317 +# shellcheck disable=SC2317,SC2329 mv() { if [[ "${!#}" == "$state/current" && "${FAIL_PROMOTION:-0}" == 1 ]]; then : > "$promotion.ready" From 5fe46c2e5588c643f9805c1929667ffda2f74f83 Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Thu, 3 Dec 2026 21:32:11 +0330 Subject: [PATCH 9/9] fix(ssl): recover interrupted IP certificate migrations Register recovery before retiring legacy renewal state and detach completed journals before deleting backups. --- install.sh | 49 ++++++++++++------ scripts/lib/ip-ssl.sh | 49 ++++++++++++------ scripts/test/ip-ssl-certificate-test.sh | 66 +++++++++++++++++++++++-- x-ui.sh | 49 ++++++++++++------ 4 files changed, 162 insertions(+), 51 deletions(-) diff --git a/install.sh b/install.sh index ccd1ce5a5..eb55a9841 100644 --- a/install.sh +++ b/install.sh @@ -365,6 +365,8 @@ ip_ssl_retire_legacy() { fi done ((${#retire[@]})) || return 0 + # A scheduled runner must be able to restore retired entries after SIGKILL. + ip_ssl_schedule "$state" "${acme%/*}" || return 1 if ip_ssl_legacy_busy "$acme"; then printf 'Wait for the existing acme.sh command to finish, then retry IP certificate setup.\n' >&2 return 1 @@ -383,13 +385,17 @@ ip_ssl_retire_legacy() { ip_ssl_recover() { local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending" - local gen='' home='' current='' entry held file name failed=0 previous='' - [[ -d "$pending" ]] || return 0 - if [[ -f "$pending/generation" ]]; then - if ! IFS= read -r gen < "$pending/generation" || [[ ! "$gen" =~ ^gen\.[a-zA-Z0-9]+$ ]]; then - printf 'Invalid IP certificate generation journal. Keep recovery files at %s.\n' "$pending" >&2 - return 1 - fi + local gen home='' current='' entry held file name failed=0 previous='' + # These directories are unpublished work or journals already detached from recovery. + if ! rm -rf -- "$state/pending-init" "$state/pending-cleanup"; then + printf 'Could not remove disposable IP certificate files at %s.\n' "$state" >&2 + return 1 + fi + [[ -e "$pending" || -L "$pending" ]] || return 0 + if [[ ! -d "$pending" || -L "$pending" || ! -f "$pending/generation" ]] || + ! IFS= read -r gen < "$pending/generation" || [[ ! "$gen" =~ ^gen\.[a-zA-Z0-9]+$ ]]; then + printf 'Invalid IP certificate generation journal. Keep recovery files at %s.\n' "$pending" >&2 + return 1 fi current=$(readlink -- "$state/current") || current='' if [[ -f "$pending/home" ]] && ! IFS= read -r home < "$pending/home"; then @@ -397,7 +403,7 @@ ip_ssl_recover() { return 1 fi - if [[ -n "$gen" && "$current" == "$gen" ]]; then + if [[ "$current" == "$gen" ]]; then # Commit is the pointer swap. Never roll back a committed generation. if [[ -f "$pending/legacy" ]]; then while IFS= read -r entry; do @@ -427,7 +433,7 @@ ip_ssl_recover() { # types are restored. A failed restore may still leave a live alias. if ((!failed)) && [[ -f "$pending/legacy" ]]; then while IFS= read -r entry; do - if ! ip_ssl_ipv4 "${entry%_ecc}" || [[ -z "$home" || -z "$gen" ]]; then failed=1; continue; fi + if ! ip_ssl_ipv4 "${entry%_ecc}" || [[ -z "$home" ]]; then failed=1; continue; fi held="$home/.xui-retired-$gen-$entry" if [[ -e "$held" ]]; then if [[ -e "$home/$entry" || -L "$home/$entry" ]] || @@ -440,14 +446,20 @@ ip_ssl_recover() { fi done < "$pending/legacy" fi - if ((!failed)) && [[ -n "$gen" ]]; then rm -rf -- "${state:?}/${gen:?}" || failed=1; fi + if ((!failed)); then rm -rf -- "${state:?}/${gen:?}" || failed=1; fi fi if ((failed)); then printf 'IP certificate recovery could not complete. Keep recovery files at %s and retry after resolving the error.\n' "$pending" >&2 return 1 fi - if ! rm -f -- "$state/staging/fullchain.pem" "$state/staging/privkey.pem" || ! rm -rf -- "$pending"; then - printf 'Could not remove the IP certificate journal at %s\n' "$pending" >&2 + # Remove the journal from the recovery path before deleting any of its files. + if ! rm -f -- "$state/staging/fullchain.pem" "$state/staging/privkey.pem" || + ! mv -T -- "$pending" "$state/pending-cleanup"; then + printf 'Could not detach the IP certificate journal at %s\n' "$pending" >&2 + return 1 + fi + if ! rm -rf -- "$state/pending-cleanup"; then + printf 'Could not remove the disposable IP certificate journal at %s\n' "$state/pending-cleanup" >&2 return 1 fi } @@ -544,18 +556,23 @@ ip_ssl_legacy_home() ( ip_ssl_transaction() ( local action="$1" acme="$2" ipv4="$3" ipv6="$4" port="$5" dir="$6" reload="$7" local state="$dir/.xui-ip-ssl" pending="$dir/.xui-ip-ssl/pending" home="${acme%/*}" - local work gen file previous rc legacy_home stage="$dir/.xui-ip-ssl/staging" + local work gen file previous rc legacy_home stage="$state/staging" pending_init="$state/pending-init" local -a scope domains=(-d "$ipv4") - mkdir -- "$pending" || return 1 + mkdir -- "$pending_init" || return 1 # Recovery runs under the caller's flock, including on normal exit. trap 'rc=$?; ip_ssl_recover "$dir" || rc=1; exit "$rc"' EXIT trap 'exit 130' INT trap 'exit 143' TERM trap 'exit 129' HUP - work=$(mktemp -d "$state/gen.XXXXXX") || return 1 + # Publish only a journal with a complete generation record. + work=$(mktemp -d "$pending_init/gen.XXXXXX") || return 1 gen="${work##*/}" - printf '%s\n' "$gen" > "$pending/generation" && mkdir -- "$work/acme" "$pending/live" || return 1 + printf '%s\n' "$gen" > "$pending_init/generation" && + mkdir -- "$work/acme" "$pending_init/live" && + mv -T -- "$pending_init" "$pending" && + mv -T -- "$pending/$gen" "$state/$gen" || return 1 + work="$state/$gen" if [[ "$action" == issue ]]; then legacy_home=$(ip_ssl_legacy_home "$home") || return 1 [[ "$legacy_home" == /* && "$legacy_home" != *[$'\n\r']* ]] || return 1 diff --git a/scripts/lib/ip-ssl.sh b/scripts/lib/ip-ssl.sh index 7fdd6b00e..afdcd00cf 100644 --- a/scripts/lib/ip-ssl.sh +++ b/scripts/lib/ip-ssl.sh @@ -308,6 +308,8 @@ ip_ssl_retire_legacy() { fi done ((${#retire[@]})) || return 0 + # A scheduled runner must be able to restore retired entries after SIGKILL. + ip_ssl_schedule "$state" "${acme%/*}" || return 1 if ip_ssl_legacy_busy "$acme"; then printf 'Wait for the existing acme.sh command to finish, then retry IP certificate setup.\n' >&2 return 1 @@ -326,13 +328,17 @@ ip_ssl_retire_legacy() { ip_ssl_recover() { local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending" - local gen='' home='' current='' entry held file name failed=0 previous='' - [[ -d "$pending" ]] || return 0 - if [[ -f "$pending/generation" ]]; then - if ! IFS= read -r gen < "$pending/generation" || [[ ! "$gen" =~ ^gen\.[a-zA-Z0-9]+$ ]]; then - printf 'Invalid IP certificate generation journal. Keep recovery files at %s.\n' "$pending" >&2 - return 1 - fi + local gen home='' current='' entry held file name failed=0 previous='' + # These directories are unpublished work or journals already detached from recovery. + if ! rm -rf -- "$state/pending-init" "$state/pending-cleanup"; then + printf 'Could not remove disposable IP certificate files at %s.\n' "$state" >&2 + return 1 + fi + [[ -e "$pending" || -L "$pending" ]] || return 0 + if [[ ! -d "$pending" || -L "$pending" || ! -f "$pending/generation" ]] || + ! IFS= read -r gen < "$pending/generation" || [[ ! "$gen" =~ ^gen\.[a-zA-Z0-9]+$ ]]; then + printf 'Invalid IP certificate generation journal. Keep recovery files at %s.\n' "$pending" >&2 + return 1 fi current=$(readlink -- "$state/current") || current='' if [[ -f "$pending/home" ]] && ! IFS= read -r home < "$pending/home"; then @@ -340,7 +346,7 @@ ip_ssl_recover() { return 1 fi - if [[ -n "$gen" && "$current" == "$gen" ]]; then + if [[ "$current" == "$gen" ]]; then # Commit is the pointer swap. Never roll back a committed generation. if [[ -f "$pending/legacy" ]]; then while IFS= read -r entry; do @@ -370,7 +376,7 @@ ip_ssl_recover() { # types are restored. A failed restore may still leave a live alias. if ((!failed)) && [[ -f "$pending/legacy" ]]; then while IFS= read -r entry; do - if ! ip_ssl_ipv4 "${entry%_ecc}" || [[ -z "$home" || -z "$gen" ]]; then failed=1; continue; fi + if ! ip_ssl_ipv4 "${entry%_ecc}" || [[ -z "$home" ]]; then failed=1; continue; fi held="$home/.xui-retired-$gen-$entry" if [[ -e "$held" ]]; then if [[ -e "$home/$entry" || -L "$home/$entry" ]] || @@ -383,14 +389,20 @@ ip_ssl_recover() { fi done < "$pending/legacy" fi - if ((!failed)) && [[ -n "$gen" ]]; then rm -rf -- "${state:?}/${gen:?}" || failed=1; fi + if ((!failed)); then rm -rf -- "${state:?}/${gen:?}" || failed=1; fi fi if ((failed)); then printf 'IP certificate recovery could not complete. Keep recovery files at %s and retry after resolving the error.\n' "$pending" >&2 return 1 fi - if ! rm -f -- "$state/staging/fullchain.pem" "$state/staging/privkey.pem" || ! rm -rf -- "$pending"; then - printf 'Could not remove the IP certificate journal at %s\n' "$pending" >&2 + # Remove the journal from the recovery path before deleting any of its files. + if ! rm -f -- "$state/staging/fullchain.pem" "$state/staging/privkey.pem" || + ! mv -T -- "$pending" "$state/pending-cleanup"; then + printf 'Could not detach the IP certificate journal at %s\n' "$pending" >&2 + return 1 + fi + if ! rm -rf -- "$state/pending-cleanup"; then + printf 'Could not remove the disposable IP certificate journal at %s\n' "$state/pending-cleanup" >&2 return 1 fi } @@ -487,18 +499,23 @@ ip_ssl_legacy_home() ( ip_ssl_transaction() ( local action="$1" acme="$2" ipv4="$3" ipv6="$4" port="$5" dir="$6" reload="$7" local state="$dir/.xui-ip-ssl" pending="$dir/.xui-ip-ssl/pending" home="${acme%/*}" - local work gen file previous rc legacy_home stage="$dir/.xui-ip-ssl/staging" + local work gen file previous rc legacy_home stage="$state/staging" pending_init="$state/pending-init" local -a scope domains=(-d "$ipv4") - mkdir -- "$pending" || return 1 + mkdir -- "$pending_init" || return 1 # Recovery runs under the caller's flock, including on normal exit. trap 'rc=$?; ip_ssl_recover "$dir" || rc=1; exit "$rc"' EXIT trap 'exit 130' INT trap 'exit 143' TERM trap 'exit 129' HUP - work=$(mktemp -d "$state/gen.XXXXXX") || return 1 + # Publish only a journal with a complete generation record. + work=$(mktemp -d "$pending_init/gen.XXXXXX") || return 1 gen="${work##*/}" - printf '%s\n' "$gen" > "$pending/generation" && mkdir -- "$work/acme" "$pending/live" || return 1 + printf '%s\n' "$gen" > "$pending_init/generation" && + mkdir -- "$work/acme" "$pending_init/live" && + mv -T -- "$pending_init" "$pending" && + mv -T -- "$pending/$gen" "$state/$gen" || return 1 + work="$state/$gen" if [[ "$action" == issue ]]; then legacy_home=$(ip_ssl_legacy_home "$home") || return 1 [[ "$legacy_home" == /* && "$legacy_home" != *[$'\n\r']* ]] || return 1 diff --git a/scripts/test/ip-ssl-certificate-test.sh b/scripts/test/ip-ssl-certificate-test.sh index eb49812d6..0ed4bd373 100644 --- a/scripts/test/ip-ssl-certificate-test.sh +++ b/scripts/test/ip-ssl-certificate-test.sh @@ -63,6 +63,8 @@ printf 'unrelated certificate\n' > "$legacy/example.net_ecc/marker" for suffix in '' _ecc; do printf "Le_Alt='no'\nLe_NextRenewTime='1'\nLe_RealKeyPath='%s/privkey.pem'\nLe_RealFullChainPath='%s/fullchain.pem'\n" \ "$cert_dir" "$cert_dir" > "$legacy/$ipv4$suffix/$ipv4.conf" + cp "$TEMP/old.pem" "$legacy/$ipv4$suffix/fullchain.cer" + cp "$TEMP/old.key" "$legacy/$ipv4$suffix/$ipv4.key" done cp "$legacy/${ipv4}_ecc/$ipv4.conf" "$TEMP/legacy.conf" cp "${acme%/*}/account.conf" "$TEMP/account.conf" @@ -73,7 +75,7 @@ cat > "$TEMP/mockbin/crontab" <<'MOCK' #!/usr/bin/env bash case "$1" in -l) cat "$CRON_FILE" ;; - -) cat > "$CRON_FILE" ;; + -) [[ "${CRON_FAIL:-0}" == 0 ]] && cat > "$CRON_FILE" ;; *) exit 1 ;; esac MOCK @@ -112,7 +114,10 @@ case "$action" in mkdir -p "$entry" if [[ "$action" == --issue ]]; then printf "Le_Alt='%s'\n" "${san:-no}" > "$conf" - if [[ "$ISSUE_MODE" == fail ]]; then exit 1; fi + case "$ISSUE_MODE" in + fail) exit 1 ;; + interrupt) kill -KILL "$PPID"; exit 1 ;; + esac else if [[ "$RENEW_MODE" == skip ]]; then exit 2; fi if [[ -n "${RENEW_BARRIER:-}" ]]; then @@ -169,6 +174,24 @@ reject() { } fixture new +: > "$ACME_LOG" +CRON_FAIL=1 reject issue +if grep -Fxq 'arg=--issue' "$ACME_LOG"; then fail 'cron registration failure reached ACME issuance'; fi +if ! live_is old || ! legacy_is_intact; then fail 'cron registration failure changed legacy state'; fi + +ISSUE_MODE=interrupt reject issue +if [[ ! -d "$state/pending" || -e "$legacy/$ipv4" || -e "$legacy/${ipv4}_ecc" ]]; then + fail 'issuance interruption did not leave retired legacy entries in the journal' +fi +cron_command=$(sed -n 's/^19 \* \* \* \* //p' "$CRON_FILE") +[[ -n "$cron_command" ]] || fail 'no recovery job was registered before retirement' +before=$(wc -l < "$ACME_LOG") +bash -c "$cron_command" || fail 'first scheduled recovery could not restore the legacy entries' +if ! live_is old || ! legacy_is_intact || [[ -e "$state/pending" || "$(wc -l < "$ACME_LOG")" != "$before" ]]; then + fail 'scheduled recovery changed the old pair or did not restore renewal metadata' +fi +printf 'PASS: failed cron registration preserves legacy state and scheduled recovery repairs interrupted issuance\n' + ISSUE_MODE=fail reject issue if ! live_is old || ! legacy_is_intact; then fail 'failed dual-stack order changed prior certificate or ACME state'; fi @@ -250,7 +273,44 @@ printf 'PASS: restoration failures retain backups and interruptions recover on n : > "$ACME_LOG" RELOAD_FAIL=1 -issue +# shellcheck disable=SC2317,SC2329 +rm() { + local journal="${!#}" committed + case "$journal" in + "$state/pending"|"$state/pending-cleanup") + committed=$(readlink -- "$state/current") || committed='' + if [[ -f "$journal/live-changing" && -f "$journal/generation" && + "$(cat "$journal/generation")" == "$committed" ]]; then + command rm -f -- "$journal/generation" || return 1 + kill -KILL "$BASHPID" + fi + ;; + esac + command rm "$@" +} +reject issue +unset -f rm +committed=$(readlink -- "$state/current") +if ! live_is new; then fail 'cleanup interruption changed the committed pair'; fi +recovery_status=0 +RENEW_MODE=skip "$runner" || recovery_status=$? +if [[ "$(readlink -- "$state/current")" != "$committed" || + "$(readlink -- "$cert_dir/fullchain.pem")" != .xui-ip-ssl/current/fullchain.pem || + "$(readlink -- "$cert_dir/privkey.pem")" != .xui-ip-ssl/current/privkey.pem ]] || ! live_is new; then + fail 'scheduled recovery replaced the committed aliases after interrupted cleanup' +fi +((recovery_status == 0)) || fail 'scheduled recovery did not survive interrupted journal cleanup' +printf 'PASS: interrupted post-commit cleanup preserves the active aliases and scheduled renewal\n' + +mkdir -p -- "$state/pending/live" +touch "$state/pending/live-changing" +cp -- "$TEMP/old.pem" "$state/pending/live/fullchain.pem" +reject "$runner" +grep -q 'Invalid IP certificate generation journal' "$TEMP/rejected" || fail 'malformed journal was not diagnosed' +if ! live_is new || [[ ! -L "$cert_dir/fullchain.pem" || ! -L "$cert_dir/privkey.pem" ]]; then + fail 'malformed journal changed the committed aliases' +fi +rm -rf -- "$state/pending" if ! live_is new || [[ ! -f "$state/current/reload-pending" ]]; then fail 'reload failure discarded valid deployment'; fi [[ "$(stat -Lc %a "$cert_dir/privkey.pem")" == 600 ]] || fail 'private key permissions changed' [[ "$(stat -Lc %a "$cert_dir/fullchain.pem")" == 644 ]] || fail 'certificate permissions changed' diff --git a/x-ui.sh b/x-ui.sh index af00030c0..927b7b7ab 100644 --- a/x-ui.sh +++ b/x-ui.sh @@ -351,6 +351,8 @@ ip_ssl_retire_legacy() { fi done ((${#retire[@]})) || return 0 + # A scheduled runner must be able to restore retired entries after SIGKILL. + ip_ssl_schedule "$state" "${acme%/*}" || return 1 if ip_ssl_legacy_busy "$acme"; then printf 'Wait for the existing acme.sh command to finish, then retry IP certificate setup.\n' >&2 return 1 @@ -369,13 +371,17 @@ ip_ssl_retire_legacy() { ip_ssl_recover() { local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending" - local gen='' home='' current='' entry held file name failed=0 previous='' - [[ -d "$pending" ]] || return 0 - if [[ -f "$pending/generation" ]]; then - if ! IFS= read -r gen < "$pending/generation" || [[ ! "$gen" =~ ^gen\.[a-zA-Z0-9]+$ ]]; then - printf 'Invalid IP certificate generation journal. Keep recovery files at %s.\n' "$pending" >&2 - return 1 - fi + local gen home='' current='' entry held file name failed=0 previous='' + # These directories are unpublished work or journals already detached from recovery. + if ! rm -rf -- "$state/pending-init" "$state/pending-cleanup"; then + printf 'Could not remove disposable IP certificate files at %s.\n' "$state" >&2 + return 1 + fi + [[ -e "$pending" || -L "$pending" ]] || return 0 + if [[ ! -d "$pending" || -L "$pending" || ! -f "$pending/generation" ]] || + ! IFS= read -r gen < "$pending/generation" || [[ ! "$gen" =~ ^gen\.[a-zA-Z0-9]+$ ]]; then + printf 'Invalid IP certificate generation journal. Keep recovery files at %s.\n' "$pending" >&2 + return 1 fi current=$(readlink -- "$state/current") || current='' if [[ -f "$pending/home" ]] && ! IFS= read -r home < "$pending/home"; then @@ -383,7 +389,7 @@ ip_ssl_recover() { return 1 fi - if [[ -n "$gen" && "$current" == "$gen" ]]; then + if [[ "$current" == "$gen" ]]; then # Commit is the pointer swap. Never roll back a committed generation. if [[ -f "$pending/legacy" ]]; then while IFS= read -r entry; do @@ -413,7 +419,7 @@ ip_ssl_recover() { # types are restored. A failed restore may still leave a live alias. if ((!failed)) && [[ -f "$pending/legacy" ]]; then while IFS= read -r entry; do - if ! ip_ssl_ipv4 "${entry%_ecc}" || [[ -z "$home" || -z "$gen" ]]; then failed=1; continue; fi + if ! ip_ssl_ipv4 "${entry%_ecc}" || [[ -z "$home" ]]; then failed=1; continue; fi held="$home/.xui-retired-$gen-$entry" if [[ -e "$held" ]]; then if [[ -e "$home/$entry" || -L "$home/$entry" ]] || @@ -426,14 +432,20 @@ ip_ssl_recover() { fi done < "$pending/legacy" fi - if ((!failed)) && [[ -n "$gen" ]]; then rm -rf -- "${state:?}/${gen:?}" || failed=1; fi + if ((!failed)); then rm -rf -- "${state:?}/${gen:?}" || failed=1; fi fi if ((failed)); then printf 'IP certificate recovery could not complete. Keep recovery files at %s and retry after resolving the error.\n' "$pending" >&2 return 1 fi - if ! rm -f -- "$state/staging/fullchain.pem" "$state/staging/privkey.pem" || ! rm -rf -- "$pending"; then - printf 'Could not remove the IP certificate journal at %s\n' "$pending" >&2 + # Remove the journal from the recovery path before deleting any of its files. + if ! rm -f -- "$state/staging/fullchain.pem" "$state/staging/privkey.pem" || + ! mv -T -- "$pending" "$state/pending-cleanup"; then + printf 'Could not detach the IP certificate journal at %s\n' "$pending" >&2 + return 1 + fi + if ! rm -rf -- "$state/pending-cleanup"; then + printf 'Could not remove the disposable IP certificate journal at %s\n' "$state/pending-cleanup" >&2 return 1 fi } @@ -530,18 +542,23 @@ ip_ssl_legacy_home() ( ip_ssl_transaction() ( local action="$1" acme="$2" ipv4="$3" ipv6="$4" port="$5" dir="$6" reload="$7" local state="$dir/.xui-ip-ssl" pending="$dir/.xui-ip-ssl/pending" home="${acme%/*}" - local work gen file previous rc legacy_home stage="$dir/.xui-ip-ssl/staging" + local work gen file previous rc legacy_home stage="$state/staging" pending_init="$state/pending-init" local -a scope domains=(-d "$ipv4") - mkdir -- "$pending" || return 1 + mkdir -- "$pending_init" || return 1 # Recovery runs under the caller's flock, including on normal exit. trap 'rc=$?; ip_ssl_recover "$dir" || rc=1; exit "$rc"' EXIT trap 'exit 130' INT trap 'exit 143' TERM trap 'exit 129' HUP - work=$(mktemp -d "$state/gen.XXXXXX") || return 1 + # Publish only a journal with a complete generation record. + work=$(mktemp -d "$pending_init/gen.XXXXXX") || return 1 gen="${work##*/}" - printf '%s\n' "$gen" > "$pending/generation" && mkdir -- "$work/acme" "$pending/live" || return 1 + printf '%s\n' "$gen" > "$pending_init/generation" && + mkdir -- "$work/acme" "$pending_init/live" && + mv -T -- "$pending_init" "$pending" && + mv -T -- "$pending/$gen" "$state/$gen" || return 1 + work="$state/$gen" if [[ "$action" == issue ]]; then legacy_home=$(ip_ssl_legacy_home "$home") || return 1 [[ "$legacy_home" == /* && "$legacy_home" != *[$'\n\r']* ]] || return 1