#!/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)}")