v0.43.1
This commit is contained in:
1 parent
5b6d4a7903
commit
4d1087e357
160 files changed
+2407
-1933
No files matched your search
@@ -37,18 +37,14 @@ PROVIDER_FIELDS = {
|
||||
"rfc2136": {"dns_server", "dns_port", "key_name", "key_secret", "key_algorithm", "sign_query"},
|
||||
}
|
||||
|
||||
|
||||
def credential(value: object) -> str:
|
||||
# API keys are ASCII tokens; reject anything that could inject INI content.
|
||||
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_./+\-=]{8,4096}", value):
|
||||
raise AcmeError("acme.invalid_api_credential")
|
||||
return value
|
||||
|
||||
|
||||
class AcmeError(Exception):
|
||||
"""Messages contain fixed diagnostics, never provider output or input secrets."""
|
||||
|
||||
|
||||
def domain(value: object, wildcard: bool = True, single_label: bool = False) -> str:
|
||||
if not isinstance(value, str) or not value.isascii() or len(value) > 253:
|
||||
raise AcmeError("acme.invalid_domain")
|
||||
@@ -62,7 +58,6 @@ def domain(value: object, wildcard: bool = True, single_label: bool = False) ->
|
||||
return value
|
||||
raise AcmeError("acme.dns_names_only")
|
||||
|
||||
|
||||
def validate(raw: object) -> dict:
|
||||
if not isinstance(raw, dict):
|
||||
raise AcmeError("acme.invalid_request")
|
||||
@@ -132,14 +127,12 @@ def validate(raw: object) -> dict:
|
||||
raise AcmeError("acme.invalid_sign_query")
|
||||
return value
|
||||
|
||||
|
||||
def private_directory(path: Path) -> None:
|
||||
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
info = path.lstat()
|
||||
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077:
|
||||
raise AcmeError("acme.unsafe_directory")
|
||||
|
||||
|
||||
def write_new(path: Path, data: bytes) -> None:
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
|
||||
with os.fdopen(fd, "wb") as stream:
|
||||
@@ -147,7 +140,6 @@ def write_new(path: Path, data: bytes) -> None:
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def credentials(value: dict) -> bytes:
|
||||
if value["provider"] == "http01":
|
||||
return b""
|
||||
@@ -163,7 +155,6 @@ def credentials(value: dict) -> bytes:
|
||||
}
|
||||
return "".join(f"dns_rfc2136_{k} = {v}\n" for k, v in lines.items()).encode("ascii")
|
||||
|
||||
|
||||
def certbot_prefix(executable: str | None = None) -> list[str]:
|
||||
if executable:
|
||||
return [executable]
|
||||
@@ -175,7 +166,6 @@ def certbot_prefix(executable: str | None = None) -> list[str]:
|
||||
return [discovered]
|
||||
raise AcmeError("acme.certbot_not_installed")
|
||||
|
||||
|
||||
def certbot_command(value: dict, work: Path, credential_file: Path, command_prefix: list[str]) -> list[str]:
|
||||
args = [*command_prefix, "certonly", "--non-interactive", "--agree-tos", "--no-eff-email",
|
||||
"--email", value["email"], "--server", DIRECTORIES[value["environment"]],
|
||||
@@ -193,9 +183,7 @@ def certbot_command(value: dict, work: Path, credential_file: Path, command_pref
|
||||
args += ["-d", name]
|
||||
return args
|
||||
|
||||
|
||||
def read_generated(work: Path, name: str) -> bytes:
|
||||
# Resolve live symlinks only inside Certbot's archive.
|
||||
archive = (work / "config" / "archive").resolve(strict=True)
|
||||
path = (work / "config" / "live" / "rustproxy" / name).resolve(strict=True)
|
||||
if not path.is_relative_to(archive):
|
||||
@@ -210,7 +198,6 @@ def read_generated(work: Path, name: str) -> bytes:
|
||||
raise AcmeError("acme.invalid_pem")
|
||||
return data
|
||||
|
||||
|
||||
def issue(raw: dict, certificate_directory: Path, executable: str | None = None) -> dict:
|
||||
value = validate(raw)
|
||||
command_prefix = certbot_prefix(executable)
|
||||
@@ -218,7 +205,6 @@ def issue(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
private_directory(certificate_directory)
|
||||
root = certificate_directory / "acme"
|
||||
private_directory(root)
|
||||
# Each profile has isolated CA accounts, credentials and lineages.
|
||||
suffix = "" if value["provider"] == "rfc2136" else "-" + value["provider"]
|
||||
work = root / (value["environment"] + "-" + value["certificate_id"] + suffix)
|
||||
private_directory(work)
|
||||
@@ -233,7 +219,6 @@ def issue(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
raise AcmeError("acme.profile_busy") from None
|
||||
for folder in ["config", "work", "logs"]:
|
||||
private_directory(work / folder)
|
||||
# Secret Store credentials exist as a plaintext file only while Certbot runs.
|
||||
credential_file = work / (value["provider"] + ".ini")
|
||||
if value["provider"] == "http01":
|
||||
webroot = certificate_directory / "acme-http01"
|
||||
@@ -260,7 +245,6 @@ def issue(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
credential_file.unlink(missing_ok=True)
|
||||
cert = read_generated(work, "fullchain.pem")
|
||||
key = read_generated(work, "privkey.pem")
|
||||
# Work on immutable copies so the active certificate never changes mid-run.
|
||||
stem = "acme-" + uuid.uuid4().hex
|
||||
cert_path = certificate_directory / (stem + ".pem")
|
||||
key_path = certificate_directory / (stem + ".key")
|
||||
@@ -277,13 +261,10 @@ def issue(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
"domains": value["domains"], "cert_file": cert_path.name, "key_file": key_path.name,
|
||||
"staged": True}
|
||||
|
||||
|
||||
|
||||
def profile_directory(certificate_directory: Path, provider: str, environment: str, certificate_id: str) -> Path:
|
||||
suffix = "" if provider == "rfc2136" else "-" + provider
|
||||
return certificate_directory / "acme" / (environment + "-" + certificate_id + suffix)
|
||||
|
||||
|
||||
def read_private(path: Path, limit: int = MAX_INPUT) -> bytes:
|
||||
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
||||
with os.fdopen(fd, "rb") as stream:
|
||||
@@ -295,7 +276,6 @@ def read_private(path: Path, limit: int = MAX_INPUT) -> bytes:
|
||||
raise AcmeError("acme.unsafe_profile")
|
||||
return data
|
||||
|
||||
|
||||
def certificate_dates(pem: bytes, executable: str | None = None) -> dict:
|
||||
"""Read validity without exposing subject/PEM data or requiring a new Python package."""
|
||||
executable = executable or shutil.which("openssl")
|
||||
@@ -310,7 +290,6 @@ def certificate_dates(pem: bytes, executable: str | None = None) -> dict:
|
||||
dates = {}
|
||||
for line in result.stdout.decode("ascii").splitlines():
|
||||
name, text = line.split("=", 1)
|
||||
# OpenSSL's English ASN.1 date print format; LC_ALL is fixed above.
|
||||
value = datetime.datetime.strptime(text.strip(), "%b %d %H:%M:%S %Y GMT").replace(tzinfo=datetime.timezone.utc)
|
||||
dates[name] = int(value.timestamp())
|
||||
if dates["notAfter"] <= dates["notBefore"]:
|
||||
@@ -319,7 +298,6 @@ def certificate_dates(pem: bytes, executable: str | None = None) -> dict:
|
||||
except (ValueError, KeyError, UnicodeError, subprocess.TimeoutExpired):
|
||||
raise AcmeError("acme.certificate_dates_invalid") from None
|
||||
|
||||
|
||||
def renewal_request(raw: object) -> dict:
|
||||
if not isinstance(raw, dict) or set(raw) - {"action", "certificate_id", "provider", "environment", "cert_file", "key_file", "dry_run", "force", "credential_ini_b64"}:
|
||||
raise AcmeError("acme.invalid_renewal_request")
|
||||
@@ -350,7 +328,6 @@ def renewal_request(raw: object) -> dict:
|
||||
value.pop("credential_ini_b64", None)
|
||||
return value
|
||||
|
||||
|
||||
def renew(raw: dict, certificate_directory: Path, executable: str | None = None) -> dict:
|
||||
"""Renew ONE existing, consented lineage; never create a profile.
|
||||
|
||||
@@ -365,7 +342,6 @@ def renew(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
certificate_directory = certificate_directory.absolute()
|
||||
private_directory(certificate_directory)
|
||||
work = profile_directory(certificate_directory, value["provider"], value["environment"], value["certificate_id"])
|
||||
# Do not create missing profile paths during renewal.
|
||||
for path in [certificate_directory / "acme", work, work / "config", work / "work", work / "logs"]:
|
||||
if not path.exists():
|
||||
raise AcmeError("acme.renewal_profile_missing")
|
||||
@@ -389,7 +365,6 @@ def renew(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
if not isinstance(names, list) or not 1 <= len(names) <= 16:
|
||||
raise AcmeError("acme.invalid_domains")
|
||||
names = [domain(n, wildcard=value["provider"] != "http01") for n in names]
|
||||
# Credentials are recreated only for the duration of this invocation.
|
||||
read_private(work / "config" / "renewal" / "rustproxy.conf", 65536)
|
||||
credential_file = work / (value["provider"] + ".ini")
|
||||
if value["provider"] != "http01":
|
||||
@@ -402,7 +377,6 @@ def renew(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
try:
|
||||
installed_cert = read_private(certificate_directory / value["cert_file"], MAX_PEM)
|
||||
installed_key = read_private(certificate_directory / value["key_file"], MAX_PEM)
|
||||
# Check dependencies/installed PEM before invoking a CA operation.
|
||||
old_dates = certificate_dates(installed_cert)
|
||||
args = [*command_prefix, "renew", "--cert-name", "rustproxy", "--non-interactive",
|
||||
"--no-random-sleep-on-renew", "--no-directory-hooks",
|
||||
@@ -434,7 +408,6 @@ def renew(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
return output
|
||||
if dates["not_after_unix"] < old_dates["not_after_unix"]:
|
||||
raise AcmeError("acme.renewal_older_certificate")
|
||||
# Content-addressed staging keeps retries idempotent.
|
||||
stem = "acme-" + hashlib.sha256(cert + b"\0" + key).hexdigest()[:48]
|
||||
paths = [(certificate_directory / (stem + ".pem"), cert), (certificate_directory / (stem + ".key"), key)]
|
||||
if len(list(certificate_directory.glob("acme-*.key"))) >= 1024 and not paths[1][0].exists():
|
||||
@@ -468,11 +441,9 @@ def main() -> None:
|
||||
result = renew(value, args.cert_dir) if isinstance(value, dict) and value.get("action") == "renew" else issue(value, args.cert_dir)
|
||||
print(json.dumps(result))
|
||||
except (AcmeError, OSError, ValueError) as error:
|
||||
# OSError/JSON errors can contain paths/input. Do not serialize them.
|
||||
message = str(error) if isinstance(error, AcmeError) else "acme.local_io_or_json_error"
|
||||
print(json.dumps({"error": message}))
|
||||
raise SystemExit(1) from None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compatibility entry point; all issuance uses acme_provider."""
|
||||
from acme_provider import * # noqa: F403
|
||||
from acme_provider import *
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user