#!/usr/bin/python3
"""Accept an OpenVPN client certificate only when the P2S issuing CA signed it.

Run by the OpenVPN server as tls-verify for each certificate of the client's chain, with its depth and subject as the
arguments. At depth 1, the CA that signed the client's certificate, the SHA-256 fingerprint OpenVPN gives in
tls_digest_sha256_1 must be that of P2S_CA; the other depths are accepted.
"""

import hashlib
import os
import ssl
import sys

P2S_CA = '/etc/swanctl/x509ca/p2s.pem'

if len(sys.argv) < 2 or sys.argv[1] != '1':
    sys.exit(0)
try:
    with open(P2S_CA, encoding='ascii') as handle:
        expected = hashlib.sha256(ssl.PEM_cert_to_DER_cert(handle.read())).hexdigest()
except (OSError, ValueError):
    sys.exit(1)
given = os.environ.get('tls_digest_sha256_1', '').replace(':', '').lower()
sys.exit(0 if given == expected else 1)
