mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
628 lines
29 KiB
Bash
628 lines
29 KiB
Bash
# 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
|
|
if ip_ssl_legacy_busy "$acme"; then
|
|
printf 'Wait for the existing acme.sh command to finish, then retry IP certificate setup.\n' >&2
|
|
return 1
|
|
fi
|
|
for name in "${retire[@]}"; do
|
|
[[ -d "$home/$name" ]] || continue
|
|
# Journal before the same-directory rename so a crash can restore it.
|
|
printf '%s\n' "$name" >> "$state/pending/legacy" &&
|
|
mv -T -- "$home/$name" "$home/.xui-retired-$gen-$name" || return 1
|
|
done
|
|
if ip_ssl_legacy_busy "$acme"; then
|
|
printf 'An existing acme.sh command started during migration. Retry IP certificate setup after it exits.\n' >&2
|
|
return 1
|
|
fi
|
|
}
|
|
|
|
ip_ssl_recover() {
|
|
local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending"
|
|
local gen='' home='' current='' entry held file name failed=0 previous=''
|
|
[[ -d "$pending" ]] || return 0
|
|
if [[ -f "$pending/generation" ]]; then
|
|
if ! IFS= read -r gen < "$pending/generation" || [[ ! "$gen" =~ ^gen\.[a-zA-Z0-9]+$ ]]; then
|
|
printf 'Invalid IP certificate generation journal. Keep recovery files at %s.\n' "$pending" >&2
|
|
return 1
|
|
fi
|
|
fi
|
|
current=$(readlink -- "$state/current") || current=''
|
|
if [[ -f "$pending/home" ]] && ! IFS= read -r home < "$pending/home"; then
|
|
printf 'Invalid ACME home in the IP certificate journal. Keep recovery files at %s.\n' "$pending" >&2
|
|
return 1
|
|
fi
|
|
|
|
if [[ -n "$gen" && "$current" == "$gen" ]]; then
|
|
# Commit is the pointer swap. Never roll back a committed generation.
|
|
if [[ -f "$pending/legacy" ]]; then
|
|
while IFS= read -r entry; do
|
|
ip_ssl_ipv4 "${entry%_ecc}" && [[ -n "$home" ]] &&
|
|
rm -rf -- "$home/.xui-retired-$gen-$entry" || failed=1
|
|
done < "$pending/legacy"
|
|
fi
|
|
if [[ -f "$state/$gen/previous" ]]; then IFS= read -r previous < "$state/$gen/previous" || failed=1; fi
|
|
for entry in "$state"/gen.*; do
|
|
name="${entry##*/}"
|
|
[[ "$name" != "$gen" && "$name" != "$previous" ]] || continue
|
|
rm -rf -- "$entry" || failed=1
|
|
done
|
|
else
|
|
if [[ -f "$pending/live-changing" ]]; then
|
|
for file in fullchain.pem privkey.pem; do
|
|
if [[ -e "$pending/live/$file" || -L "$pending/live/$file" ]]; then
|
|
rm -f -- "$pending/restore" &&
|
|
cp -a -- "$pending/live/$file" "$pending/restore" &&
|
|
mv -Tf -- "$pending/restore" "$dir/$file" || failed=1
|
|
else
|
|
rm -f -- "$dir/$file" || failed=1
|
|
fi
|
|
done
|
|
fi
|
|
# Keep stock cron away from the public paths until the original file
|
|
# types are restored. A failed restore may still leave a live alias.
|
|
if ((!failed)) && [[ -f "$pending/legacy" ]]; then
|
|
while IFS= read -r entry; do
|
|
if ! ip_ssl_ipv4 "${entry%_ecc}" || [[ -z "$home" || -z "$gen" ]]; then failed=1; continue; fi
|
|
held="$home/.xui-retired-$gen-$entry"
|
|
if [[ -e "$held" ]]; then
|
|
if [[ -e "$home/$entry" || -L "$home/$entry" ]] ||
|
|
! mv -T -- "$held" "$home/$entry"; then
|
|
printf 'ACME recovery copy remains at %s\n' "$held" >&2
|
|
failed=1
|
|
fi
|
|
elif [[ ! -d "$home/$entry" ]]; then
|
|
failed=1
|
|
fi
|
|
done < "$pending/legacy"
|
|
fi
|
|
if ((!failed)) && [[ -n "$gen" ]]; then rm -rf -- "${state:?}/${gen:?}" || failed=1; fi
|
|
fi
|
|
if ((failed)); then
|
|
printf 'IP certificate recovery could not complete. Keep recovery files at %s and retry after resolving the error.\n' "$pending" >&2
|
|
return 1
|
|
fi
|
|
if ! rm -f -- "$state/staging/fullchain.pem" "$state/staging/privkey.pem" || ! rm -rf -- "$pending"; then
|
|
printf 'Could not remove the IP certificate journal at %s\n' "$pending" >&2
|
|
return 1
|
|
fi
|
|
}
|
|
|
|
ip_ssl_aliases() {
|
|
local dir="$1" state="$1/.xui-ip-ssl" pending="$1/.xui-ip-ssl/pending"
|
|
local file seed
|
|
if [[ -f "$state/current/config" ]]; then
|
|
for file in fullchain.pem privkey.pem; do
|
|
[[ "$(readlink -- "$dir/$file")" == ".xui-ip-ssl/current/$file" ]] || return 1
|
|
done
|
|
return 0
|
|
fi
|
|
# The seed contains the original bytes, so converting either alias first
|
|
# still exposes the same pair. The journal keeps the original file types.
|
|
seed=$(mktemp -d "$state/gen.XXXXXX") || return 1
|
|
for file in fullchain.pem privkey.pem; do
|
|
if [[ -e "$pending/live/$file" || -L "$pending/live/$file" ]]; then
|
|
# Follow the original live symlink relative to its own directory.
|
|
cp -pL -- "$dir/$file" "$seed/$file" || return 1
|
|
fi
|
|
done
|
|
ip_ssl_link "$state" "${seed##*/}" "$state/current" &&
|
|
touch "$pending/live-changing" || return 1
|
|
for file in fullchain.pem privkey.pem; do
|
|
ip_ssl_link "$state" ".xui-ip-ssl/current/$file" "$dir/$file" || return 1
|
|
done
|
|
}
|
|
|
|
ip_ssl_validate_pair() {
|
|
local chain="$1" key="$2" ipv4="$3" ipv6="$4" cert_pub key_pub
|
|
[[ -s "$chain" && -s "$key" ]] &&
|
|
openssl crl2pkcs7 -nocrl -certfile "$chain" -out /dev/null &&
|
|
openssl verify -purpose sslserver -untrusted "$chain" -verify_ip "$ipv4" "$chain" >/dev/null || return 1
|
|
[[ -z "$ipv6" ]] || openssl verify -purpose sslserver -untrusted "$chain" -verify_ip "$ipv6" "$chain" >/dev/null || return 1
|
|
cert_pub=$(openssl x509 -in "$chain" -pubkey -noout) &&
|
|
key_pub=$(openssl pkey -in "$key" -passin pass: -pubout) &&
|
|
[[ -n "$cert_pub" && "$cert_pub" == "$key_pub" ]]
|
|
}
|
|
|
|
ip_ssl_reload() {
|
|
local gen="$1" reload="$2"
|
|
if sh -c "$reload" 9>&-; then
|
|
rm -f -- "$gen/reload-pending" ||
|
|
printf 'Could not clear the IP certificate reload marker.\n' >&2
|
|
else
|
|
printf 'A valid certificate is installed. Panel reload failed and will be retried by the IP certificate job.\n' >&2
|
|
fi
|
|
}
|
|
|
|
ip_ssl_schedule() (
|
|
local state="$1" home="$2" command line existing
|
|
[[ "$state" != *[$'\n\r%']* ]] || return 1
|
|
# Different destinations share the user's crontab, but can order and stage in parallel.
|
|
exec 8>>"$home/.xui-ip-crontab.lock" && flock -x 8 || return 1
|
|
command=$(ip_ssl_shell_quote "$state/renew-v1")
|
|
line="19 * * * * $command # x-ui managed IP certificate"
|
|
if ! existing=$(LC_ALL=C crontab -l 2>&1); then
|
|
case "$existing" in
|
|
*"no crontab for "*|*"No such file or directory"*) existing='' ;;
|
|
*) printf 'Could not read crontab: %s\n' "$existing" >&2; return 1 ;;
|
|
esac
|
|
fi
|
|
if grep -Fxq -- "$line" <<< "$existing"; then return 0; fi
|
|
{ printf '%s\n' "$existing"; printf '%s\n' "$line"; } | crontab -
|
|
)
|
|
|
|
ip_ssl_account_config() (
|
|
local home="$1" cert_home="$2" ACCOUNT_CONF_PATH=''
|
|
# acme.sh sources account.conf after parsing --cert-home, so a saved
|
|
# CERT_HOME overrides the command line. Keep this override private.
|
|
if [[ -f "$home/account.conf" ]]; then
|
|
# shellcheck disable=SC1091
|
|
source "$home/account.conf" || return 1
|
|
fi
|
|
local original="${ACCOUNT_CONF_PATH:-$home/account.conf}"
|
|
if [[ -f "$original" ]]; then cat -- "$original" || return 1; fi
|
|
printf '\nCERT_HOME=%s\n' "$(ip_ssl_shell_quote "$cert_home")"
|
|
)
|
|
|
|
ip_ssl_legacy_home() (
|
|
local home="$1" ACCOUNT_CONF_PATH='' CERT_HOME=''
|
|
if [[ -f "$home/account.conf" ]]; then
|
|
# shellcheck disable=SC1091
|
|
source "$home/account.conf" || return 1
|
|
fi
|
|
if [[ -n "$ACCOUNT_CONF_PATH" && -f "$ACCOUNT_CONF_PATH" ]]; then
|
|
# shellcheck disable=SC1090
|
|
source "$ACCOUNT_CONF_PATH" || return 1
|
|
fi
|
|
printf '%s\n' "${CERT_HOME:-$home}"
|
|
)
|
|
|
|
ip_ssl_transaction() (
|
|
local action="$1" acme="$2" ipv4="$3" ipv6="$4" port="$5" dir="$6" reload="$7"
|
|
local state="$dir/.xui-ip-ssl" pending="$dir/.xui-ip-ssl/pending" home="${acme%/*}"
|
|
local work gen file previous rc legacy_home stage="$dir/.xui-ip-ssl/staging"
|
|
local -a scope domains=(-d "$ipv4")
|
|
mkdir -- "$pending" || return 1
|
|
# Recovery runs under the caller's flock, including on normal exit.
|
|
trap 'rc=$?; ip_ssl_recover "$dir" || rc=1; exit "$rc"' EXIT
|
|
trap 'exit 130' INT
|
|
trap 'exit 143' TERM
|
|
trap 'exit 129' HUP
|
|
|
|
work=$(mktemp -d "$state/gen.XXXXXX") || return 1
|
|
gen="${work##*/}"
|
|
printf '%s\n' "$gen" > "$pending/generation" && mkdir -- "$work/acme" "$pending/live" || return 1
|
|
if [[ "$action" == issue ]]; then
|
|
legacy_home=$(ip_ssl_legacy_home "$home") || return 1
|
|
[[ "$legacy_home" == /* && "$legacy_home" != *[$'\n\r']* ]] || return 1
|
|
printf '%s\n' "$legacy_home" > "$pending/home" &&
|
|
ip_ssl_retire_legacy "$state" "$acme" "$ipv4" "$dir" "$gen" "$legacy_home" || return 1
|
|
fi
|
|
for file in fullchain.pem privkey.pem; do
|
|
[[ ! -e "$dir/$file" && ! -L "$dir/$file" ]] ||
|
|
cp -a -- "$dir/$file" "$pending/live/$file" || return 1
|
|
done
|
|
if [[ -f "$state/current/config" ]]; then
|
|
previous=$(readlink -- "$state/current") &&
|
|
printf '%s\n' "$previous" > "$work/previous" || return 1
|
|
fi
|
|
if [[ "$action" != issue ]]; then
|
|
cp -a -- "$state/current/acme/." "$work/acme/" || return 1
|
|
fi
|
|
[[ ! -L "$stage" ]] && mkdir -p -- "$stage" && chmod 700 -- "$stage" &&
|
|
rm -f -- "$stage/fullchain.pem" "$stage/privkey.pem" || return 1
|
|
ip_ssl_account_config "$home" "$work/acme" > "$pending/account.conf" || return 1
|
|
scope=(--home "$home" --cert-home "$work/acme" --accountconf "$pending/account.conf")
|
|
# acme.sh saves destinations in single quotes. A fixed private working
|
|
# directory makes relative install paths safe even with a quoted parent.
|
|
cd -- "$state" || return 1
|
|
if [[ "$action" == issue ]]; then
|
|
[[ -z "$ipv6" ]] || domains+=(-d "$ipv6")
|
|
if ! "$acme" --issue "${scope[@]}" "${domains[@]}" --keylength ec-256 --standalone "${IP_SSL_LISTEN_ARGS[@]}" \
|
|
--server letsencrypt --certificate-profile shortlived --days 6 --httpport "$port" --force; then
|
|
printf 'IP certificate issuance failed. Check external port 80 on each selected address.\n' >&2
|
|
return 1
|
|
fi
|
|
else
|
|
rc=0
|
|
local -a force=()
|
|
[[ "$action" != renew-force ]] || force=(--force)
|
|
"$acme" --renew "${scope[@]}" -d "$ipv4" --ecc "${force[@]}" || rc=$?
|
|
# acme.sh uses 2 when a certificate is not due for renewal.
|
|
if ((rc == 2)); then return 0; fi
|
|
((rc == 0)) || return "$rc"
|
|
fi
|
|
# A renewal may already have copied to staging. Require both outputs from
|
|
# this explicit install so an incomplete copy cannot reuse an older file.
|
|
rm -f -- "$stage/fullchain.pem" "$stage/privkey.pem" || return 1
|
|
if ! "$acme" --installcert "${scope[@]}" --ecc -d "$ipv4" --key-file staging/privkey.pem \
|
|
--fullchain-file staging/fullchain.pem --reloadcmd ""; then
|
|
printf 'Could not stage the IP certificate and key.\n' >&2
|
|
return 1
|
|
fi
|
|
if ! ip_ssl_validate_pair "$stage/fullchain.pem" "$stage/privkey.pem" "$ipv4" "$ipv6"; then
|
|
printf 'Staged IP certificate failed SAN, validity or private-key checks.\n' >&2
|
|
return 1
|
|
fi
|
|
cp -- "$stage/privkey.pem" "$work/privkey.pem" &&
|
|
cp -- "$stage/fullchain.pem" "$work/fullchain.pem" &&
|
|
chmod 600 -- "$work/privkey.pem" && chmod 644 -- "$work/fullchain.pem" &&
|
|
printf 'managed_acme=%q\nmanaged_ipv4=%q\nmanaged_ipv6=%q\nmanaged_reload=%q\n' "$acme" "$ipv4" "$ipv6" "$reload" > "$work/config" &&
|
|
touch "$work/reload-pending" || return 1
|
|
if [[ "$action" == issue ]]; then ip_ssl_schedule "$state" "$home" || return 1; fi
|
|
ip_ssl_aliases "$dir" &&
|
|
ip_ssl_link "$state" "$gen" "$state/current" || return 1
|
|
ip_ssl_reload "$work" "$reload"
|
|
)
|
|
|
|
ip_ssl_scheduled() (
|
|
local dir="$1" state="$1/.xui-ip-ssl" action="${2:-renew}"
|
|
local managed_acme managed_ipv4 managed_ipv6 managed_reload
|
|
ip_ssl_lock "$dir" && ip_ssl_recover "$dir" || return 1
|
|
[[ -f "$state/current/config" ]] || return 0
|
|
# This file is generated with Bash quoting under the private state directory.
|
|
# shellcheck disable=SC1091
|
|
source "$state/current/config" || return 1
|
|
if [[ -f "$state/current/reload-pending" ]]; then ip_ssl_reload "$state/current" "$managed_reload"; fi
|
|
ip_ssl_transaction "$action" "$managed_acme" "$managed_ipv4" "$managed_ipv6" '' "$dir" "$managed_reload"
|
|
)
|
|
|
|
ip_ssl_revoke_managed() (
|
|
local dir="$1" state="$1/.xui-ip-ssl" managed_acme managed_ipv4 gen account
|
|
ip_ssl_lock "$dir" && ip_ssl_recover "$dir" || return 1
|
|
[[ -f "$state/current/config" ]] || return 1
|
|
# shellcheck disable=SC1091
|
|
source "$state/current/config" || return 1
|
|
account=$(mktemp "$state/.account.XXXXXX") || return 1
|
|
trap 'rm -f -- "$account"' EXIT
|
|
ip_ssl_account_config "${managed_acme%/*}" "$state/current/acme" > "$account" || return 1
|
|
"$managed_acme" --revoke --home "${managed_acme%/*}" --cert-home "$state/current/acme" --accountconf "$account" -d "$managed_ipv4" --ecc ||
|
|
printf 'CA revocation failed. Removing local renewal state and files.\n' >&2
|
|
# Keep the lock inode and inert scheduled runner for later issuance.
|
|
rm -f -- "$state/current" "$dir/fullchain.pem" "$dir/privkey.pem" || return 1
|
|
for gen in "$state"/gen.*; do rm -rf -- "$gen" || return 1; done
|
|
)
|
|
|
|
ip_ssl_write_runner() {
|
|
local state="$1" temp
|
|
temp=$(mktemp "$state/.runner.XXXXXX") || return 1
|
|
if {
|
|
printf '#!/bin/bash\n# x-ui managed IP certificate deployment v1\n'
|
|
# The OpenRC service commands live in /sbin on Alpine.
|
|
# shellcheck disable=SC2016
|
|
printf 'export PATH="${PATH:+$PATH:}/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"\n'
|
|
declare -f ip_ssl_ipv4 ip_ssl_shell_quote ip_ssl_link ip_ssl_lock ip_ssl_legacy_busy \
|
|
ip_ssl_retire_legacy ip_ssl_recover ip_ssl_aliases ip_ssl_validate_pair ip_ssl_reload \
|
|
ip_ssl_schedule ip_ssl_account_config ip_ssl_legacy_home ip_ssl_transaction ip_ssl_scheduled
|
|
# shellcheck disable=SC2016
|
|
printf '\nip_ssl_scheduled "$(cd -- "$(dirname -- "$0")/.." && pwd -P)"\n'
|
|
} > "$temp" && chmod 700 -- "$temp" && mv -Tf -- "$temp" "$state/renew-v1"; then
|
|
return 0
|
|
fi
|
|
rm -f -- "$temp" || printf 'Could not remove incomplete renewal helper %s\n' "$temp" >&2
|
|
return 1
|
|
}
|
|
|
|
ip_ssl_issue_and_install() (
|
|
local acme="$1" ipv4="$2" ipv6="$3" port="$4" 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"
|
|
)
|