ezmtls-server 1.0.0__tar.gz
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_server-1.0.0/LICENSE +21 -0
- ezmtls_server-1.0.0/PKG-INFO +92 -0
- ezmtls_server-1.0.0/README.md +64 -0
- ezmtls_server-1.0.0/pyproject.toml +48 -0
- ezmtls_server-1.0.0/pyproject.toml.orig +41 -0
- ezmtls_server-1.0.0/src/ezmtls_server/__init__.py +11 -0
- ezmtls_server-1.0.0/src/ezmtls_server/_base.py +371 -0
- ezmtls_server-1.0.0/src/ezmtls_server/cli.py +82 -0
- ezmtls_server-1.0.0/src/ezmtls_server/echo.py +50 -0
- ezmtls_server-1.0.0/src/ezmtls_server/errors.py +23 -0
- ezmtls_server-1.0.0/src/ezmtls_server/https.py +546 -0
- ezmtls_server-1.0.0/src/ezmtls_server/py.typed +0 -0
- ezmtls_server-1.0.0/src/ezmtls_server/tls.py +179 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Winux Nomacs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ezmtls-server
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Receive mutual TLS connections directly in Python (raw TLS and HTTPS handlers), for when nothing such as nginx can sit in front.
|
|
5
|
+
Keywords: mtls,tls,server,client-certificates,asyncio
|
|
6
|
+
Author: Winux Nomacs
|
|
7
|
+
Author-email: Winux Nomacs <WinuxNomacs@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Security :: Cryptography
|
|
15
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Dist: click>=8.5.1
|
|
18
|
+
Requires-Dist: cryptography>=50.0.2
|
|
19
|
+
Requires-Dist: ezmtls>=1.0.0
|
|
20
|
+
Requires-Dist: h11>=0.16.0
|
|
21
|
+
Requires-Python: >=3.12
|
|
22
|
+
Project-URL: Homepage, https://winuxnomacs.github.io/ezmtls/
|
|
23
|
+
Project-URL: Documentation, https://winuxnomacs.github.io/ezmtls/
|
|
24
|
+
Project-URL: Source, https://github.com/WinuxNomacs/ezmtls
|
|
25
|
+
Project-URL: Changelog, https://github.com/WinuxNomacs/ezmtls/blob/main/CHANGELOG.md
|
|
26
|
+
Project-URL: Issues, https://github.com/WinuxNomacs/ezmtls/issues
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# ezmtls-server
|
|
30
|
+
|
|
31
|
+
Receive mutual TLS connections directly in Python, for when nothing such as nginx can sit in front of
|
|
32
|
+
your application. Part of the ezmtls family.
|
|
33
|
+
|
|
34
|
+
**Documentation: https://winuxnomacs.github.io/ezmtls/**
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
pip install ezmtls-server
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Use it on a trusted network or behind a firewall. When you can put nginx in front of your app, prefer that
|
|
41
|
+
(`ezcerts nginx` generates the configuration).
|
|
42
|
+
|
|
43
|
+
HTTPS handlers, plain or `async` functions, with the client's verified identity in `req.peer`:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from ezmtls_server import HTTPSServer, Request
|
|
47
|
+
|
|
48
|
+
server = HTTPSServer("fullchain.pem", "key.pem", ca="ca.crt", crl="crl-bundle.pem")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@server.post("/readings")
|
|
52
|
+
def store(req: Request) -> dict[str, object]:
|
|
53
|
+
save(req.peer.name, req.json()) # your code
|
|
54
|
+
return {"ok": True}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
server.run("127.0.0.1:8443")
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Raw TLS handlers, for protocols other than HTTP:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from ezmtls_server import Connection, TLSServer
|
|
64
|
+
|
|
65
|
+
server = TLSServer("fullchain.pem", "key.pem", ca="ca.crt", crl="crl-bundle.pem")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@server.handler
|
|
69
|
+
async def handle(conn: Connection) -> None:
|
|
70
|
+
await conn.write(f"hello {conn.peer.name}\n".encode()) # the client's verified identity
|
|
71
|
+
while line := await conn.readline():
|
|
72
|
+
await conn.write(line)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
server.run("127.0.0.1:9443")
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Built in: TLS 1.3 with client certificates required, deadlines for the handshake and every read and
|
|
79
|
+
write, a connection limit, certificate and CRL reloading, warnings before the CRL expires, and a
|
|
80
|
+
graceful stop on Ctrl+C. HTTPS answers every request, malformed or not, with a proper status.
|
|
81
|
+
|
|
82
|
+
`ezmtls-server echo` is a ready-made raw TLS test server: it greets each client with its identity and
|
|
83
|
+
echoes lines back.
|
|
84
|
+
|
|
85
|
+
```
|
|
86
|
+
ezmtls-server echo --cert fullchain.pem --key key.pem --ca ca.crt --crl crl-bundle.pem
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Certificates come from [ezcerts](https://pypi.org/project/ezcerts/) (or any CA); clients connect with
|
|
90
|
+
[ezmtls](https://pypi.org/project/ezmtls/).
|
|
91
|
+
|
|
92
|
+
Python 3.12 or later, on Linux, macOS and Windows. MIT licence.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# ezmtls-server
|
|
2
|
+
|
|
3
|
+
Receive mutual TLS connections directly in Python, for when nothing such as nginx can sit in front of
|
|
4
|
+
your application. Part of the ezmtls family.
|
|
5
|
+
|
|
6
|
+
**Documentation: https://winuxnomacs.github.io/ezmtls/**
|
|
7
|
+
|
|
8
|
+
```
|
|
9
|
+
pip install ezmtls-server
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Use it on a trusted network or behind a firewall. When you can put nginx in front of your app, prefer that
|
|
13
|
+
(`ezcerts nginx` generates the configuration).
|
|
14
|
+
|
|
15
|
+
HTTPS handlers, plain or `async` functions, with the client's verified identity in `req.peer`:
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from ezmtls_server import HTTPSServer, Request
|
|
19
|
+
|
|
20
|
+
server = HTTPSServer("fullchain.pem", "key.pem", ca="ca.crt", crl="crl-bundle.pem")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@server.post("/readings")
|
|
24
|
+
def store(req: Request) -> dict[str, object]:
|
|
25
|
+
save(req.peer.name, req.json()) # your code
|
|
26
|
+
return {"ok": True}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
server.run("127.0.0.1:8443")
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Raw TLS handlers, for protocols other than HTTP:
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from ezmtls_server import Connection, TLSServer
|
|
36
|
+
|
|
37
|
+
server = TLSServer("fullchain.pem", "key.pem", ca="ca.crt", crl="crl-bundle.pem")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@server.handler
|
|
41
|
+
async def handle(conn: Connection) -> None:
|
|
42
|
+
await conn.write(f"hello {conn.peer.name}\n".encode()) # the client's verified identity
|
|
43
|
+
while line := await conn.readline():
|
|
44
|
+
await conn.write(line)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
server.run("127.0.0.1:9443")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Built in: TLS 1.3 with client certificates required, deadlines for the handshake and every read and
|
|
51
|
+
write, a connection limit, certificate and CRL reloading, warnings before the CRL expires, and a
|
|
52
|
+
graceful stop on Ctrl+C. HTTPS answers every request, malformed or not, with a proper status.
|
|
53
|
+
|
|
54
|
+
`ezmtls-server echo` is a ready-made raw TLS test server: it greets each client with its identity and
|
|
55
|
+
echoes lines back.
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
ezmtls-server echo --cert fullchain.pem --key key.pem --ca ca.crt --crl crl-bundle.pem
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Certificates come from [ezcerts](https://pypi.org/project/ezcerts/) (or any CA); clients connect with
|
|
62
|
+
[ezmtls](https://pypi.org/project/ezmtls/).
|
|
63
|
+
|
|
64
|
+
Python 3.12 or later, on Linux, macOS and Windows. MIT licence.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ezmtls-server"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Receive mutual TLS connections directly in Python (raw TLS and HTTPS handlers), for when nothing such as nginx can sit in front."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.12"
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 4 - Beta",
|
|
11
|
+
"Intended Audience :: Developers",
|
|
12
|
+
"Operating System :: OS Independent",
|
|
13
|
+
"Programming Language :: Python :: 3",
|
|
14
|
+
"Topic :: Security :: Cryptography",
|
|
15
|
+
"Topic :: Internet :: WWW/HTTP :: HTTP Servers",
|
|
16
|
+
"Typing :: Typed",
|
|
17
|
+
]
|
|
18
|
+
keywords = [
|
|
19
|
+
"mtls",
|
|
20
|
+
"tls",
|
|
21
|
+
"server",
|
|
22
|
+
"client-certificates",
|
|
23
|
+
"asyncio",
|
|
24
|
+
]
|
|
25
|
+
dependencies = [
|
|
26
|
+
"click>=8.5.1",
|
|
27
|
+
"cryptography>=50.0.2",
|
|
28
|
+
"ezmtls>=1.0.0",
|
|
29
|
+
"h11>=0.16.0",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[[project.authors]]
|
|
33
|
+
name = "Winux Nomacs"
|
|
34
|
+
email = "WinuxNomacs@users.noreply.github.com"
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://winuxnomacs.github.io/ezmtls/"
|
|
38
|
+
Documentation = "https://winuxnomacs.github.io/ezmtls/"
|
|
39
|
+
Source = "https://github.com/WinuxNomacs/ezmtls"
|
|
40
|
+
Changelog = "https://github.com/WinuxNomacs/ezmtls/blob/main/CHANGELOG.md"
|
|
41
|
+
Issues = "https://github.com/WinuxNomacs/ezmtls/issues"
|
|
42
|
+
|
|
43
|
+
[project.scripts]
|
|
44
|
+
ezmtls-server = "ezmtls_server.cli:main"
|
|
45
|
+
|
|
46
|
+
[build-system]
|
|
47
|
+
requires = ["uv_build==0.12.3"]
|
|
48
|
+
build-backend = "uv_build"
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ezmtls-server"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Receive mutual TLS connections directly in Python (raw TLS and HTTPS handlers), for when nothing such as nginx can sit in front."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "Winux Nomacs", email = "WinuxNomacs@users.noreply.github.com" }
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.12"
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 4 - Beta",
|
|
14
|
+
"Intended Audience :: Developers",
|
|
15
|
+
"Operating System :: OS Independent",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Topic :: Security :: Cryptography",
|
|
18
|
+
"Topic :: Internet :: WWW/HTTP :: HTTP Servers",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
keywords = ["mtls", "tls", "server", "client-certificates", "asyncio"]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"click>=8.5.1",
|
|
24
|
+
"cryptography>=50.0.2",
|
|
25
|
+
"ezmtls>=1.0.0",
|
|
26
|
+
"h11>=0.16.0",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://winuxnomacs.github.io/ezmtls/"
|
|
31
|
+
Documentation = "https://winuxnomacs.github.io/ezmtls/"
|
|
32
|
+
Source = "https://github.com/WinuxNomacs/ezmtls"
|
|
33
|
+
Changelog = "https://github.com/WinuxNomacs/ezmtls/blob/main/CHANGELOG.md"
|
|
34
|
+
Issues = "https://github.com/WinuxNomacs/ezmtls/issues"
|
|
35
|
+
|
|
36
|
+
[project.scripts]
|
|
37
|
+
ezmtls-server = "ezmtls_server.cli:main"
|
|
38
|
+
|
|
39
|
+
[build-system]
|
|
40
|
+
requires = ["uv_build==0.12.3"]
|
|
41
|
+
build-backend = "uv_build"
|
|
@@ -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__"]
|
|
@@ -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")
|