Skip to content

Instantly share code, notes, and snippets.

@JulienPalard
Last active November 13, 2020 13:44
Show Gist options
  • Save JulienPalard/d88c59f20b42a97dc6c385cb1bf70860 to your computer and use it in GitHub Desktop.
Save JulienPalard/d88c59f20b42a97dc6c385cb1bf70860 to your computer and use it in GitHub Desktop.
"""Copy a flat hierarchy (all .crt .csr, key files in the same directory) to an easy-rsa v3 hierarchy.
You'll manually need to copy openssl-easyrsa.cnf / safessl-easyrsa.cnf though.
Disclamer: I am no security expert, use at your own risk, and only if you understand better than me what's youre doing and why you're doing it.
Usage:
python3 easyrsa2to3.py SRC_DIR DEST_DIR
Example:
python3 easyrsa2to3.py /etc/openvpn/keys /root/easy-rsa-3/
"""
from subprocess import check_output
from pathlib import Path
from hashlib import sha512
import sys
import shutil
def main():
source_path = Path(sys.argv[1])
output_path = Path(sys.argv[2])
output_path.mkdir()
pki = output_path / "pki"
pki.mkdir()
certs_by_serial = pki / "certs_by_serial"
certs_by_serial.mkdir()
issued = pki / "issued"
issued.mkdir()
private = pki / "private"
private.mkdir()
renewed = pki / "renewed"
renewed.mkdir()
revoked = pki / "revoked"
revoked.mkdir()
reqs = pki / "reqs"
reqs.mkdir()
for subdir in "renewed", "revoked":
r_certs_by_serial = pki / subdir / "certs_by_serial"
r_certs_by_serial.mkdir()
r_private_by_serial = pki / subdir / "private_by_serial"
r_private_by_serial.mkdir()
r_reqs_by_serial = pki / subdir / "reqs_by_serial"
r_reqs_by_serial.mkdir()
shutil.copy2(source_path / "ca.crt", pki)
shutil.copy2(source_path / "ca.key", private)
shutil.copy2(source_path / "index.txt", pki)
shutil.copy2(source_path / "serial", pki)
by_hash = {sha512(file.read_bytes()).hexdigest(): file for file in source_path.glob("*.*") if not file.name.endswith(".pem")}
for file in source_path.glob("*.pem"):
print("Found", file)
hash = sha512(file.read_bytes()).hexdigest()
cert = by_hash.get(hash)
if not cert:
print(" - Has no crt file, skip")
continue
csr = source_path / cert.name.replace(".crt", ".csr")
key = source_path / cert.name.replace(".crt", ".key")
print(" - crt", cert, "(exists:", cert.exists(), ")")
print(" - csr", csr, "(exists:", csr.exists(), ")")
print(" - key", key, "(exists:", key.exists(), ")")
serial = check_output(["openssl", "x509", "-in", str(file.resolve()), "-noout", "-serial"], universal_newlines=True).split("=")[-1].strip()
print(" - serial", serial)
shutil.copy2(file, certs_by_serial / (serial + ".pem"))
shutil.copy2(cert, issued)
shutil.copy2(key, private)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment