diff --git a/.github/workflows/command-tests.yml b/.github/workflows/command-tests.yml index fc29714..013c043 100644 --- a/.github/workflows/command-tests.yml +++ b/.github/workflows/command-tests.yml @@ -31,7 +31,7 @@ jobs: timeout-minutes: 5 steps: - uses: actions/checkout@v4 - - name: Install archive tooling for restore tests - run: sudo apt-get update && sudo apt-get install -y zip unzip sqlite3 jq + - name: Install unit and transport test dependencies + run: sudo apt-get update && sudo apt-get install -y zip unzip sqlite3 jq openssl python3 socat - name: Run all unit tests run: bash tests/run_all.sh diff --git a/README.md b/README.md index ed8165a..0e5d274 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,32 @@ Once installed, manage the node using the global `pg-node` command: sudo pg-node status ``` +Use `help` to view all commands: +`pg-node help` + +### Node certificate management + +New `pg-node install` runs default to Let's Encrypt IP certificates. Unattended +installation requires `--ssl-ip YOUR_PUBLIC_IPV4`; optionally add `--ssl-ipv6`. +Use `--ssl-domain DOMAIN`, paired `--cert-path`/`--key-path`, or explicit +`--self-signed` to choose another source. `--ssl-http-port` (`--ssl-port`) changes +the local HTTP-01 listener; public port 80 must still reach it. + +`--no-ssl` is exclusively for private backends behind an external TLS web server. +The panel must use the web server's TLS endpoints for both node and maintenance +requests. API-key authentication stays required. Certificate source metadata is +stored under the instance data directory; `renew-cert` follows that source and +`show-cert` displays its identity, expiry, fingerprint and legacy PEM. +Renewal uses SIGHUP and verifies fresh TLS connections, with no restart fallback. +`certificate-status --json` reports local deployment and renewal state. +Upgrade both node and node-serviced to releases supporting certificate hot reload +before enabling this workflow on an existing installation with +`sudo pg-node certificate-renewal-enable`. + +Old unattended commands relying on implicit self-signed certificates must add +`--self-signed`. Routine updates preserve certificate paths and files. See +[the node TLS deployment guide](https://github.com/PasarGuard/node/blob/main/docs/node-tls.md) +for nginx examples, verification fields, renewal, private bindings and rollback. --- ## 🔧 Installation Options @@ -210,7 +236,10 @@ The following flags can be supplied to `pasarguard install`: | `pg-node logs` | Streams live logs from the node container. | | `pg-node core-update` | Updates or switches the installed Xray-core binary version. | | `pg-node geofiles` | Downloads official `geoip.dat` and `geosite.dat` routing assets. | -| `pg-node renew-cert` | Regenerates self-signed TLS certificates with SAN entries. | +| `pg-node renew-cert` | Renews or validates certificates according to their configured source. | +| `pg-node certificate-status [--json]` | Reports local renewal state, expiry, verified fingerprint and errors. | +| `pg-node certificate-renewal-enable` | Enables the managed ACME scheduler after both services support SIGHUP reload. | +| `pg-node show-cert` | Displays certificate identity, expiry, fingerprint, and legacy PEM. | | `pg-node service-install` | Registers and enables the companion `systemd` service daemon. | | `pg-node service-status` | Inspects systemd service status (`pg-node-service.service`). | | `pg-node service-logs` | Tails journalctl logs for the background service. | diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 3b57dc9..996dae2 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -213,6 +213,11 @@ Installs or re-installs a worker node instance. - `--use-rest`: Connect to panel over REST protocol. - `--service-port `: Port for proxy traffic. - `--api-port `: Port for node daemon API. +- `--ssl-ip `: Issue a Let's Encrypt IP certificate (default source; explicit IP required unattended). +- `--ssl-ipv6 `: Add an IPv6 identifier alongside `--ssl-ip`. +- `--ssl-domain `: Issue a Let's Encrypt domain certificate. +- `--ssl-http-port ` (`--ssl-port`): Local HTTP-01 listener; public port 80 must reach it. +- `--no-ssl`: Use a private backend behind an external TLS web server. API-key authentication remains required. - `--self-signed`: Automatically generate self-signed TLS certificates with SAN. - `--cert-path `: Path to existing public TLS certificate. - `--key-path `: Path to existing private TLS key. @@ -273,11 +278,23 @@ sudo pg-node geofiles russia ``` #### `renew-cert` -Regenerates self-signed SSL/TLS certificates and Subject Alternative Names (SANs) for the node. + + + + +Renews ACME or self-signed certificates according to the saved source. Without `source.json`, a legacy certificate whose subject and issuer match is treated as self-signed and regenerated with a new certificate and key. Custom and other legacy certificates are validated without replacement; external TLS certificates are managed on the web server. + + ```bash sudo pg-node renew-cert ``` +#### `show-cert` +Displays certificate identity, expiry, SHA-256 fingerprint, and legacy PEM. +```bash +sudo pg-node show-cert +``` + #### `edit` / `edit-env` Edits the node's `docker-compose.yml` or `.env` file in the system default editor. diff --git a/docs/ssl-and-certificates.md b/docs/ssl-and-certificates.md index 8d20392..ff14bdf 100644 --- a/docs/ssl-and-certificates.md +++ b/docs/ssl-and-certificates.md @@ -90,6 +90,14 @@ sudo pasarguard install --no-ssl Worker nodes (`pg-node`) communicate with the central panel over encrypted gRPC or REST channels. +New installs default to Let's Encrypt IP certificates; unattended installs require +`--ssl-ip YOUR_PUBLIC_IPV4` (optionally `--ssl-ipv6`). Use `--ssl-domain DOMAIN`, +paired `--cert-path`/`--key-path`, or `--self-signed` for another source. +`--no-ssl` requires a private backend behind an external TLS web server; configure +the panel with the web server's TLS endpoints for both node and maintenance requests. +See [the node TLS deployment guide](https://github.com/PasarGuard/node/blob/main/docs/node-tls.md) +for routing, renewal, verification, and rollback details. + ### Self-Signed Certificate Generation Nodes can generate their own self-signed certificates with a single flag: ```bash @@ -113,16 +121,60 @@ PasarGuard automatically normalizes entries to OpenSSL format (`IP:198.51.100.2, ### Certificate Verification Levels The `pg-node-service` daemon inspects certificates upon startup using OpenSSL syntax and subject-versus-issuer comparison: -- **CA-Signed / Differing Subject and Issuer (`0`)**: Issuer does not match Subject. Configures strict TLS client verification (`verify=1`). -- **Self-Signed (`2`)**: Issuer matches Subject. Allows local communication with verification relaxed (`verify=0`). +- **CA-Signed / Differing Subject and Issuer (`0`)**: Issuer does not match Subject. Uses server TLS without requesting client certificates (`verify=0`); API-key authentication remains required. +- **Self-Signed (`2`)**: Issuer matches Subject. Uses server TLS without requesting client certificates (`verify=0`); API-key authentication remains required. - **Invalid / Unreadable (`1`)**: Missing file or invalid certificate syntax. The service logs an error and halts startup (fails closed) by default. Insecure operation requires an explicit opt-in (`ALLOW_INSECURE_TLS=true`) before relaxed verification (`verify=0`) is permitted. ### Certificate Renewal (`renew-cert`) -To regenerate an expired or outdated node certificate: +To renew or validate a node certificate according to its saved source: ```bash sudo pg-node renew-cert ``` -This updates the certificate in `/var/lib/pg-node/certs/` and restarts the node container and companion service. +ACME sources renew through acme.sh. Self-signed sources regenerate only when you +explicitly run `renew-cert`, preserving the 3,650-day lifetime and installed SANs. +The command prints the new certificate fingerprint. +Custom and legacy sources validate the operator-maintained files. External TLS +certificates and graceful frontend reloads remain managed on the web server. + +Certificate deployment preserves configured file paths and container mappings, +sends SIGHUP to the Compose `node` process and the systemd maintenance main +process, and verifies their fingerprints through fresh TLS handshakes. Only an +installed maintenance service is checked. Success requires all deployed endpoints +to match. Reload failures retain previous file backups (`.previous`) and retry the +reload without issuance. There is no automatic restart fallback. + +**Rollout prerequisite:** first upgrade both node and node-serviced to versions +supporting certificate reload on SIGHUP. That initial software upgrade requires a +restart. Enabling hooks against older versions can terminate them on SIGHUP. +After the upgrade, enable or migrate an existing managed ACME installation: + +```bash +sudo pg-node certificate-renewal-enable +sudo pg-node certificate-status +sudo pg-node certificate-status --json +``` + +New managed ACME installations register one per-instance cron entry. It ticks +every five minutes and checks normal renewal eligibility hourly. Certificate +storage is isolated under `$DATA_DIR/certs/acme`, outside the shared ACME cron +scan. Migration copies this certificate's existing ACME directory before disabling +its old shared renewal entry; unrelated certificates and cron jobs stay intact. +The fallback renewal time is two thirds of the issued lifetime. The scheduler +updates only the isolated domain configuration with this fallback, clearing the +old fixed-day setting so supported acme.sh CA renewal guidance can take precedence. Transient failures retry with exponential backoff and jitter +from five minutes up to one hour, honoring longer reported Retry-After delays. +Configuration rejections suspend issuance until `.env` or source metadata changes, +or an operator runs `renew-cert` to retry explicitly. Self-signed, custom, and +external certificates are never regenerated by scheduled jobs. + +Atomic local state lives in `$DATA_DIR/certs/renewal-status.json`; private ACME +diagnostics are in `acme-last-attempt.log`, alongside `renewal.log`. These remain +available without panel connectivity. Status distinguishes the last verified +active fingerprint from the files currently on disk, reports current file date +validity separately, and never treats a past successful reload as proof that an +expired file is still valid. Use `show-cert` for identity, fingerprint and legacy +PEM output. For custom replacements, place the complete matching pair at the +configured paths before invoking `renew-cert`. ### Expiration Monitoring During startup, `pg-node-service` inspects the certificate validity window for CA-signed certificates (where Subject and Issuer differ): diff --git a/pg-node-service.sh b/pg-node-service.sh index 8c3f019..fa75876 100755 --- a/pg-node-service.sh +++ b/pg-node-service.sh @@ -85,15 +85,25 @@ describe_certificate() { return 0 } -# Decide the socat client-certificate verification level: require a client cert -# only for CA-signed certificates. -tls_verify_level() { - local cert_file="$1" - if check_certificate "$cert_file" >/dev/null 2>&1; then - echo "verify=1" - else - echo "verify=0" - fi +# Server issuer classification must never enable mutual TLS. API keys authenticate clients. +tls_verify_level() { echo "verify=0"; } + +private_backend_host() { + command -v python3 >/dev/null 2>&1 || { log "python3 is required to validate private NODE_HOST"; return 1; } + python3 - "$1" <<'PYHOST' +import ipaddress, sys +try: + value = sys.argv[1].strip() + if '%' in value: raise ValueError('zones are not allowed') + addr = ipaddress.ip_address(value) + if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped: addr = addr.ipv4_mapped + allowed = ('127.0.0.0/8', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16') if addr.version == 4 else ('::1/128', 'fc00::/7') + if not any(addr in ipaddress.ip_network(n) for n in allowed): raise ValueError('address is not a private backend') + print(addr) +except ValueError as err: + print('Invalid plaintext NODE_HOST: ' + str(err), file=sys.stderr) + sys.exit(1) +PYHOST } # Byte length of a string. ${#s} counts characters, so a multibyte UTF-8 body @@ -134,6 +144,17 @@ if [[ -z "$API_KEY" ]]; then exit 1 fi +case "${TLS_ENABLED-true}" in + true|TRUE|True|1|t|T) TLS_ENABLED=true ;; + false|FALSE|False|0|f|F) TLS_ENABLED=false ;; + *) log "Invalid TLS_ENABLED: expected a boolean"; exit 1 ;; +esac +if [[ "$TLS_ENABLED" == false ]]; then + NODE_HOST=$(private_backend_host "${NODE_HOST-127.0.0.1}") || exit 1 + command -v socat >/dev/null 2>&1 || { log "socat is required for external TLS backend mode"; exit 1; } +else + NODE_HOST="${NODE_HOST-0.0.0.0}" + [[ "${NODE_HOST,,}" != localhost ]] || NODE_HOST=127.0.0.1 if [[ -z "${SSL_CERT_FILE:-}" || -z "${SSL_KEY_FILE:-}" ]]; then log "TLS required: set SSL_CERT_FILE and SSL_KEY_FILE in the env file" exit 1 @@ -165,6 +186,7 @@ fi describe_certificate "$SSL_CERT_FILE" log "TLS enabled on port $API_PORT with cert=$SSL_CERT_FILE key=$SSL_KEY_FILE" +fi log "API key protection enabled" # Escape JSON special characters for HTTP response formatting. @@ -432,7 +454,7 @@ handle_connection() { # Check if we should use socat (recommended) or openssl s_server if command -v socat >/dev/null 2>&1; then - log "Starting HTTPS server with socat on port $API_PORT..." + log "Starting service with socat on $NODE_HOST:$API_PORT (TLS_ENABLED=$TLS_ENABLED)..." # For socat, we need to handle the case where we're called as a subprocess if [[ "${1:-}" == "--handle-connection" ]]; then @@ -443,21 +465,22 @@ if command -v socat >/dev/null 2>&1; then exit 0 fi - # Determine verify level based on certificate type - verify_level=$(tls_verify_level "$SSL_CERT_FILE") - if [[ "$verify_level" == "verify=1" ]]; then - log "Enabling client certificate verification (CA-signed certificate detected)" + family=4 + bind_host="$NODE_HOST" + if [[ "$NODE_HOST" == *:* ]]; then family=6; bind_host="[$NODE_HOST]"; fi + if [[ "$TLS_ENABLED" == false ]]; then + listen="TCP${family}-LISTEN:${API_PORT},bind=${bind_host},reuseaddr,fork" else - log "Disabling client certificate verification (self-signed or invalid certificate)" + listen="OPENSSL-LISTEN:${API_PORT},pf=ip${family},bind=${bind_host},cert=${SSL_CERT_FILE},key=${SSL_KEY_FILE},verify=0,reuseaddr,fork" fi - - exec socat \ - "OPENSSL-LISTEN:${API_PORT},cert=${SSL_CERT_FILE},key=${SSL_KEY_FILE},${verify_level},reuseaddr,fork" \ - EXEC:"'$0' --handle-connection" + exec socat "$listen" EXEC:"'$0' --handle-connection" + else log "socat not available, using openssl s_server" log "Install socat with your system package manager for better performance" + openssl_bind="${NODE_HOST}:${API_PORT}" + [[ "$NODE_HOST" != *:* ]] || openssl_bind="[${NODE_HOST}]:${API_PORT}" # Main server loop with openssl s_server log "Bash REST API listening on https://localhost:${API_PORT}" @@ -466,7 +489,7 @@ else if coproc OPENSSL { openssl s_server \ -quiet \ - -accept "$API_PORT" \ + -accept "$openssl_bind" \ -cert "$SSL_CERT_FILE" \ -key "$SSL_KEY_FILE" \ -ign_eof \ diff --git a/pg-node.sh b/pg-node.sh index 58d1846..1c616a7 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -53,7 +53,7 @@ bootstrap_pg_node_shared_libs() { # outdated copy can never be sourced (the files are small). Best-effort: if the # refresh fails (e.g. no network) any existing copy is kept and the presence # check below still guards against a genuinely missing library. -if [ "$running_from_checkout" = false ]; then +if [ "$running_from_checkout" = false ] && [[ " $* " != *" certificate-"* && " $* " != *" renew-cert "* ]]; then bootstrap_pg_node_shared_libs || true fi @@ -128,8 +128,12 @@ done set -- "${ARGS[@]}" COMMAND="${1:-}" # Fetch IP address from ifconfig.io API -NODE_IP_V4=$(curl -s -4 --fail --max-time 5 ifconfig.io 2>/dev/null || echo "") -NODE_IP_V6=$(curl -s -6 --fail --max-time 5 ifconfig.io 2>/dev/null || echo "") +NODE_IP_V4='' NODE_IP_V6='' +case "$COMMAND" in + certificate-*|renew-cert|show-cert) ;; + *) NODE_IP_V4=$(curl -s -4 --fail --max-time 5 ifconfig.io 2>/dev/null || echo "") + NODE_IP_V6=$(curl -s -6 --fail --max-time 5 ifconfig.io 2>/dev/null || echo "");; +esac NODE_IP="${NODE_IP_V4:-}" if [ -z "$NODE_IP" ]; then NODE_IP="${NODE_IP_V6:-}" @@ -262,19 +266,30 @@ configure_firewall_for_port() { colorized_echo yellow "$hint" } -# Download and install the pg-node CLI script to /usr/local/bin. +# Install this pg-node CLI version to /usr/local/bin, including branch installs. install_node_script() { print_script_execution_header "pg-node" "$SCRIPT_COMMIT_SHA" "install" colorized_echo blue "Installing node script" TARGET_PATH="/usr/local/bin/$APP_NAME" TEMP_FILE=$(create_temp_file "pg-node-script" ".sh") - # Download script to temp file first - colorized_echo cyan " Downloading script from GitHub..." - if ! github_download_file "$(github_raw_url "$FETCH_REPO" "pg-node.sh")" "$TEMP_FILE"; then - colorized_echo red "✗ Failed to download script from $(github_raw_url "$FETCH_REPO" "pg-node.sh")" + # The ACME hook immediately invokes the installed CLI. Fetching main here + # can replace a branch installer with an older CLI that treats renew-cert + # as self-signed renewal and ignores --deploy-acme. + colorized_echo cyan " Copying the running installer..." + local script_source="${BASH_SOURCE[0]:-}" + if [ -f "$script_source" ]; then + if ! cp "$script_source" "$TEMP_FILE"; then + rm -f "$TEMP_FILE" + return 1 + fi + elif [ -n "${BASH_EXECUTION_STRING:-}" ]; then + # Support the documented bash -c "$(curl ...)" installation form. + printf '%s\n' "$BASH_EXECUTION_STRING" >"$TEMP_FILE" || return 1 + else + colorized_echo red "✗ Cannot locate the running installer" rm -f "$TEMP_FILE" - exit 1 + return 1 fi # Replace APP_NAME in the script - the script has APP_NAME="" on line 5 @@ -283,7 +298,10 @@ install_node_script() { sed -i "s|^APP_NAME=.*|APP_NAME=\"$APP_NAME\"|" "$TEMP_FILE" fi - install_shared_libs_from_repo "$FETCH_REPO" common.sh system.sh docker.sh github.sh + if ! install_shared_libs_from_repo "$FETCH_REPO" common.sh system.sh docker.sh github.sh; then + rm -f "$TEMP_FILE" + return 1 + fi # Remove old file if it exists if [ -f "$TARGET_PATH" ]; then @@ -756,38 +774,7 @@ install_node() { mkdir -p "$APP_DIR" colorized_echo green " ✓ Directories created" colorized_echo cyan "" - colorized_echo yellow "A self-signed certificate will be generated by default." - if [ "${INSTALL_SELF_SIGNED:-false}" = true ]; then - use_public_cert="" - elif [ -n "${INSTALL_CERT_PATH:-}" ] && [ -n "${INSTALL_KEY_PATH:-}" ]; then - use_public_cert="y" - elif [ "$AUTO_CONFIRM" = true ]; then - use_public_cert="" - else - read -r -p "Do you want to use your own public certificate instead? (Y/n): " use_public_cert - fi - if [[ "$use_public_cert" =~ ^[Yy]$ ]]; then - if [ -n "${INSTALL_CERT_PATH:-}" ] && [ -f "$INSTALL_CERT_PATH" ]; then - cp "$INSTALL_CERT_PATH" "$SSL_CERT_FILE" - colorized_echo blue "Certificate copied to $SSL_CERT_FILE" - else - read_and_save_file "Please paste the content OR the path to the Client Certificate file." "$SSL_CERT_FILE" 1 - colorized_echo blue "Certificate saved to $SSL_CERT_FILE" - fi - - if [ -n "${INSTALL_KEY_PATH:-}" ] && [ -f "$INSTALL_KEY_PATH" ]; then - cp "$INSTALL_KEY_PATH" "$SSL_KEY_FILE" - colorized_echo blue "Private key copied to $SSL_KEY_FILE" - else - read_and_save_file "Please paste the content OR the path to the Private Key file." "$SSL_KEY_FILE" 1 - colorized_echo blue "Private key saved to $SSL_KEY_FILE" - fi - # cp/paste create the key with the default umask (0644); restrict it. - harden_secret_file "$SSL_KEY_FILE" - else - gen_self_signed_cert - colorized_echo blue "self-signed certificate successfully generated" - fi + with_node_cert_lock prepare_install_node_certificate || exit 1 if [ -n "${INSTALL_API_KEY:-}" ]; then API_KEY="$INSTALL_API_KEY" elif [ "$AUTO_CONFIRM" = true ]; then @@ -878,6 +865,12 @@ install_node() { else sed -i 's/^# \(SERVICE_PROTOCOL *=.*\)/SERVICE_PROTOCOL= "grpc"/' "$APP_DIR/.env" fi + sed -i '/^[[:space:]]*TLS_ENABLED[[:space:]]*=/d' "$ENV_FILE" + echo "TLS_ENABLED=$TLS_ENABLED" >>"$ENV_FILE" + if [ "$TLS_ENABLED" = false ]; then + sed -i '/^[[:space:]]*NODE_HOST[[:space:]]*=/d' "$ENV_FILE" + echo 'NODE_HOST=127.0.0.1' >>"$ENV_FILE" + fi colorized_echo green ".env file modified successfully" # Modifying compose file colorized_echo blue "Modifying docker-compose.yml..." @@ -890,21 +883,7 @@ install_node() { colorized_echo yellow " ⚠ Failed to set container name (may not be critical)" fi fi - container_path="" - existing_volume=$(yq eval -r ".services[\"$service_name\"].volumes[0]" "$APP_DIR/docker-compose.yml" 2>/dev/null) - if [ -n "$existing_volume" ] && [ "$existing_volume" != "null" ]; then - # Extract container path (everything after the colon) - if [[ "$existing_volume" == *:* ]]; then - container_path="${existing_volume#*:}" - else - # If no colon found, use the existing volume as container path - container_path="$existing_volume" - fi - fi - # For custom names, keep host/container paths aligned to the APP_NAME data dir - if [ "$APP_NAME" != "pg-node" ] || [ -z "$container_path" ]; then - container_path="$DATA_DIR" - fi + container_path="$DATA_DIR" colorized_echo cyan " Command: yq eval ...volumes[0] = \"${DATA_DIR}:${container_path}\"..." if yq eval ".services[\"$service_name\"].volumes[0] = \"${DATA_DIR}:${container_path}\"" -i "$APP_DIR/docker-compose.yml" 2>/dev/null; then colorized_echo green " ✓ Volume path configured: ${DATA_DIR}:${container_path}" @@ -912,8 +891,8 @@ install_node() { colorized_echo yellow " ⚠ Failed to configure volume (may not be critical)" fi # Keep SSL paths in .env aligned with the mapped volume (important for node-serviced on host) - ssl_cert_env="${container_path}/certs/ssl_cert.pem" - ssl_key_env="${container_path}/certs/ssl_key.pem" + ssl_cert_env="$SSL_CERT_FILE" + ssl_key_env="$SSL_KEY_FILE" sed -i "s|^SSL_CERT_FILE *=.*|SSL_CERT_FILE= ${ssl_cert_env}|" "$APP_DIR/.env" sed -i "s|^SSL_KEY_FILE *=.*|SSL_KEY_FILE= ${ssl_key_env}|" "$APP_DIR/.env" set_install_image_tag "$node_version" "$APP_DIR/docker-compose.yml" @@ -1063,12 +1042,12 @@ sync_env_ssl_paths() { local current_cert current_key updated=false current_cert=$(grep -E '^[[:space:]]*SSL_CERT_FILE[[:space:]]*=' "$ENV_FILE" | head -n1 | sed "s/^[[:space:]]*SSL_CERT_FILE[[:space:]]*=[[:space:]]*//;s/[\"']//g") current_key=$(grep -E '^[[:space:]]*SSL_KEY_FILE[[:space:]]*=' "$ENV_FILE" | head -n1 | sed "s/^[[:space:]]*SSL_KEY_FILE[[:space:]]*=[[:space:]]*//;s/[\"']//g") - if [[ -z "$current_cert" || "$current_cert" =~ /var/lib/pg-node/ ]]; then + if [[ -z "$current_cert" || "$current_cert" = /var/lib/pg-node/certs/ssl_cert.pem ]]; then sed -i "s|^[[:space:]]*SSL_CERT_FILE[[:space:]]*=.*|SSL_CERT_FILE= ${desired_cert}|" "$ENV_FILE" grep -q '^[[:space:]]*SSL_CERT_FILE[[:space:]]*=' "$ENV_FILE" || echo "SSL_CERT_FILE= ${desired_cert}" >>"$ENV_FILE" updated=true fi - if [[ -z "$current_key" || "$current_key" =~ /var/lib/pg-node/ ]]; then + if [[ -z "$current_key" || "$current_key" = /var/lib/pg-node/certs/ssl_key.pem ]]; then sed -i "s|^[[:space:]]*SSL_KEY_FILE[[:space:]]*=.*|SSL_KEY_FILE= ${desired_key}|" "$ENV_FILE" grep -q '^[[:space:]]*SSL_KEY_FILE[[:space:]]*=' "$ENV_FILE" || echo "SSL_KEY_FILE= ${desired_key}" >>"$ENV_FILE" updated=true @@ -1249,6 +1228,20 @@ install_command() { INSTALL_SELF_SIGNED=true shift ;; + --ssl-ip | --ssl-ipv6 | --ssl-domain | --ssl-http-port | --ssl-port) + [ -n "${2:-}" ] || { cert_error "$1 requires a value"; return 1; } + case "$1" in + --ssl-ip) INSTALL_SSL_IP="$2";; + --ssl-ipv6) INSTALL_SSL_IPV6="$2";; + --ssl-domain) INSTALL_SSL_DOMAIN="$2";; + *) INSTALL_SSL_HTTP_PORT="$2";; + esac + shift 2 + ;; + --no-ssl) + INSTALL_NO_SSL=true + shift + ;; --api-port) INSTALL_API_PORT="$2" shift 2 @@ -1271,6 +1264,7 @@ install_command() { ;; esac done + validate_ssl_selection || return 1 # Check if node is already installed if is_node_installed; then colorized_echo red "node is already installed at $APP_DIR" @@ -1291,6 +1285,7 @@ install_command() { if ! command -v curl >/dev/null 2>&1; then install_package curl fi + command -v openssl >/dev/null 2>&1 || install_package openssl if ! command -v docker >/dev/null 2>&1; then install_docker fi @@ -1315,7 +1310,6 @@ install_command() { install_node_script install_completion up_node - show_node_logs local install_service_choice="" if [ -n "${INSTALL_SERVICE_CHOICE:-}" ]; then install_service_choice="$INSTALL_SERVICE_CHOICE" @@ -1331,11 +1325,24 @@ install_command() { fi colorized_echo blue "================================" colorized_echo magenta " node is set up with the following IP: $NODE_IP and Port: $SERVICE_PORT." - colorized_echo magenta "Please use the following Certificate in pasarguard Panel (it's located in ${DATA_DIR}/certs):" - cat "$SSL_CERT_FILE" + local registration_failed=0 + if ! register_node_acme_reload; then + registration_failed=1 + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME reload registration or scheduler installation failed; run certificate-renewal-enable' + colorized_echo red 'Managed renewal setup failed. The scheduler was not installed successfully; run certificate-renewal-enable after correcting the error.' + elif [ "${TLS_ENABLED:-true}" = false ]; then + write_node_cert_status external_tls + elif verify_node_cert_services; then + write_node_cert_status deployed + else + write_node_cert_status unverified 'Initial TLS endpoint verification failed; inspect service logs' + fi + show_node_certificate || registration_failed=1 colorized_echo blue "================================" colorized_echo magenta "Next, use the API Key (UUID v4) in pasarguard Panel: " colorized_echo red "${API_KEY}" + return "$registration_failed" } # Uninstall node containers, configuration, scripts, and optionally data directories. uninstall_command() { @@ -1361,6 +1368,7 @@ uninstall_command() { if service_installed; then uninstall_service_command fi + remove_node_cert_scheduler || return 1 uninstall_completion uninstall_node_script uninstall_node @@ -1517,7 +1525,6 @@ install_service_command() { exit 1 fi ensure_env_exists - sync_env_ssl_paths get_occupied_ports local api_port existing_api_port="" local default_api_port=62051 @@ -2111,7 +2118,7 @@ _node_completions() local cur cmds COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" - cmds="up down restart status logs install update uninstall install-script uninstall-script core-update geofiles renew-cert version-script script-version edit edit-env completion service-install service-uninstall service-restart service-status service-logs service-update service-start service-stop" + cmds="up down restart status logs install update uninstall install-script uninstall-script core-update geofiles renew-cert certificate-status certificate-renewal-enable show-cert version-script script-version edit edit-env completion service-install service-uninstall service-restart service-status service-logs service-update service-start service-stop" if [ "$COMP_CWORD" -ge 2 ] && [ "${COMP_WORDS[1]}" = "geofiles" ]; then COMPREPLY=( $(compgen -W "iran russia china help" -- "$cur") ) return 0 @@ -2144,6 +2151,9 @@ commands=( core-update geofiles renew-cert + certificate-status + certificate-renewal-enable + show-cert version-script script-version edit @@ -2236,7 +2246,7 @@ usage() { colorized_echo yellow " edit-env $(tput sgr0)✓ Edit .env file (via nano or vi)" colorized_echo yellow " core-update $(tput sgr0)✓ Update/Change Xray core" colorized_echo yellow " geofiles $(tput sgr0)✓ Download geoip and geosite files for specific regions" - colorized_echo yellow " renew-cert $(tput sgr0)✓ Regenerate SSL/TLS certificate" + colorized_echo yellow " renew-cert $(tput sgr0)✓ Renew or validate the active certificate source" colorized_echo yellow " version-script $(tput sgr0)✓ Show script version and commit" colorized_echo yellow " completion $(tput sgr0)✓ Install bash/zsh tab completion" echo @@ -2264,6 +2274,14 @@ usage() { colorized_echo yellow " --service-port PORT $(tput sgr0)✓ Set service port" colorized_echo yellow " --cert-path PATH $(tput sgr0)✓ Set public certificate path" colorized_echo yellow " --key-path PATH $(tput sgr0)✓ Set private key path" + echo " certificate-renewal-enable Enable managed ACME scheduler after upgrading both services" + echo " certificate-status [--json] Show local renewal and deployment status" + echo " show-cert Display identity, expiry, SHA-256 fingerprint and legacy PEM" + echo " --ssl-ip IPV4 Let's Encrypt IP certificate (default; required unattended)" + echo " --ssl-ipv6 IPV6 Add IPv6 SAN (requires --ssl-ip)" + echo " --ssl-domain DOMAIN Let's Encrypt domain certificate" + echo " --ssl-http-port PORT HTTP challenge port (alias: --ssl-port; public port 80 must reach it)" + echo " --no-ssl Private backend behind external TLS termination only" colorized_echo yellow " --self-signed $(tput sgr0)✓ Generate self-signed certificate" colorized_echo yellow " --api-port PORT $(tput sgr0)✓ Set API port for node service" colorized_echo yellow " --install-service $(tput sgr0)✓ Install systemd service" @@ -2397,112 +2415,733 @@ geofiles_command() { fi } -# Backup existing certificates and generate a renewed self-signed TLS certificate. -renew_cert_command() { - check_running_as_root - # Check if node is installed - if ! is_node_installed; then - colorized_echo red "✗ Node is not installed. Please install node first." - exit 1 - fi - colorized_echo cyan "================================" - colorized_echo cyan "Renewing SSL/TLS Certificate" - colorized_echo cyan "================================" - colorized_echo yellow "This will create a new SSL/TLS certificate for your node." - - # Check if existing certificate is self-signed (generated by script) - local is_self_signed=false - if [ -f "$SSL_CERT_FILE" ]; then - # Check if certificate is self-signed (subject == issuer) - local subject=$(openssl x509 -in "$SSL_CERT_FILE" -noout -subject 2>/dev/null | sed 's/^subject= *//') - local issuer=$(openssl x509 -in "$SSL_CERT_FILE" -noout -issuer 2>/dev/null | sed 's/^issuer= *//') - if [ "$subject" = "$issuer" ]; then - is_self_signed=true +# Node certificate management is deliberately independent of panel verification. +cert_error() { colorized_echo red "$*" >&2; return 1; } + +node_env_value() { + [ -f "$ENV_FILE" ] || return 0 + sed -n "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*//p" "$ENV_FILE" | head -n1 | tr -d '\r\"\047' | sed 's/[[:space:]]*$//' +} + +load_active_cert_paths() { + local value + value=$(node_env_value SSL_CERT_FILE) + [ -z "$value" ] || SSL_CERT_FILE="$value" + value=$(node_env_value SSL_KEY_FILE) + [ -z "$value" ] || SSL_KEY_FILE="$value" +} + +# Never source certificate metadata as executable shell code. +cert_metadata() { jq -r --arg key "$1" '.[$key] // empty' "$DATA_DIR/certs/source.json"; } + +save_cert_source() { + local stage + stage=$(mktemp "$DATA_DIR/certs/.source.XXXXXX") || return 1 + jq -n --arg source "$1" --arg identifier "${2:-}" --arg ipv6 "${3:-}" --arg port "${4:-80}" \ + '{source:$source, identifier:$identifier, ipv6:$ipv6, http_port:$port}' >"$stage" || return 1 + chmod 600 "$stage" + mv -f "$stage" "$DATA_DIR/certs/source.json" +} + +validate_node_cert_pair() ( + set -o pipefail + local cert="$1" key="$2" identity="${3:-}" ipv6="${4:-}" + local cert_pub key_pub start end now + openssl x509 -in "$cert" -noout >/dev/null 2>&1 || { cert_error "Invalid certificate: $cert"; return 1; } + cert_pub=$(openssl x509 -in "$cert" -pubkey -noout | openssl pkey -pubin -outform DER | openssl dgst -sha256) || return 1 + key_pub=$(openssl pkey -in "$key" -passin pass: -pubout -outform DER | openssl dgst -sha256) || return 1 + [ "$cert_pub" = "$key_pub" ] || { cert_error "Certificate and private key do not match"; return 1; } + start=$(openssl x509 -in "$cert" -startdate -noout); start=$(date -d "${start#*=}" +%s) || return 1 + end=$(openssl x509 -in "$cert" -enddate -noout); end=$(date -d "${end#*=}" +%s) || return 1 + now=$(date +%s) + [ "$start" -le "$now" ] && [ "$end" -gt "$now" ] || { cert_error "Certificate is expired or not yet valid"; return 1; } + # Parse every PEM block, rejecting a malformed/truncated full chain. + local begins ends + begins=$(grep -c '^-----BEGIN CERTIFICATE-----' "$cert") + ends=$(grep -c '^-----END CERTIFICATE-----' "$cert") + [ "$begins" -eq "$ends" ] && openssl crl2pkcs7 -nocrl -certfile "$cert" -outform DER >/dev/null 2>&1 || { + cert_error 'Invalid certificate chain'; return 1; + } + # SAN is mandatory; never rely on Common Name fallback. + openssl x509 -in "$cert" -noout -ext subjectAltName | grep -qE 'DNS:|IP Address:' || { cert_error "Certificate requires SANs"; return 1; } + local id flag + for id in "$identity" "$ipv6"; do + [ -n "$id" ] || continue + if is_ip_address "$id"; then flag=-checkip; else + flag=-checkhost + openssl x509 -in "$cert" -noout -ext subjectAltName | grep -q 'DNS:' || return 1 fi + openssl x509 -in "$cert" -noout "$flag" "$id" | grep -q 'does match certificate' || { cert_error "Certificate SAN does not match $id"; return 1; } + done +) + +# Nested certificate operations (including synchronous ACME reload hooks) share +# the same open lock descriptor. Never unlink the lock file: waiters use its inode. +with_node_cert_lock() { + local lock_file="$DATA_DIR/certs/.deployment.lock" status=0 + mkdir -p "$DATA_DIR/certs" || return 1 + if [[ "${PG_NODE_CERT_LOCK_FD:-}" =~ ^[0-9]+$ ]] && + [ "$(readlink "/proc/self/fd/$PG_NODE_CERT_LOCK_FD")" = "$lock_file" ] && + flock -n "$PG_NODE_CERT_LOCK_FD"; then + "$@" + return $? + fi + local PG_NODE_CERT_LOCK_FD + exec {PG_NODE_CERT_LOCK_FD}>"$lock_file" || return 1 + if flock -x "$PG_NODE_CERT_LOCK_FD"; then + export PG_NODE_CERT_LOCK_FD + "$@" || status=$? + else + status=1 fi - - # Only backup if it's a self-signed certificate (generated by script) - if [ "$is_self_signed" = true ] && [ -f "$SSL_CERT_FILE" ]; then - # Clean up old backups first (keep only the 2 most recent) - local cert_backups=($(ls -t "${SSL_CERT_FILE}.backup."* 2>/dev/null | tail -n +3 2>/dev/null)) - local key_backups=($(ls -t "${SSL_KEY_FILE}.backup."* 2>/dev/null | tail -n +3 2>/dev/null)) - - if [ ${#cert_backups[@]} -gt 0 ] || [ ${#key_backups[@]} -gt 0 ]; then - colorized_echo blue "Cleaning up old backups (keeping 2 most recent)..." - for backup in "${cert_backups[@]}"; do - if [ -f "$backup" ]; then - rm -f "$backup" 2>/dev/null && colorized_echo cyan " Removed old backup: $(basename "$backup")" - fi - done - for backup in "${key_backups[@]}"; do - if [ -f "$backup" ]; then - rm -f "$backup" 2>/dev/null && colorized_echo cyan " Removed old backup: $(basename "$backup")" - fi - done + exec {PG_NODE_CERT_LOCK_FD}>&- + return "$status" +} + +# Stage and validate before touching either active file. Keep backups for rollback. +deploy_node_cert_pair() { + with_node_cert_lock deploy_node_cert_pair_locked "$@" +} + +deploy_node_cert_pair_locked() ( + local cert="$1" key="$2" identity="${3:-}" ipv6="${4:-}" + validate_node_cert_pair "$cert" "$key" "$identity" "$ipv6" || return 1 + mkdir -p "$(dirname "$SSL_CERT_FILE")" "$(dirname "$SSL_KEY_FILE")" || return 1 + chmod 700 "$(dirname "$SSL_KEY_FILE")" || return 1 + local stage_cert="" stage_key="" + trap 'rm -f -- "$stage_cert" "$stage_key"' EXIT + stage_cert=$(mktemp "${SSL_CERT_FILE}.stage.XXXXXX") || return 1 + stage_key=$(mktemp "${SSL_KEY_FILE}.stage.XXXXXX") || return 1 + cp "$cert" "$stage_cert" && cp "$key" "$stage_key" || return 1 + chmod 644 "$stage_cert" && chmod 600 "$stage_key" || return 1 + validate_node_cert_pair "$stage_cert" "$stage_key" "$identity" "$ipv6" || return 1 + if [ -f "$SSL_CERT_FILE" ]; then cp -p "$SSL_CERT_FILE" "${SSL_CERT_FILE}.previous" || return 1; fi + if [ -f "$SSL_KEY_FILE" ]; then cp -p "$SSL_KEY_FILE" "${SSL_KEY_FILE}.previous" || return 1; fi + if ! mv -f "$stage_key" "$SSL_KEY_FILE" || ! mv -f "$stage_cert" "$SSL_CERT_FILE"; then + [ ! -f "${SSL_CERT_FILE}.previous" ] || cp -p "${SSL_CERT_FILE}.previous" "$SSL_CERT_FILE" + [ ! -f "${SSL_KEY_FILE}.previous" ] || cp -p "${SSL_KEY_FILE}.previous" "$SSL_KEY_FILE" + cert_error "Deployment failed; restored previous certificate files" + return 1 + fi +) + +validate_node_acme_chain() { + openssl verify -purpose sslserver -untrusted "$1" "$1" >/dev/null 2>&1 || { + cert_error 'ACME full chain does not verify against configured system trust'; return 1; + } +} + +get_node_acme() { + if [ -x "${HOME}/.acme.sh/acme.sh" ]; then printf '%s\n' "${HOME}/.acme.sh/acme.sh" + elif [ -x /root/.acme.sh/acme.sh ]; then printf '%s\n' /root/.acme.sh/acme.sh + elif command -v acme.sh >/dev/null 2>&1; then command -v acme.sh + else return 1; fi +} + +ensure_node_acme() { + local package installer + for package in socat openssl; do command -v "$package" >/dev/null 2>&1 || install_package "$package" || return 1; done + if ! command -v crontab >/dev/null 2>&1; then + case "${OS:-}" in Ubuntu*|Debian*) package=cron;; *) package=cronie;; esac + install_package "$package" || return 1 + fi + if ! get_node_acme >/dev/null; then + installer=$(mktemp) || return 1 + curl -fsSL https://get.acme.sh -o "$installer" && sh "$installer" -- --nocron || return 1 + rm -f "$installer" + fi + local acme + acme=$(get_node_acme) || return 1 + mkdir -p "$DATA_DIR/certs/acme" && chmod 700 "$DATA_DIR/certs/acme" || return 1 +} + +validate_ssl_selection() { + local count=0 + [ "${INSTALL_SELF_SIGNED:-false}" != true ] || count=$((count+1)) + [ "${INSTALL_NO_SSL:-false}" != true ] || count=$((count+1)) + [ -z "${INSTALL_SSL_IP:-}" ] || count=$((count+1)) + [ -z "${INSTALL_SSL_DOMAIN:-}" ] || count=$((count+1)) + if [ -n "${INSTALL_CERT_PATH:-}${INSTALL_KEY_PATH:-}" ]; then + [ -n "${INSTALL_CERT_PATH:-}" ] && [ -n "${INSTALL_KEY_PATH:-}" ] || { cert_error "Use --cert-path and --key-path together"; return 1; } + count=$((count+1)) + fi + [ "$count" -le 1 ] || { cert_error "Conflicting certificate selections"; return 1; } + [ -z "${INSTALL_SSL_IPV6:-}" ] || [ -n "${INSTALL_SSL_IP:-}" ] || { cert_error "--ssl-ipv6 requires --ssl-ip"; return 1; } + local port="${INSTALL_SSL_HTTP_PORT:-80}" + [[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] && [ "$port" -le 65535 ] || { cert_error "Invalid SSL HTTP challenge port"; return 1; } + if [ "$count" -eq 0 ] && { [ "$AUTO_CONFIRM" = true ] || [ ! -t 0 ]; }; then + cert_error "Unattended IP issuance requires --ssl-ip IPV4. Old unattended commands must add --self-signed to keep self-signed behavior." + return 1 + fi +} + +# Retained paths can point outside the instance's bind mount. Copy the selected +# active pair into that mount before writing its paths to .env. +prepare_install_node_certificate() { + choose_node_certificate || return 1 + if [ "$TLS_ENABLED" = true ] && + { [[ "$SSL_CERT_FILE" != "$DATA_DIR/"* ]] || [[ "$SSL_KEY_FILE" != "$DATA_DIR/"* ]]; }; then + local cert="$SSL_CERT_FILE" key="$SSL_KEY_FILE" + SSL_CERT_FILE="$DATA_DIR/certs/ssl_cert.pem" + SSL_KEY_FILE="$DATA_DIR/certs/ssl_key.pem" + deploy_node_cert_pair "$cert" "$key" || return 1 + fi +} + +node_image_supports_plaintext() { + local ref="${node_version:-latest}" config + if [ "$ref" = latest ]; then + ref=$(curl -fsSL https://api.github.com/repos/PasarGuard/node/releases/latest | jq -er '.tag_name') || return 1 + fi + [[ "$ref" =~ ^(dev|v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?)$ ]] || return 1 + config=$(curl -fsSL "https://raw.githubusercontent.com/PasarGuard/node/$ref/.env.example") || return 1 + printf '%s\n' "$config" | grep -Eq '^[[:space:]#]*TLS_ENABLED[[:space:]]*=' +} + +choose_node_certificate() { + validate_ssl_selection || return 1 + if [ -z "${INSTALL_SSL_IP:-}${INSTALL_SSL_DOMAIN:-}${INSTALL_CERT_PATH:-}" ] && [ "${INSTALL_SELF_SIGNED:-false}" != true ] && [ "${INSTALL_NO_SSL:-false}" != true ]; then + echo "1) Let's Encrypt IP certificate (default)" + echo "2) Let's Encrypt domain certificate" + echo "3) Custom certificate and key paths" + echo "4) Self-signed certificate" + echo " For local IPs, use a self-signed or private CA certificate containing the local IPs." + echo " This option generates a self-signed certificate; import a private CA certificate with option 3." + echo "5) External web server terminates TLS (advanced)" + local selection + read -r -p "Certificate [1]: " selection + case "${selection:-1}" in + 1) read -r -p "Public IPv4 [${NODE_IP_V4:-}]: " INSTALL_SSL_IP + INSTALL_SSL_IP="${INSTALL_SSL_IP:-${NODE_IP_V4:-}}" + read -r -p "Optional public IPv6: " INSTALL_SSL_IPV6 ;; + 2) read -r -p "Domain: " INSTALL_SSL_DOMAIN + [ -n "$INSTALL_SSL_DOMAIN" ] || { cert_error "Domain is required"; return 1; } ;; + 3) read -r -p "Certificate path: " INSTALL_CERT_PATH + read -r -p "Key path: " INSTALL_KEY_PATH + [ -n "$INSTALL_CERT_PATH" ] && [ -n "$INSTALL_KEY_PATH" ] || return 1 ;; + 4) INSTALL_SELF_SIGNED=true ;; + 5) INSTALL_NO_SSL=true ;; + *) cert_error "Invalid certificate selection"; return 1 ;; + esac + fi + TLS_ENABLED=true + if [ "${INSTALL_NO_SSL:-false}" = true ]; then + node_image_supports_plaintext || { + cert_error "Cannot verify plaintext support for node image ${node_version:-latest}; select a compatible image or enable TLS." + return 1 + } + TLS_ENABLED=false + save_cert_source external_tls + elif [ "${INSTALL_SELF_SIGNED:-false}" = true ]; then + local active_cert="$SSL_CERT_FILE" active_key="$SSL_KEY_FILE" stage + stage=$(mktemp -d "$DATA_DIR/certs/.self-signed.XXXXXX") || return 1 + SSL_CERT_FILE="$stage/fullchain.pem"; SSL_KEY_FILE="$stage/privkey.pem" + gen_self_signed_cert || return 1 + SSL_CERT_FILE="$active_cert"; SSL_KEY_FILE="$active_key" + deploy_node_cert_pair "$stage/fullchain.pem" "$stage/privkey.pem" || return 1 + rm -rf "$stage" + save_cert_source self_signed + elif [ -n "${INSTALL_CERT_PATH:-}" ]; then + SSL_CERT_FILE="$DATA_DIR/certs/custom/fullchain.pem"; SSL_KEY_FILE="$DATA_DIR/certs/custom/privkey.pem" + deploy_node_cert_pair "$INSTALL_CERT_PATH" "$INSTALL_KEY_PATH" || return 1 + save_cert_source custom + else + local source=acme_domain identifier="${INSTALL_SSL_DOMAIN:-}" ipv6="${INSTALL_SSL_IPV6:-}" + if [ -n "${INSTALL_SSL_IP:-}" ]; then source=acme_ip; identifier="$INSTALL_SSL_IP"; fi + if [ "$source" = acme_ip ]; then + command -v python3 >/dev/null 2>&1 || install_package python3 || return 1 + python3 - "$identifier" "$ipv6" <<'PYIP' || return 1 +import ipaddress, sys +try: + for value, version in zip(sys.argv[1:], (4, 6)): + if version == 6 and not value: continue + addr = ipaddress.ip_address(value) + if addr.version != version or not addr.is_global or '%' in value: + raise ValueError('ACME requires public IPv4 and optional public IPv6 identifiers') +except ValueError as err: + print(err, file=sys.stderr) + sys.exit(1) +PYIP + else + [[ "$identifier" =~ ^([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$ ]] || { cert_error "Invalid domain identifier"; return 1; } fi - - # Create new backup - local backup_cert="${SSL_CERT_FILE}.backup.$(date +%Y%m%d_%H%M%S)" - local backup_key="${SSL_KEY_FILE}.backup.$(date +%Y%m%d_%H%M%S)" - colorized_echo blue "Backing up existing self-signed certificate..." - cp "$SSL_CERT_FILE" "$backup_cert" 2>/dev/null || true - if [ -f "$SSL_KEY_FILE" ]; then - cp "$SSL_KEY_FILE" "$backup_key" 2>/dev/null || true + local dir="$identifier" + [ "$source" != acme_ip ] || dir=ip + SSL_CERT_FILE="$DATA_DIR/certs/$dir/fullchain.pem"; SSL_KEY_FILE="$DATA_DIR/certs/$dir/privkey.pem" + issue_node_acme "$source" "$identifier" "$ipv6" "${INSTALL_SSL_HTTP_PORT:-80}" || return 1 + save_cert_source "$source" "$identifier" "$ipv6" "${INSTALL_SSL_HTTP_PORT:-80}" + fi +} + +issue_node_acme() { + with_node_cert_lock issue_node_acme_locked "$@" +} + +issue_node_acme_locked() { + local source="$1" identifier="$2" ipv6="$3" port="$4" acme + ensure_node_acme || return 1 + get_occupied_ports + if is_port_occupied "$port"; then cert_error "Challenge port $port is in use. Configure challenge routing or free it explicitly; no services were stopped."; return 1; fi + [ "$port" = 80 ] || colorized_echo yellow "Route public TCP port 80 to local challenge port $port." + acme=$(get_node_acme) || return 1 + local args=(--issue -d "$identifier" --standalone --server letsencrypt --httpport "$port" --force) + [ -z "$ipv6" ] || args+=(-d "$ipv6") + [ "$source" != acme_ip ] || args+=(--certificate-profile shortlived --days 4) + run_node_acme "$acme" "${args[@]}" || { cert_error "ACME issuance failed; existing certificates were preserved. Retry explicitly."; return 1; } + stage_node_acme "$acme" "$identifier" || return 1 + validate_node_acme_chain "$DATA_DIR/certs/.acme-staging/fullchain.pem" || return 1 + deploy_node_cert_pair "$DATA_DIR/certs/.acme-staging/fullchain.pem" "$DATA_DIR/certs/.acme-staging/privkey.pem" "$identifier" "$ipv6" +} + +stage_node_acme() { + with_node_cert_lock stage_node_acme_locked "$@" +} + +stage_node_acme_locked() { + local acme="$1" identifier="$2" reload="${3:-:}" stage="$DATA_DIR/certs/.acme-staging" + mkdir -p "$stage" && chmod 700 "$stage" || return 1 + local ecc + for ecc in '--ecc' ''; do + local key_target=no cert_target=no + if [ "$reload" = : ]; then + rm -f "$stage/fullchain.pem" "$stage/privkey.pem" + key_target="$stage/privkey.pem"; cert_target="$stage/fullchain.pem" fi - colorized_echo green " ✓ Backup created: $(basename "$backup_cert")" - if [ -f "$backup_key" ]; then - colorized_echo green " ✓ Backup created: $(basename "$backup_key")" + local args=(--installcert -d "$identifier" --key-file "$key_target" --fullchain-file "$cert_target" --reloadcmd "$reload") + [ -z "$ecc" ] || args+=("$ecc") + if run_node_acme "$acme" "${args[@]}" && + { [ "$reload" != : ] || { [ -s "$stage/fullchain.pem" ] && [ -s "$stage/privkey.pem" ]; }; }; then + if [ "$reload" = : ]; then + chmod 600 "$stage/privkey.pem" || return 1 + local reset_args=(--installcert -d "$identifier" --key-file no --fullchain-file no --reloadcmd :) + [ -z "$ecc" ] || reset_args+=("$ecc") + run_node_acme "$acme" "${reset_args[@]}" || return 1 + fi + printf '%s' "$ecc" >"$stage/key-type" + return 0 fi - elif [ -f "$SSL_CERT_FILE" ]; then - # User-provided certificate - don't backup, just warn - colorized_echo yellow "⚠ Existing certificate appears to be user-provided (not self-signed)." - colorized_echo yellow " It will be replaced with a new self-signed certificate." - if [ "$AUTO_CONFIRM" != true ]; then - read -p "Continue? (y/N): " confirm - if [[ ! "$confirm" =~ ^[Yy]$ ]]; then - colorized_echo yellow "Cancelled." - exit 0 + done + cert_error "ACME deployment failed; active certificate files were preserved" +} + +register_node_acme_reload() { + with_node_cert_lock register_node_acme_reload_locked "$@" +} + +register_node_acme_reload_locked() { + [ -f "$DATA_DIR/certs/source.json" ] || return 0 + case "$(cert_metadata source)" in acme_ip|acme_domain) ;; *) return 0;; esac + local acme hook + acme=$(get_node_acme) || return 1 + migrate_node_acme_storage "$acme" "$(cert_metadata identifier)" || return 1 + printf -v hook 'env %q %q %q renew-cert --deploy-acme' "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" + stage_node_acme "$acme" "$(cert_metadata identifier)" "$hook" || return 1 + install_node_cert_scheduler +} + +show_node_certificate() { + local source=legacy + [ ! -f "$DATA_DIR/certs/source.json" ] || source=$(cert_metadata source) + colorized_echo cyan "Certificate source: $source" + if [ "$source" = external_tls ]; then + colorized_echo yellow "Configure the panel with the web server's TLS address and ports. Manage its certificate on the web server." + return 0 + fi + openssl x509 -in "$SSL_CERT_FILE" -noout -subject -issuer -dates -ext subjectAltName || return 1 + local pin + pin=$(set -o pipefail; openssl x509 -in "$SSL_CERT_FILE" -outform DER | openssl dgst -sha256 | awk '{print tolower($NF)}') || { + cert_error "Could not calculate the certificate SHA-256 pin" + return 1 + } + [[ "$pin" =~ ^[0-9a-f]{64}$ ]] || { cert_error "Invalid certificate SHA-256 pin"; return 1; } + colorized_echo cyan "SHA-256 certificate pin (leaf DER): $pin" + colorized_echo cyan 'PEM for older panels:' + colorized_echo yellow 'If multiple PEM certificate blocks appear below, copy only the first block (the node certificate) into the panel certificate field, including its BEGIN CERTIFICATE and END CERTIFICATE lines.' + cat "$SSL_CERT_FILE" +} + +run_node_acme() { + local acme="$1"; shift + "$acme" --cert-home "$DATA_DIR/certs/acme" "$@" +} + +migrate_node_acme_storage() { + local acme="$1" identifier="$2" base old suffix hook encoded_hook + printf -v hook 'env %q %q %q renew-cert --deploy-acme' "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" + encoded_hook=$(printf '%s' "$hook" | openssl base64 -A) || return 1 + base=$(dirname "$(readlink -f "$acme")") + mkdir -p "$DATA_DIR/certs/acme" || return 1 + for suffix in _ecc ''; do + old="$base/$identifier$suffix" + if [ -f "$old/$identifier.conf" ]; then + grep -Fqx -e "Le_ReloadCmd='$hook'" \ + -e "Le_ReloadCmd='__ACME_BASE64__START_${encoded_hook}__ACME_BASE64__END_'" \ + "$old/$identifier.conf" || continue + if [ ! -d "$DATA_DIR/certs/acme/$identifier$suffix" ]; then + cp -a "$old" "$DATA_DIR/certs/acme/" || return 1 fi + local args=(--remove -d "$identifier") + [ -z "$suffix" ] || args+=(--ecc) + "$acme" "${args[@]}" || return 1 fi + done +} + +node_cert_fingerprint() ( + set -o pipefail + openssl x509 -in "$1" -outform DER 2>/dev/null | openssl dgst -sha256 | awk '{print tolower($NF)}' +) + +node_cert_status_value() { + [ -f "$DATA_DIR/certs/renewal-status.json" ] || return 0 + jq -r --arg key "$1" '.[$key] // empty' "$DATA_DIR/certs/renewal-status.json" +} + +write_node_cert_status() ( + local state="$1" error="${2:-}" next="${3:-0}" failures="${4:-}" stage old='{}' + local file="$DATA_DIR/certs/renewal-status.json" pin='' expiry='' source=legacy now + now=$(date +%s) + [ ! -f "$file" ] || old=$(cat "$file") + failures="${failures:-$(printf '%s' "$old" | jq -r '.failures // 0')}" + [ ! -f "$DATA_DIR/certs/source.json" ] || source=$(cert_metadata source) + pin=$(node_cert_fingerprint "$SSL_CERT_FILE") || pin='' + expiry=$(openssl x509 -in "$SSL_CERT_FILE" -enddate -noout 2>/dev/null) || expiry='' + expiry="${expiry#*=}" + stage=$(mktemp "$DATA_DIR/certs/.status.XXXXXX") || return 1 + trap 'rm -f "$stage"' EXIT + jq -n --argjson old "$old" --arg source "$source" --arg state "$state" \ + --arg error "$error" --arg pin "$pin" --arg expiry "$expiry" \ + --argjson now "$now" --argjson next "$next" --argjson failures "$failures" \ + '$old + {source:$source, deployment_state:$state, error:$error, + file_fingerprint:$pin, file_expiry:$expiry, next_attempt:$next, failures:$failures} + | if $state == "attempting" then .last_attempt=$now else . end + | if $state == "deployed" then .active_fingerprint=$pin | .expiry=$expiry | + .last_success=$now | .failures=0 | .error="" else . end' >"$stage" || return 1 + chmod 600 "$stage" && mv -f "$stage" "$file" +) + +certificate_status_command() { + [ "$#" -eq 0 ] || { [ "$#" -eq 1 ] && [ "$1" = --json ]; } || { cert_error 'Usage: certificate-status [--json]'; return 1; } + load_active_cert_paths + local source=legacy status='{}' expiry='' valid=false + [ ! -f "$DATA_DIR/certs/source.json" ] || source=$(cert_metadata source) + [ ! -f "$DATA_DIR/certs/renewal-status.json" ] || status=$(cat "$DATA_DIR/certs/renewal-status.json") + expiry=$(openssl x509 -in "$SSL_CERT_FILE" -enddate -noout 2>/dev/null) || expiry='' + if validate_node_cert_pair "$SSL_CERT_FILE" "$SSL_KEY_FILE" >/dev/null 2>&1; then valid=true; fi + status=$(jq -n --argjson old "$status" --arg source "$source" --arg expiry "${expiry#*=}" \ + --argjson valid "$valid" '$old + {source:$source, files_currently_valid:$valid, file_expiry:$expiry} + | .deployment_state //= "unknown" | .active_fingerprint //= null | .expiry //= null + | .last_attempt //= null | .last_success //= null | .next_attempt //= null | .error //= ""') || return 1 + if [ "${1:-}" = --json ]; then printf '%s\n' "$status" + else printf '%s\n' "$status" | jq -r 'to_entries[] | "\(.key): \(.value)"'; fi +} + +reload_node_cert_services() { + detect_compose + local failed=0 + $COMPOSE -f "$COMPOSE_FILE" -p "$APP_NAME" restart node || failed=1 + if service_installed && systemctl is-active --quiet "$SERVICE_NAME"; then + systemctl kill --kill-whom=main --signal=SIGHUP "$SERVICE_NAME" || failed=1 + fi + return "$failed" +} + +verify_node_cert_endpoint() ( + set -o pipefail + local host="$1" port="$2" expected="$3" identity="$4" peer connect + [[ "$port" =~ ^[0-9]+$ ]] && [ "$port" -ge 1 ] && [ "$port" -le 65535 ] || return 1 + connect="$host:$port" + [[ "$host" != *:* ]] || connect="[$host]:$port" + peer=$(timeout 10 openssl s_client -connect "$connect" -servername "$identity" -showcerts /dev/null | + openssl x509 -outform DER 2>/dev/null | openssl dgst -sha256 | awk '{print tolower($NF)}') || return 1 + [ "$peer" = "$expected" ] +) + +verify_node_cert_services() { + local pin identity host port attempt + pin=$(node_cert_fingerprint "$SSL_CERT_FILE") || return 1 + identity=$(cert_metadata identifier 2>/dev/null) || identity='' + host=$(node_env_value NODE_HOST); host="${host:-127.0.0.1}" + case "$host" in 0.0.0.0) host=127.0.0.1;; ::|'[::]') host=::1;; esac + local ports=("$(node_env_value SERVICE_PORT)") + if service_installed && systemctl is-active --quiet "$SERVICE_NAME"; then ports+=("$(node_env_value API_PORT)"); fi + for port in "${ports[@]}"; do + for attempt in 1 2 3 4 5; do + if verify_node_cert_endpoint "$host" "$port" "$pin" "${identity:-$host}"; then break; fi + [ "$attempt" -lt 5 ] || return 1 + sleep 1 + done + done +} + +finish_node_cert_deployment() { + if ! validate_node_cert_pair "$SSL_CERT_FILE" "$SSL_KEY_FILE"; then + write_node_cert_status invalid_files 'Current certificate files are invalid or expired; no reload attempted' "$(( $(date +%s) + 300 ))" + return 1 fi - - # Generate new certificate - gen_self_signed_cert - - # Ask user if they want to restart the node - if docker ps --format '{{.Names}}' | grep -q "^$APP_NAME$"; then - colorized_echo cyan "" - colorized_echo yellow "The node needs to be restarted to apply the new certificate." - local restart_choice="" - if [ "$AUTO_CONFIRM" = true ]; then - restart_choice="n" - else - read -p "Do you want to restart the node now? (y/N): " restart_choice + if reload_node_cert_services && verify_node_cert_services; then + write_node_cert_status deployed '' "$(( $(date +%s) + 3600 ))" || return 1 + colorized_echo green 'Certificate hot reload verified on all configured TLS endpoints.' + else + write_node_cert_status reload_pending 'Node restart, maintenance reload or endpoint verification failed' "$(( $(date +%s) + 300 ))" || return 1 + cert_error 'Certificate reload incomplete. Retained files and backups; retrying deployment until renewal is due.' + return 1 + fi +} + +install_node_cert_scheduler() ( + local cron_lock_fd + exec {cron_lock_fd}>/var/lock/pg-node-cert-crontab.lock || return 1 + flock -x "$cron_lock_fd" || return 1 + local entry entries stage + printf -v entry '*/5 * * * * env %q %q %q certificate-renewal-tick >>%q 2>&1 # pg-node-cert:%s' \ + "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" "$DATA_DIR/certs/renewal.log" "$APP_NAME" + entry="${entry//%/\\%}" + touch "$DATA_DIR/certs/renewal.log" && chmod 600 "$DATA_DIR/certs/renewal.log" || return 1 + entries=$(crontab -l 2>/dev/null) || entries='' + stage=$(mktemp) || return 1 + printf '%s\n' "$entries" | sed "/# pg-node-cert:${APP_NAME}$/d" >"$stage" + printf '%s\n' "$entry" >>"$stage" + crontab "$stage" + local result=$? + rm -f "$stage" + return "$result" +) + +remove_node_cert_scheduler() ( + local cron_lock_fd + exec {cron_lock_fd}>/var/lock/pg-node-cert-crontab.lock || return 1 + flock -x "$cron_lock_fd" || return 1 + local entries stage + entries=$(crontab -l 2>/dev/null) || return 0 + stage=$(mktemp) || return 1 + printf '%s\n' "$entries" | sed "/# pg-node-cert:${APP_NAME}$/d" >"$stage" + crontab "$stage" + local result=$? + rm -f "$stage" + return "$result" +) + +node_cert_config_digest() { + { cat "$DATA_DIR/certs/source.json" "$ENV_FILE"; } | sha256sum | awk '{print $1}' +} + +certificate_renewal_tick() { + check_running_as_root + with_node_cert_lock certificate_renewal_tick_locked +} + +certificate_renewal_tick_locked() { + local source state next now digest + [ -f "$DATA_DIR/certs/source.json" ] || return 0 + source=$(cert_metadata source) + case "$source" in acme_ip|acme_domain) ;; *) return 0;; esac + load_active_cert_paths + now=$(date +%s); next=$(node_cert_status_value next_attempt) + state=$(node_cert_status_value deployment_state) + digest=$(node_cert_config_digest) || return 1 + if [ "$state" = suspended ]; then + [ "$(cat "$DATA_DIR/certs/.suspended-config" 2>/dev/null)" != "$digest" ] || return 0 + elif [ "${next:-0}" -gt "$now" ]; then return 0; fi + case "$state" in + reload_pending) + local start end + start=$(openssl x509 -in "$SSL_CERT_FILE" -startdate -noout) || return 1 + start=$(date -d "${start#*=}" +%s) || return 1 + end=$(openssl x509 -in "$SSL_CERT_FILE" -enddate -noout) || return 1 + end=$(date -d "${end#*=}" +%s) || return 1 + if [ "$now" -ge "$((start+(end-start)*2/3))" ]; then + renew_node_acme_scheduled + else + finish_node_cert_deployment + fi + ;; + deployment_pending) renew_cert_command_locked --deploy-acme;; + *) renew_node_acme_scheduled;; + esac +} + +# acme.sh evaluates ARI during --renew. Supply an exact lifetime-based fallback +# without --days, which would pin its schedule and reject later CA windows. +# Only the isolated, locked domain configuration is edited, never sourced here. +set_node_acme_fallback() ( + local identifier="$1" due="$2" suffix='' config stage + [ "$(cat "$DATA_DIR/certs/.acme-staging/key-type" 2>/dev/null)" != --ecc ] || suffix=_ecc + config="$DATA_DIR/certs/acme/$identifier$suffix/$identifier.conf" + [ -f "$config" ] || return 0 + stage=$(mktemp "${config}.stage.XXXXXX") || return 1 + trap 'rm -f "$stage"' EXIT + sed '/^Le_RenewalDays=/d; /^Le_NextRenewTime=/d' "$config" >"$stage" || return 1 + printf "Le_NextRenewTime='%s'\n" "$due" >>"$stage" + chmod 600 "$stage" && mv -f "$stage" "$config" +) + +renew_node_acme_scheduled() { + local acme identifier rc=0 start end now failures delay retry_after recovery=false + # Retry the installed files first, even when renewal is due. A skipped or + # failed issuance must leave this recovery scheduled independently of ACME. + case "$(node_cert_status_value deployment_state)" in + reload_pending) + if finish_node_cert_deployment; then return 0; fi + recovery=true + ;; + deployment_pending) renew_cert_command_locked --deploy-acme; return $?;; + esac + acme=$(get_node_acme) || { + if [ "$recovery" = false ]; then + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME client is missing' fi - if [[ "$restart_choice" =~ ^[Yy]$ ]]; then - colorized_echo blue "Restarting node to apply new certificate..." - restart_command -n --no-restart-service - colorized_echo green "✓ Node restarted with new certificate" - else - colorized_echo yellow "Skipped restart. Please restart the node manually to apply the new certificate." - colorized_echo yellow "You can restart it later with: $APP_NAME restart" + return 1 + } + identifier=$(cert_metadata identifier) + if [ -z "$identifier" ]; then + if [ "$recovery" = false ]; then + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME identifier is missing' fi + return 1 + fi + now=$(date +%s) + start=$(openssl x509 -in "$SSL_CERT_FILE" -startdate -noout); start=$(date -d "${start#*=}" +%s) || return 1 + end=$(openssl x509 -in "$SSL_CERT_FILE" -enddate -noout); end=$(date -d "${end#*=}" +%s) || return 1 + set_node_acme_fallback "$identifier" "$((start+(end-start)*2/3))" || return 1 + if [ "$recovery" = false ]; then write_node_cert_status attempting || return 1; fi + local args=(--renew -d "$identifier") + [ "$(cat "$DATA_DIR/certs/.acme-staging/key-type" 2>/dev/null)" != --ecc ] || args+=(--ecc) + # acme.sh honors ARI and CA polling delays. Keep private diagnostic output + # local; only fixed, sanitized messages go into machine-readable status. + (umask 077; run_node_acme "$acme" "${args[@]}" >"$DATA_DIR/certs/acme-last-attempt.log" 2>&1) || rc=$? + # A hook may already have recorded a partial reload. Never issue again. + case "$(node_cert_status_value deployment_state)" in reload_pending|deployment_pending) return 1;; esac + if [ "$rc" -eq 0 ] || [ "$rc" -eq 2 ]; then + if [ "$(node_cert_status_value deployment_state)" = deployed ]; then return 0; fi + if [ "$rc" -eq 0 ]; then + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME completed without running the deployment hook; run certificate-renewal-enable' + return 1 + fi + write_node_cert_status waiting '' "$((now+3600))" + return 0 + fi + if grep -Eqi 'unauthorized|rejectedIdentifier|invalidContact|accountDoesNotExist|Invalid domain|Challenge port .* in use' "$DATA_DIR/certs/acme-last-attempt.log"; then + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME configuration rejected; correct configuration or run renew-cert' + return 1 + fi + failures=$(node_cert_status_value failures); failures=$((${failures:-0}+1)) + delay=300 + local i + for ((i=1; i/dev/null) || retry_after=0 + [ "$retry_after" -le "$((now+delay))" ] || delay=$((retry_after-now)) + fi + write_node_cert_status retry_pending 'Transient ACME failure; see acme-last-attempt.log' "$((now+delay))" "$failures" + return 1 +} + +renew_cert_command() { + with_node_cert_lock renew_cert_command_locked "$@" +} + +renew_cert_command_locked() { + check_running_as_root + ensure_env_exists + load_active_cert_paths + case "${1:-}" in + ''|--deploy-acme) [ "$#" -le 1 ] || return 1;; + *) cert_error 'Usage: renew-cert [--deploy-acme]'; return 1;; + esac + local source=legacy + [ ! -f "$DATA_DIR/certs/source.json" ] || source=$(cert_metadata source) + if [ "${1:-}" = --deploy-acme ]; then + case "$source" in acme_ip|acme_domain) ;; *) cert_error 'ACME hook requires a managed ACME source'; return 1;; esac + fi + if [ "$source" = legacy ]; then + local subject issuer + subject=$(openssl x509 -in "$SSL_CERT_FILE" -noout -subject 2>/dev/null | sed 's/^subject= *//') + issuer=$(openssl x509 -in "$SSL_CERT_FILE" -noout -issuer 2>/dev/null | sed 's/^issuer= *//') + if [ -n "$subject" ] && [ "$subject" = "$issuer" ]; then source=self_signed; fi + fi + case "$source" in + acme_ip|acme_domain) + local acme identifier ipv6 + acme=$(get_node_acme) || return 1 + identifier=$(cert_metadata identifier); ipv6=$(cert_metadata ipv6) + if [ "${1:-}" != --deploy-acme ]; then + # An explicit retry first completes any pending deployment. + if [ "$(node_cert_status_value deployment_state)" = deployment_pending ]; then + renew_cert_command_locked --deploy-acme + return $? + fi + if [ "$(node_cert_status_value deployment_state)" = reload_pending ]; then + finish_node_cert_deployment + return $? + fi + write_node_cert_status attempting || return 1 + # The registered hook deploys and verifies both listeners. + # Explicit retry clears suspension but still honors CA due times. + register_node_acme_reload || return 1 + renew_node_acme_scheduled || return 1 + show_node_certificate || return 1 + return 0 + fi + write_node_cert_status deployment_pending 'Certificate staging or validation pending; previous active observation retained' "$(( $(date +%s) + 300 ))" || return 1 + if [ -n "${CERT_FULLCHAIN_PATH:-}${CERT_KEY_PATH:-}" ]; then + [ -n "${CERT_FULLCHAIN_PATH:-}" ] && [ -n "${CERT_KEY_PATH:-}" ] || return 1 + local stage="$DATA_DIR/certs/.acme-staging" + mkdir -p "$stage" && chmod 700 "$stage" || return 1 + cp "$CERT_FULLCHAIN_PATH" "$stage/fullchain.pem" && + cp "$CERT_KEY_PATH" "$stage/privkey.pem" && + chmod 600 "$stage/privkey.pem" || return 1 + elif [ ! -s "$DATA_DIR/certs/.acme-staging/fullchain.pem" ] || + [ ! -s "$DATA_DIR/certs/.acme-staging/privkey.pem" ]; then + # Install the already renewed pair from durable ACME storage. + # Restore the permanent hook after staging resets its targets. + stage_node_acme "$acme" "$identifier" || return 1 + register_node_acme_reload || return 1 + fi + validate_node_acme_chain "$DATA_DIR/certs/.acme-staging/fullchain.pem" || return 1 + deploy_node_cert_pair "$DATA_DIR/certs/.acme-staging/fullchain.pem" "$DATA_DIR/certs/.acme-staging/privkey.pem" "$identifier" "$ipv6" || return 1 + ;; + self_signed) + write_node_cert_status attempting || return 1 + # Reuse the active certificate's names, including on unattended renewals. + local INSTALL_SAN_ENTRIES + INSTALL_SAN_ENTRIES=$(set -o pipefail; openssl x509 -in "$SSL_CERT_FILE" -noout -ext subjectAltName | + tr ',' '\n' | sed -n 's/^[[:space:]]*DNS:/DNS:/p; s/^[[:space:]]*IP Address:/IP:/p' | + paste -sd, -) || { cert_error "Could not read existing certificate SANs"; return 1; } + [ -n "$INSTALL_SAN_ENTRIES" ] || { cert_error "Existing certificate requires DNS or IP SANs for renewal"; return 1; } + INSTALL_SELF_SIGNED=true + choose_node_certificate || return 1 + ;; + custom|legacy) + write_node_cert_status attempting || return 1 + validate_node_cert_pair "$SSL_CERT_FILE" "$SSL_KEY_FILE" || return 1 + colorized_echo yellow "Custom/legacy certificates are externally renewed. Validated current files; no certificate was regenerated." + ;; + external_tls) colorized_echo yellow "Manage and renew the certificate on the TLS web server."; return 0 ;; + *) cert_error "Unknown certificate source: $source"; return 1 ;; + esac + finish_node_cert_deployment || return 1 + if [ "${1:-}" = --deploy-acme ]; then + colorized_echo green "ACME certificate deployed; TLS hot reload verified." + else + show_node_certificate fi - - colorized_echo cyan "" - colorized_echo cyan "================================" - colorized_echo green "✓ Certificate renewal completed!" - colorized_echo cyan "================================" - colorized_echo magenta "Please use the following Certificate in pasarguard Panel (it's located in ${DATA_DIR}/certs):" - cat "$SSL_CERT_FILE" - colorized_echo cyan "================================" - restart_command } # Main CLI dispatch handler for pg-node. pg_node_main() { - # Bring existing env SSL paths in line with the current APP_NAME (safe no-op if not installed/default) - sync_env_ssl_paths + # Upgrades keep the active certificate paths and files unchanged. + load_active_cert_paths case "$1" in install) @@ -2542,6 +3181,20 @@ pg_node_main() { shift geofiles_command "$@" ;; + show-cert) + show_node_certificate + ;; + certificate-status) + shift + certificate_status_command "$@" + ;; + certificate-renewal-enable) + check_running_as_root + register_node_acme_reload + ;; + certificate-renewal-tick) + certificate_renewal_tick + ;; renew-cert) shift renew_cert_command "$@" diff --git a/tests/integration_pgnode_service_tls.sh b/tests/integration_pgnode_service_tls.sh new file mode 100644 index 0000000..7673ec3 --- /dev/null +++ b/tests/integration_pgnode_service_tls.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Real HTTP/TLS sockets and authentication; no host services or ACME accounts. +set -euo pipefail +ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +python3 - "$ROOT_DIR/pg-node-service.sh" <<'PY' +import hashlib, http.client, os, pathlib, re, shutil, signal, socket, ssl, subprocess, sys, tempfile, time +with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + script = root / 'service.sh' + shutil.copyfile(sys.argv[1], script) + script.chmod(0o700) + def openssl(*args): + subprocess.run(['openssl', *map(str, args)], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + # Use a CA-signed leaf to ensure issuer classification never requires mTLS. + openssl('req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-days', '1', '-addext', 'basicConstraints=critical,CA:TRUE', '-addext', 'keyUsage=critical,keyCertSign,cRLSign', '-subj', '/CN=test-ca', '-keyout', root/'ca.key', '-out', root/'ca.pem') + openssl('req', '-new', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-subj', '/CN=test-leaf', '-keyout', root/'leaf.key', '-out', root/'leaf.csr') + (root/'ext').write_text('subjectAltName=IP:127.0.0.1\nextendedKeyUsage=serverAuth\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\n') + openssl('x509', '-req', '-in', root/'leaf.csr', '-CA', root/'ca.pem', '-CAkey', root/'ca.key', '-CAcreateserial', '-days', '1', '-extfile', root/'ext', '-out', root/'leaf.pem') + def environment(enabled, host, port): + envfile = root/'service.env' + envfile.write_text(f'API_KEY=test-key\nTLS_ENABLED={enabled}\nNODE_HOST={host}\nAPI_PORT={port}\nSSL_CERT_FILE={root / "leaf.pem" if enabled == "true" else root / "absent.pem"}\nSSL_KEY_FILE={root / "leaf.key" if enabled == "true" else root / "absent.key"}\n') + return dict(os.environ, ENV_FILE=str(envfile)) + for enabled in ('true', 'false'): + with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + with (root/'service.log').open('wb') as log: + process = subprocess.Popen(['bash', str(script)], env=environment(enabled, '127.0.0.1', port), stdout=log, stderr=log, start_new_session=True) + try: + def request(key=None): + if enabled == 'true': + client = http.client.HTTPSConnection('127.0.0.1', port, timeout=1, context=ssl.create_default_context(cafile=str(root/'ca.pem'))) + else: + client = http.client.HTTPConnection('127.0.0.1', port, timeout=1) + try: + client.request('GET', '/', headers={'Connection': 'close', **({'x-api-key': key} if key else {})}) + response = client.getresponse() + response.read() + return response.status + finally: + client.close() + deadline = time.monotonic() + 5 + while True: + try: + assert request() == 401 + break + except (OSError, http.client.HTTPException): + if process.poll() is not None or time.monotonic() >= deadline: + raise AssertionError((root/'service.log').read_text()) + time.sleep(.03) + assert request('wrong') == 401 + assert request('test-key') == 200 + if enabled == 'true': + # Exercise the manager's real fresh-handshake verifier, with + # both the matching leaf pin and an unexpected replacement. + manager = pathlib.Path(sys.argv[1]).with_name('pg-node.sh').read_text() + verifier = re.search(r'^verify_node_cert_endpoint\(\) \(.*?^\)', manager, re.M | re.S).group() + pin = hashlib.sha256(ssl.PEM_cert_to_DER_cert((root/'leaf.pem').read_text())).hexdigest() + for expected, code in ((pin, 0), ('0'*64, 1)): + result = subprocess.run(['bash', '-c', verifier + '\nverify_node_cert_endpoint "$@"', '_', + '127.0.0.1', str(port), expected, 'localhost'], capture_output=True, timeout=15) + assert result.returncode == code, result.stderr.decode() + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + process.wait(timeout=5) + for enabled, host in [('invalid', '127.0.0.1'), ('false', '0.0.0.0'), ('false', '::'), ('false', '8.8.8.8'), ('false', 'fe80::1'), ('false', '::ffff:8.8.8.8')]: + result = subprocess.run(['bash', str(script)], env=environment(enabled, host, 62050), capture_output=True, timeout=3) + assert result.returncode != 0, (enabled, host) + for host in ('::1', '10.1.1.1', '172.16.0.1', '192.168.0.1', 'fd00::1', '::ffff:192.168.1.1'): + result = subprocess.run(['bash', '-c', 'PG_NODE_SERVICE_SOURCE_ONLY=true source "$1"; private_backend_host "$2"', '_', str(script), host], capture_output=True, timeout=3) + assert result.returncode == 0, (host, result.stderr) +print('Maintenance transport tests passed') +PY diff --git a/tests/run_all.sh b/tests/run_all.sh index 6b825aa..6935e95 100755 --- a/tests/run_all.sh +++ b/tests/run_all.sh @@ -13,6 +13,10 @@ SUITES=( "unit_lib_system.sh" "unit_pasarguard.sh" "unit_pgnode.sh" + "unit_pgnode_script_install.sh" + "unit_pgnode_tls.sh" + "unit_pgnode_renewal.sh" + "integration_pgnode_service_tls.sh" "unit_pgnode_service.sh" "unit_restore_archive_safety.sh" "unit_restore_recovery.sh" diff --git a/tests/unit_pgnode.sh b/tests/unit_pgnode.sh index 9921f0e..98fc81e 100644 --- a/tests/unit_pgnode.sh +++ b/tests/unit_pgnode.sh @@ -372,6 +372,10 @@ run_install_command() { detect_compose() { :; } curl() { echo "curl $*" >> "$INSTALL_CALLS"; release_api_reply "$@"; } install_node() { echo "install_node $1" >> "$INSTALL_CALLS"; } + register_node_acme_reload() { return "${INSTALL_REGISTRATION_STATUS:-0}"; } + show_node_certificate() { echo 'certificate information'; } + node_cert_config_digest() { echo test-config; } + write_node_cert_status() { echo "cert_status $*" >>"$INSTALL_CALLS"; } install_node_script() { :; } install_completion() { :; } up_node() { :; } @@ -381,7 +385,8 @@ run_install_command() { SERVICE_PORT="62050" API_KEY="00000000-0000-4000-8000-000000000000" SSL_CERT_FILE="/dev/null" - install_command "$@" 2>&1 + # Version selection uses an explicit certificate source for unattended installs. + install_command --self-signed "$@" 2>&1 ); then INSTALL_STATUS=0 else @@ -399,6 +404,14 @@ release_lookup_done() { grep -q "api.github.com/repos/PasarGuard/node/releases" "$INSTALL_CALLS" } +INSTALL_REGISTRATION_STATUS=1 +run_install_command --dev +assert_eq "$INSTALL_STATUS" "1" "install: failed renewal setup returns nonzero" +assert_true "install: failed renewal setup records suspended status" grep -q '^cert_status suspended ' "$INSTALL_CALLS" +assert_true "install: failed renewal setup displays certificate" grep -q 'certificate information' <<<"$INSTALL_OUT" +assert_true "install: failed renewal setup displays API key" grep -q '00000000-0000-4000-8000-000000000000' <<<"$INSTALL_OUT" +assert_true "install: failed renewal setup reports scheduler failure" grep -q 'scheduler was not installed' <<<"$INSTALL_OUT" +unset INSTALL_REGISTRATION_STATUS run_install_command --dev assert_eq "$INSTALL_STATUS" "0" "install --dev: exits 0" assert_eq "$(installed_version)" "dev" "install --dev: installs image tag dev" diff --git a/tests/unit_pgnode_renewal.sh b/tests/unit_pgnode_renewal.sh new file mode 100644 index 0000000..e52084e --- /dev/null +++ b/tests/unit_pgnode_renewal.sh @@ -0,0 +1,194 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +WORK_DIR=$(mktemp -d) +trap 'rm -rf "$WORK_DIR"' EXIT +export APP_TMP_DIR="$WORK_DIR/tmp" APP_DIR="$WORK_DIR/app" DATA_DIR="$WORK_DIR/data" PG_NODE_SOURCE_ONLY=true +mkdir -p "$APP_TMP_DIR" "$APP_DIR" "$DATA_DIR/certs" +curl() { :; } +source "$ROOT_DIR/pg-node.sh" +check_running_as_root() { :; } +colorized_echo() { printf '%s\n' "$*"; } +expect_fail() { if "$@"; then echo "FAIL: accepted $*" >&2; exit 1; fi; } +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 6 -subj '/CN=test' \ + -addext 'subjectAltName=IP:192.0.2.1' -keyout "$SSL_KEY_FILE" -out "$SSL_CERT_FILE" >/dev/null 2>&1 +printf 'SSL_CERT_FILE=%s\nSSL_KEY_FILE=%s\nSERVICE_PORT=62050\nAPI_PORT=62051\n' "$SSL_CERT_FILE" "$SSL_KEY_FILE" >"$ENV_FILE" +# A controllable clock leaves certificate parsing on the real date command. +clock_now=$(command date +%s) +date() { if [ "$*" = +%s ]; then echo "$clock_now"; else command date "$@"; fi; } +acme_calls="$WORK_DIR/acme-calls" +acme_validation_failures="$WORK_DIR/acme-validation-failures" +get_node_acme() { echo mock_acme; } +mock_acme() { + if [[ " $* " != *" --cert-home $DATA_DIR/certs/acme "* ]]; then + echo 'wrong cert-home' >>"$acme_validation_failures" + fi + # Scheduler and synchronous hook retain the certificate lock. + if flock -n "$DATA_DIR/certs/.deployment.lock" true; then + echo 'missing deployment lock' >>"$acme_validation_failures" + fi + echo call >>"$acme_calls" + case "$acme_result" in + skip) return 2;; + transient) echo 'network failed secret-token'; return 1;; + ca_delay) echo 'Retry-After: 7200'; return 1;; + config) echo 'rejectedIdentifier secret-token'; return 1;; + success) finish_node_cert_deployment;; + esac +} +reload_calls="$WORK_DIR/reloads" +reload_node_cert_services() { echo signal >>"$reload_calls"; return 0; } +verify_node_cert_services() { [ "$verify_ok" = true ]; } +verify_ok=true +# Scheduler ignores every operator-managed source, even expired self-signed files. +for source in self_signed custom external_tls; do + save_cert_source "$source" + certificate_renewal_tick + [ ! -e "$acme_calls" ] +done +save_cert_source acme_ip 192.0.2.1 '' 80 +# Exact fallback stays unpinned so acme.sh can honor CA renewal windows. +mkdir -p "$DATA_DIR/certs/acme/192.0.2.1" +printf "Le_RenewalDays='6'\nLe_NextRenewTime='1'\nLe_Domain='192.0.2.1'\n" >"$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf" +acme_result=skip +certificate_renewal_tick +[ "$(node_cert_status_value next_attempt)" -eq "$((clock_now+3600))" ] +if grep -q '^Le_RenewalDays=' "$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf"; then + echo 'FAIL: renewal days remain pinned' >&2; exit 1 +fi +grep -q "Le_NextRenewTime='$((clock_now+4*86400))'" "$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf" +certificate_renewal_tick +[ "$(wc -l <"$acme_calls")" -eq 1 ] +clock_now=$((clock_now+3600)); acme_result=transient +expect_fail certificate_renewal_tick +[ "$(node_cert_status_value failures)" -eq 1 ] +next=$(node_cert_status_value next_attempt) +[ "$next" -ge "$((clock_now+300))" ] && [ "$next" -le "$((clock_now+360))" ] +if grep -q secret-token "$DATA_DIR/certs/renewal-status.json"; then + echo 'FAIL: status exposes secret-token' >&2; exit 1 +fi +clock_now="$next" +expect_fail certificate_renewal_tick +[ "$(node_cert_status_value failures)" -eq 2 ] +next=$(node_cert_status_value next_attempt) +[ "$next" -ge "$((clock_now+600))" ] && [ "$next" -le "$((clock_now+720))" ] +clock_now="$next"; acme_result=ca_delay +expect_fail certificate_renewal_tick +[ "$(node_cert_status_value next_attempt)" -eq "$((clock_now+7200))" ] +clock_now=$((clock_now+7200)); acme_result=config +expect_fail certificate_renewal_tick +[ "$(node_cert_status_value deployment_state)" = suspended ] +previous_calls=$(wc -l <"$acme_calls") +clock_now=$((clock_now+10000)) +certificate_renewal_tick +[ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] +# Configuration changes resume checks; retries may not expose ACME output in status. +printf '\n# corrected challenge routing\n' >>"$ENV_FILE" +acme_result=skip +certificate_renewal_tick +[ "$(wc -l <"$acme_calls")" -eq "$((previous_calls+1))" ] +# Success requires both fresh endpoint checks. A partial reload preserves the last +# verified observation and retries only signalling, without any ACME invocation. +clock_now=$(command date +%s) +write_node_cert_status deployed +active_pin=$(node_cert_status_value active_fingerprint) +verify_ok=false +expect_fail finish_node_cert_deployment +[ "$(node_cert_status_value active_fingerprint)" = "$active_pin" ] +[ "$(node_cert_status_value deployment_state)" = reload_pending ] +previous_calls=$(wc -l <"$acme_calls") +clock_now=$((clock_now+300)); verify_ok=true +certificate_renewal_tick +[ "$(node_cert_status_value deployment_state)" = deployed ] +[ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] +[ "$(stat -c %a "$DATA_DIR/certs/renewal-status.json")" = 600 ] +# A persistent listener failure must not prevent renewal once disk files are due. +verify_ok=false +expect_fail finish_node_cert_deployment +clock_now=$((clock_now+5*86400)) +for acme_result in skip transient ca_delay config; do + expect_fail certificate_renewal_tick + previous_calls=$((previous_calls+1)) + [ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] + [ "$(node_cert_status_value deployment_state)" = reload_pending ] + [ "$(node_cert_status_value active_fingerprint)" = "$active_pin" ] + [ "$(node_cert_status_value next_attempt)" -eq "$((clock_now+300))" ] + clock_now=$((clock_now+300)) +done +# Recovery also survives a missing client and resumes without invoking ACME. +get_node_acme() { return 1; } +expect_fail certificate_renewal_tick +[ "$(node_cert_status_value deployment_state)" = reload_pending ] +clock_now=$((clock_now+300)); verify_ok=true +certificate_renewal_tick +[ "$(node_cert_status_value deployment_state)" = deployed ] +[ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] +[ -z "$(find "$DATA_DIR/certs" -name '.status.*' -print)" ] +certificate_status_command --json | jq -e '.files_currently_valid and .last_success != null' >/dev/null +clock_now=$((clock_now+7*86400)) +certificate_status_command --json | jq -e '.files_currently_valid == false' >/dev/null +expect_fail certificate_status_command --bogus +# Invalid trailing PEM blocks cannot be mistaken for a valid full chain. +clock_now=$(command date +%s) +cp "$SSL_CERT_FILE" "$WORK_DIR/broken-chain" +printf '\n-----BEGIN CERTIFICATE-----\ninvalid\n' >>"$WORK_DIR/broken-chain" +expect_fail validate_node_cert_pair "$WORK_DIR/broken-chain" "$SSL_KEY_FILE" +# Idempotent scheduler registration preserves unrelated jobs and removes only ours. +cronfile="$WORK_DIR/crontab" +printf '0 0 * * * echo unrelated\n' >"$cronfile" +crontab() { if [ "$1" = -l ]; then cat "$cronfile"; else cp "$1" "$cronfile"; fi; } +install_node_cert_scheduler +install_node_cert_scheduler +[ "$(grep -c 'pg-node-cert:' "$cronfile")" -eq 1 ] +grep -q '^\*/5 ' "$cronfile" +remove_node_cert_scheduler +[ "$(cat "$cronfile")" = '0 0 * * * echo unrelated' ] +# Concurrent instances must preserve each other's entries and unrelated jobs. +crontab() { + if [ "$1" = -l ]; then cat "$cronfile"; sleep 0.1 + else cp "$1" "$cronfile"; fi +} +(APP_NAME=pg-node-one; install_node_cert_scheduler) & +first=$! +(APP_NAME=pg-node-two; install_node_cert_scheduler) & +second=$! +wait "$first"; wait "$second" +[ "$(grep -c 'pg-node-cert:' "$cronfile")" -eq 2 ] +(APP_NAME=pg-node-one; remove_node_cert_scheduler) & +first=$! +(APP_NAME=pg-node-three; install_node_cert_scheduler) & +second=$! +wait "$first"; wait "$second" +[ "$(grep -c 'pg-node-cert:' "$cronfile")" -eq 2 ] +grep -q 'pg-node-cert:pg-node-two$' "$cronfile" +grep -q 'pg-node-cert:pg-node-three$' "$cronfile" +grep -q 'echo unrelated' "$cronfile" +# A retry without hook environment recovers both files without renewal. +get_node_acme() { echo mock_acme; } +unset CERT_FULLCHAIN_PATH CERT_KEY_PATH +rm -rf "$DATA_DIR/certs/.acme-staging" +cp "$SSL_CERT_FILE" "$WORK_DIR/renewed-cert" +cp "$SSL_KEY_FILE" "$WORK_DIR/renewed-key" +stage_node_acme() { + mkdir -p "$DATA_DIR/certs/.acme-staging" + cp "$WORK_DIR/renewed-cert" "$DATA_DIR/certs/.acme-staging/fullchain.pem" + cp "$WORK_DIR/renewed-key" "$DATA_DIR/certs/.acme-staging/privkey.pem" +} +register_node_acme_reload() { :; } +# Synthetic self-signed fixture substitutes for system trust only. +validate_node_acme_chain() { :; } +write_node_cert_status deployment_pending +previous_calls=$(wc -l <"$acme_calls") +renew_cert_command +[ "$(node_cert_status_value deployment_state)" = deployed ] +[ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] +cmp "$WORK_DIR/renewed-cert" "$SSL_CERT_FILE" +cmp "$WORK_DIR/renewed-key" "$SSL_KEY_FILE" +# Complete staging is used directly on a later retry. +stage_node_acme() { return 1; } +write_node_cert_status deployment_pending +renew_cert_command +if [ -s "$acme_validation_failures" ]; then + cat "$acme_validation_failures" >&2; exit 1 +fi +echo 'Certificate renewal scheduler tests passed' diff --git a/tests/unit_pgnode_script_install.sh b/tests/unit_pgnode_script_install.sh new file mode 100644 index 0000000..c114d09 --- /dev/null +++ b/tests/unit_pgnode_script_install.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +WORK_DIR=$(mktemp -d) +trap 'rm -rf "$WORK_DIR"' EXIT +export ROOT_DIR WORK_DIR +export APP_TMP_DIR="$WORK_DIR/tmp" APP_DIR="$WORK_DIR/app" DATA_DIR="$WORK_DIR/data" +export PG_NODE_SOURCE_ONLY=true PG_NODE_SCRIPT_DIR="$ROOT_DIR" +mkdir -p "$APP_TMP_DIR" "$APP_DIR" "$DATA_DIR" "$WORK_DIR/bin" +# Block source-time IP detection and any accidental network requests. +curl() { :; } +export -f curl + +cat >"$WORK_DIR/install-harness.sh" <<'HARNESS' +colorized_echo() { :; } +print_script_execution_header() { :; } +github_download_file() { echo 'Unexpected script download' >&2; return 1; } +install_shared_libs_from_repo() { :; } +# Redirect the production install destination without touching system files. +mv() { + [ "$2" = "/usr/local/bin/$APP_NAME" ] + TARGET_PATH="$WORK_DIR/bin/$APP_NAME" + command mv "$1" "$TARGET_PATH" +} +rm() { + local arg + for arg in "$@"; do + case "$arg" in /usr/*) echo 'Unexpected system file removal' >&2; return 1;; esac + done + command rm "$@" +} +APP_NAME="pg-node-install-regression" +install_node_script +sed "s|^APP_NAME=.*|APP_NAME=\"$APP_NAME\"|" "$EXPECTED_SCRIPT" >"$WORK_DIR/expected.sh" +cmp "$WORK_DIR/expected.sh" "$TARGET_PATH" +[ -x "$TARGET_PATH" ] +# The installed copy must retain the ACME deployment handler. +grep -q -- '--deploy-acme' "$TARGET_PATH" +HARNESS + +# File/checkout invocation must preserve the running version. +export EXPECTED_SCRIPT="$ROOT_DIR/pg-node.sh" +bash -c 'source "$ROOT_DIR/pg-node.sh"; source "$WORK_DIR/install-harness.sh"' + +# Reproduce bash -c "$(curl ...)": the script has no backing source file. +cat "$ROOT_DIR/pg-node.sh" >"$WORK_DIR/inline.sh" +printf '\nsource "$WORK_DIR/install-harness.sh"\n' >>"$WORK_DIR/inline.sh" +export EXPECTED_SCRIPT="$WORK_DIR/inline.sh" +bash -c "$(cat "$WORK_DIR/inline.sh")" @ install-script + +echo 'Node script installation tests passed' diff --git a/tests/unit_pgnode_service.sh b/tests/unit_pgnode_service.sh index e8e2328..ee2295b 100644 --- a/tests/unit_pgnode_service.sh +++ b/tests/unit_pgnode_service.sh @@ -54,8 +54,7 @@ fi # tls_verify_level: client-cert verification on only for CA-signed certs. # Mock check_certificate returning 0 for tls_verify_level test. check_certificate() { return 0; } -assert_eq "$(tls_verify_level /tmp/cert.pem)" "verify=1" "tls_verify_level: CA-signed -> verify=1" -# Mock check_certificate returning 2 for tls_verify_level test. +assert_eq "$(tls_verify_level /tmp/cert.pem)" "verify=0" "tls_verify_level: CA-signed keeps API-key authentication" check_certificate() { return 2; } assert_eq "$(tls_verify_level /tmp/cert.pem)" "verify=0" "tls_verify_level: self-signed -> verify=0" # Mock check_certificate returning 1 for tls_verify_level test. diff --git a/tests/unit_pgnode_tls.sh b/tests/unit_pgnode_tls.sh new file mode 100644 index 0000000..b2c107f --- /dev/null +++ b/tests/unit_pgnode_tls.sh @@ -0,0 +1,310 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +WORK_DIR=$(mktemp -d) +trap 'rm -rf "$WORK_DIR"' EXIT +export APP_TMP_DIR="$WORK_DIR/tmp" APP_NAME=pg-node-tls-test APP_DIR="$WORK_DIR/app" DATA_DIR="$WORK_DIR/data" +mkdir -p "$APP_TMP_DIR" "$APP_DIR" "$DATA_DIR/certs" +curl() { :; } +export PG_NODE_SOURCE_ONLY=true +source "$ROOT_DIR/pg-node.sh" +colorized_echo() { printf '%s\n' "$*"; } +check_running_as_root() { :; } +get_occupied_ports() { OCCUPIED_PORTS=""; } +AUTO_CONFIRM=true +expect_fail() { if "$@"; then echo "FAIL: accepted $*" >&2; exit 1; fi; } +expect_fail validate_ssl_selection +INSTALL_SSL_IPV6=2001:db8::1 +expect_fail validate_ssl_selection +unset INSTALL_SSL_IPV6 +INSTALL_SELF_SIGNED=true INSTALL_SSL_IP=192.0.2.1 +expect_fail validate_ssl_selection +unset INSTALL_SELF_SIGNED +INSTALL_SSL_HTTP_PORT=0 +expect_fail validate_ssl_selection +INSTALL_SSL_HTTP_PORT=8080 +validate_ssl_selection +unset INSTALL_SSL_IP +INSTALL_CERT_PATH=/not-found +expect_fail validate_ssl_selection +unset INSTALL_CERT_PATH +# Reject unsupported plaintext selections before saving metadata or certificates. +( + INSTALL_NO_SSL=true + node_version=v0.5.7 + curl() { printf '# No plaintext setting\n'; } + expect_fail choose_node_certificate + [ ! -e "$DATA_DIR/certs/source.json" ] + [ ! -e "$SSL_CERT_FILE" ] + node_version=dev + curl() { printf '# TLS_ENABLED = true\n'; } + choose_node_certificate + [ "$TLS_ENABLED" = false ] + [ "$(cert_metadata source)" = external_tls ] + rm "$DATA_DIR/certs/source.json" +) +# Generate a real valid pair; preserve full chain bytes and permissions on deployment. +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 2 -subj '/CN=unused' \ + -addext 'subjectAltName=IP:192.0.2.1,IP:2001:db8::1,DNS:node.example.com,DNS:*.example.net' \ + -keyout "$WORK_DIR/key" -out "$WORK_DIR/cert" >/dev/null 2>&1 +validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" 192.0.2.1 2001:db8::1 +validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" node.example.com +expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" wrong.example.com +expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" 192.0.2.2 +openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:prime256v1 -out "$WORK_DIR/wrong-key" +expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/wrong-key" +# Advance validation's clock past notAfter; newer OpenSSL rejects -days -1. +( + expiry=$(openssl x509 -in "$WORK_DIR/cert" -enddate -noout) + future=$(date -d "${expiry#*=}" +%s) + date() { + if [ "$*" = +%s ]; then printf '%s\n' "$((future + 1))" + else command date "$@"; fi + } + expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" +) +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 1 -subj '/CN=node.example.com' \ + -keyout "$WORK_DIR/no-san-key" -out "$WORK_DIR/no-san" >/dev/null 2>&1 +expect_fail validate_node_cert_pair "$WORK_DIR/no-san" "$WORK_DIR/no-san-key" node.example.com + +deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" 192.0.2.1 +cmp "$WORK_DIR/cert" "$SSL_CERT_FILE" +[ "$(stat -c %a "$SSL_KEY_FILE")" = 600 ] +expect_fail deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/wrong-key" +cmp "$WORK_DIR/key" "$SSL_KEY_FILE" +# Concurrent deployments cannot interleave their key and certificate moves. +move_log="$WORK_DIR/moves" +( + mv() { + if [ "${*: -1}" = "$SSL_KEY_FILE" ]; then + echo key >>"$move_log" + sleep 0.1 + elif [ "${*: -1}" = "$SSL_CERT_FILE" ]; then + echo cert >>"$move_log" + fi + command mv "$@" + } + deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" & + first=$! + deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" & + second=$! + wait "$first" + wait "$second" +) +[ "$(cat "$move_log")" = "$(printf 'key\ncert\nkey\ncert')" ] +# Failure closes the descriptor and removes temporary files. +( + cp() { return 1; } + expect_fail deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" +) +flock -n "$DATA_DIR/certs/.deployment.lock" true +# Synchronous reload subprocesses inherit ownership without deadlocking. +with_node_cert_lock bash -c 'flock -n "$PG_NODE_CERT_LOCK_FD" && ! flock -n "$DATA_DIR/certs/.deployment.lock" true' +[ -z "$(find "$DATA_DIR/certs" -name '*.stage.*' -print)" ] +# Selected certificates outside the data mount are relocated with matching paths. +( + choose_node_certificate() { TLS_ENABLED=true; } + SSL_CERT_FILE="$WORK_DIR/cert"; SSL_KEY_FILE="$WORK_DIR/key" + with_node_cert_lock prepare_install_node_certificate + [ "$SSL_CERT_FILE" = "$DATA_DIR/certs/ssl_cert.pem" ] + [ "$SSL_KEY_FILE" = "$DATA_DIR/certs/ssl_key.pem" ] + cmp "$WORK_DIR/cert" "$SSL_CERT_FILE" + cmp "$WORK_DIR/key" "$SSL_KEY_FILE" +) +# Self-signed output exposes the leaf certificate pin, not a PEM-file checksum. +save_cert_source self_signed +cert_output=$(show_node_certificate) +expected_pin=$(openssl x509 -in "$WORK_DIR/cert" -noout -fingerprint -sha256 | cut -d= -f2 | tr -d ':' | tr '[:upper:]' '[:lower:]') +[[ "$cert_output" == *"SHA-256 certificate pin (leaf DER): $expected_pin"* ]] +[[ "$cert_output" != *certificate_sha256* ]] +[[ "$cert_output" != *server_ca* ]] +active_cert="$SSL_CERT_FILE" +SSL_CERT_FILE="$WORK_DIR/no-certificate" +expect_fail show_node_certificate +SSL_CERT_FILE="$active_cert" +# Mock ACME: ECC fails, RSA succeeds; confirm installation tries both and preserves old files on failure. +acme_calls="$WORK_DIR/acme-calls" +mock_acme() { + # ACME staging is owned by the same lock as certificate deployment. + if flock -n "$DATA_DIR/certs/.deployment.lock" true; then + echo 'FAIL: ACME ran without the deployment lock' >&2 + return 1 + fi + printf '%s\n' "$*" >>"$acme_calls" + [[ " $* " != *' --ecc '* ]] || return 1 + local key='' cert='' + while [ $# -gt 0 ]; do + case "$1" in --key-file) key="$2"; shift;; --fullchain-file) cert="$2"; shift;; esac + shift + done + [ "$key" != no ] || key='' + [ "$cert" != no ] || cert='' + [ -z "$key" ] || cp "$WORK_DIR/key" "$key" + [ -z "$cert" ] || cp "$WORK_DIR/cert" "$cert" +} +ensure_node_acme() { :; } +validate_node_acme_chain() { :; } +get_node_acme() { echo mock_acme; } +issue_node_acme acme_ip 192.0.2.1 2001:db8::1 8080 +grep -q -- '--certificate-profile shortlived --days 4' "$acme_calls" +grep -q -- '--httpport 8080' "$acme_calls" +grep -q -- '--ecc' "$acme_calls" +mock_acme() { return 1; } +expect_fail issue_node_acme acme_ip 192.0.2.1 '' 80 +cmp "$WORK_DIR/key" "$SSL_KEY_FILE" +# Renewal never changes source implicitly; hook must reload both node and maintenance. +printf 'SSL_CERT_FILE=%s\nSSL_KEY_FILE=%s\n' "$SSL_CERT_FILE" "$SSL_KEY_FILE" >"$ENV_FILE" +save_cert_source external_tls +renew_cert_command +save_cert_source custom +verify_node_cert_services() { return 0; } +install_node_cert_scheduler() { :; } +reload_called=false +detect_compose() { :; } +reload_node_cert_services() { + if flock -n "$DATA_DIR/certs/.deployment.lock" true; then + echo 'FAIL: deployment lock released before reload' >&2 + return 1 + fi + reload_called=true +} +renew_cert_command +[ "$reload_called" = true ] +cmp "$WORK_DIR/key" "$SSL_KEY_FILE" +# Renewal preserves installed DNS, wildcard, IPv4 and IPv6 SANs without prompting. +( + ENV_FILE="$WORK_DIR/renew.env" + SSL_CERT_FILE="$WORK_DIR/renew.pem" SSL_KEY_FILE="$WORK_DIR/renew.key" + printf 'SSL_CERT_FILE=%s\nSSL_KEY_FILE=%s\n' "$SSL_CERT_FILE" "$SSL_KEY_FILE" >"$ENV_FILE" + NODE_IP=198.51.100.2 NODE_IP_V4=198.51.100.2 NODE_IP_V6='' + read() { + if [[ "$*" == *'Enter additional SAN entries'* ]]; then + touch "$WORK_DIR/san-prompt" + return 1 + fi + builtin read "$@" + } + for mode in self_signed legacy; do + cp "$WORK_DIR/cert" "$SSL_CERT_FILE" + cp "$WORK_DIR/key" "$SSL_KEY_FILE" + if [ "$mode" = legacy ]; then + rm -f "$DATA_DIR/certs/source.json" + AUTO_CONFIRM=true + else + save_cert_source self_signed + AUTO_CONFIRM=false + fi + reload_called=false + renew_cert_command "$ENV_FILE" + reload_called=false + expect_fail renew_cert_command >"$acme_calls" + if [[ " $* " == *' --renew '* ]]; then + CERT_FULLCHAIN_PATH="$WORK_DIR/cert" CERT_KEY_PATH="$WORK_DIR/key" renew_cert_command --deploy-acme + fi +} +register_node_acme_reload +grep -q -- '--key-file no --fullchain-file no' "$acme_calls" +reload_called=false +CERT_FULLCHAIN_PATH="$WORK_DIR/cert" CERT_KEY_PATH="$WORK_DIR/key" renew_cert_command --deploy-acme >"$WORK_DIR/deploy-output" +[ "$reload_called" = true ] +# The internal hook does not duplicate the installer's certificate output. +if grep -q -- 'BEGIN CERTIFICATE' "$WORK_DIR/deploy-output"; then + echo 'FAIL: deployment hook printed PEM' >&2; exit 1 +fi +# Explicit renewal still prints the resulting certificate once. +renew_cert_command >"$WORK_DIR/renew-output" +[ "$(grep -c -- '^-----BEGIN CERTIFICATE-----' "$WORK_DIR/renew-output")" = 1 ] || { cat "$WORK_DIR/renew-output"; exit 1; } +# Signal both actual deployment targets; propagate individual failures. +unset -f reload_node_cert_services +# Restore just this function from the checkout without executing the installer. +eval "$(sed -n '/^reload_node_cert_services() {/,/^}/p' "$ROOT_DIR/pg-node.sh")" +COMPOSE=mock_compose +compose_called=false +maintenance_called=false +mock_compose() { compose_called=true; [[ "$*" == *"-p $APP_NAME restart node" ]]; } +service_installed() { SERVICE_NAME="$APP_NAME-service"; return 0; } +systemctl() { + [ "$*" != "is-active --quiet $APP_NAME-service" ] || return 0 + maintenance_called=true + [ "$*" = "kill --kill-whom=main --signal=SIGHUP $APP_NAME-service" ] +} +reload_node_cert_services +[ "$compose_called" = true ] && [ "$maintenance_called" = true ] +systemctl() { [ "$1" = is-active ]; } +expect_fail reload_node_cert_services +systemctl() { + [ "$1" != is-active ] || return 1 + maintenance_called=true + return 0 +} +maintenance_called=false +reload_node_cert_services +[ "$maintenance_called" = false ] +mock_compose() { return 1; } +expect_fail reload_node_cert_services +# Only running maintenance services add their API listener to verification. +eval "$(sed -n '/^verify_node_cert_services() {/,/^}/p' "$ROOT_DIR/pg-node.sh")" +printf 'SERVICE_PORT=62050\nAPI_PORT=62051\n' >>"$ENV_FILE" +verified_ports="$WORK_DIR/verified-ports" +verify_node_cert_endpoint() { echo "$2" >>"$verified_ports"; } +verify_node_cert_services +[ "$(cat "$verified_ports")" = 62050 ] +: >"$verified_ports" +systemctl() { [ "$1" = is-active ]; } +verify_node_cert_services +[ "$(cat "$verified_ports")" = "$(printf '62050\n62051')" ] +# Shared ACME entries belong to this node only when their reload hook matches. +( + shared="$WORK_DIR/shared-acme" + mkdir -p "$shared/192.0.2.1" "$shared/192.0.2.1_ecc" + printf '#!/usr/bin/env bash\nprintf "%%s\\n" "$*" >>"$MIGRATION_CALLS"\n' >"$shared/acme.sh" + chmod +x "$shared/acme.sh" + export MIGRATION_CALLS="$WORK_DIR/migration-calls" + printf "Le_ReloadCmd='systemctl reload nginx'\n" >"$shared/192.0.2.1/192.0.2.1.conf" + printf "Le_ReloadCmd='env DATA_DIR=/another-node /usr/local/bin/pg-node renew-cert --deploy-acme'\n" >"$shared/192.0.2.1_ecc/192.0.2.1.conf" + migrate_node_acme_storage "$shared/acme.sh" 192.0.2.1 + [ ! -e "$MIGRATION_CALLS" ] + [ ! -d "$DATA_DIR/certs/acme/192.0.2.1" ] + [ ! -d "$DATA_DIR/certs/acme/192.0.2.1_ecc" ] + printf -v hook 'env %q %q %q renew-cert --deploy-acme' "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" + printf "Le_ReloadCmd='%s'\n" "$hook" >"$shared/192.0.2.1/192.0.2.1.conf" + encoded=$(printf '%s' "$hook" | openssl base64 -A) + printf "Le_ReloadCmd='__ACME_BASE64__START_%s__ACME_BASE64__END_'\n" "$encoded" >"$shared/192.0.2.1_ecc/192.0.2.1.conf" + migrate_node_acme_storage "$shared/acme.sh" 192.0.2.1 + cmp "$shared/192.0.2.1/192.0.2.1.conf" "$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf" + cmp "$shared/192.0.2.1_ecc/192.0.2.1.conf" "$DATA_DIR/certs/acme/192.0.2.1_ecc/192.0.2.1.conf" + [ "$(cat "$MIGRATION_CALLS")" = "$(printf '%s\n' '--remove -d 192.0.2.1 --ecc' '--remove -d 192.0.2.1')" ] +) +# Failed hook staging must leave the scheduler uninstalled. +( + stage_node_acme() { return 1; } + migrate_node_acme_storage() { :; } + install_node_cert_scheduler() { touch "$WORK_DIR/unexpected-scheduler"; } + expect_fail register_node_acme_reload + [ ! -e "$WORK_DIR/unexpected-scheduler" ] +) +# Upgrade loading honors managed paths unchanged. +SSL_CERT_FILE=/wrong; SSL_KEY_FILE=/wrong +load_active_cert_paths +[ "$SSL_CERT_FILE" != /wrong ] +echo 'TLS installer tests passed'