ezmtls-server 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.
@@ -0,0 +1,11 @@
1
+ """Receive mutual TLS connections directly in Python, for when nothing (such as nginx) can sit in
2
+ front of the application. Use it behind a firewall or on a trusted network."""
3
+
4
+ from importlib.metadata import version
5
+
6
+ from ezmtls_server.https import HTTPSServer, Request, Response
7
+ from ezmtls_server.tls import Connection, TLSServer
8
+
9
+ __version__ = version("ezmtls-server")
10
+
11
+ __all__ = ["Connection", "HTTPSServer", "Request", "Response", "TLSServer", "__version__"]
ezmtls_server/_base.py ADDED
@@ -0,0 +1,371 @@
1
+ """What every ezmtls-server server shares: the TLS listener and its protections.
2
+
3
+ Failure handling (see upcoming-changes.md, "Unattended failure list (ezmtls-server)"):
4
+ - The port is bound before anything else, so "address in use" is a clear error.
5
+ - TLS 1.3 with a required client certificate from the CA, no session tickets; a handshake must
6
+ finish within `handshake_timeout` (scanners and stalled clients are closed, logged at debug
7
+ level).
8
+ - At most `max_connections` at once; beyond that new connections are closed and a warning is logged
9
+ (at most every `_CAP_LOG_EVERY` seconds).
10
+ - The certificate, key and CRL are watched every `reload_interval` seconds and reloaded when they
11
+ change; a file that does not load leaves the previous ones in use (logged). The CRL's expiry is
12
+ watched too: a warning within `crl_warning`, an error once it has expired (OpenSSL then refuses
13
+ every client).
14
+ - A handler raising is logged and closes that connection only; the server keeps serving.
15
+ - `stop()` (or Ctrl+C / SIGTERM / Ctrl+Break with `run()`) stops accepting, gives open connections
16
+ `stop_timeout` seconds, then cancels them; a second stop request (or signal) cancels them at once.
17
+ """
18
+
19
+ import asyncio
20
+ import contextlib
21
+ import datetime as dt
22
+ import logging
23
+ import os
24
+ import signal
25
+ import socket
26
+ import ssl
27
+ import sys
28
+ import threading
29
+ import time
30
+ from collections.abc import Generator
31
+ from pathlib import Path
32
+ from types import FrameType
33
+ from typing import Any
34
+
35
+ from cryptography import x509
36
+
37
+ from ezmtls._net import bind
38
+ from ezmtls._x509 import now
39
+ from ezmtls.errors import EzmtlsError, PeerNotVerifiedError
40
+ from ezmtls.tls import PeerIdentity, ReloadableServerContext
41
+
42
+ log = logging.getLogger("ezmtls_server")
43
+
44
+ #: Where servers listen unless told otherwise: loopback. Other addresses must be asked for.
45
+ DEFAULT_LISTEN = "127.0.0.1:9443"
46
+ _CAP_LOG_EVERY = 10.0
47
+ _CLOSE_TIMEOUT = 1.0
48
+
49
+ StrPath = str | os.PathLike[str]
50
+ Passphrase = str | bytes
51
+
52
+
53
+ def parse_listen(listen: str) -> tuple[str, int]:
54
+ """ "HOST:PORT" (IPv6 in brackets) into a host and a port, or an EzmtlsError."""
55
+ host, sep, port = listen.rpartition(":")
56
+ host = host.removeprefix("[").removesuffix("]")
57
+ if not sep or not port.isascii() or not port.isdigit():
58
+ raise EzmtlsError(f"listen on HOST:PORT (an IP address and a port), not {listen!r}")
59
+ return host, int(port)
60
+
61
+
62
+ def _positive(name: str, value: float) -> float:
63
+ if value <= 0:
64
+ raise ValueError(f"{name} must be positive, not {value}")
65
+ return value
66
+
67
+
68
+ class ServerBase:
69
+ """The listener: subclasses implement `_handle` for one verified connection."""
70
+
71
+ def __init__(
72
+ self,
73
+ cert: StrPath,
74
+ key: StrPath | None = None,
75
+ *,
76
+ ca: StrPath,
77
+ crl: StrPath | None = None,
78
+ key_passphrase: Passphrase | None = None,
79
+ handshake_timeout: float = 10.0,
80
+ idle_timeout: float = 60.0,
81
+ max_connections: int = 256,
82
+ stop_timeout: float = 10.0,
83
+ reload_interval: float = 5.0,
84
+ crl_warning: dt.timedelta = dt.timedelta(days=1),
85
+ ) -> None:
86
+ self.handshake_timeout = _positive("handshake_timeout", handshake_timeout)
87
+ self.idle_timeout = _positive("idle_timeout", idle_timeout)
88
+ self.max_connections = int(_positive("max_connections", max_connections))
89
+ self.stop_timeout = _positive("stop_timeout", stop_timeout)
90
+ self.reload_interval = _positive("reload_interval", reload_interval)
91
+ self.crl_warning = crl_warning
92
+ self.tls = ReloadableServerContext(cert, key, ca=ca, crl=crl, key_passphrase=key_passphrase)
93
+ self._watched = tuple(Path(p) for p in (cert, key, crl) if p is not None)
94
+ self._crl = Path(crl) if crl is not None else None
95
+ self._mtimes = self._current_mtimes()
96
+ self._crl_next_update = self._read_crl_next_update()
97
+ self._crl_state = "ok"
98
+ self._stream_limit = 64 * 1024
99
+ self._active: set[asyncio.Task[None]] = set()
100
+ self._writers: set[asyncio.StreamWriter] = set()
101
+ self._loop: asyncio.AbstractEventLoop | None = None
102
+ self._stop_event: asyncio.Event | None = None
103
+ self._force_event: asyncio.Event | None = None
104
+ self._stop_requested = False
105
+ self._last_cap_log = 0.0
106
+ self._refused = 0
107
+ self._port: int | None = None
108
+
109
+ @property
110
+ def port(self) -> int | None:
111
+ """The port listened on while serving (useful with port 0), else None."""
112
+ return self._port
113
+
114
+ # ----- running ---------------------------------------------------------------------------
115
+
116
+ def run(self, listen: str = DEFAULT_LISTEN, *, sock: socket.socket | None = None) -> None:
117
+ """Serve until Ctrl+C, SIGTERM or Ctrl+Break (Windows), then stop gracefully; a second
118
+ signal stops at once. Blocks; for use in a program's main thread."""
119
+ with self._signals():
120
+ asyncio.run(self.serve(listen, sock=sock))
121
+
122
+ async def serve(
123
+ self, listen: str = DEFAULT_LISTEN, *, sock: socket.socket | None = None
124
+ ) -> None:
125
+ """Serve until `stop()` is called or the task is cancelled. With `sock` (bound and
126
+ listening), serve on it instead of binding `listen`. A stop asked for before this starts
127
+ (a signal during start-up) makes it stop as soon as it is listening."""
128
+ self._before_serve()
129
+ if sock is None:
130
+ sock = bind(*parse_listen(listen))
131
+ self._loop = asyncio.get_running_loop()
132
+ self._stop_event = asyncio.Event()
133
+ self._force_event = asyncio.Event()
134
+ if self._stop_requested: # asked before the loop was known: stop() could not set it
135
+ self._stop_event.set()
136
+ server = await asyncio.start_server(
137
+ self._accept,
138
+ sock=sock,
139
+ ssl=self.tls.context,
140
+ ssl_handshake_timeout=self.handshake_timeout,
141
+ limit=self._stream_limit,
142
+ )
143
+ self._port = int(sock.getsockname()[1])
144
+ watcher = asyncio.create_task(self._watch(), name="ezmtls-server watcher")
145
+ try:
146
+ await server.start_serving()
147
+ log.info("listening on %s port %d", sock.getsockname()[0], self._port)
148
+ stopped = asyncio.create_task(self._stop_event.wait())
149
+ done, _ = await asyncio.wait({stopped, watcher}, return_when=asyncio.FIRST_COMPLETED)
150
+ stopped.cancel()
151
+ if watcher in done:
152
+ watcher.result() # it only ends by raising: let that stop the server
153
+ finally:
154
+ server.close() # no new connections
155
+ await self._drain(self._force_event)
156
+ # Server.wait_closed() waits for every connection's TLS shutdown, which a client that
157
+ # never answers can hold up for asyncio's 30 s SSL shutdown timeout: abort leftovers.
158
+ for writer in list(self._writers):
159
+ writer.transport.abort()
160
+ with contextlib.suppress(TimeoutError):
161
+ async with asyncio.timeout(_CLOSE_TIMEOUT):
162
+ await server.wait_closed()
163
+ watcher.cancel()
164
+ with contextlib.suppress(asyncio.CancelledError):
165
+ await watcher
166
+ self._port = None
167
+ self._loop = None
168
+ self._stop_requested = False # used up: a later serve() starts afresh
169
+ log.info("stopped")
170
+
171
+ def stop(self, force: bool = False) -> None:
172
+ """Ask the server to stop (from any thread): open connections get `stop_timeout` seconds,
173
+ or are cancelled at once with `force` (or when stop was already asked for)."""
174
+ force = force or self._stop_requested
175
+ self._stop_requested = True # before reading the loop: serve() checks it after setting it
176
+ loop = self._loop
177
+ if loop is None:
178
+ return # serve() has not started: it sees _stop_requested
179
+
180
+ def apply() -> None:
181
+ if self._stop_event is not None:
182
+ self._stop_event.set()
183
+ if force and self._force_event is not None:
184
+ self._force_event.set()
185
+
186
+ with contextlib.suppress(RuntimeError): # the loop has already closed
187
+ loop.call_soon_threadsafe(apply)
188
+
189
+ async def _drain(self, force_event: asyncio.Event) -> None:
190
+ loop = asyncio.get_running_loop()
191
+ deadline = loop.time() + self.stop_timeout
192
+ if self._active:
193
+ log.info(
194
+ "waiting up to %g s for %d connection(s)", self.stop_timeout, len(self._active)
195
+ )
196
+ while self._active and not force_event.is_set():
197
+ remaining = deadline - loop.time()
198
+ if remaining <= 0:
199
+ break
200
+ forced = asyncio.create_task(force_event.wait())
201
+ await asyncio.wait(
202
+ {*self._active, forced}, timeout=remaining, return_when=asyncio.FIRST_COMPLETED
203
+ )
204
+ forced.cancel()
205
+ pending = set(self._active)
206
+ if pending:
207
+ log.warning("cancelling %d connection(s) still open", len(pending))
208
+ for task in pending:
209
+ task.cancel()
210
+ await asyncio.wait(pending, timeout=self.stop_timeout)
211
+
212
+ @contextlib.contextmanager
213
+ def _signals(self) -> Generator[None]:
214
+ if threading.current_thread() is not threading.main_thread():
215
+ yield
216
+ return
217
+ handled = [signal.SIGINT, signal.SIGTERM]
218
+ if sys.platform == "win32":
219
+ handled.append(signal.SIGBREAK) # Windows: Ctrl+Break and console close
220
+
221
+ def handler(sig: int, frame: FrameType | None) -> None:
222
+ log.info("stopping (signal %d)", sig)
223
+ self.stop()
224
+
225
+ previous: dict[int, Any] = {sig: signal.signal(sig, handler) for sig in handled}
226
+ try:
227
+ yield
228
+ finally:
229
+ for sig, old in previous.items():
230
+ signal.signal(sig, old)
231
+
232
+ # ----- connections -----------------------------------------------------------------------
233
+
234
+ async def _accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
235
+ task = asyncio.current_task()
236
+ stopping = self._stop_event is None or self._stop_event.is_set()
237
+ if task is None or stopping or len(self._active) >= self.max_connections:
238
+ if not stopping:
239
+ self._refuse()
240
+ writer.transport.abort()
241
+ return
242
+ self._active.add(task)
243
+ self._writers.add(writer)
244
+ try:
245
+ peer = self._peer(writer)
246
+ if peer is not None:
247
+ await self._handle(reader, writer, peer)
248
+ except Exception:
249
+ log.exception("unexpected error on a connection; closed it")
250
+ finally:
251
+ self._active.discard(task)
252
+ await self._close(writer)
253
+ self._writers.discard(writer)
254
+
255
+ @staticmethod
256
+ async def _close(writer: asyncio.StreamWriter) -> None:
257
+ """Close gracefully (TLS close_notify) if the client answers within a second, else abort."""
258
+ writer.close()
259
+ try:
260
+ async with asyncio.timeout(_CLOSE_TIMEOUT):
261
+ await writer.wait_closed()
262
+ except (Exception, asyncio.CancelledError):
263
+ writer.transport.abort()
264
+
265
+ def _before_serve(self) -> None:
266
+ """Refuse to start when the subclass is not ready (no handler yet)."""
267
+
268
+ async def _handle(
269
+ self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, peer: PeerIdentity
270
+ ) -> None:
271
+ raise NotImplementedError
272
+
273
+ def _refuse(self) -> None:
274
+ self._refused += 1
275
+ now_ = time.monotonic()
276
+ if now_ - self._last_cap_log >= _CAP_LOG_EVERY:
277
+ log.warning(
278
+ "connection limit of %d reached: refused %d connection(s)",
279
+ self.max_connections,
280
+ self._refused,
281
+ )
282
+ self._last_cap_log = now_
283
+ self._refused = 0
284
+
285
+ @staticmethod
286
+ def _peer(writer: asyncio.StreamWriter) -> PeerIdentity | None:
287
+ ssl_object: ssl.SSLObject | None = writer.get_extra_info("ssl_object")
288
+ der = ssl_object.getpeercert(binary_form=True) if ssl_object is not None else None
289
+ if not der:
290
+ return None
291
+ try:
292
+ return PeerIdentity.from_certificate(x509.load_der_x509_certificate(der))
293
+ except PeerNotVerifiedError as exc:
294
+ log.warning("refused a client: %s", exc)
295
+ return None
296
+
297
+ # ----- certificate, key and CRL ----------------------------------------------------------
298
+
299
+ def _current_mtimes(self) -> tuple[int | None, ...]:
300
+ def mtime(path: Path) -> int | None:
301
+ try:
302
+ return path.stat().st_mtime_ns
303
+ except OSError:
304
+ return None
305
+
306
+ return tuple(mtime(p) for p in self._watched)
307
+
308
+ def _read_crl_next_update(self) -> dt.datetime | None:
309
+ """The earliest next-update of the CRLs in the file (a bundle may hold several)."""
310
+ if self._crl is None:
311
+ return None
312
+ try:
313
+ data = self._crl.read_bytes()
314
+ except OSError:
315
+ return None
316
+ marker = b"-----BEGIN X509 CRL-----"
317
+ times: list[dt.datetime] = []
318
+ for block in data.split(marker)[1:]:
319
+ with contextlib.suppress(ValueError):
320
+ crl = x509.load_pem_x509_crl(marker + block)
321
+ if crl.next_update_utc is not None:
322
+ times.append(crl.next_update_utc)
323
+ return min(times) if times else None
324
+
325
+ async def _watch(self) -> None:
326
+ """Reload changed files and watch the CRL's expiry. Never ends on an error: a dead
327
+ watcher would leave the server with an old CRL for good."""
328
+ while True:
329
+ await asyncio.sleep(self.reload_interval)
330
+ try:
331
+ self._check_files()
332
+ self._check_crl_expiry()
333
+ except Exception:
334
+ log.exception("unexpected error watching the certificate files; retrying")
335
+
336
+ def _check_files(self) -> None:
337
+ mtimes = self._current_mtimes()
338
+ if mtimes == self._mtimes:
339
+ return
340
+ self._mtimes = mtimes # retried on the next change, not every interval
341
+ try:
342
+ self.tls.reload()
343
+ except (OSError, ssl.SSLError, ValueError, EzmtlsError) as exc:
344
+ log.error("could not reload the certificate, key or CRL; keeping the previous: %s", exc)
345
+ return
346
+ self._crl_next_update = self._read_crl_next_update()
347
+ log.info("reloaded the certificate, key and CRL")
348
+
349
+ def _check_crl_expiry(self) -> None:
350
+ next_update = self._crl_next_update
351
+ if next_update is None:
352
+ return
353
+ left = next_update - now()
354
+ state = (
355
+ "expired" if left <= dt.timedelta(0) else "soon" if left < self.crl_warning else "ok"
356
+ )
357
+ if state == self._crl_state:
358
+ return
359
+ self._crl_state = state
360
+ if state == "expired":
361
+ log.error(
362
+ "the CRL expired at %s UTC: every client is refused until a fresh one is published",
363
+ f"{next_update:%Y-%m-%d %H:%M}",
364
+ )
365
+ elif state == "soon":
366
+ log.warning(
367
+ "the CRL expires at %s UTC; publish a fresh one before then",
368
+ f"{next_update:%Y-%m-%d %H:%M}",
369
+ )
370
+ else:
371
+ log.info("the CRL is fresh again")
ezmtls_server/cli.py ADDED
@@ -0,0 +1,82 @@
1
+ """Command-line interface of ezmtls-server. A thin layer over the library API."""
2
+
3
+ from pathlib import Path
4
+
5
+ import click
6
+
7
+ from ezmtls._cli import SectionedGroup, address, with_key_passphrase
8
+ from ezmtls_server import __version__
9
+
10
+
11
+ class _MainGroup(SectionedGroup):
12
+ sections = (("Testing", ("echo",)),)
13
+
14
+
15
+ _FILE = click.Path(exists=True, dir_okay=False, path_type=Path)
16
+
17
+
18
+ @click.group(
19
+ cls=_MainGroup,
20
+ epilog="""\b
21
+ Example (files from an ezcerts CA folder):
22
+ ezmtls-server echo --cert ca/issued/web/fullchain.pem --key ca/issued/web/key.pem \\
23
+ --ca ca/public/ca.crt --crl ca/public/crl-bundle.pem
24
+
25
+
26
+ Run 'ezmtls-server COMMAND --help' for a command's options.
27
+ Docs: https://winuxnomacs.github.io/ezmtls/""",
28
+ )
29
+ @click.version_option(__version__, prog_name="ezmtls-server")
30
+ def main() -> None:
31
+ """Receive mTLS connections directly in Python.
32
+
33
+ Meant for a trusted network or behind a firewall, when nothing such as nginx can sit in front.
34
+ """
35
+
36
+
37
+ @main.command()
38
+ @click.option(
39
+ "--listen", default="127.0.0.1:9443", show_default=True, help="Address and port to listen on."
40
+ )
41
+ @click.option("--cert", required=True, type=_FILE, help="Server certificate chain (fullchain.pem).")
42
+ @click.option(
43
+ "--key",
44
+ type=_FILE,
45
+ help="Its private key, unless --cert holds it. If encrypted, the passphrase comes from"
46
+ " EZMTLS_KEY_PASSPHRASE or is prompted for.",
47
+ )
48
+ @click.option("--ca", required=True, type=_FILE, help="CA certificate that issues the clients.")
49
+ @click.option("--crl", type=_FILE, help="CRL bundle; reloaded when it changes.")
50
+ @click.option(
51
+ "--idle-timeout",
52
+ default=60.0,
53
+ show_default=True,
54
+ type=click.FloatRange(1),
55
+ help="Close a connection after this many seconds without data.",
56
+ )
57
+ def echo(
58
+ listen: str, cert: Path, key: Path | None, ca: Path, crl: Path | None, idle_timeout: float
59
+ ) -> None:
60
+ """Raw TCP mTLS echo server for testing non-HTTP clients.
61
+
62
+ Sends the verified client identity as one JSON line, then echoes each line back.
63
+ """
64
+ import logging
65
+
66
+ from ezmtls._net import bind
67
+ from ezmtls_server.echo import echo_server
68
+
69
+ logging.basicConfig(level="INFO", format="%(asctime)s %(levelname)s %(name)s: %(message)s")
70
+ host, port = address(listen, "--listen")
71
+ sock = bind(host, port) # a port in use fails before any passphrase prompt
72
+ try:
73
+ server = with_key_passphrase(
74
+ lambda passphrase: echo_server(
75
+ cert, key, ca=ca, crl=crl, key_passphrase=passphrase, idle_timeout=idle_timeout
76
+ ),
77
+ f"Passphrase for {key or cert}",
78
+ )
79
+ click.echo(f"echo server on {host}:{sock.getsockname()[1]}; Ctrl+C to stop", err=True)
80
+ server.run(sock=sock)
81
+ finally:
82
+ sock.close()
ezmtls_server/echo.py ADDED
@@ -0,0 +1,50 @@
1
+ """A raw TCP mTLS echo server, for testing applications that do not speak HTTP.
2
+
3
+ On connect it sends one JSON line with the verified client identity, then echoes every line it
4
+ receives. Built on TLSServer: its limits, reloads and stop behaviour apply.
5
+ """
6
+
7
+ import json
8
+
9
+ from ezmtls_server._base import Passphrase, StrPath
10
+ from ezmtls_server.tls import Connection, TLSServer
11
+
12
+ MAX_LINE = 64 * 1024
13
+
14
+
15
+ def echo_server(
16
+ cert: StrPath,
17
+ key: StrPath | None = None,
18
+ *,
19
+ ca: StrPath,
20
+ crl: StrPath | None = None,
21
+ key_passphrase: Passphrase | None = None,
22
+ idle_timeout: float = 60.0,
23
+ reload_interval: float = 5.0,
24
+ ) -> TLSServer:
25
+ """A TLSServer that greets each client with its identity as JSON, then echoes its lines."""
26
+ server = TLSServer(
27
+ cert,
28
+ key,
29
+ ca=ca,
30
+ crl=crl,
31
+ key_passphrase=key_passphrase,
32
+ idle_timeout=idle_timeout,
33
+ max_line=MAX_LINE,
34
+ reload_interval=reload_interval,
35
+ )
36
+
37
+ @server.handler
38
+ async def echo(conn: Connection) -> None:
39
+ who = conn.peer
40
+ hello = {
41
+ "name": who.name,
42
+ "role": who.role,
43
+ "subject": who.subject,
44
+ "serial": f"{who.serial:x}",
45
+ }
46
+ await conn.write(json.dumps(hello).encode() + b"\n")
47
+ while line := await conn.readline():
48
+ await conn.write(line)
49
+
50
+ return server
@@ -0,0 +1,23 @@
1
+ """Exceptions raised by ezmtls-server. All derive from `ezmtls.errors.EzmtlsError`."""
2
+
3
+ from ezmtls.errors import EzmtlsError
4
+
5
+ __all__ = ["HTTPError", "IdleTimeoutError", "LineTooLongError"]
6
+
7
+
8
+ class IdleTimeoutError(EzmtlsError, TimeoutError):
9
+ """The client sent nothing (or did not read what was sent) within the idle timeout."""
10
+
11
+
12
+ class LineTooLongError(EzmtlsError):
13
+ """The client sent a line longer than the server's `max_line`."""
14
+
15
+
16
+ class HTTPError(EzmtlsError):
17
+ """Raise it in an HTTPS handler to answer with `status` and `message` (as JSON
18
+ `{"error": message}`)."""
19
+
20
+ def __init__(self, status: int, message: str) -> None:
21
+ super().__init__(message)
22
+ self.status = status
23
+ self.message = message