156 lines
7.5 KiB
Python
156 lines
7.5 KiB
Python
|
|
"""Issue a QUIC server certificate with a stable DNS identity using the existing CA.
|
|||
|
|
|
|||
|
|
This prepares files only: it never changes live YAML, restarts a service, or exports keys.
|
|||
|
|
Install the optional dependency from deploy/quic/requirements.txt before running.
|
|||
|
|
"""
|
|||
|
|
import argparse
|
|||
|
|
import ipaddress
|
|||
|
|
import json
|
|||
|
|
import re
|
|||
|
|
from datetime import datetime, timedelta, timezone
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
from cryptography import x509
|
|||
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
|||
|
|
from cryptography.hazmat.primitives.asymmetric import ec, rsa
|
|||
|
|
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
|||
|
|
|
|||
|
|
|
|||
|
|
def public_bytes(key):
|
|||
|
|
return key.public_key().public_bytes(
|
|||
|
|
serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def anniversary(now, years):
|
|||
|
|
try:
|
|||
|
|
return now.replace(year=now.year + years)
|
|||
|
|
except ValueError: # A February 29 anniversary in a non-leap year.
|
|||
|
|
return now.replace(year=now.year + years, day=28)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def prepare(ca_cert, ca_key, server_key, output, server_name="am-freescan.internal", days=365,
|
|||
|
|
years=None, renew_ca_years=None):
|
|||
|
|
name = server_name.lower()
|
|||
|
|
labels = name.split(".")
|
|||
|
|
if len(name) > 253 or len(labels) < 2 or any(
|
|||
|
|
not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label) for label in labels
|
|||
|
|
):
|
|||
|
|
raise ValueError("认证名称必须为明确的DNS名称,不能含通配符")
|
|||
|
|
try:
|
|||
|
|
ipaddress.ip_address(name)
|
|||
|
|
except ValueError:
|
|||
|
|
pass
|
|||
|
|
else:
|
|||
|
|
raise ValueError("认证名称不能是IP地址")
|
|||
|
|
if not 1 <= days <= 21960:
|
|||
|
|
raise ValueError("证书有效天数必须在1–21960之间")
|
|||
|
|
if years is not None and not 1 <= years <= 60:
|
|||
|
|
raise ValueError("有效年数必须在1–60之间")
|
|||
|
|
if renew_ca_years is not None and not 1 <= renew_ca_years <= 60:
|
|||
|
|
raise ValueError("CA续签年数必须在1–60之间")
|
|||
|
|
ca = x509.load_pem_x509_certificate(Path(ca_cert).read_bytes())
|
|||
|
|
original_ca_fingerprint = ca.fingerprint(hashes.SHA256()).hex()
|
|||
|
|
authority = serialization.load_pem_private_key(Path(ca_key).read_bytes(), password=None)
|
|||
|
|
server = serialization.load_pem_private_key(Path(server_key).read_bytes(), password=None)
|
|||
|
|
if not isinstance(authority, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey)):
|
|||
|
|
raise ValueError("签发CA须使用RSA或EC密钥")
|
|||
|
|
if not isinstance(server, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey)):
|
|||
|
|
raise ValueError("服务端须使用RSA或EC密钥")
|
|||
|
|
ca_public = ca.public_key().public_bytes(
|
|||
|
|
serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo
|
|||
|
|
)
|
|||
|
|
if ca_public != public_bytes(authority):
|
|||
|
|
raise ValueError("CA证书与CA私钥不匹配")
|
|||
|
|
if not ca.extensions.get_extension_for_class(x509.BasicConstraints).value.ca:
|
|||
|
|
raise ValueError("提供的证书不是CA证书")
|
|||
|
|
try:
|
|||
|
|
if not ca.extensions.get_extension_for_class(x509.KeyUsage).value.key_cert_sign:
|
|||
|
|
raise ValueError("CA不允许签发证书")
|
|||
|
|
except x509.ExtensionNotFound:
|
|||
|
|
pass
|
|||
|
|
now = datetime.now(timezone.utc)
|
|||
|
|
if not ca.not_valid_before_utc <= now < ca.not_valid_after_utc:
|
|||
|
|
raise ValueError("CA证书尚未生效或已过期")
|
|||
|
|
if renew_ca_years is not None:
|
|||
|
|
if ca.subject != ca.issuer:
|
|||
|
|
raise ValueError("仅支持用原密钥续签自签根CA;中间CA须由原上级签发")
|
|||
|
|
ca.verify_directly_issued_by(ca)
|
|||
|
|
renewal = (x509.CertificateBuilder().subject_name(ca.subject).issuer_name(ca.issuer)
|
|||
|
|
.public_key(ca.public_key()).serial_number(x509.random_serial_number())
|
|||
|
|
.not_valid_before(ca.not_valid_before_utc)
|
|||
|
|
.not_valid_after(anniversary(now, renew_ca_years)))
|
|||
|
|
for extension in ca.extensions:
|
|||
|
|
renewal = renewal.add_extension(extension.value, extension.critical)
|
|||
|
|
ca = renewal.sign(authority, hashes.SHA256())
|
|||
|
|
expires = min(anniversary(now, years) if years is not None else now + timedelta(days=days),
|
|||
|
|
ca.not_valid_after_utc)
|
|||
|
|
if expires - now < timedelta(days=1):
|
|||
|
|
raise ValueError("CA剩余有效期不足一天")
|
|||
|
|
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
|
|||
|
|
cert = (
|
|||
|
|
x509.CertificateBuilder()
|
|||
|
|
.subject_name(subject)
|
|||
|
|
.issuer_name(ca.subject)
|
|||
|
|
.public_key(server.public_key())
|
|||
|
|
.serial_number(x509.random_serial_number())
|
|||
|
|
.not_valid_before(max(now - timedelta(minutes=5), ca.not_valid_before_utc))
|
|||
|
|
.not_valid_after(expires)
|
|||
|
|
.add_extension(x509.SubjectAlternativeName([x509.DNSName(name)]), critical=False)
|
|||
|
|
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
|||
|
|
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
|
|||
|
|
.add_extension(x509.KeyUsage(
|
|||
|
|
digital_signature=True, content_commitment=False,
|
|||
|
|
key_encipherment=isinstance(server, rsa.RSAPrivateKey),
|
|||
|
|
data_encipherment=False, key_agreement=False, key_cert_sign=False,
|
|||
|
|
crl_sign=False, encipher_only=None, decipher_only=None
|
|||
|
|
), critical=True)
|
|||
|
|
.add_extension(x509.SubjectKeyIdentifier.from_public_key(server.public_key()), critical=False)
|
|||
|
|
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca.public_key()), critical=False)
|
|||
|
|
.sign(authority, hashes.SHA256())
|
|||
|
|
)
|
|||
|
|
output = Path(output).resolve()
|
|||
|
|
output.mkdir(parents=True, exist_ok=False)
|
|||
|
|
(output / "quic-gateway.crt").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
|||
|
|
(output / "cmvr-quic-ca.crt").write_bytes(ca.public_bytes(serialization.Encoding.PEM))
|
|||
|
|
manifest = {
|
|||
|
|
"serverName": name,
|
|||
|
|
"subjectAltName": {"dns": [name], "ip": []},
|
|||
|
|
"certificateSha256": cert.fingerprint(hashes.SHA256()).hex(),
|
|||
|
|
"caSha256": ca.fingerprint(hashes.SHA256()).hex(),
|
|||
|
|
"originalCaSha256": original_ca_fingerprint,
|
|||
|
|
"caCertificateRenewed": renew_ca_years is not None,
|
|||
|
|
"caPublicKeyUnchanged": True,
|
|||
|
|
"caNotAfter": ca.not_valid_after_utc.isoformat(),
|
|||
|
|
"notBefore": cert.not_valid_before_utc.isoformat(),
|
|||
|
|
"notAfter": cert.not_valid_after_utc.isoformat(),
|
|||
|
|
"serverKeyReused": True,
|
|||
|
|
"privateKeysIncluded": False,
|
|||
|
|
"activated": False,
|
|||
|
|
}
|
|||
|
|
(output / "identity.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|||
|
|
return manifest
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|||
|
|
parser.add_argument("--ca-cert", type=Path, required=True)
|
|||
|
|
parser.add_argument("--ca-key", type=Path, required=True)
|
|||
|
|
parser.add_argument("--server-key", type=Path, required=True)
|
|||
|
|
parser.add_argument("--output-dir", type=Path, required=True)
|
|||
|
|
parser.add_argument("--server-name", default="am-freescan.internal")
|
|||
|
|
parser.add_argument("--days", type=int, default=365)
|
|||
|
|
parser.add_argument("--years", type=int, help="按日历年签发,优先于days,最多60年")
|
|||
|
|
parser.add_argument("--renew-ca-years", type=int, help="明确选择用原密钥续签自签根CA,不改变CA身份")
|
|||
|
|
args = parser.parse_args()
|
|||
|
|
try:
|
|||
|
|
result = prepare(args.ca_cert, args.ca_key, args.server_key, args.output_dir,
|
|||
|
|
args.server_name, args.days, args.years, args.renew_ca_years)
|
|||
|
|
except (ValueError, OSError, x509.ExtensionNotFound) as error:
|
|||
|
|
parser.exit(1, f"证书准备失败:{error}\n")
|
|||
|
|
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
main()
|