Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/command-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
31 changes: 30 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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. |
Expand Down
19 changes: 18 additions & 1 deletion docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,11 @@ Installs or re-installs a worker node instance.
- `--use-rest`: Connect to panel over REST protocol.
- `--service-port <PORT>`: Port for proxy traffic.
- `--api-port <PORT>`: Port for node daemon API.
- `--ssl-ip <IPV4>`: Issue a Let's Encrypt IP certificate (default source; explicit IP required unattended).
- `--ssl-ipv6 <IPV6>`: Add an IPv6 identifier alongside `--ssl-ip`.
- `--ssl-domain <DOMAIN>`: Issue a Let's Encrypt domain certificate.
- `--ssl-http-port <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>`: Path to existing public TLS certificate.
- `--key-path <PATH>`: Path to existing private TLS key.
Expand Down Expand Up @@ -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.
<!-- coderabbit-ai-generated:v1 -->

<!-- coderabbit-ai-generated-section:v1:fdca7fbcafa4be6c7f810a92d31d766377a4c34233bf708b5072ff4112948af2 -->

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.

<!-- /coderabbit-ai-generated:v1 -->
```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.

Expand Down
60 changes: 56 additions & 4 deletions docs/ssl-and-certificates.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down
63 changes: 43 additions & 20 deletions pg-node-service.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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}"

Expand All @@ -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 \
Expand Down
Loading
Loading