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
+91
View File
@@ -0,0 +1,91 @@
name: OpenVPN JWT Identity Preparation
on:
workflow_run:
workflows:
- OpenVPN Ansible
types:
- completed
jobs:
prepare-identities:
name: Prepare unregistered VPN identities
runs-on: hetzner-ubuntu-latest
if: >-
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.head_branch == 'main'
container:
image: gitea.infrastructure.helmholz.cloud/gitea_admin/ansible-utilities:latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ github.event.workflow_run.head_sha }}
- name: Find VPN nodes awaiting JWT registration
id: pending
run: |
set -eu
ansible-inventory -i inventories/prod/hosts.ini --list |
python3 -c '
import json
import sys
inventory = json.load(sys.stdin)
vpn_hosts = inventory.get("vpn_nodes", {}).get("hosts", [])
hostvars = inventory.get("_meta", {}).get("hostvars", {})
pending = []
for hostname in vpn_hosts:
registered = hostvars.get(hostname, {}).get("openvpn_jwt_registered", False)
if str(registered).strip().lower() not in {"true", "yes", "1", "on"}:
pending.append(hostname)
print(",".join(pending))
' > /tmp/openvpn-jwt-pending-hosts
pending_hosts=$(cat /tmp/openvpn-jwt-pending-hosts)
if [ -n "$pending_hosts" ]; then
echo "has_hosts=true" >> "$GITHUB_OUTPUT"
echo "hosts=$pending_hosts" >> "$GITHUB_OUTPUT"
echo "Preparing JWT identities for: $pending_hosts"
else
echo "has_hosts=false" >> "$GITHUB_OUTPUT"
echo "No VPN nodes are awaiting JWT registration."
fi
- name: Setup SSH
if: steps.pending.outputs.has_hosts == 'true'
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
run: |
set -eu
mkdir -p ~/.ssh
printf '%s\n' "$SSH_PRIVATE_KEY" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
ssh-keygen -y -f ~/.ssh/id_ed25519 > /dev/null
- name: Install Ansible collections
if: steps.pending.outputs.has_hosts == 'true'
run: ansible-galaxy collection install -r requirements.yml
- name: Prepare JWT identities
if: steps.pending.outputs.has_hosts == 'true'
env:
ANSIBLE_CONFIG: ${{ github.workspace }}/ansible.cfg
PENDING_HOSTS: ${{ steps.pending.outputs.hosts }}
run: |
set -eu
ansible-playbook \
-i inventories/prod/hosts.ini \
playbooks/openvpn-jwt-identity.yml \
--limit "$PENDING_HOSTS"
- name: Upload public JWT keys
if: steps.pending.outputs.has_hosts == 'true'
uses: actions/upload-artifact@v4
with:
name: openvpn-jwt-public-keys
path: artifacts/openvpn-jwt-public-keys/*.pem
if-no-files-found: error
retention-days: 7
-71
View File
@@ -1,71 +0,0 @@
name: OpenVPN JWT Identity Preparation
on:
workflow_dispatch:
inputs:
vpn_host:
description: Inventory hostname of the VPN server to prepare
required: true
type: string
jobs:
prepare-identity:
name: Prepare VPN JWT identity
runs-on: hetzner-ubuntu-latest
container:
image: gitea.infrastructure.helmholz.cloud/gitea_admin/ansible-utilities:latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup SSH
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
run: |
set -eu
mkdir -p ~/.ssh
printf '%s\n' "$SSH_PRIVATE_KEY" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
ssh-keygen -y -f ~/.ssh/id_ed25519 > /dev/null
- name: Install Ansible collections
run: ansible-galaxy collection install -r requirements.yml
- name: Validate selected VPN host
env:
VPN_HOST: ${{ github.event.inputs.vpn_host }}
run: |
set -eu
ansible-inventory -i inventories/prod/hosts.ini --list | python3 -c '
import json
import os
import sys
inventory = json.load(sys.stdin)
selected_host = os.environ["VPN_HOST"]
vpn_hosts = inventory.get("vpn_nodes", {}).get("hosts", [])
if selected_host not in vpn_hosts:
print("vpn_host must exactly match a host in the vpn_nodes inventory group", file=sys.stderr)
sys.exit(1)
'
- name: Prepare JWT identity
env:
ANSIBLE_CONFIG: ${{ github.workspace }}/ansible.cfg
VPN_HOST: ${{ github.event.inputs.vpn_host }}
run: |
set -eu
ansible-playbook \
-i inventories/prod/hosts.ini \
playbooks/openvpn-pki-identity.yml \
--limit "$VPN_HOST"
- name: Upload public JWT key
uses: actions/upload-artifact@v4
with:
name: openvpn-pki-public-keys
path: artifacts/openvpn-pki-public-keys/*.pem
if-no-files-found: error
retention-days: 7
+1 -1
View File
@@ -1 +1 @@
/artifacts/openvpn-pki-public-keys/
/artifacts/openvpn-jwt-public-keys/
+2 -2
View File
@@ -1,7 +1,7 @@
[vpn_nodes]
# vpn01 ansible_host=65.108.95.144 private_ip=10.100.0.1
vpn01-test ansible_host=10.100.0.2 private_ip=10.100.0.2
vpn02-test ansible_host=10.100.0.5 private_ip=10.100.0.5
# vpn01-test ansible_host=10.100.0.2 private_ip=10.100.0.2 openvpn_jwt_registered=false
vpn02-test ansible_host=10.100.0.5 private_ip=10.100.0.5 openvpn_jwt_registered=false
# vpn01-bmw ansible_host=65.108.93.171 private_ip=10.100.0.3
[nat_gateways]
@@ -4,4 +4,4 @@
become: true
roles:
- role: openvpn_pki
- openvpn_jwt
+20 -1
View File
@@ -7,4 +7,23 @@
- common
- networking
- radius_nat
- openvpn
- role: openvpn
when: openvpn_jwt_registered | default(false) | bool
- role: openvpn_jwt
when: openvpn_jwt_registered | default(false) | bool
vars:
openvpn_jwt_export_public_key: false
- role: openvpn_pki
when: openvpn_jwt_registered | default(false) | bool
tasks:
- name: Run pending OpenVPN restart handlers after certificate issuance
ansible.builtin.meta: flush_handlers
- name: Start OpenVPN and attach TAP interface after certificate setup
ansible.builtin.import_role:
name: openvpn
tasks_from: bridge-tap.yml
when:
- openvpn_jwt_registered | default(false) | bool
- openvpn_restart_result is not defined
+9
View File
@@ -0,0 +1,9 @@
---
openbao_cli_version: "2.7.0"
openbao_cli_binary_path: /usr/bin/bao
openbao_cli_architecture_map:
x86_64: amd64
aarch64: arm64
openbao_cli_verify_checksum_signature: true
openbao_cli_gpg_key_url: https://openbao.org/assets/openbao-gpg-pub-20240618.asc
openbao_cli_gpg_primary_fingerprint: 66D15FDD87287219C8E15478D200CD702853E6D0
+165
View File
@@ -0,0 +1,165 @@
---
- name: Validate OpenBao CLI platform
ansible.builtin.assert:
that:
- ansible_facts.distribution in ['Debian', 'Ubuntu']
- ansible_facts.architecture in openbao_cli_architecture_map
fail_msg: >-
OpenBao CLI installation supports Debian and Ubuntu amd64 and arm64 only;
detected {{ ansible_facts.distribution }} {{ ansible_facts.architecture }}.
- name: Set OpenBao release package facts
ansible.builtin.set_fact:
openbao_cli_package_name: "openbao_{{ openbao_cli_version }}_linux_{{ openbao_cli_architecture_map[ansible_facts.architecture] }}.deb"
openbao_cli_release_url: "https://github.com/openbao/openbao/releases/download/v{{ openbao_cli_version }}"
- name: Read currently installed OpenBao CLI version
ansible.builtin.command:
argv:
- "{{ openbao_cli_binary_path }}"
- version
register: openbao_cli_current_version
changed_when: false
failed_when: false
when: ansible_facts.pkg_mgr == 'apt'
- name: Set OpenBao CLI installation requirement using exact version equality
ansible.builtin.set_fact:
openbao_cli_install_required: >-
{{ (openbao_cli_current_version.stdout | default('') | trim) != ('OpenBao v' ~ openbao_cli_version) }}
- name: Install pinned OpenBao CLI from the official release
when: openbao_cli_install_required
block:
- name: Create OpenBao CLI temporary directory
ansible.builtin.tempfile:
state: directory
suffix: openbao-cli
register: openbao_cli_tmp
- name: Install GnuPG for mandatory checksum signature verification
ansible.builtin.apt:
name: gnupg
state: present
when: openbao_cli_verify_checksum_signature | bool
- name: Download official OpenBao release checksums
ansible.builtin.get_url:
url: "{{ openbao_cli_release_url }}/checksums.txt"
dest: "{{ openbao_cli_tmp.path }}/checksums.txt"
mode: "0600"
- name: Download signature for official OpenBao checksums
ansible.builtin.get_url:
url: "{{ openbao_cli_release_url }}/checksums.txt.gpgsig"
dest: "{{ openbao_cli_tmp.path }}/checksums.txt.gpgsig"
mode: "0600"
when: openbao_cli_verify_checksum_signature | bool
- name: Download OpenBao signing public key
ansible.builtin.get_url:
url: "{{ openbao_cli_gpg_key_url }}"
dest: "{{ openbao_cli_tmp.path }}/openbao-gpg-key.asc"
mode: "0600"
when: openbao_cli_verify_checksum_signature | bool
- name: Create isolated GnuPG home
ansible.builtin.file:
path: "{{ openbao_cli_tmp.path }}/gnupg"
state: directory
mode: "0700"
when: openbao_cli_verify_checksum_signature | bool
- name: Import OpenBao signing key into isolated keyring
ansible.builtin.command:
argv:
- gpg
- --batch
- --homedir
- "{{ openbao_cli_tmp.path }}/gnupg"
- --import
- "{{ openbao_cli_tmp.path }}/openbao-gpg-key.asc"
register: openbao_cli_gpg_import
changed_when: false
when: openbao_cli_verify_checksum_signature | bool
- name: Read imported signing-key fingerprints
ansible.builtin.command:
argv:
- gpg
- --batch
- --homedir
- "{{ openbao_cli_tmp.path }}/gnupg"
- --with-colons
- --fingerprint
- --list-keys
register: openbao_cli_gpg_fingerprints
changed_when: false
when: openbao_cli_verify_checksum_signature | bool
- name: Require the documented OpenBao primary key fingerprint
ansible.builtin.assert:
that:
- openbao_cli_gpg_fingerprints.stdout | regex_findall('(?m)^pub:') | length == 1
- >-
openbao_cli_gpg_fingerprints.stdout | regex_findall('(?m)^fpr:.*$') |
map('regex_search', '[A-F0-9]{40}') |
select('equalto', openbao_cli_gpg_primary_fingerprint) | list | length == 1
fail_msg: The imported OpenBao signing key did not match the pinned primary fingerprint.
when: openbao_cli_verify_checksum_signature | bool
- name: Verify official checksums.txt signature
ansible.builtin.command:
argv:
- gpg
- --batch
- --homedir
- "{{ openbao_cli_tmp.path }}/gnupg"
- --verify
- "{{ openbao_cli_tmp.path }}/checksums.txt.gpgsig"
- "{{ openbao_cli_tmp.path }}/checksums.txt"
register: openbao_cli_gpg_verify
changed_when: false
when: openbao_cli_verify_checksum_signature | bool
- name: Find checksum for the requested Debian package
ansible.builtin.command:
argv:
- awk
- "$2 == \"{{ openbao_cli_package_name }}\" {print $1}"
- "{{ openbao_cli_tmp.path }}/checksums.txt"
register: openbao_cli_expected_checksum
changed_when: false
- name: Require a single valid SHA-256 checksum for the package
ansible.builtin.assert:
that:
- openbao_cli_expected_checksum.stdout | trim is match('^[a-fA-F0-9]{64}$')
fail_msg: "No unique valid checksum for {{ openbao_cli_package_name }} in official release checksums."
- name: Download checksummed OpenBao Debian package
ansible.builtin.get_url:
url: "{{ openbao_cli_release_url }}/{{ openbao_cli_package_name }}"
dest: "{{ openbao_cli_tmp.path }}/{{ openbao_cli_package_name }}"
checksum: "sha256:{{ openbao_cli_expected_checksum.stdout | trim }}"
mode: "0600"
- name: Install OpenBao CLI Debian package
ansible.builtin.apt:
deb: "{{ openbao_cli_tmp.path }}/{{ openbao_cli_package_name }}"
state: present
always:
- name: Remove OpenBao CLI temporary directory after success or failure
ansible.builtin.file:
path: "{{ openbao_cli_tmp.path }}"
state: absent
when: openbao_cli_tmp is defined and openbao_cli_tmp.path is defined
- name: Verify installed OpenBao CLI version exactly matches the pin
ansible.builtin.command:
argv:
- "{{ openbao_cli_binary_path }}"
- version
register: openbao_cli_installed_version
changed_when: false
failed_when: (openbao_cli_installed_version.stdout | trim) != ('OpenBao v' ~ openbao_cli_version)
-30
View File
@@ -1,30 +0,0 @@
-----BEGIN CERTIFICATE-----
MIIFHTCCBAWgAwIBAgIIQ5gRV6nKlhwwDQYJKoZIhvcNAQELBQAwdDELMAkGA1UE
BhMCREUxCz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XbeC+LfYAJp1Cb0b7SZyBcLEyLmWYu4Yrc6v2KthFKnxSqf7ycfjmL2sFhKC8A
eNESwb21YfE8cDRJcxWMLaB0RT3h0BFSrJm9kQrXGYfzVuzqZzYuJsHWEklrKqyM
EiEpcjnVHYKtirndZKQG02GVlj+O0hbzTTI6W1ZIllVBUeKU93qstLQOm4AxHgs3
FAEi9b1uMxpUKM3GP9NPlzyOiC68cdunFBz0mqDgXgvtO0QB1Z6ClWl8vrXLFkJ6
ceN81JI+TRgN5QC8mr1+asuMdTQqfyzxAoIBAGueFquOes04tOWzKOnwI/jKMsUM
tbC5sTFEb/Prub4OFWPU+AIGHmcTICF8ez7iiZFkPcJFQ4xqcWl41e3YBQaYTRCz
2RUwyk3CLLcSdLIH6u6CeND+XVtI3RrKPuy/64N4pMEbIgeM/UMJc9xyNWyQCMmQ
gl8bseanfRM1zLUkyCvE6QFLjsjFJkQUHzEM4qTUKqIxLx/Y5tED6LhkqS39sbEO
4i/+d+Atz5uRtA3ziCXkokbfE8VYFOivAgqiGzVR60MR0Ptctnf7esM/KNefHS9f
kAC98L5t3Qvf73hSFVJfZB8a7GSbobsfAo//YHVEm0Gm5SS/9N4THfafMJI=
-----END RSA PRIVATE KEY-----
+4 -3
View File
@@ -3,9 +3,10 @@
ansible.builtin.systemd:
name: "{{ openvpn_service }}"
state: restarted
register: openvpn_restart_result
listen: Restart openvpn
- name: Wait for tap0
- name: Wait for tap0 after OpenVPN restart
ansible.builtin.command: ip link show tap0
register: openvpn_tap_check
retries: 10
@@ -14,12 +15,12 @@
changed_when: false
listen: Restart openvpn
- name: Bring tap0 up
- name: Bring tap0 up after OpenVPN restart
ansible.builtin.command: ip link set tap0 up
changed_when: false
listen: Restart openvpn
- name: Attach tap0 to bridge
- name: Attach tap0 to bridge after OpenVPN restart
ansible.builtin.command: ip link set tap0 master br-main-vpn
changed_when: false
listen: Restart openvpn
-18
View File
@@ -15,24 +15,6 @@
group: root
mode: "0644"
- name: Deploy server certificate
ansible.builtin.copy:
src: certs/server.crt
dest: "{{ openvpn_cert_dir }}/server.crt"
owner: root
group: root
mode: "0644"
notify: Restart openvpn
- name: Deploy server private key
ansible.builtin.copy:
src: certs/server.key
dest: "{{ openvpn_cert_dir }}/server.key"
owner: root
group: root
mode: "0600"
notify: Restart openvpn
- name: Deploy tls-crypt key
ansible.builtin.copy:
src: certs/tls-crypt.key
-2
View File
@@ -5,5 +5,3 @@
ansible.builtin.import_tasks: certs.yml
- name: Import OpenVPN configuration tasks
ansible.builtin.import_tasks: config.yml
- name: Import OpenVPN bridge-tap tasks
ansible.builtin.import_tasks: bridge-tap.yml
+54
View File
@@ -0,0 +1,54 @@
# OpenVPN JWT identity
This role manages each VPN node's local RSA identity and JWT generator. It is
separate from `openvpn_pki`, which manages the OpenVPN server certificate.
`tasks/main.yml` delegates to three focused task files:
- `generator.yml` installs the configured generator and checks its Python
interpreter and dependencies.
- `keys.yml` creates or validates the RSA private/public key pair.
- `public_key.yml` fetches only the public key to the controller.
Run the dedicated identity playbook for selected nodes:
```bash
ansible-playbook \
-i inventories/prod/hosts.ini \
playbooks/openvpn-jwt-identity.yml \
--limit vpn01-test
```
The Gitea workflow `.gitea/workflows/openvpn-jwt-identity.yml` runs after the
main OpenVPN workflow succeeds. It selects every
`vpn_nodes` host whose
`openvpn_jwt_registered` value is false or missing. It uploads the resulting
PEM files as the `openvpn-jwt-public-keys` artifact. An administrator adds
each new public key to OpenBao's existing trusted-key bundle while preserving
the other keys. After registration is confirmed, set that host's
`openvpn_jwt_registered` value to `true`; the regular OpenVPN deployment can
then proceed for that VM.
The regular `openvpn.yml` deployment skips the `openvpn`, `openvpn_jwt`, and
`openvpn_pki` roles when the flag is false or absent. Shared base roles still
run.
The private key remains on the VPN node at `/etc/vault-jwt/private.pem` by
default, with root ownership and mode `0600`.
Only the public key is copied to
`artifacts/openvpn-jwt-public-keys/<inventory_hostname>.pem` for manual
registration with OpenBao. The role does not configure OpenBao.
Existing keys must be a matching RSA pair at the configured size. The role
fails without replacing an incomplete, invalid, wrong-size, or mismatched
identity.
Install the collections in `requirements.yml`, including
`community.crypto`, on the Ansible controller before running this role.
The role creates the Python virtual environment and installs the pinned
`PyJWT[crypto]` dependency. Override `openvpn_jwt_virtualenv` to change the
environment location. If you also override `openvpn_jwt_python`, point it to
an interpreter inside that same environment.
`openvpn_jwt_role` and `openvpn_jwt_generator_args` configure the generator
invocation used by the certificate lifecycle script.
+15
View File
@@ -0,0 +1,15 @@
openvpn_jwt_directory: /etc/vault-jwt
openvpn_jwt_private_key_path: "{{ openvpn_jwt_directory }}/private.pem"
openvpn_jwt_public_key_path: "{{ openvpn_jwt_directory }}/public.pem"
openvpn_jwt_rsa_bits: 3072
openvpn_jwt_public_key_artifact_directory: "{{ playbook_dir }}/../artifacts/openvpn-jwt-public-keys"
openvpn_jwt_generator_script: /usr/local/bin/generate-vault-jwt.py
openvpn_jwt_virtualenv: /opt/vault-jwt/venv
openvpn_jwt_python: "{{ openvpn_jwt_virtualenv }}/bin/python"
openvpn_jwt_pyjwt_version: "2.15.1"
openvpn_jwt_role: vpn-servers
openvpn_jwt_auth_mount: jwt-vpn
# The generator must write only the JWT to stdout.
openvpn_jwt_generator_args: []
openvpn_jwt_export_public_key: true
+52
View File
@@ -0,0 +1,52 @@
---
- name: Create JWT identity directory
ansible.builtin.file:
path: "{{ openvpn_jwt_directory }}"
state: directory
owner: root
group: root
mode: "0700"
- name: Deploy JWT generator script
ansible.builtin.template:
src: generate-vault-jwt.py.j2
dest: "{{ openvpn_jwt_generator_script }}"
owner: root
group: root
mode: "0750"
- name: Check JWT generator script
ansible.builtin.stat:
path: "{{ openvpn_jwt_generator_script }}"
register: openvpn_jwt_generator_stat
- name: Require executable JWT generator
ansible.builtin.assert:
that:
- openvpn_jwt_generator_stat.stat.isreg | default(false)
- openvpn_jwt_generator_stat.stat.executable | default(false)
fail_msg: >-
JWT generator is missing or not executable:
{{ openvpn_jwt_generator_script }}
- name: Check JWT Python interpreter
ansible.builtin.stat:
path: "{{ openvpn_jwt_python }}"
register: openvpn_jwt_python_stat
- name: Require JWT Python interpreter
ansible.builtin.assert:
that:
- openvpn_jwt_python_stat.stat.exists
- openvpn_jwt_python_stat.stat.executable | default(false)
fail_msg: >-
JWT Python interpreter is missing or not executable:
{{ openvpn_jwt_python }}
- name: Validate JWT Python dependencies
ansible.builtin.command:
argv:
- "{{ openvpn_jwt_python }}"
- -c
- "import jwt; import cryptography; assert hasattr(jwt, 'encode')"
changed_when: false
+154
View File
@@ -0,0 +1,154 @@
---
- name: Check for existing JWT private key
ansible.builtin.stat:
path: "{{ openvpn_jwt_private_key_path }}"
register: openvpn_jwt_private_key_stat
- name: Check for existing JWT public key
ansible.builtin.stat:
path: "{{ openvpn_jwt_public_key_path }}"
register: openvpn_jwt_public_key_stat
- name: Refuse incomplete JWT identity
ansible.builtin.assert:
that:
- openvpn_jwt_private_key_stat.stat.exists == openvpn_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_jwt_private_key_path }}"
type: RSA
size: "{{ openvpn_jwt_rsa_bits }}"
owner: root
group: root
mode: "0600"
when: not openvpn_jwt_private_key_stat.stat.exists
- name: Generate JWT public key from existing private key
community.crypto.openssl_publickey:
path: "{{ openvpn_jwt_public_key_path }}"
privatekey_path: "{{ openvpn_jwt_private_key_path }}"
format: PEM
owner: root
group: root
mode: "0644"
when: not openvpn_jwt_public_key_stat.stat.exists
- name: Validate existing JWT private key
ansible.builtin.command:
argv:
- openssl
- pkey
- -in
- "{{ openvpn_jwt_private_key_path }}"
- -check
- -noout
register: openvpn_jwt_private_key_validation
changed_when: false
failed_when: false
when: openvpn_jwt_private_key_stat.stat.exists
- name: Validate existing JWT public key
ansible.builtin.command:
argv:
- openssl
- pkey
- -pubin
- -in
- "{{ openvpn_jwt_public_key_path }}"
- -pubcheck
- -noout
register: openvpn_jwt_public_key_validation
changed_when: false
failed_when: false
when: openvpn_jwt_public_key_stat.stat.exists
- name: Fail clearly for invalid existing JWT identity keys
ansible.builtin.assert:
that:
- openvpn_jwt_private_key_validation.rc == 0
- openvpn_jwt_public_key_validation.rc == 0
fail_msg: Existing JWT identity contains an invalid private or public key. The identity was not replaced.
when: openvpn_jwt_private_key_stat.stat.exists
- name: Read existing JWT private key type and size
ansible.builtin.command:
argv: [openssl, pkey, -in, "{{ openvpn_jwt_private_key_path }}", -text, -noout]
register: openvpn_jwt_private_key_details
changed_when: false
when: openvpn_jwt_private_key_stat.stat.exists
no_log: true
- name: Read existing JWT public key type and size
ansible.builtin.command:
argv: [openssl, pkey, -pubin, -in, "{{ openvpn_jwt_public_key_path }}", -text, -noout]
register: openvpn_jwt_public_key_details
changed_when: false
when: openvpn_jwt_public_key_stat.stat.exists
no_log: true
- name: Require existing JWT identity to be configured-size RSA
ansible.builtin.assert:
that:
- "('Private-Key: (' ~ (openvpn_jwt_rsa_bits | string) ~ ' bit') in openvpn_jwt_private_key_details.stdout"
- "('Public-Key: (' ~ (openvpn_jwt_rsa_bits | string) ~ ' bit') in openvpn_jwt_public_key_details.stdout"
- "'modulus:' in openvpn_jwt_private_key_details.stdout"
- "'Modulus:' in openvpn_jwt_public_key_details.stdout"
fail_msg: Existing JWT identity must be an RSA key pair of the configured size. The identity was not replaced.
when: openvpn_jwt_private_key_stat.stat.exists
no_log: true
- name: Derive public key from existing JWT private key
ansible.builtin.command:
argv:
- openssl
- pkey
- -in
- "{{ openvpn_jwt_private_key_path }}"
- -pubout
register: openvpn_jwt_derived_public_key
changed_when: false
when: openvpn_jwt_private_key_stat.stat.exists
- name: Read stored JWT public key
ansible.builtin.command:
argv:
- openssl
- pkey
- -pubin
- -in
- "{{ openvpn_jwt_public_key_path }}"
- -pubout
register: openvpn_jwt_stored_public_key
changed_when: false
when: openvpn_jwt_public_key_stat.stat.exists
no_log: true
- name: Refuse mismatched existing JWT identity
ansible.builtin.assert:
that:
- openvpn_jwt_derived_public_key.stdout == openvpn_jwt_stored_public_key.stdout
fail_msg: Existing JWT public key does not match its private key. The identity was not replaced.
when: openvpn_jwt_private_key_stat.stat.exists
- name: Enforce JWT private key ownership and permissions
ansible.builtin.file:
path: "{{ openvpn_jwt_private_key_path }}"
state: file
owner: root
group: root
mode: "0600"
when: openvpn_jwt_private_key_stat.stat.exists
- name: Enforce JWT public key ownership and permissions
ansible.builtin.file:
path: "{{ openvpn_jwt_public_key_path }}"
state: file
owner: root
group: root
mode: "0644"
when: openvpn_jwt_public_key_stat.stat.exists
+13
View File
@@ -0,0 +1,13 @@
---
- name: Provision the JWT Python environment
ansible.builtin.import_tasks: python_environment.yml
- name: Configure the JWT generator and runtime
ansible.builtin.import_tasks: generator.yml
- name: Create or validate the local JWT key pair
ansible.builtin.import_tasks: keys.yml
- name: Export the JWT public key for registration
ansible.builtin.import_tasks: public_key.yml
when: openvpn_jwt_export_public_key | bool
+15
View File
@@ -0,0 +1,15 @@
---
- name: Create public key artifact directory on controller
ansible.builtin.file:
path: "{{ openvpn_jwt_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_jwt_public_key_path }}"
dest: "{{ openvpn_jwt_public_key_artifact_directory }}/{{ inventory_hostname }}.pem"
flat: true
validate_checksum: true
@@ -0,0 +1,14 @@
---
- name: Install Python virtual environment support
ansible.builtin.apt:
name: python3-venv
state: present
update_cache: true
cache_valid_time: 3600
- name: Install PyJWT and cryptography in the JWT virtual environment
ansible.builtin.pip:
name: "PyJWT[crypto]=={{ openvpn_jwt_pyjwt_version }}"
virtualenv: "{{ openvpn_jwt_virtualenv }}"
virtualenv_command: /usr/bin/python3 -m venv
state: present
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
import time
import uuid
import jwt
PRIVATE_KEY = "{{ openvpn_jwt_private_key_path }}"
now = int(time.time())
payload = {
"iss": "helmholz-server-identity",
"sub": "{{ inventory_hostname }}",
"aud": "vault-pki",
"iat": now,
"nbf": now,
"exp": now + 600,
"jti": str(uuid.uuid4())
}
with open(PRIVATE_KEY, "r") as f:
private_key = f.read()
token = jwt.encode(
payload,
private_key,
algorithm="RS256"
)
print(token)
+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 }}