ezmtls 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ezmtls/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Mutual TLS made easy, client side: SSL contexts with a client certificate, peer identities for
2
+ servers, and `ezmtls connect`. The CA is ezcerts; the ready-made server is ezmtls-server."""
3
+
4
+ from importlib.metadata import version
5
+
6
+ from ezmtls.tls import PeerIdentity, client_context, peer_identity, server_context
7
+
8
+ __version__ = version("ezmtls")
9
+
10
+ __all__ = ["PeerIdentity", "__version__", "client_context", "peer_identity", "server_context"]
ezmtls/_cli.py ADDED
@@ -0,0 +1,93 @@
1
+ """Pieces shared by the command-line interfaces of ezmtls, ezcerts and ezmtls-server.
2
+
3
+ Private to the ezmtls family: the sibling packages import these.
4
+ """
5
+
6
+ import ipaddress
7
+ import os
8
+ from collections.abc import Callable, Sequence
9
+ from typing import Any
10
+
11
+ import click
12
+
13
+ from ezmtls.errors import EzmtlsError, PassphraseRequiredError
14
+
15
+ KEY_ENV = "EZMTLS_KEY_PASSPHRASE"
16
+
17
+
18
+ class Group(click.Group):
19
+ """Turns the library's errors into a one-line message and exit code 1."""
20
+
21
+ def invoke(self, ctx: click.Context) -> Any:
22
+ try:
23
+ return super().invoke(ctx)
24
+ except EzmtlsError as exc:
25
+ raise click.ClickException(str(exc)) from exc
26
+ except OSError as exc:
27
+ # A file that cannot be read or written: say which and why, not a traceback.
28
+ where = f"{exc.filename}: " if exc.filename else ""
29
+ raise click.ClickException(f"{where}{exc.strerror or exc}") from exc
30
+
31
+
32
+ class SectionedGroup(Group):
33
+ """Top-level help that lists the commands under headings, in the order they are used."""
34
+
35
+ sections: Sequence[tuple[str, Sequence[str]]] = ()
36
+
37
+ def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
38
+ column = max(len(n) for n in self.commands)
39
+ width = formatter.width - 6 - column
40
+ listed: set[str] = set()
41
+ for title, names in self.sections:
42
+ rows = [(n.ljust(column), self.commands[n].get_short_help_str(width)) for n in names]
43
+ listed.update(names)
44
+ with formatter.section(title):
45
+ formatter.write_dl(rows)
46
+ if missing := set(self.commands) - listed:
47
+ raise RuntimeError(f"commands missing from the help sections: {sorted(missing)}")
48
+
49
+
50
+ def passphrase(env: str, prompt: str, *, confirm: bool = False) -> str:
51
+ value = os.environ.get(env)
52
+ if value:
53
+ return value
54
+ answer: str = click.prompt(
55
+ f"{prompt} (or set {env})", hide_input=True, confirmation_prompt=confirm
56
+ )
57
+ return answer
58
+
59
+
60
+ def with_key_passphrase[T](load: Callable[[str | None], T], prompt: str) -> T:
61
+ """Load a key with EZMTLS_KEY_PASSPHRASE when set, prompting when the key needs one.
62
+
63
+ The variable means "the passphrase for keys that need one": a key that turns out not to be
64
+ encrypted is loaded without it instead of failing.
65
+ """
66
+ from_env = os.environ.get(KEY_ENV) or None
67
+ try:
68
+ return load(from_env)
69
+ except PassphraseRequiredError:
70
+ return load(passphrase(KEY_ENV, prompt))
71
+ except EzmtlsError as exc:
72
+ if from_env is None:
73
+ raise
74
+ try:
75
+ return load(None) # an unencrypted key, refused only because a passphrase was given
76
+ except PassphraseRequiredError:
77
+ raise exc from None # it is encrypted: the passphrase was simply wrong
78
+
79
+
80
+ def address(value: str, what: str) -> tuple[str, int]:
81
+ """An IP address and a port (0-65535), checked before anything else happens."""
82
+ host, sep, port = value.rpartition(":")
83
+ host = host.removeprefix("[").removesuffix("]")
84
+ valid = sep and port.isascii() and port.isdigit() and 0 <= int(port) <= 65535
85
+ try:
86
+ ipaddress.ip_address(host)
87
+ except ValueError:
88
+ valid = False
89
+ if not valid:
90
+ raise click.BadParameter(
91
+ f"use HOST:PORT with an IP address and a port 0-65535, not {value!r}", param_hint=what
92
+ )
93
+ return host, int(port)
ezmtls/_files.py ADDED
@@ -0,0 +1,95 @@
1
+ """Crash-safe file writes."""
2
+
3
+ import contextlib
4
+ import functools
5
+ import os
6
+ import tempfile
7
+ import time
8
+ from collections.abc import Callable, Sequence
9
+ from pathlib import Path
10
+
11
+ #: On Windows a file another process has open cannot be replaced or opened for a moment (the CA
12
+ #: service serving crl.pem while the CLI publishes a new one): retry for this long.
13
+ REPLACE_RETRY_SECONDS = 1.0
14
+ _RETRY_STEP = 0.05
15
+ _WINDOWS = os.name == "nt"
16
+
17
+
18
+ def atomic_write(path: Path, data: bytes, *, private: bool = False) -> None:
19
+ """Write `data` to `path` so that readers see either the old file or the new one, never a mix.
20
+
21
+ The data goes to a temporary file in the same folder, is flushed to disk, then renamed over the
22
+ target. Private files (keys) are readable by the owner only on POSIX systems; on Windows the
23
+ file inherits the folder's permissions.
24
+ """
25
+ tmp = _stage(path, data, private)
26
+ try:
27
+ _retry_on_windows(lambda: tmp.replace(path))
28
+ except BaseException:
29
+ with contextlib.suppress(FileNotFoundError):
30
+ tmp.unlink()
31
+ raise
32
+
33
+
34
+ def atomic_write_all(files: Sequence[tuple[Path, bytes, bool]]) -> None:
35
+ """Write several `(path, data, private)` files that belong together (a key and its
36
+ certificate): all or none. Every file is written to its temporary file first, so a full disk
37
+ or an unwritable folder changes nothing; then each is renamed over its target, and if a rename
38
+ fails the targets already replaced get their old contents back. Only a crash between the
39
+ renames can leave a mix."""
40
+ staged: list[tuple[Path, Path, bytes | None, bool]] = []
41
+ try:
42
+ for path, data, private in files:
43
+ old = read_bytes(path) if path.is_file() else None
44
+ staged.append((path, _stage(path, data, private), old, private))
45
+ for i, (path, tmp, _, _) in enumerate(staged):
46
+ try:
47
+ _retry_on_windows(functools.partial(tmp.replace, path))
48
+ except BaseException:
49
+ for done, _, old, private in staged[:i]:
50
+ with contextlib.suppress(OSError):
51
+ if old is None:
52
+ done.unlink()
53
+ else:
54
+ atomic_write(done, old, private=private)
55
+ raise
56
+ finally:
57
+ for _, tmp, _, _ in staged:
58
+ with contextlib.suppress(FileNotFoundError):
59
+ tmp.unlink()
60
+
61
+
62
+ def _stage(path: Path, data: bytes, private: bool) -> Path:
63
+ """A flushed temporary file holding `data`, next to `path`, for renaming over it."""
64
+ path.parent.mkdir(parents=True, exist_ok=True)
65
+ # mkstemp creates the file with mode 0600 on POSIX.
66
+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
67
+ tmp = Path(tmp_name)
68
+ try:
69
+ with os.fdopen(fd, "wb") as f:
70
+ f.write(data)
71
+ f.flush()
72
+ os.fsync(f.fileno())
73
+ if not private:
74
+ tmp.chmod(0o644)
75
+ except BaseException:
76
+ with contextlib.suppress(FileNotFoundError):
77
+ tmp.unlink()
78
+ raise
79
+ return tmp
80
+
81
+
82
+ def read_bytes(path: Path) -> bytes:
83
+ """`path.read_bytes()`, retried briefly on Windows while another process replaces the file."""
84
+ return _retry_on_windows(path.read_bytes)
85
+
86
+
87
+ def _retry_on_windows[T](action: Callable[[], T]) -> T:
88
+ deadline = time.monotonic() + REPLACE_RETRY_SECONDS
89
+ while True:
90
+ try:
91
+ return action()
92
+ except PermissionError:
93
+ if not _WINDOWS or time.monotonic() >= deadline:
94
+ raise
95
+ time.sleep(_RETRY_STEP)
ezmtls/_net.py ADDED
@@ -0,0 +1,21 @@
1
+ """Binding listening sockets with clear errors (shared by the CA service and `echo`, which must not
2
+ need the `server` extra)."""
3
+
4
+ import ipaddress
5
+ import socket
6
+
7
+ from ezmtls.errors import EzmtlsError
8
+
9
+
10
+ def bind(host: str, port: int) -> socket.socket:
11
+ """A listening socket on `host` (an IP address) and `port`, or an EzmtlsError saying why not."""
12
+ try:
13
+ family = socket.AF_INET6 if ipaddress.ip_address(host).version == 6 else socket.AF_INET
14
+ except ValueError as exc:
15
+ raise EzmtlsError(f"listen address must be an IP address, not {host!r}") from exc
16
+ if not 0 <= port <= 65535:
17
+ raise EzmtlsError(f"listen port must be 0-65535, not {port}")
18
+ try:
19
+ return socket.create_server((host, port), family=family, backlog=128)
20
+ except OSError as exc:
21
+ raise EzmtlsError(f"cannot listen on {host}:{port}: {exc.strerror or exc}") from exc
ezmtls/_x509.py ADDED
@@ -0,0 +1,85 @@
1
+ """Low-level X.509 helpers shared with the sibling packages (ezcerts, ezmtls-server).
2
+
3
+ Private to the ezmtls family: ezcerts imports these, so a change here is a change for it too.
4
+ """
5
+
6
+ import datetime as dt
7
+
8
+ from cryptography import x509
9
+ from cryptography.hazmat.primitives import serialization
10
+ from cryptography.hazmat.primitives.asymmetric import ec
11
+ from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes
12
+
13
+ from ezmtls.errors import BadPassphraseError, EzmtlsError, PassphraseRequiredError
14
+
15
+ #: The identities ezcerts puts in certificates (URI SANs); the protocol shared by all packages.
16
+ CLIENT_URN_PREFIX = "urn:ezmtls:client:"
17
+ ADMIN_URN_PREFIX = "urn:ezmtls:admin:"
18
+
19
+
20
+ def now() -> dt.datetime:
21
+ return dt.datetime.now(dt.UTC)
22
+
23
+
24
+ def generate_key() -> ec.EllipticCurvePrivateKey:
25
+ """A new ECDSA P-256 private key."""
26
+ return ec.generate_private_key(ec.SECP256R1())
27
+
28
+
29
+ def to_passphrase(passphrase: str | bytes | None) -> bytes | None:
30
+ if passphrase is None:
31
+ return None
32
+ data = passphrase.encode() if isinstance(passphrase, str) else passphrase
33
+ return data or None
34
+
35
+
36
+ def key_to_pem(key: PrivateKeyTypes, passphrase: str | bytes | None) -> bytes:
37
+ """PKCS#8 PEM, encrypted when a passphrase is given."""
38
+ password = to_passphrase(passphrase)
39
+ encryption: serialization.KeySerializationEncryption = (
40
+ serialization.BestAvailableEncryption(password)
41
+ if password
42
+ else serialization.NoEncryption()
43
+ )
44
+ return key.private_bytes(
45
+ serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, encryption
46
+ )
47
+
48
+
49
+ def load_key(pem: bytes, passphrase: str | bytes | None, what: str) -> PrivateKeyTypes:
50
+ """Load a PEM private key, turning cryptography's errors into ones a user can act on."""
51
+ password = to_passphrase(passphrase)
52
+ try:
53
+ return serialization.load_pem_private_key(pem, password)
54
+ except TypeError as exc:
55
+ # Raised both for "encrypted but no password" and "not encrypted but password given".
56
+ if password is None:
57
+ raise PassphraseRequiredError(
58
+ f"the {what} is encrypted: a passphrase is required"
59
+ ) from exc
60
+ raise EzmtlsError(f"the {what} is not encrypted but a passphrase was given") from exc
61
+ except ValueError as exc:
62
+ if password is None:
63
+ raise EzmtlsError(
64
+ f"the {what} could not be read: it is not a PEM private key, or it is damaged"
65
+ ) from exc
66
+ raise BadPassphraseError(f"wrong passphrase for the {what}") from exc
67
+
68
+
69
+ def san_to_str(name: x509.GeneralName) -> str:
70
+ if isinstance(name, x509.IPAddress):
71
+ return str(name.value)
72
+ if isinstance(name, (x509.DNSName, x509.UniformResourceIdentifier, x509.RFC822Name)):
73
+ return name.value
74
+ return str(name)
75
+
76
+
77
+ def sans_of(cert: x509.Certificate) -> list[x509.GeneralName]:
78
+ try:
79
+ return list(cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value)
80
+ except x509.ExtensionNotFound:
81
+ return []
82
+
83
+
84
+ def cert_pem(cert: x509.Certificate) -> bytes:
85
+ return cert.public_bytes(serialization.Encoding.PEM)
ezmtls/cli.py ADDED
@@ -0,0 +1,366 @@
1
+ """Command-line interface of ezmtls (the client side). A thin layer over the library API."""
2
+
3
+ import dataclasses
4
+ from pathlib import Path
5
+
6
+ import click
7
+
8
+ from ezmtls import __version__
9
+ from ezmtls._cli import KEY_ENV, Group, SectionedGroup, passphrase, with_key_passphrase
10
+ from ezmtls.est import (
11
+ Enrollment,
12
+ ESTClient,
13
+ _dropped_on_refusal, # pyright: ignore[reportPrivateUsage]
14
+ _pending_key, # pyright: ignore[reportPrivateUsage]
15
+ )
16
+
17
+ TOKEN_ENV = "EZMTLS_EST_TOKEN" # noqa: S105 (a variable name)
18
+
19
+
20
+ class _MainGroup(SectionedGroup):
21
+ sections = (
22
+ ("Clients", ("connect", "crl")),
23
+ ("Certificates from a CA (EST)", ("est",)),
24
+ )
25
+
26
+
27
+ @click.group(
28
+ cls=_MainGroup,
29
+ epilog="""\b
30
+ Example:
31
+ ezmtls est enroll https://ca.internal:8443 device-7 --ca ca.crt --out device.pem
32
+ ezmtls connect https://api.internal:8443/ --cert device.pem --ca ca.crt
33
+
34
+
35
+ Run 'ezmtls COMMAND --help' for a command's options.
36
+ Docs: https://winuxnomacs.github.io/ezmtls/""",
37
+ )
38
+ @click.version_option(__version__, prog_name="ezmtls")
39
+ def main() -> None:
40
+ """Make mTLS connections with a client certificate.
41
+
42
+ Certificates come from your CA (ezcerts or another). A key that needs a passphrase takes it from
43
+ EZMTLS_KEY_PASSPHRASE when set, otherwise it is prompted for.
44
+ """
45
+
46
+
47
+ @main.command(short_help="Test a TLS endpoint with a client certificate.")
48
+ @click.argument("target")
49
+ @click.option(
50
+ "--cert",
51
+ required=True,
52
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
53
+ help="Client certificate: the file from `ezcerts export`, a fullchain.pem (with --key) or a"
54
+ " .p12.",
55
+ )
56
+ @click.option(
57
+ "--key", type=click.Path(exists=True, dir_okay=False, path_type=Path), help="Private key file."
58
+ )
59
+ @click.option(
60
+ "--ca",
61
+ required=True,
62
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
63
+ help="The CA certificate to trust (with ezcerts: public/ca.crt in the CA folder).",
64
+ )
65
+ @click.option(
66
+ "--crl",
67
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
68
+ help="CRL bundle: refuse a revoked server (`ezmtls crl fetch` keeps one fresh).",
69
+ )
70
+ @click.option("--server-name", help="Name to verify the server against (default: the target host).")
71
+ @click.option(
72
+ "--timeout",
73
+ default=10.0,
74
+ show_default=True,
75
+ type=click.FloatRange(0.1),
76
+ help="Seconds to wait for the connection, the handshake and the response.",
77
+ )
78
+ @click.option(
79
+ "--max-body",
80
+ default=2048,
81
+ show_default=True,
82
+ type=click.IntRange(0),
83
+ help="Bytes of the response to print (0: none).",
84
+ )
85
+ def connect(
86
+ target: str,
87
+ cert: Path,
88
+ key: Path | None,
89
+ ca: Path,
90
+ crl: Path | None,
91
+ server_name: str | None,
92
+ timeout: float,
93
+ max_body: int,
94
+ ) -> None:
95
+ """Connect to TARGET (https://host:port/path or host:port) with a client certificate.
96
+
97
+ Shows the server certificate, TLS version and cipher, and for https:// the response. Exits with
98
+ status 1 and the reason if the connection, the handshake or the server's check of the client
99
+ certificate fails. A key that needs a passphrase takes it from EZMTLS_KEY_PASSPHRASE when set,
100
+ otherwise it is prompted for.
101
+ """
102
+ from ezmtls.probe import probe
103
+ from ezmtls.tls import client_context
104
+
105
+ ctx = with_key_passphrase(
106
+ lambda passphrase: client_context(cert, key, ca=ca, crl=crl, key_passphrase=passphrase),
107
+ f"Passphrase for {key or cert}",
108
+ )
109
+ result = probe(target, ctx, server_name=server_name, timeout=timeout)
110
+ server = result.server
111
+ click.echo(f"Connected to {result.host}:{result.port} ({result.address})")
112
+ click.echo(f" TLS: {result.tls_version}, {result.cipher}")
113
+ click.echo(f" server: {server.subject} (serial {server.serial:x})")
114
+ click.echo(f" names: {', '.join(server.sans)}")
115
+ click.echo(f" expires: {server.not_after:%Y-%m-%d %H:%M} UTC")
116
+ if result.http_status is not None:
117
+ click.echo(f" HTTP: {result.http_status}")
118
+ elif not result.data:
119
+ click.echo(" data: none received (connection open; client certificate accepted)")
120
+ if result.data and max_body:
121
+ click.echo("")
122
+ click.echo(result.data[:max_body].decode("utf-8", errors="replace"))
123
+ if len(result.data) > max_body:
124
+ click.echo(f"... ({len(result.data) - max_body} more bytes)")
125
+
126
+
127
+ # ----- EST ---------------------------------------------------------------------------------------
128
+
129
+ _CA_OPTION = click.option(
130
+ "--ca",
131
+ required=True,
132
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
133
+ help="The CA certificate to trust (with ezcerts: public/ca.crt).",
134
+ )
135
+
136
+
137
+ @main.group(cls=Group)
138
+ def est() -> None:
139
+ """Get and renew certificates from an EST server (RFC 7030), such as ezcerts serve."""
140
+
141
+
142
+ def _report(enrolled: Enrollment, written: list[Path]) -> None:
143
+ cert = enrolled.certificate
144
+ click.echo(f"certificate {cert.subject.rfc4514_string()} (serial {cert.serial_number:x})")
145
+ click.echo(f" expires: {cert.not_valid_after_utc:%Y-%m-%d %H:%M} UTC")
146
+ click.echo(f" files: {', '.join(str(p) for p in written)}")
147
+
148
+
149
+ @est.command("cacerts")
150
+ @click.argument("url")
151
+ @_CA_OPTION
152
+ @click.option("--out", type=click.Path(dir_okay=False, path_type=Path), help="Write here (PEM).")
153
+ def est_cacerts(url: str, ca: Path, out: Path | None) -> None:
154
+ """Show the CA certificates the server at URL (https://host[:port]) publishes."""
155
+ from ezmtls._files import atomic_write
156
+ from ezmtls._x509 import cert_pem
157
+
158
+ pem = b"".join(cert_pem(c) for c in ESTClient(url, ca=ca).cacerts())
159
+ if out is None:
160
+ click.echo(pem.decode(), nl=False)
161
+ else:
162
+ atomic_write(out, pem)
163
+ click.echo(f"wrote {out}")
164
+
165
+
166
+ @est.command("enroll")
167
+ @click.argument("url")
168
+ @click.argument("name")
169
+ @_CA_OPTION
170
+ @click.option(
171
+ "--out",
172
+ required=True,
173
+ type=click.Path(dir_okay=False, path_type=Path),
174
+ help="Certificate file; with no --key-out it holds the key too (owner-only).",
175
+ )
176
+ @click.option(
177
+ "--key-out", type=click.Path(dir_okay=False, path_type=Path), help="Write the key here."
178
+ )
179
+ @click.option(
180
+ "--server-key", is_flag=True, help="Let the CA make the key (for devices that cannot)."
181
+ )
182
+ @click.option("--encrypt-key", is_flag=True, help=f"Encrypt the key (passphrase: {KEY_ENV}).")
183
+ def est_enroll(
184
+ url: str,
185
+ name: str,
186
+ ca: Path,
187
+ out: Path,
188
+ key_out: Path | None,
189
+ server_key: bool,
190
+ encrypt_key: bool,
191
+ ) -> None:
192
+ """Get a first certificate for NAME from the server at URL with a one-time token.
193
+
194
+ The token (from `ezcerts token create NAME`) is read from EZMTLS_EST_TOKEN, or prompted for.
195
+ The key is made here and never leaves this machine, unless --server-key.
196
+ """
197
+ for path in (out, key_out):
198
+ if path is not None and path.exists():
199
+ raise click.ClickException(f"{path} exists; renew with `ezmtls est renew` instead")
200
+ secret = (
201
+ passphrase(KEY_ENV, "Passphrase for the new key", confirm=True) if encrypt_key else None
202
+ )
203
+ token = passphrase(TOKEN_ENV, f"Enrollment token for {name}")
204
+ client = ESTClient(url, ca=ca)
205
+ if server_key:
206
+ enrolled = client.serverkeygen(name, token)
207
+ else:
208
+ # The key waits in a .pending file until saved: run again after a lost answer, and the
209
+ # CA answers with the certificate it already issued for it (the token is used up).
210
+ target = key_out or out
211
+ pending = target.with_name(target.name + ".pending")
212
+ key = _pending_key(pending, secret, None)
213
+ with _dropped_on_refusal(pending):
214
+ enrolled = client.enroll(name, token, key=key)
215
+ enrolled = dataclasses.replace(enrolled, pending_key=pending)
216
+ enrolled.save(out, key_out, key_passphrase=secret)
217
+ _report(enrolled, [out, *([key_out] if key_out else [])])
218
+
219
+
220
+ @est.command("renew")
221
+ @click.argument("url")
222
+ @click.option(
223
+ "--cert",
224
+ required=True,
225
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
226
+ help="The current certificate (with its key, or with --key).",
227
+ )
228
+ @click.option(
229
+ "--key", type=click.Path(exists=True, dir_okay=False, path_type=Path), help="Its key file."
230
+ )
231
+ @_CA_OPTION
232
+ @click.option(
233
+ "--same-key", is_flag=True, help="Keep the key (keys in hardware; the server must allow it)."
234
+ )
235
+ @click.option(
236
+ "--if-due",
237
+ is_flag=True,
238
+ help="Only when less than a third of the certificate's lifetime is left (a daily cron job).",
239
+ )
240
+ def est_renew(
241
+ url: str, cert: Path, key: Path | None, ca: Path, same_key: bool, if_due: bool
242
+ ) -> None:
243
+ """Renew the certificate in --cert with the server at URL, replacing the files.
244
+
245
+ A new key is made unless --same-key; an encrypted key stays encrypted with the same passphrase
246
+ (from EZMTLS_KEY_PASSPHRASE, or prompted for). With one file holding key and certificate, it is
247
+ replaced in a single step.
248
+ """
249
+ client = ESTClient(url, ca=ca)
250
+ used: list[str | None] = []
251
+
252
+ def renew(secret: str | None) -> Enrollment:
253
+ result = client.reenroll(cert, key, key_passphrase=secret, same_key=same_key)
254
+ used.append(secret)
255
+ return result
256
+
257
+ if if_due:
258
+ from ezmtls.renew import Renewer
259
+
260
+ when = Renewer(client, cert, key)
261
+ if not when.due():
262
+ click.echo(f"not due: renewal starts {when.renew_at():%Y-%m-%d %H:%M} UTC")
263
+ return
264
+ renewed = with_key_passphrase(renew, f"Passphrase for {key or cert}")
265
+ renewed.save(cert, key, key_passphrase=used[-1])
266
+ _report(renewed, [cert, *([key] if key else [])])
267
+
268
+
269
+ @est.command("keep")
270
+ @click.argument("url")
271
+ @click.option(
272
+ "--cert",
273
+ required=True,
274
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
275
+ help="The certificate to keep renewed (with its key, or with --key).",
276
+ )
277
+ @click.option(
278
+ "--key", type=click.Path(exists=True, dir_okay=False, path_type=Path), help="Its key file."
279
+ )
280
+ @_CA_OPTION
281
+ @click.option(
282
+ "--same-key", is_flag=True, help="Keep the key (keys in hardware; the server must allow it)."
283
+ )
284
+ @click.option(
285
+ "--interval",
286
+ default=3600.0,
287
+ show_default=True,
288
+ type=click.FloatRange(1),
289
+ help="Seconds between checks (after a failure: 5 minutes, or this if shorter).",
290
+ )
291
+ def est_keep(
292
+ url: str, cert: Path, key: Path | None, ca: Path, same_key: bool, interval: float
293
+ ) -> None:
294
+ """Keep renewing the certificate in --cert with the server at URL, until stopped.
295
+
296
+ For a service (systemd, a container): it renews once a third of the lifetime is left, logs
297
+ each step, retries failures, and stops on SIGTERM, Ctrl+C or Ctrl+Break.
298
+ """
299
+ import logging
300
+ import signal
301
+ import sys
302
+
303
+ from ezmtls.est import _load_key # pyright: ignore[reportPrivateUsage]
304
+ from ezmtls.renew import Renewer
305
+
306
+ logging.basicConfig(level="INFO", format="%(asctime)s %(levelname)s %(name)s: %(message)s")
307
+
308
+ def unlock(secret: str | None) -> str | None:
309
+ _load_key(key or cert, secret) # fails now, not at the first renewal
310
+ return secret
311
+
312
+ secret = with_key_passphrase(unlock, f"Passphrase for {key or cert}")
313
+ renewer = Renewer(
314
+ ESTClient(url, ca=ca), cert, key, key_passphrase=secret, same_key=same_key,
315
+ check_every=interval, retry_every=min(300.0, interval),
316
+ ) # fmt: skip
317
+
318
+ def stop(sig: int, frame: object) -> None:
319
+ click.echo(f"stopping (signal {sig})", err=True)
320
+ renewer.stop()
321
+
322
+ handled = [signal.SIGINT, signal.SIGTERM]
323
+ if sys.platform == "win32":
324
+ handled.append(signal.SIGBREAK) # Windows: Ctrl+Break
325
+ for sig in handled:
326
+ signal.signal(sig, stop)
327
+ click.echo(
328
+ f"keeping {cert} renewed; renewal starts {renewer.renew_at():%Y-%m-%d %H:%M} UTC", err=True
329
+ )
330
+ renewer.run()
331
+
332
+
333
+ # ----- CRLs --------------------------------------------------------------------------------------
334
+
335
+
336
+ @main.group(cls=Group)
337
+ def crl() -> None:
338
+ """Keep the CA's CRLs on this machine, to refuse revoked servers."""
339
+
340
+
341
+ @crl.command("fetch")
342
+ @click.argument("url")
343
+ @_CA_OPTION
344
+ @click.option(
345
+ "--out",
346
+ required=True,
347
+ type=click.Path(dir_okay=False, path_type=Path),
348
+ help="The cached CRL bundle (use it with --crl, or CRLCache in Python).",
349
+ )
350
+ @click.option(
351
+ "--if-due", is_flag=True, help="Only when half the cached CRLs' lifetime has passed (cron)."
352
+ )
353
+ def crl_fetch(url: str, ca: Path, out: Path, if_due: bool) -> None:
354
+ """Fetch the CRLs from the CA service at URL (https://host[:port]) into --out.
355
+
356
+ They must be signed by the CA in --ca and not older than the cached ones; otherwise the cache
357
+ is kept and the command fails.
358
+ """
359
+ from ezmtls.crl import CRLCache
360
+
361
+ cache = CRLCache(url, ca=ca, path=out)
362
+ if if_due and not cache.due():
363
+ click.echo(f"{out} is fresh until {cache.next_update():%Y-%m-%d %H:%M} UTC; not due")
364
+ return
365
+ cache.refresh()
366
+ click.echo(f"wrote {out} (next update {cache.next_update():%Y-%m-%d %H:%M} UTC)")