ezmtls 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-1.0.0/LICENSE +21 -0
- ezmtls-1.0.0/PKG-INFO +65 -0
- ezmtls-1.0.0/README.md +39 -0
- ezmtls-1.0.0/pyproject.toml +46 -0
- ezmtls-1.0.0/pyproject.toml.orig +39 -0
- ezmtls-1.0.0/src/ezmtls/__init__.py +10 -0
- ezmtls-1.0.0/src/ezmtls/_cli.py +93 -0
- ezmtls-1.0.0/src/ezmtls/_files.py +95 -0
- ezmtls-1.0.0/src/ezmtls/_net.py +21 -0
- ezmtls-1.0.0/src/ezmtls/_x509.py +85 -0
- ezmtls-1.0.0/src/ezmtls/cli.py +366 -0
- ezmtls-1.0.0/src/ezmtls/crl.py +246 -0
- ezmtls-1.0.0/src/ezmtls/errors.py +52 -0
- ezmtls-1.0.0/src/ezmtls/est.py +376 -0
- ezmtls-1.0.0/src/ezmtls/probe.py +205 -0
- ezmtls-1.0.0/src/ezmtls/py.typed +0 -0
- ezmtls-1.0.0/src/ezmtls/renew.py +181 -0
- ezmtls-1.0.0/src/ezmtls/requests_adapter.py +62 -0
- ezmtls-1.0.0/src/ezmtls/tls.py +402 -0
ezmtls-1.0.0/LICENSE
ADDED
|
@@ -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.
|
ezmtls-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ezmtls
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Mutual TLS made easy, client side: SSL contexts with client certificates, peer identities for servers, and a connection tester.
|
|
5
|
+
Keywords: mtls,tls,x509,client-certificates,ssl
|
|
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
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Dist: click>=8.5.1
|
|
18
|
+
Requires-Dist: cryptography>=50.0.2
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Project-URL: Homepage, https://winuxnomacs.github.io/ezmtls/
|
|
21
|
+
Project-URL: Documentation, https://winuxnomacs.github.io/ezmtls/
|
|
22
|
+
Project-URL: Source, https://github.com/WinuxNomacs/ezmtls
|
|
23
|
+
Project-URL: Changelog, https://github.com/WinuxNomacs/ezmtls/blob/main/CHANGELOG.md
|
|
24
|
+
Project-URL: Issues, https://github.com/WinuxNomacs/ezmtls/issues
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# ezmtls
|
|
28
|
+
|
|
29
|
+
Said "easy mTLS". Mutual TLS for your Python application, client side: an `ssl.SSLContext` with your
|
|
30
|
+
client certificate for any HTTP library, the verified identity of whoever connected to your server, and
|
|
31
|
+
a command to test any mTLS endpoint.
|
|
32
|
+
|
|
33
|
+
**Documentation: https://winuxnomacs.github.io/ezmtls/**
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
pip install ezmtls
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import httpx
|
|
41
|
+
|
|
42
|
+
from ezmtls.tls import client_context
|
|
43
|
+
|
|
44
|
+
ctx = client_context("alice.pem", ca="ca.crt") # or ("fullchain.pem", "key.pem", ca=...), or a .p12
|
|
45
|
+
with httpx.Client(verify=ctx) as client:
|
|
46
|
+
client.get("https://api.internal:8443/")
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
- **Clients:** httpx, aiohttp, asyncio and requests (`ezmtls.requests_adapter.MTLSAdapter`). The context
|
|
50
|
+
trusts only your CA, checks the server's name and requires TLS 1.3.
|
|
51
|
+
- **Servers:** `server_context` requires client certificates from your CA (with CRL checks), and
|
|
52
|
+
`peer_identity` / `peer_identity_from_headers` tell you who connected, directly or behind nginx.
|
|
53
|
+
- **Getting certificates:** an EST (RFC 7030) client, `ezmtls.est.ESTClient` and `ezmtls est enroll |
|
|
54
|
+
renew | cacerts`, gets and renews certificates from the CA service with the key made on the device;
|
|
55
|
+
`ezmtls.renew.Renewer` and `ezmtls est keep` renew automatically before expiry.
|
|
56
|
+
- **Revoked servers:** `ezmtls.crl.CRLCache` keeps the CA's CRLs fresh on the client (signature and
|
|
57
|
+
rollback checked) and refuses revoked servers; `on_stale` chooses what happens if they expire.
|
|
58
|
+
- **Testing:** `ezmtls connect https://host:port/ --cert alice.pem --ca ca.crt` shows the TLS session,
|
|
59
|
+
the server certificate and the response, or says plainly why it failed.
|
|
60
|
+
|
|
61
|
+
Its companions:
|
|
62
|
+
- [ezcerts](https://pypi.org/project/ezcerts/) runs the CA that issues the certificates;
|
|
63
|
+
- [ezmtls-server](https://pypi.org/project/ezmtls-server/) receives mTLS connections directly in Python.
|
|
64
|
+
|
|
65
|
+
Python 3.12 or later, on Linux, macOS and Windows. MIT licence.
|
ezmtls-1.0.0/README.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# ezmtls
|
|
2
|
+
|
|
3
|
+
Said "easy mTLS". Mutual TLS for your Python application, client side: an `ssl.SSLContext` with your
|
|
4
|
+
client certificate for any HTTP library, the verified identity of whoever connected to your server, and
|
|
5
|
+
a command to test any mTLS endpoint.
|
|
6
|
+
|
|
7
|
+
**Documentation: https://winuxnomacs.github.io/ezmtls/**
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
pip install ezmtls
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from ezmtls.tls import client_context
|
|
17
|
+
|
|
18
|
+
ctx = client_context("alice.pem", ca="ca.crt") # or ("fullchain.pem", "key.pem", ca=...), or a .p12
|
|
19
|
+
with httpx.Client(verify=ctx) as client:
|
|
20
|
+
client.get("https://api.internal:8443/")
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
- **Clients:** httpx, aiohttp, asyncio and requests (`ezmtls.requests_adapter.MTLSAdapter`). The context
|
|
24
|
+
trusts only your CA, checks the server's name and requires TLS 1.3.
|
|
25
|
+
- **Servers:** `server_context` requires client certificates from your CA (with CRL checks), and
|
|
26
|
+
`peer_identity` / `peer_identity_from_headers` tell you who connected, directly or behind nginx.
|
|
27
|
+
- **Getting certificates:** an EST (RFC 7030) client, `ezmtls.est.ESTClient` and `ezmtls est enroll |
|
|
28
|
+
renew | cacerts`, gets and renews certificates from the CA service with the key made on the device;
|
|
29
|
+
`ezmtls.renew.Renewer` and `ezmtls est keep` renew automatically before expiry.
|
|
30
|
+
- **Revoked servers:** `ezmtls.crl.CRLCache` keeps the CA's CRLs fresh on the client (signature and
|
|
31
|
+
rollback checked) and refuses revoked servers; `on_stale` chooses what happens if they expire.
|
|
32
|
+
- **Testing:** `ezmtls connect https://host:port/ --cert alice.pem --ca ca.crt` shows the TLS session,
|
|
33
|
+
the server certificate and the response, or says plainly why it failed.
|
|
34
|
+
|
|
35
|
+
Its companions:
|
|
36
|
+
- [ezcerts](https://pypi.org/project/ezcerts/) runs the CA that issues the certificates;
|
|
37
|
+
- [ezmtls-server](https://pypi.org/project/ezmtls-server/) receives mTLS connections directly in Python.
|
|
38
|
+
|
|
39
|
+
Python 3.12 or later, on Linux, macOS and Windows. MIT licence.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ezmtls"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Mutual TLS made easy, client side: SSL contexts with client certificates, peer identities for servers, and a connection tester."
|
|
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",
|
|
16
|
+
"Typing :: Typed",
|
|
17
|
+
]
|
|
18
|
+
keywords = [
|
|
19
|
+
"mtls",
|
|
20
|
+
"tls",
|
|
21
|
+
"x509",
|
|
22
|
+
"client-certificates",
|
|
23
|
+
"ssl",
|
|
24
|
+
]
|
|
25
|
+
dependencies = [
|
|
26
|
+
"click>=8.5.1",
|
|
27
|
+
"cryptography>=50.0.2",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[[project.authors]]
|
|
31
|
+
name = "Winux Nomacs"
|
|
32
|
+
email = "WinuxNomacs@users.noreply.github.com"
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://winuxnomacs.github.io/ezmtls/"
|
|
36
|
+
Documentation = "https://winuxnomacs.github.io/ezmtls/"
|
|
37
|
+
Source = "https://github.com/WinuxNomacs/ezmtls"
|
|
38
|
+
Changelog = "https://github.com/WinuxNomacs/ezmtls/blob/main/CHANGELOG.md"
|
|
39
|
+
Issues = "https://github.com/WinuxNomacs/ezmtls/issues"
|
|
40
|
+
|
|
41
|
+
[project.scripts]
|
|
42
|
+
ezmtls = "ezmtls.cli:main"
|
|
43
|
+
|
|
44
|
+
[build-system]
|
|
45
|
+
requires = ["uv_build==0.12.3"]
|
|
46
|
+
build-backend = "uv_build"
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ezmtls"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Mutual TLS made easy, client side: SSL contexts with client certificates, peer identities for servers, and a connection tester."
|
|
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",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
keywords = ["mtls", "tls", "x509", "client-certificates", "ssl"]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"click>=8.5.1",
|
|
24
|
+
"cryptography>=50.0.2",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://winuxnomacs.github.io/ezmtls/"
|
|
29
|
+
Documentation = "https://winuxnomacs.github.io/ezmtls/"
|
|
30
|
+
Source = "https://github.com/WinuxNomacs/ezmtls"
|
|
31
|
+
Changelog = "https://github.com/WinuxNomacs/ezmtls/blob/main/CHANGELOG.md"
|
|
32
|
+
Issues = "https://github.com/WinuxNomacs/ezmtls/issues"
|
|
33
|
+
|
|
34
|
+
[project.scripts]
|
|
35
|
+
ezmtls = "ezmtls.cli:main"
|
|
36
|
+
|
|
37
|
+
[build-system]
|
|
38
|
+
requires = ["uv_build==0.12.3"]
|
|
39
|
+
build-backend = "uv_build"
|
|
@@ -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"]
|
|
@@ -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)
|
|
@@ -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)
|
|
@@ -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
|
|
@@ -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)
|