refactor(vpn): split JWT identity and OpenVPN certificate lifecycle
OpenVPN Ansible / Ansible Syntax Check (push) Successful in 43s
OpenVPN Ansible / Ansible Lint (push) Successful in 1m8s
OpenVPN Ansible / Deploy VPN Networking and OpenVPN (push) Successful in 3m32s
OpenVPN Ansible / Generate SBOM (push) Successful in 55s
OpenVPN Ansible / Scan SBOM with Trivy (push) Successful in 18s

- Add a dedicated role and workflow to generate VPN JWT identities and export public keys
- Run identity preparation automatically for VPN nodes awaiting OpenBao registration
- Gate OpenVPN and PKI setup until each node is registered
- Split PKI setup into runtime, configuration, service, and initial certificate tasks
- Restore TAP and bridge attachment after OpenVPN restarts
- Remove bundled server certificate and private key
This commit is contained in:
2026-11-27 17:58:46 +01:00
parent 36d2845a3a
commit 4b8e7f3592
35 changed files with 1322 additions and 303 deletions
+43 -54
View File
@@ -1,63 +1,52 @@
# OpenVPN PKI JWT identity preparation
# OpenVPN PKI certificate lifecycle
This role prepares one local JWT RSA identity per VPN server so an administrator
can register each public key with the existing OpenBao JWT configuration. It
does not configure OpenBao or request certificates.
This role manages the OpenVPN server certificate through the configured
OpenBao PKI signing endpoint. JWT identity management belongs to the separate
`openvpn_jwt` role, which runs before this role in `playbooks/openvpn.yml`.
## Prepare an identity
## Task layout
Run the dedicated playbook, limiting it to the new VPN server when appropriate:
`tasks/main.yml` delegates to focused stages:
```bash
ansible-playbook \
-i inventories/prod/hosts.ini \
playbooks/openvpn-pki-identity.yml \
--limit vpn01-test
- `runtime.yml`: OpenBao CLI, runtime packages, and company VPN CA fingerprint.
- `setup.yml`: certificate directories, OpenBao API CA, and lifecycle scripts.
- `service.yml`: protected configuration and systemd service/timer.
- `initial_certificate.yml`: initial issuance only when `server.crt` is absent.
Subsequent Ansible deployments do not renew an existing certificate. The
daily systemd timer invokes the lifecycle script, which decides whether the
certificate needs renewal.
On initial setup, the certificate is issued before OpenVPN is restarted or
started. Ansible then flushes the restart handler, which restarts OpenVPN and
waits for TAP before bringing it up and attaching it to the bridge. A separate
start/TAP task runs only when no restart handler ran. The daily timer is enabled
after the initial issuance attempt.
## CA configuration
The OpenBao API CA is deployed to `/root/openbao-ca.crt` and is used only for
OpenBao API TLS. The company VPN Root CA deployed by the `openvpn` role at
`/etc/openvpn/certs/ca.crt` anchors OpenVPN server certificate validation.
The role calculates that certificate's SHA-256 fingerprint on the VPN node.
## Certificate configuration
Configure node-specific names in inventory. For example:
```yaml
openvpn_pki_certificate_common_name: "{{ inventory_hostname }}"
openvpn_pki_certificate_dns_sans:
- "{{ inventory_hostname }}"
```
The playbook targets `vpn_nodes` and uses privilege escalation. It creates the
identity on the selected server; it does not deploy certificates or alter the
OpenVPN service.
## Key locations and retrieval
The server stores its root-owned identity in `/etc/vault-jwt/` by default:
- `private.pem`: RSA 3072-bit private key, mode `0600`.
- `public.pem`: corresponding PEM public key, mode `0644`.
Only `public.pem` is fetched to the controller, as
`artifacts/openvpn-pki-public-keys/<inventory_hostname>.pem`. The artifacts
directory is ignored by Git. The private key is generated on the VPN server
with `community.crypto.openssl_privatekey`; it is never fetched.
## Register the public key in OpenBao
Provide the fetched PEM public key to the OpenBao administrator using the
approved secure process. The administrator should combine the new PEM public
key with all currently registered PEM public keys into a bundle, then update
the existing JWT authentication configuration with that complete bundle. The
update must preserve every previously registered key; replacing the configured
key set with only the new key would invalidate identities already in use.
Public-key registration is a manual administrator operation and is not
performed by this role.
## Existing identity behavior
The role creates a missing identity only when both key files are absent. If
both already exist, it leaves them unchanged and fetches the existing public
key again. If exactly one key file exists, the role fails rather than
replacing or silently repairing the identity. Investigate and recover the
matching pair deliberately before rerunning. Do not delete or replace the
private key as a routine way to resolve errors: OpenBao registrations depend
on the corresponding public key.
The private key must remain on its VPN server because it is the credential
used to prove that server's identity. Copying it to the controller or
registering it with OpenBao would defeat the separation between private key
custody and public-key registration.
Set `openvpn_pki_bao_addr`, `openvpn_pki_bao_cacert`, and
`openvpn_pki_sign_endpoint` to match the OpenBao deployment. The lifecycle
script runs as root from `/usr/local/libexec/openvpn-pki/`, using the
protected configuration at `/etc/openvpn/openbao-vpn.conf`. It uses the same
`flock` lock for initial issuance and timer runs.
## Requirements
Install the `community.crypto` collection on the Ansible controller. It is not
currently listed in the repository's `requirements.yml`.
Install the collections listed in the repository's `requirements.yml`,
including `community.crypto` for the `openvpn_jwt` role.
+17 -5
View File
@@ -1,6 +1,18 @@
---
openvpn_pki_jwt_directory: /etc/vault-jwt
openvpn_pki_jwt_private_key_path: "{{ openvpn_pki_jwt_directory }}/private.pem"
openvpn_pki_jwt_public_key_path: "{{ openvpn_pki_jwt_directory }}/public.pem"
openvpn_pki_jwt_rsa_bits: 3072
openvpn_pki_public_key_artifact_directory: "{{ playbook_dir }}/../artifacts/openvpn-pki-public-keys"
openvpn_pki_bao_addr: "https://10.1.0.101:30200"
openvpn_pki_bao_cacert: /root/openbao-ca.crt
openvpn_pki_deployed_ca_source: "{{ openvpn_pki_certificate_dir }}/ca.crt"
openvpn_pki_sign_endpoint: vpn-Intermediate-pki/sign/vpn-servers
openvpn_pki_certificate_ttl: 1128h
openvpn_pki_certificate_dir: "{{ openvpn_cert_dir | default('/etc/openvpn/certs') }}"
openvpn_pki_certificate_common_name: "{{ inventory_hostname }}"
openvpn_pki_certificate_dns_sans: []
openvpn_pki_certificate_rsa_bits: 4096
openvpn_pki_expected_issuer: ""
openvpn_pki_require_server_auth_eku: true
openvpn_pki_renew_before_days: 15
openvpn_pki_working_directory: "{{ openvpn_pki_certificate_dir }}/.pki-work"
openvpn_pki_script_directory: /usr/local/libexec/openvpn-pki
openvpn_pki_config_path: /etc/openvpn/openbao-vpn.conf
openvpn_pki_service: "{{ openvpn_service | default('openvpn@server.service') }}"
@@ -0,0 +1,10 @@
-----BEGIN CERTIFICATE-----
MIIBbTCCARSgAwIBAgIUVIlalnN+qp4SnO6TeCnyhOej4tAwCgYIKoZIzj0EAwIw
FTETMBEGA1UEAxMKb3BlbmJhby1jYTAeFw0yNjExMjAxNzA4NDBaFw0zNjExMTcx
NzA4NDBaMBUxEzARBgNVBAMTCm9wZW5iYW8tY2EwWTATBgcqhkjOPQIBBggqhkjO
PQMBBwNCAAS29w4pGpvGF4MvRhJ4Nzw6E2WWQ8w1XaNE/CiKOLZNdiZsx6Q6IY6j
MReHV/N133Mf2UUUSbVHdWn307aC2U46o0IwQDAOBgNVHQ8BAf8EBAMCAqQwDwYD
VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU80e1lro0vF072OBJBm3Droxp+6gwCgYI
KoZIzj0EAwIDRwAwRAIgIc+d06gwSKl9rIiVBbii3Yg+SC/sxdSYto/0EPJ/SvMC
IEHFRvZ171ouXOL521avaBDq+eQOlXLVjGeYpJOi7oQk
-----END CERTIFICATE-----
@@ -0,0 +1,310 @@
#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
log() { printf '[openvpn-pki] %s\n' "$*" >&2; }
die() { log "ERROR: $*"; exit 1; }
[[ $# -le 2 ]] || die "Usage: openbao-vpn-cert.sh [CONFIG_FILE] [--skip-openvpn-restart]"
CONFIG_FILE=${1:-/etc/openvpn/openbao-vpn.conf}
skip_openvpn_restart=false
if [[ ${2:-} == --skip-openvpn-restart ]]; then
skip_openvpn_restart=true
elif [[ $# -gt 1 ]]; then
die "Usage: openbao-vpn-cert.sh [CONFIG_FILE] [--skip-openvpn-restart]"
fi
[[ -r "$CONFIG_FILE" ]] || die "Configuration file is not readable"
# This is a root-owned Ansible template, with every value shell-quoted.
set -a
# shellcheck disable=SC1090
source "$CONFIG_FILE"
set +a
required_vars=(BAO_ADDR BAO_CACERT OPENVPN_CA_CERT OPENVPN_CA_FINGERPRINT BAO_BINARY JWT_PRIVATE_KEY JWT_SCRIPT JWT_PYTHON JWT_ROLE JWT_AUTH_PATH JWT_GENERATOR_ARGS_JSON PKI_SIGN_PATH CERT_TTL CERT_DIR WORKING_DIR CERT_NAME REQUIRE_SERVER_AUTH_EKU CERT_ALT_NAMES_JSON RSA_KEY_BITS RENEW_BEFORE_DAYS OPENVPN_SERVICE)
for name in "${required_vars[@]}"; do
[[ -n "${!name:-}" ]] || die "Required configuration value $name is empty"
done
for dependency in openssl jq mktemp install mv cp rm cmp cat chmod awk sed grep tr sort systemctl flock ip stat; do
command -v "$dependency" >/dev/null 2>&1 || die "Required executable is missing: $dependency"
done
[[ -x "$BAO_BINARY" ]] || die "OpenBao CLI is not executable: $BAO_BINARY"
[[ -x "$JWT_PYTHON" ]] || die "JWT Python interpreter is not executable: $JWT_PYTHON"
[[ -r "$JWT_SCRIPT" ]] || die "JWT generator script is not readable"
[[ -r "$JWT_PRIVATE_KEY" ]] || die "JWT private key is not readable"
[[ -r "$BAO_CACERT" ]] || die "OpenBao CA trust certificate is not readable"
[[ -r "$OPENVPN_CA_CERT" ]] || die "Deployed OpenVPN Root CA trust certificate is missing or unreadable"
[[ -d "$CERT_DIR" && -w "$CERT_DIR" ]] || die "Certificate directory is missing or not writable"
[[ -d "$WORKING_DIR" && -w "$WORKING_DIR" ]] || die "Staging directory is missing or not writable"
[[ "$RSA_KEY_BITS" =~ ^[0-9]+$ ]] && (( RSA_KEY_BITS >= 2048 )) || die "RSA_KEY_BITS must be at least 2048"
[[ "$RENEW_BEFORE_DAYS" =~ ^[0-9]+$ ]] || die "RENEW_BEFORE_DAYS must be a non-negative integer"
[[ "$REQUIRE_SERVER_AUTH_EKU" == true || "$REQUIRE_SERVER_AUTH_EKU" == false ]] || die "REQUIRE_SERVER_AUTH_EKU must be true or false"
certificate_fingerprint() {
openssl x509 -in "$1" -noout -fingerprint -sha256 |
sed 's/.*=//' | tr -d ':' | tr '[:lower:]' '[:upper:]'
}
restart_openvpn() {
local attempt
if [[ "$skip_openvpn_restart" == true ]]; then
log "Deferring OpenVPN restart to the Ansible handler"
return 0
fi
systemctl restart "$OPENVPN_SERVICE"
for attempt in {1..10}; do
if ip link show tap0 >/dev/null 2>&1; then
ip link set tap0 up
ip link set tap0 master br-main-vpn
return 0
fi
sleep 10
done
log "OpenVPN restarted but tap0 did not become available"
return 1
}
root_fingerprint=$(certificate_fingerprint "$OPENVPN_CA_CERT") || die "Deployed company VPN Root CA is invalid"
expected_root_fingerprint=$(printf '%s' "$OPENVPN_CA_FINGERPRINT" | tr -d ':' | tr '[:lower:]' '[:upper:]')
[[ "$root_fingerprint" == "$expected_root_fingerprint" ]] || die "Configured company VPN Root CA fingerprint differs from its deployed certificate"
valid_dns_name() {
local value=$1 label
local -a labels=()
[[ ${#value} -le 253 && "$value" != *..* ]] || return 1
IFS=. read -r -a labels <<<"$value"
for label in "${labels[@]}"; do
[[ ${#label} -le 63 && "$label" =~ ^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?$ ]] || return 1
done
}
valid_dns_name "$CERT_NAME" || die "Certificate common name is not a valid DNS name"
jq -e 'type == "array" and all(.[]; type == "string")' <<<"$CERT_ALT_NAMES_JSON" >/dev/null || die "Certificate DNS SANs must be a JSON string array"
mapfile -t ALT_NAMES < <(jq -r '.[]' <<<"$CERT_ALT_NAMES_JSON")
((${#ALT_NAMES[@]} > 0)) || die "At least one DNS SAN is required"
declare -A seen_names=()
for name in "${ALT_NAMES[@]}"; do
valid_dns_name "$name" || die "Invalid DNS SAN configured"
seen_names["$name"]=1
done
[[ -n "${seen_names[$CERT_NAME]:-}" ]] || die "Certificate SAN list must include the common name"
workdir=$(mktemp -d "$WORKING_DIR/.openvpn-pki.XXXXXX") || die "Could not create staging directory"
cert_device=$(stat -c '%d' "$CERT_DIR") || die "Could not identify certificate filesystem"
work_device=$(stat -c '%d' "$workdir") || die "Could not identify staging filesystem"
[[ "$cert_device" == "$work_device" ]] || die "Staging directory must be on the certificate filesystem"
old_key_present=false
old_cert_present=false
replacement_started=false
preserve_workdir=false
cleanup() {
local status=$?
trap - EXIT
if [[ "$replacement_started" == true && $status -ne 0 ]]; then
log "Installation failed; restoring the previous certificate and key"
local rollback_failed=false
if [[ "$old_key_present" == true ]]; then
cp -p -- "$workdir/old-server.key" "$CERT_DIR/.server.key.rollback" || rollback_failed=true
mv -f -- "$CERT_DIR/.server.key.rollback" "$CERT_DIR/server.key" || rollback_failed=true
else
rm -f -- "$CERT_DIR/server.key" || rollback_failed=true
fi
if [[ "$old_cert_present" == true ]]; then
cp -p -- "$workdir/old-server.crt" "$CERT_DIR/.server.crt.rollback" || rollback_failed=true
mv -f -- "$CERT_DIR/.server.crt.rollback" "$CERT_DIR/server.crt" || rollback_failed=true
else
rm -f -- "$CERT_DIR/server.crt" || rollback_failed=true
fi
if [[ "$rollback_failed" != true ]]; then
restart_openvpn || rollback_failed=true
fi
if [[ "$rollback_failed" == true ]]; then
preserve_workdir=true
log "CRITICAL: rollback was incomplete; backups remain at $workdir"
status=1
fi
fi
if [[ "$preserve_workdir" != true ]]; then
rm -rf -- "$workdir"
else
log "Staging data was retained for manual recovery"
fi
exit "$status"
}
trap cleanup EXIT
existing_certificate_is_valid() {
local current_dir="$workdir/current"
local subject actual_sans expected_sans
[[ -s "$CERT_DIR/server.crt" && -s "$CERT_DIR/server.key" ]] || return 1
mkdir -m 0700 "$current_dir" || return 1
/usr/bin/python3 "$(dirname "$0")/split-pem-chain.py" \
"$CERT_DIR/server.crt" "$current_dir" "$OPENVPN_CA_CERT" >/dev/null 2>&1 || return 1
openssl verify -CAfile "$OPENVPN_CA_CERT" -untrusted "$current_dir/intermediates.pem" \
"$current_dir/leaf.pem" >/dev/null 2>&1 || return 1
openssl x509 -in "$current_dir/leaf.pem" -checkend "$((RENEW_BEFORE_DAYS * 86400))" -noout >/dev/null 2>&1 || return 1
subject=$(openssl x509 -in "$current_dir/leaf.pem" -noout -subject -nameopt RFC2253 2>/dev/null) || return 1
subject=${subject#subject=}
[[ "$subject" =~ (^|,)CN=([^,]+) ]] && [[ "${BASH_REMATCH[2]}" == "$CERT_NAME" ]] || return 1
if [[ -n "${EXPECTED_ISSUER:-}" ]]; then
local issuer
issuer=$(openssl x509 -in "$current_dir/leaf.pem" -noout -issuer -nameopt RFC2253 2>/dev/null) || return 1
[[ "${issuer#issuer=}" == "$EXPECTED_ISSUER" ]] || return 1
fi
for name in "${ALT_NAMES[@]}"; do
openssl x509 -in "$current_dir/leaf.pem" -checkhost "$name" -noout >/dev/null 2>&1 || return 1
done
openssl x509 -in "$current_dir/leaf.pem" -noout -ext subjectAltName 2>/dev/null |
awk '/X509v3 Subject Alternative Name:/ {in_san=1; next} in_san {gsub(/^[[:space:]]+/, ""); printf "%s ", $0}' |
tr ',' '\n' | sed -n 's/^[[:space:]]*DNS:[[:space:]]*//p' | tr '[:upper:]' '[:lower:]' | sort -u >"$current_dir/actual-dns-sans" || return 1
printf '%s\n' "${ALT_NAMES[@]}" | tr '[:upper:]' '[:lower:]' | sort -u >"$current_dir/expected-dns-sans" || return 1
cmp -s "$current_dir/actual-dns-sans" "$current_dir/expected-dns-sans" || return 1
openssl x509 -in "$current_dir/leaf.pem" -pubkey -noout >"$current_dir/cert.pub" 2>/dev/null || return 1
openssl pkey -in "$CERT_DIR/server.key" -pubout >"$current_dir/key.pub" 2>/dev/null || return 1
cmp -s "$current_dir/cert.pub" "$current_dir/key.pub" || return 1
openssl rsa -pubin -in "$current_dir/cert.pub" -text -noout >"$current_dir/rsa-details" 2>/dev/null || return 1
grep -Fq "Public-Key: ($RSA_KEY_BITS bit)" "$current_dir/rsa-details" || return 1
if [[ "$REQUIRE_SERVER_AUTH_EKU" == true ]]; then
openssl x509 -in "$current_dir/leaf.pem" -noout -ext extendedKeyUsage >"$current_dir/eku" 2>/dev/null || return 1
grep -Eiq 'TLS Web Server Authentication|1\.3\.6\.1\.5\.5\.7\.3\.1' "$current_dir/eku" || return 1
fi
return 0
}
if existing_certificate_is_valid; then
log "Existing certificate is valid and outside the renewal window; no action required"
exit 0
fi
login_json="$workdir/login.json"
issue_json="$workdir/issue.json"
log "Generating a local RSA key and CSR for $CERT_NAME"
openssl genpkey -algorithm RSA -pkeyopt "rsa_keygen_bits:$RSA_KEY_BITS" -out "$workdir/server.key" 2>/dev/null
chmod 0600 "$workdir/server.key"
{
printf '[req]\ndistinguished_name=dn\nreq_extensions=req_ext\nprompt=no\n[dn]\n'
printf 'CN=%s\n[req_ext]\nsubjectAltName=@alt_names\n[alt_names]\n' "$CERT_NAME"
index=1
declare -A emitted_names=()
for name in "${ALT_NAMES[@]}"; do
if [[ -n "${emitted_names[$name]:-}" ]]; then
continue
fi
printf 'DNS.%d=%s\n' "$index" "$name"
index=$((index + 1))
emitted_names["$name"]=1
done
} >"$workdir/req.cnf"
openssl req -new -key "$workdir/server.key" -out "$workdir/server.csr" -config "$workdir/req.cnf"
log "Creating short-lived JWT and authenticating to OpenBao"
generator_args=()
mapfile -t generator_args < <(jq -r '.[]' <<<"$JWT_GENERATOR_ARGS_JSON")
if ! JWT_PRIVATE_KEY="$JWT_PRIVATE_KEY" JWT_ROLE="$JWT_ROLE" \
"$JWT_PYTHON" "$JWT_SCRIPT" "${generator_args[@]}" >"$workdir/jwt" 2>"$workdir/jwt-generator.err"; then
die "JWT generation failed (details suppressed to protect credentials)"
fi
[[ -s "$workdir/jwt" ]] || die "JWT generator returned an empty token"
tr -d '\r\n' <"$workdir/jwt" >"$workdir/jwt-clean"
mv -f -- "$workdir/jwt-clean" "$workdir/jwt"
[[ -s "$workdir/jwt" ]] || die "JWT generator returned an empty token"
chmod 0600 "$workdir/jwt"
if ! BAO_ADDR="$BAO_ADDR" BAO_CACERT="$BAO_CACERT" \
"$BAO_BINARY" write -format=json "auth/$JWT_AUTH_PATH/login" \
"role=$JWT_ROLE" "jwt=@$workdir/jwt" >"$login_json" 2>"$workdir/bao-login.err"; then
die "OpenBao JWT authentication failed (details suppressed)"
fi
token=$(jq -er '.auth.client_token' "$login_json" 2>/dev/null) || die "OpenBao authentication response was invalid"
rm -f -- "$workdir/jwt" "$workdir/jwt-generator.err" "$workdir/bao-login.err" "$login_json"
log "Requesting certificate from the configured PKI endpoint"
alt_names_csv=$(IFS=,; printf '%s' "${ALT_NAMES[*]}")
if ! BAO_ADDR="$BAO_ADDR" BAO_CACERT="$BAO_CACERT" BAO_TOKEN="$token" \
"$BAO_BINARY" write -format=json "$PKI_SIGN_PATH" \
"csr=@$workdir/server.csr" "ttl=$CERT_TTL" "common_name=$CERT_NAME" "alt_names=$alt_names_csv" \
>"$issue_json" 2>"$workdir/bao-issue.err"; then
unset token
die "OpenBao certificate signing failed (details suppressed)"
fi
unset token
jq -er '.data.certificate' "$issue_json" >"$workdir/leaf.crt" 2>/dev/null || die "OpenBao response did not contain a leaf certificate"
jq -er '.data.ca_chain[]' "$issue_json" >"$workdir/ca-chain-all.pem" 2>/dev/null || die "OpenBao response did not contain a CA chain"
root_fingerprint=$(certificate_fingerprint "$OPENVPN_CA_CERT")
: >"$workdir/intermediates.pem"
first_intermediate=""
awk -v dir="$workdir" '
/-----BEGIN CERTIFICATE-----/ {
n++
file=sprintf("%s/chain-%04d.pem", dir, n)
}
n > 0 { print > file }
/-----END CERTIFICATE-----/ { close(file); n=0 }
' "$workdir/ca-chain-all.pem"
shopt -s nullglob
chain_files=("$workdir"/chain-*.pem)
((${#chain_files[@]} > 0)) || die "OpenBao returned no parseable CA certificates"
for chain_cert in "${chain_files[@]}"; do
fingerprint=$(certificate_fingerprint "$chain_cert") || die "OpenBao returned an invalid CA certificate"
if [[ "$fingerprint" != "$root_fingerprint" ]]; then
[[ -n "$first_intermediate" ]] || first_intermediate=$chain_cert
cat "$chain_cert" >>"$workdir/intermediates.pem"
fi
done
[[ -s "$workdir/intermediates.pem" ]] || die "OpenBao returned no intermediate certificate"
log "Validating certificate chain, validity, identity, SANs and private-key match"
openssl verify -CAfile "$OPENVPN_CA_CERT" -untrusted "$workdir/intermediates.pem" "$workdir/leaf.crt" >/dev/null
openssl x509 -in "$workdir/leaf.crt" -checkend 0 -noout >/dev/null
subject=$(openssl x509 -in "$workdir/leaf.crt" -noout -subject -nameopt RFC2253 | sed 's/^subject=//')
[[ "$subject" =~ (^|,)CN=([^,]+) ]] || die "Issued certificate has no common name"
[[ "${BASH_REMATCH[2]}" == "$CERT_NAME" ]] || die "Issued certificate common name did not match configuration"
issuer=$(openssl x509 -in "$workdir/leaf.crt" -noout -issuer -nameopt RFC2253 | sed 's/^issuer=//')
if [[ -n "${EXPECTED_ISSUER:-}" ]]; then
[[ "$issuer" == "$EXPECTED_ISSUER" ]] || die "Issued certificate issuer did not match configured issuer"
else
[[ -n "$first_intermediate" ]] || die "No issuing intermediate certificate was returned"
intermediate_subject=$(openssl x509 -in "$first_intermediate" -noout -subject -nameopt RFC2253 | sed 's/^subject=//')
[[ "$issuer" == "$intermediate_subject" ]] || die "Issued certificate issuer did not match the returned intermediate"
fi
for name in "${ALT_NAMES[@]}"; do
openssl x509 -in "$workdir/leaf.crt" -checkhost "$name" -noout >/dev/null || die "Issued certificate is missing configured DNS identity"
done
openssl x509 -in "$workdir/leaf.crt" -noout -ext subjectAltName |
awk '/X509v3 Subject Alternative Name:/ {in_san=1; next} in_san {gsub(/^[[:space:]]+/, ""); printf "%s ", $0}' |
tr ',' '\n' | sed -n 's/^[[:space:]]*DNS:[[:space:]]*//p' | tr '[:upper:]' '[:lower:]' | sort -u >"$workdir/actual-dns-sans"
printf '%s\n' "${ALT_NAMES[@]}" | tr '[:upper:]' '[:lower:]' | sort -u >"$workdir/expected-dns-sans"
cmp -s "$workdir/actual-dns-sans" "$workdir/expected-dns-sans" || die "Issued certificate DNS SAN set did not exactly match configuration"
if [[ "$REQUIRE_SERVER_AUTH_EKU" == true ]]; then
openssl x509 -in "$workdir/leaf.crt" -noout -ext extendedKeyUsage >"$workdir/eku"
grep -Eiq 'TLS Web Server Authentication|1\.3\.6\.1\.5\.5\.7\.3\.1' "$workdir/eku" || die "Issued certificate lacks required serverAuth EKU"
fi
openssl x509 -in "$workdir/leaf.crt" -pubkey -noout >"$workdir/cert.pub"
openssl pkey -in "$workdir/server.key" -pubout >"$workdir/key.pub"
cmp -s "$workdir/cert.pub" "$workdir/key.pub" || die "Issued certificate does not match its private key"
openssl rsa -pubin -in "$workdir/cert.pub" -text -noout >"$workdir/rsa-details" 2>/dev/null || die "Issued certificate public key is not RSA"
grep -Fq "Public-Key: ($RSA_KEY_BITS bit)" "$workdir/rsa-details" || die "Issued certificate RSA key size did not match configuration"
cat "$workdir/leaf.crt" "$workdir/intermediates.pem" >"$workdir/server.crt"
install -o root -g root -m 0600 "$workdir/server.key" "$workdir/new-server.key"
install -o root -g root -m 0644 "$workdir/server.crt" "$workdir/new-server.crt"
if [[ -e "$CERT_DIR/server.key" ]]; then
cp -p -- "$CERT_DIR/server.key" "$workdir/old-server.key"
old_key_present=true
fi
if [[ -e "$CERT_DIR/server.crt" ]]; then
cp -p -- "$CERT_DIR/server.crt" "$workdir/old-server.crt"
old_cert_present=true
fi
replacement_started=true
install -o root -g root -m 0600 "$workdir/new-server.key" "$CERT_DIR/.server.key.new"
install -o root -g root -m 0644 "$workdir/new-server.crt" "$CERT_DIR/.server.crt.new"
mv -f -- "$CERT_DIR/.server.key.new" "$CERT_DIR/server.key"
mv -f -- "$CERT_DIR/.server.crt.new" "$CERT_DIR/server.crt"
restart_openvpn
log "Certificate and private key installed successfully"
printf 'CERTIFICATE_INSTALLED\n'
replacement_started=false
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""Extract the first certificate and the remaining certificates in a PEM chain."""
import os
import re
import subprocess
import sys
from typing import Tuple
from pathlib import Path
from typing import NoReturn
def fail(message: str) -> "NoReturn":
print(message, file=sys.stderr)
raise SystemExit(1)
if len(sys.argv) != 4:
fail("Usage: split-pem-chain.py FULL_CHAIN OUTPUT_DIRECTORY ROOT_CA")
source = Path(sys.argv[1])
output_dir = Path(sys.argv[2])
root_ca = Path(sys.argv[3])
try:
data = source.read_bytes()
except OSError as exc:
fail(f"Could not read certificate chain: {exc}")
blocks = re.findall(
br"-----BEGIN CERTIFICATE-----\s*.*?-----END CERTIFICATE-----",
data,
flags=re.DOTALL,
)
if not blocks:
fail("Full-chain file contains no PEM certificates")
certificate_pattern = re.compile(
br"-----BEGIN CERTIFICATE-----\s*.*?-----END CERTIFICATE-----", re.DOTALL
)
if len(certificate_pattern.findall(data)) != len(blocks):
fail("Full-chain file contains malformed or nested PEM certificate blocks")
remaining = re.sub(
br"-----BEGIN CERTIFICATE-----\s*.*?-----END CERTIFICATE-----",
b"",
data,
flags=re.DOTALL,
)
if remaining.strip():
fail("Full-chain file contains data outside PEM certificate blocks")
try:
def inspect_certificate(block: bytes, description: str) -> Tuple[bytes, bool]:
pem = block.decode("ascii")
fingerprint = subprocess.check_output(
["openssl", "x509", "-noout", "-fingerprint", "-sha256"],
input=pem,
text=True,
stderr=subprocess.DEVNULL,
).strip()
basic_constraints = subprocess.run(
["openssl", "x509", "-noout", "-ext", "basicConstraints"],
input=pem,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=False,
)
is_ca = basic_constraints.returncode == 0 and re.search(
r"CA\s*:\s*TRUE", basic_constraints.stdout, re.IGNORECASE
) is not None
if basic_constraints.returncode not in (0, 1):
fail(f"Could not inspect {description} Basic Constraints")
return fingerprint.encode(), is_ca
root_fingerprint = subprocess.check_output(
["openssl", "x509", "-in", str(root_ca), "-noout", "-fingerprint", "-sha256"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
_, leaf_is_ca = inspect_certificate(blocks[0], "leaf certificate")
if leaf_is_ca:
fail("First certificate in full-chain file is a CA certificate, not a leaf")
intermediate_blocks = []
for index, block in enumerate(blocks[1:], start=2):
fingerprint, is_ca = inspect_certificate(block, f"chain certificate {index}")
if not is_ca:
fail(f"Chain certificate {index} is not a CA certificate")
if fingerprint != root_fingerprint:
intermediate_blocks.append(block)
except (OSError, subprocess.CalledProcessError, UnicodeDecodeError) as exc:
fail(f"Could not inspect certificates in the existing chain: {exc}")
try:
leaf = output_dir / "leaf.pem"
intermediates = output_dir / "intermediates.pem"
leaf.write_bytes(blocks[0] + b"\n")
intermediates.write_bytes(b"\n".join(block + b"\n" for block in intermediate_blocks))
os.chmod(leaf, 0o600)
os.chmod(intermediates, 0o600)
except OSError as exc:
fail(f"Could not write extracted certificate chain: {exc}")
print(f"CHAIN_SPLIT_OK {len(intermediate_blocks)}")
-62
View File
@@ -1,62 +0,0 @@
---
- name: Create JWT identity directory
ansible.builtin.file:
path: "{{ openvpn_pki_jwt_directory }}"
state: directory
owner: root
group: root
mode: "0700"
- name: Check for existing JWT private key
ansible.builtin.stat:
path: "{{ openvpn_pki_jwt_private_key_path }}"
register: openvpn_pki_jwt_private_key_stat
- name: Check for existing JWT public key
ansible.builtin.stat:
path: "{{ openvpn_pki_jwt_public_key_path }}"
register: openvpn_pki_jwt_public_key_stat
- name: Refuse incomplete JWT identity
ansible.builtin.assert:
that:
- openvpn_pki_jwt_private_key_stat.stat.exists == openvpn_pki_jwt_public_key_stat.stat.exists
fail_msg: >-
Only one JWT key file exists. Refusing to replace or repair an existing
identity automatically. Inspect the files and recover the matching key
pair deliberately before rerunning this playbook.
- name: Generate JWT RSA private key
community.crypto.openssl_privatekey:
path: "{{ openvpn_pki_jwt_private_key_path }}"
type: RSA
size: "{{ openvpn_pki_jwt_rsa_bits }}"
owner: root
group: root
mode: "0600"
when: not openvpn_pki_jwt_private_key_stat.stat.exists
- name: Generate JWT public key from existing private key
community.crypto.openssl_publickey:
path: "{{ openvpn_pki_jwt_public_key_path }}"
privatekey_path: "{{ openvpn_pki_jwt_private_key_path }}"
format: PEM
owner: root
group: root
mode: "0644"
when: not openvpn_pki_jwt_public_key_stat.stat.exists
- name: Create public key artifact directory on controller
ansible.builtin.file:
path: "{{ openvpn_pki_public_key_artifact_directory }}"
state: directory
mode: "0700"
delegate_to: localhost
become: false
- name: Fetch JWT public key to controller
ansible.builtin.fetch:
src: "{{ openvpn_pki_jwt_public_key_path }}"
dest: "{{ openvpn_pki_public_key_artifact_directory }}/{{ inventory_hostname }}.pem"
flat: true
validate_checksum: true
@@ -0,0 +1,21 @@
---
- name: Check whether the OpenVPN server certificate exists
ansible.builtin.stat:
path: "{{ openvpn_pki_certificate_dir }}/server.crt"
register: openvpn_pki_server_certificate
- name: Issue the initial OpenVPN server certificate
ansible.builtin.command:
argv:
- /usr/bin/flock
- -n
- /run/lock/openbao-vpn-cert.lock
- "{{ openvpn_pki_script_directory }}/openbao-vpn-cert.sh"
- "{{ openvpn_pki_config_path }}"
- --skip-openvpn-restart
when: not openvpn_pki_server_certificate.stat.exists
register: openvpn_pki_initial_certificate
changed_when: "'CERTIFICATE_INSTALLED' in openvpn_pki_initial_certificate.stdout"
no_log: true
notify: Restart openvpn
+18 -2
View File
@@ -1,3 +1,19 @@
---
- name: Import JWT identity preparation tasks
ansible.builtin.import_tasks: identity.yml
- name: Install OpenVPN PKI runtime
ansible.builtin.import_tasks: runtime.yml
- name: Prepare certificate files and OpenBao configuration
ansible.builtin.import_tasks: setup.yml
- name: Install certificate lifecycle service and timer units
ansible.builtin.import_tasks: service.yml
- name: Issue certificate only when it is absent
ansible.builtin.import_tasks: initial_certificate.yml
- name: Enable and start daily certificate lifecycle timer
ansible.builtin.systemd:
name: openbao-vpn-cert.timer
enabled: true
state: started
daemon_reload: true
+29
View File
@@ -0,0 +1,29 @@
---
- name: Install OpenBao CLI
ansible.builtin.import_role:
name: openbao_cli
- name: Install OpenVPN PKI runtime dependencies
ansible.builtin.apt:
name:
- openssl
- jq
- python3
- util-linux
state: present
update_cache: true
cache_valid_time: 3600
- name: Calculate deployed company VPN Root CA fingerprint
ansible.builtin.command:
argv:
- openssl
- x509
- -in
- "{{ openvpn_pki_deployed_ca_source }}"
- -noout
- -fingerprint
- -sha256
register: openvpn_pki_company_ca_fingerprint
changed_when: false
- name: Normalize deployed company VPN Root CA fingerprint
ansible.builtin.set_fact:
openvpn_pki_company_ca_fingerprint_value: "{{ openvpn_pki_company_ca_fingerprint.stdout | regex_replace('^.*=', '') | replace(':', '') | upper }}"
+24
View File
@@ -0,0 +1,24 @@
---
- name: Deploy lifecycle script configuration
ansible.builtin.template:
src: openbao-vpn.conf.j2
dest: "{{ openvpn_pki_config_path }}"
owner: root
group: root
mode: "0600"
- name: Deploy certificate lifecycle service
ansible.builtin.template:
src: openbao-vpn-cert.service.j2
dest: /etc/systemd/system/openbao-vpn-cert.service
owner: root
group: root
mode: "0644"
- name: Deploy daily certificate lifecycle timer
ansible.builtin.template:
src: openbao-vpn-cert.timer.j2
dest: /etc/systemd/system/openbao-vpn-cert.timer
owner: root
group: root
mode: "0644"
+62
View File
@@ -0,0 +1,62 @@
---
- name: Create OpenVPN PKI directories
ansible.builtin.file:
path: "{{ item.path }}"
state: directory
owner: root
group: root
mode: "{{ item.mode }}"
loop:
- { path: "{{ openvpn_pki_certificate_dir }}", mode: "0755" }
- { path: "{{ openvpn_pki_working_directory }}", mode: "0700" }
- { path: "{{ openvpn_pki_script_directory }}", mode: "0755" }
- { path: "{{ openvpn_pki_config_path | dirname }}", mode: "0755" }
- name: Require certificate staging directory on certificate filesystem
ansible.builtin.assert:
that:
- openvpn_pki_working_directory == openvpn_pki_certificate_dir or openvpn_pki_working_directory.startswith(openvpn_pki_certificate_dir ~ '/')
fail_msg: >-
openvpn_pki_working_directory must be inside openvpn_pki_certificate_dir
so certificate and key replacement stays on one filesystem.
- name: Install OpenBao API CA certificate
ansible.builtin.copy:
src: certs/openbao-ca.crt
dest: "{{ openvpn_pki_bao_cacert }}"
owner: root
group: root
mode: "0644"
- name: Validate OpenBao API CA certificate
ansible.builtin.command:
argv:
- openssl
- x509
- -in
- "{{ openvpn_pki_bao_cacert }}"
- -noout
- -checkend
- "0"
changed_when: false
- name: Deploy OpenVPN certificate lifecycle script
ansible.builtin.copy:
src: scripts/openbao-vpn-cert.sh
dest: "{{ openvpn_pki_script_directory }}/openbao-vpn-cert.sh"
owner: root
group: root
mode: "0750"
- name: Deploy PEM chain helper
ansible.builtin.copy:
src: scripts/split-pem-chain.py
dest: "{{ openvpn_pki_script_directory }}/split-pem-chain.py"
owner: root
group: root
mode: "0750"
@@ -0,0 +1,11 @@
[Unit]
Description=OpenVPN certificate lifecycle
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
User=root
Group=root
ExecStart=/usr/bin/flock -n /run/lock/openbao-vpn-cert.lock {{ openvpn_pki_script_directory }}/openbao-vpn-cert.sh {{ openvpn_pki_config_path }}
TimeoutStartSec=5min
@@ -0,0 +1,10 @@
[Unit]
Description=Daily OpenVPN certificate lifecycle check
[Timer]
OnCalendar=daily
Persistent=true
Unit=openbao-vpn-cert.service
[Install]
WantedBy=timers.target
@@ -0,0 +1,22 @@
BAO_ADDR={{ openvpn_pki_bao_addr | quote }}
BAO_CACERT={{ openvpn_pki_bao_cacert | quote }}
OPENVPN_CA_CERT={{ (openvpn_pki_certificate_dir ~ '/ca.crt') | quote }}
OPENVPN_CA_FINGERPRINT={{ openvpn_pki_company_ca_fingerprint_value | quote }}
BAO_BINARY={{ openbao_cli_binary_path | default('/usr/bin/bao') | quote }}
JWT_PRIVATE_KEY={{ openvpn_jwt_private_key_path | quote }}
JWT_SCRIPT={{ openvpn_jwt_generator_script | quote }}
JWT_PYTHON={{ openvpn_jwt_python | quote }}
JWT_ROLE={{ openvpn_jwt_role | quote }}
JWT_AUTH_PATH={{ openvpn_jwt_auth_mount | quote }}
JWT_GENERATOR_ARGS_JSON={{ openvpn_jwt_generator_args | to_json | quote }}
PKI_SIGN_PATH={{ openvpn_pki_sign_endpoint | quote }}
CERT_TTL={{ openvpn_pki_certificate_ttl | quote }}
CERT_DIR={{ openvpn_pki_certificate_dir | quote }}
WORKING_DIR={{ openvpn_pki_working_directory | quote }}
CERT_NAME={{ openvpn_pki_certificate_common_name | quote }}
EXPECTED_ISSUER={{ openvpn_pki_expected_issuer | quote }}
REQUIRE_SERVER_AUTH_EKU={{ openvpn_pki_require_server_auth_eku | bool | ternary('true', 'false') | quote }}
CERT_ALT_NAMES_JSON={{ (openvpn_pki_certificate_dns_sans + [openvpn_pki_certificate_common_name]) | unique | to_json | quote }}
RSA_KEY_BITS={{ openvpn_pki_certificate_rsa_bits | int }}
RENEW_BEFORE_DAYS={{ openvpn_pki_renew_before_days | int }}
OPENVPN_SERVICE={{ openvpn_pki_service | quote }}