mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 08:25:26 +03:00
feat(ssl): detect IPv6 and safely manage dual-stack IP certificates (#6971)
Automatically discover eligible public IPv6 addresses for IP certificates in the installer and x-ui menu, requiring explicit consent or XUI_SSL_IPV6 for unattended dual-stack issuance. Require compatible acme.sh and both listener families for dual-stack HTTP-01. Stage and validate certificate, key, IP SANs and ACME renewal metadata before atomic generation promotion; retain a known-good deployment on failure. Serialize issuance and renewal, register recovery before retiring legacy entries, detach journals atomically before cleanup, and retry failed reloads. Keep installer service setup and existing domain certificate paths intact. Validation: reviewed head 5fe46c2e5588c643f9805c1929667ffda2f74f83; CI 12/12 and Docs CI passed. Live Let's Encrypt production issuance and cron-triggered forced renewal on public IPv4/IPv6 succeeded with distinct certificate serials, valid SANs, correct permissions, and HTTPS on both families from the staging host. External IPv4 HTTPS passed. External IPv6 HTTPS from the client, naturally due renewal, and actual panel reload were not independently tested. See https://github.com/MHSanaei/3x-ui/pull/6971#issuecomment-7388224118. Closes #6885.
This commit is contained in:
@@ -12,6 +12,10 @@ on:
|
||||
- "install.sh"
|
||||
- "deploy/test/installer-panel-port.sh"
|
||||
- ".github/workflows/ci.yml"
|
||||
- "x-ui.sh"
|
||||
- "scripts/lib/ip-ssl.sh"
|
||||
- "scripts/sync-ip-ssl-helpers.sh"
|
||||
- "scripts/test/**"
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
@@ -25,6 +29,10 @@ on:
|
||||
- "install.sh"
|
||||
- "deploy/test/installer-panel-port.sh"
|
||||
- ".github/workflows/ci.yml"
|
||||
- "x-ui.sh"
|
||||
- "scripts/lib/ip-ssl.sh"
|
||||
- "scripts/sync-ip-ssl-helpers.sh"
|
||||
- "scripts/test/**"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -575,11 +583,26 @@ 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 deploy/test/installer-panel-port.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
|
||||
- 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
|
||||
|
||||
|
||||
+22
-1
@@ -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; 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
|
||||
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.
|
||||
|
||||
@@ -80,6 +80,80 @@ 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.
|
||||
|
||||
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. 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
|
||||
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:
|
||||
|
||||
```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
|
||||
|
||||
+683
-97
@@ -54,9 +54,652 @@ 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<NF;i++)if($i=="src"){print $(i+1);exit}}') || source=''
|
||||
if [[ -n "$source" ]]; then preferred=$(ip_ssl_expand_ipv6 "$source") || preferred=''; fi
|
||||
while IFS= read -r line; do
|
||||
[[ " $line " == *' scope global '* ]] || continue
|
||||
case " $line " in
|
||||
*' tentative '*|*' optimistic '*|*' deprecated '*|*' dadfailed '*|*' detached '*|*' preferred_lft 0sec '*) continue ;;
|
||||
esac
|
||||
IFS=' ' read -r -a fields <<< "$line"
|
||||
cidr=''
|
||||
for ((i=0; i+1<${#fields[@]}; i++)); do
|
||||
if [[ "${fields[i]}" == inet6 ]]; then cidr="${fields[i+1]}"; break; fi
|
||||
done
|
||||
[[ "$cidr" =~ ^([^/]+)/([0-9]{1,3})$ ]] || continue
|
||||
((10#${BASH_REMATCH[2]} <= 128)) || continue
|
||||
address="${BASH_REMATCH[1]}"
|
||||
ip_ssl_public_ipv6 "$address" || continue
|
||||
expanded=$(ip_ssl_expand_ipv6 "$address") || continue
|
||||
if [[ -n "${seen[$expanded]:-}" ]]; then
|
||||
[[ "${seen[$expanded]}" == temporary && " $line " != *' temporary '* ]] || continue
|
||||
fi
|
||||
label=stable; rank=1
|
||||
if [[ "$expanded" == "$preferred" ]]; then label='default route'; rank=0; fi
|
||||
if [[ " $line " == *' temporary '* ]]; then
|
||||
seen[$expanded]=temporary
|
||||
privacy+=("$rank"$'\t'"$address"$'\t'"temporary")
|
||||
else
|
||||
seen[$expanded]=stable
|
||||
stable+=("$rank"$'\t'"$address"$'\t'"$label")
|
||||
fi
|
||||
done < <(ip -o -6 addr show up scope global 2> /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_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"
|
||||
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
|
||||
# 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
|
||||
[[ ! -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
|
||||
((${#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
|
||||
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=''
|
||||
# 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
|
||||
printf 'Invalid ACME home in the IP certificate journal. Keep recovery files at %s.\n' "$pending" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
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
|
||||
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" ]]; 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)); 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
|
||||
# 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
|
||||
}
|
||||
|
||||
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="$state/staging" pending_init="$state/pending-init"
|
||||
local -a scope domains=(-d "$ipv4")
|
||||
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
|
||||
|
||||
# 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_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
|
||||
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" 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
|
||||
[[ "$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() {
|
||||
is_ipv4 "$1" || is_ipv6 "$1"
|
||||
}
|
||||
@@ -183,7 +826,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
|
||||
@@ -566,7 +1209,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}"
|
||||
@@ -581,30 +1229,7 @@ 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"
|
||||
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=""
|
||||
@@ -647,59 +1272,17 @@ 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
|
||||
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}"
|
||||
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"
|
||||
@@ -714,8 +1297,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
|
||||
}
|
||||
|
||||
@@ -1009,7 +1591,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
|
||||
@@ -1017,25 +1599,29 @@ 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
|
||||
|
||||
# Stop panel if running (port 80 needed)
|
||||
if [[ $release == "alpine" ]]; then
|
||||
rc-service x-ui stop > /dev/null 2>&1
|
||||
else
|
||||
systemctl stop x-ui > /dev/null 2>&1
|
||||
fi
|
||||
|
||||
setup_ip_certificate "${server_ip}" "${ipv6_addr}"
|
||||
if [ $? -eq 0 ]; then
|
||||
local ipv6_addr
|
||||
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}"
|
||||
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}"
|
||||
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}"
|
||||
else
|
||||
# Stop panel if running (port 80 needed)
|
||||
if [[ $release == "alpine" ]]; then
|
||||
rc-service x-ui stop > /dev/null 2>&1
|
||||
else
|
||||
systemctl stop x-ui > /dev/null 2>&1
|
||||
fi
|
||||
|
||||
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 on both selected addresses.${plain}"
|
||||
SSL_HOST="${server_ip}"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
3)
|
||||
|
||||
@@ -0,0 +1,644 @@
|
||||
# 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<NF;i++)if($i=="src"){print $(i+1);exit}}') || source=''
|
||||
if [[ -n "$source" ]]; then preferred=$(ip_ssl_expand_ipv6 "$source") || preferred=''; fi
|
||||
while IFS= read -r line; do
|
||||
[[ " $line " == *' scope global '* ]] || continue
|
||||
case " $line " in
|
||||
*' tentative '*|*' optimistic '*|*' deprecated '*|*' dadfailed '*|*' detached '*|*' preferred_lft 0sec '*) continue ;;
|
||||
esac
|
||||
IFS=' ' read -r -a fields <<< "$line"
|
||||
cidr=''
|
||||
for ((i=0; i+1<${#fields[@]}; i++)); do
|
||||
if [[ "${fields[i]}" == inet6 ]]; then cidr="${fields[i+1]}"; break; fi
|
||||
done
|
||||
[[ "$cidr" =~ ^([^/]+)/([0-9]{1,3})$ ]] || continue
|
||||
((10#${BASH_REMATCH[2]} <= 128)) || continue
|
||||
address="${BASH_REMATCH[1]}"
|
||||
ip_ssl_public_ipv6 "$address" || continue
|
||||
expanded=$(ip_ssl_expand_ipv6 "$address") || continue
|
||||
if [[ -n "${seen[$expanded]:-}" ]]; then
|
||||
[[ "${seen[$expanded]}" == temporary && " $line " != *' temporary '* ]] || continue
|
||||
fi
|
||||
label=stable; rank=1
|
||||
if [[ "$expanded" == "$preferred" ]]; then label='default route'; rank=0; fi
|
||||
if [[ " $line " == *' temporary '* ]]; then
|
||||
seen[$expanded]=temporary
|
||||
privacy+=("$rank"$'\t'"$address"$'\t'"temporary")
|
||||
else
|
||||
seen[$expanded]=stable
|
||||
stable+=("$rank"$'\t'"$address"$'\t'"$label")
|
||||
fi
|
||||
done < <(ip -o -6 addr show up scope global 2> /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_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"
|
||||
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
|
||||
# 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
|
||||
[[ ! -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
|
||||
((${#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
|
||||
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=''
|
||||
# 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
|
||||
printf 'Invalid ACME home in the IP certificate journal. Keep recovery files at %s.\n' "$pending" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
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
|
||||
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" ]]; 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)); 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
|
||||
# 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
|
||||
}
|
||||
|
||||
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="$state/staging" pending_init="$state/pending-init"
|
||||
local -a scope domains=(-d "$ipv4")
|
||||
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
|
||||
|
||||
# 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_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
|
||||
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" 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
|
||||
[[ "$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"
|
||||
)
|
||||
@@ -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
|
||||
@@ -0,0 +1,58 @@
|
||||
# IP certificate regression tests
|
||||
|
||||
Run from the repository root in Bash. The suite uses temporary files, mocks ACME
|
||||
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
|
||||
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`, `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;
|
||||
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 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:
|
||||
|
||||
```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
|
||||
bash scripts/test/ip-ssl-acme-lifecycle-test.sh /tmp/acme-3.1.5.sh /tmp/acme-3.1.6.sh
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -0,0 +1,486 @@
|
||||
#!/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" 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" <<EOF
|
||||
[ca]
|
||||
default_ca = fixture
|
||||
[fixture]
|
||||
database = $TEMP/ca-index
|
||||
serial = $TEMP/ca-serial
|
||||
new_certs_dir = $TEMP
|
||||
default_md = sha256
|
||||
policy = subject
|
||||
[subject]
|
||||
commonName = supplied
|
||||
EOF
|
||||
for name in old new later v4 dns expired; do
|
||||
san="IP:$ipv4,IP:$ipv6"
|
||||
case "$name" in
|
||||
v4) san="IP:$ipv4" ;;
|
||||
dns) san="DNS:$ipv4,DNS:$ipv6" ;;
|
||||
esac
|
||||
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
|
||||
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/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"
|
||||
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"
|
||||
cp "$TEMP/old.pem" "$cert_dir/fullchain.pem"
|
||||
cp "$TEMP/old.key" "$cert_dir/privkey.pem"
|
||||
|
||||
cat > "$TEMP/mockbin/crontab" <<'MOCK'
|
||||
#!/usr/bin/env bash
|
||||
case "$1" in
|
||||
-l) cat "$CRON_FILE" ;;
|
||||
-) [[ "${CRON_FAIL:-0}" == 0 ]] && 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"
|
||||
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|--renew)
|
||||
mkdir -p "$entry"
|
||||
if [[ "$action" == --issue ]]; then
|
||||
printf "Le_Alt='%s'\n" "${san:-no}" > "$conf"
|
||||
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
|
||||
: > "$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)
|
||||
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' "$action" >&2; exit 1 ;;
|
||||
esac
|
||||
MOCK
|
||||
env chmod +x "$acme" "$TEMP/mockbin/crontab"
|
||||
reload="test \"\$RELOAD_FAIL\" = 0 && printf 'reloaded\\n' >> '$RELOAD_LOG'"
|
||||
|
||||
fixture() {
|
||||
export ISSUED_CERT="$TEMP/$1.pem" ISSUED_KEY="$TEMP/${2:-$1}.key"
|
||||
}
|
||||
|
||||
issue() {
|
||||
ip_ssl_issue_and_install "$acme" "${1:-$ipv4}" "$ipv6" "$port" "${2:-$cert_dir}" "$reload"
|
||||
}
|
||||
|
||||
live_is() {
|
||||
cmp "$TEMP/$1.pem" "$cert_dir/fullchain.pem" && cmp "$TEMP/$1.key" "$cert_dir/privkey.pem"
|
||||
}
|
||||
|
||||
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"
|
||||
}
|
||||
|
||||
reject() {
|
||||
if "$@" > "$TEMP/rejected" 2>&1; then fail "unexpected success: $*"; fi
|
||||
}
|
||||
|
||||
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
|
||||
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
|
||||
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
|
||||
# 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 "$@"
|
||||
}
|
||||
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,SC2329
|
||||
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,SC2329
|
||||
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,SC2329
|
||||
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
|
||||
# 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'
|
||||
[[ ! -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'
|
||||
[[ "$(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,SC2329
|
||||
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,SC2329
|
||||
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'
|
||||
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")
|
||||
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'
|
||||
|
||||
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'
|
||||
}
|
||||
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
|
||||
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" </dev/null > "$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'
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/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=SC2317,SC2329
|
||||
setup_ip_certificate() { captured="${2:-}"; called=1; }
|
||||
# shellcheck disable=SC2317,SC2329
|
||||
systemctl() { stopped=1; }
|
||||
export NONINTERACTIVE=1 XUI_SSL_MODE=ip XUI_SSL_IPV6='not:ipv6'
|
||||
called=0; stopped=0
|
||||
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; 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 </dev/null > "$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 > /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() { :; }
|
||||
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
|
||||
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: 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'
|
||||
@@ -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'
|
||||
@@ -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 '' </dev/null)" '' 'unattended mode skips detection without explicit configuration'
|
||||
same "$(ip_ssl_select_ipv6 0 '2606:4700::2' </dev/null)" '2606:4700::2' 'unattended explicit override'
|
||||
if ip_ssl_select_ipv6 0 'bad:ipv6' </dev/null 2>"$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'
|
||||
@@ -56,7 +56,13 @@ case "$1" in
|
||||
printf 'webBasePath: %s\n' "${path:-/}" ;;
|
||||
esac
|
||||
exit 0 ;;
|
||||
-getCert) echo 'cert: /tmp/panel.example/fullchain.pem'; exit 0 ;;
|
||||
-getCert)
|
||||
if [[ "$TEST_READ_MODE" == ssl_failure ]]; then
|
||||
echo 'cert:'
|
||||
else
|
||||
echo 'cert: /tmp/panel.example/fullchain.pem'
|
||||
fi
|
||||
exit 0 ;;
|
||||
-getApiToken) echo 'apiToken: test-token'; exit 0 ;;
|
||||
esac
|
||||
printf 'write\n' >> "$state/writes"
|
||||
@@ -125,7 +131,13 @@ SSL_HOST=panel.example
|
||||
curl() { printf '203.0.113.10\n200\n'; }
|
||||
systemctl() { printf '%s\n' "$*" >> "$TEST_SETTINGS_DIR/restarts"; }
|
||||
rc-service() { printf '%s\n' "$*" >> "$TEST_SETTINGS_DIR/restarts"; }
|
||||
prompt_and_setup_ssl() { printf '%s\n' "$*" > "$TEST_SETTINGS_DIR/ssl"; }
|
||||
prompt_and_setup_ssl() {
|
||||
printf '%s\n' "$*" > "$TEST_SETTINGS_DIR/ssl"
|
||||
if [[ "$TEST_READ_MODE" == ssl_failure ]]; then
|
||||
printf 'ssl\n' >> "$TEST_SETTINGS_DIR/lifecycle"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
write_install_result() { printf '%s\n' "$@" > "$TEST_SETTINGS_DIR/result"; }
|
||||
install_postgres_local() { echo 'unexpected PostgreSQL installation' >&2; exit 97; }
|
||||
chown() { :; }
|
||||
@@ -295,6 +307,23 @@ func TestScriptConfigReadFailureKeepsServiceSetup(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("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, want := range map[string]string{
|
||||
"lifecycle": "ssl\nmigrate\nfail2ban\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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallMigrationFailurePreventsServiceStart(t *testing.T) {
|
||||
dir, out, err := runScriptConfig(t, "install.sh", "/a/", false, "migration_failure", 1, true)
|
||||
if err == nil || !strings.Contains(out, "Database migration failed") {
|
||||
|
||||
@@ -40,9 +40,652 @@ 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<NF;i++)if($i=="src"){print $(i+1);exit}}') || source=''
|
||||
if [[ -n "$source" ]]; then preferred=$(ip_ssl_expand_ipv6 "$source") || preferred=''; fi
|
||||
while IFS= read -r line; do
|
||||
[[ " $line " == *' scope global '* ]] || continue
|
||||
case " $line " in
|
||||
*' tentative '*|*' optimistic '*|*' deprecated '*|*' dadfailed '*|*' detached '*|*' preferred_lft 0sec '*) continue ;;
|
||||
esac
|
||||
IFS=' ' read -r -a fields <<< "$line"
|
||||
cidr=''
|
||||
for ((i=0; i+1<${#fields[@]}; i++)); do
|
||||
if [[ "${fields[i]}" == inet6 ]]; then cidr="${fields[i+1]}"; break; fi
|
||||
done
|
||||
[[ "$cidr" =~ ^([^/]+)/([0-9]{1,3})$ ]] || continue
|
||||
((10#${BASH_REMATCH[2]} <= 128)) || continue
|
||||
address="${BASH_REMATCH[1]}"
|
||||
ip_ssl_public_ipv6 "$address" || continue
|
||||
expanded=$(ip_ssl_expand_ipv6 "$address") || continue
|
||||
if [[ -n "${seen[$expanded]:-}" ]]; then
|
||||
[[ "${seen[$expanded]}" == temporary && " $line " != *' temporary '* ]] || continue
|
||||
fi
|
||||
label=stable; rank=1
|
||||
if [[ "$expanded" == "$preferred" ]]; then label='default route'; rank=0; fi
|
||||
if [[ " $line " == *' temporary '* ]]; then
|
||||
seen[$expanded]=temporary
|
||||
privacy+=("$rank"$'\t'"$address"$'\t'"temporary")
|
||||
else
|
||||
seen[$expanded]=stable
|
||||
stable+=("$rank"$'\t'"$address"$'\t'"$label")
|
||||
fi
|
||||
done < <(ip -o -6 addr show up scope global 2> /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_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"
|
||||
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
|
||||
# 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
|
||||
[[ ! -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
|
||||
((${#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
|
||||
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=''
|
||||
# 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
|
||||
printf 'Invalid ACME home in the IP certificate journal. Keep recovery files at %s.\n' "$pending" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
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
|
||||
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" ]]; 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)); 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
|
||||
# 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
|
||||
}
|
||||
|
||||
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="$state/staging" pending_init="$state/pending-init"
|
||||
local -a scope domains=(-d "$ipv4")
|
||||
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
|
||||
|
||||
# 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_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
|
||||
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" 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
|
||||
[[ "$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() {
|
||||
is_ipv4 "$1" || is_ipv6 "$1"
|
||||
}
|
||||
@@ -1487,7 +2130,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
|
||||
@@ -1498,7 +2147,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
|
||||
@@ -1524,8 +2175,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
|
||||
@@ -1639,6 +2298,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)"
|
||||
|
||||
@@ -1659,7 +2319,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
|
||||
@@ -1677,7 +2337,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
|
||||
@@ -1685,10 +2345,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
|
||||
@@ -1722,24 +2380,13 @@ 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 dcron > /dev/null 2>&1
|
||||
;;
|
||||
*)
|
||||
LOGW "Unsupported OS for automatic socat installation"
|
||||
;;
|
||||
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
|
||||
@@ -1779,53 +2426,12 @@ 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
|
||||
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
|
||||
|
||||
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"
|
||||
@@ -1838,8 +2444,11 @@ 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}"
|
||||
fi
|
||||
LOGI "Panel will restart to apply SSL certificate..."
|
||||
restart
|
||||
else
|
||||
|
||||
Reference in New Issue
Block a user