Skip to content

Commit 8106a32

Browse files
James Boultonclaude
andcommitted
Device certificates: optional encrypted key with a passphrase hook
- DeviceCertificates(key_passphrase=...): a string, bytes, or a function called each time the key is loaded. Keys are written encrypted, and a key stored unencrypted is encrypted when first loaded with one. - The connection passes it to load_cert_chain. A key that can't be loaded, e.g. the passphrase isn't available, is retried with backoff, not treated as the server refusing the certificate. - docs/connections.md: supplying the passphrase from a systemd credential (systemd-creds, LoadCredentialEncrypted), and what that protects with and without a TPM. Tested on dash.dashio.io: a plain key encrypted on first load, then a certificate login with it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 5413c98 commit 8106a32

6 files changed

Lines changed: 186 additions & 28 deletions

File tree

‎CLAUDE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ Notes for working on python-dashio, the Python library for the DashIO protocol a
8989
- The DashConnection takes the certificate from its one device (a second device raises `ValueError`), and makes a new paho client when it changes login: client ID `d-<device_id>` and `tls_set_context` for port 8885, a random client ID for 8883, because the broker refuses `d-` client IDs on password logins.
9090
- A certificate not yet used to log in (PENDING, or a renewal) is checked first with a TLS handshake and a short read (`_check_certificate()`): with TLS 1.3 the broker refuses a client certificate with an alert after the handshake, which paho only reports as a lost connection. Refused: PENDING falls back to the password for an hour and reports 420; a renewal rolls back to the previous certificate. Unreachable: check again with backoff.
9191
- On the first certificate login the connection erases its password and `state_callback("CERT")` lets the program erase its copy. A new Dash login from the app (the DASHIO message, when the dashio callback accepts it) calls `reset()`: back to PASSWORD, keys deleted.
92+
- `key_passphrase` (a string, bytes, or a function called on each load) keeps the keys encrypted (PKCS8 `BestAvailableEncryption`); a plain key is encrypted when first loaded with one. The connection passes it to `load_cert_chain(password=)`. A key that can't be loaded is retried with backoff, never treated as a refusal. The docs recommend a systemd credential (`LoadCredentialEncrypted`) for the passphrase.
9293
- The DashIO Server CA is bundled as `dashio/certs/dashio-server-ca.crt` (package data). `cryptography` is a dependency.
9394
- **`DashStore` and history upload (SDU):** a port of the firmware's DashIO Storage Manager (`../zephyr-dashio-tally/port.md`, ESP-IDF port in `../dashesp/components/dashio_dsm`), using sqlite instead of a flash ring buffer.
9495
- `Device(..., store=DashStore(path))` gives every TimeGraph, EventLog and Map on the device the store (`control._store`). They record into it as well as their ring buffers, and answer the app's history requests from it.

‎dashio/dash_connection.py‎

Lines changed: 41 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
import zmq
3838

3939
from .constants import CONNECTION_PUB_URL
40+
from .device_certificates import DeviceCertificates
4041
from .iotcontrol.enums import ConnectionState
4142

4243
logger = logging.getLogger(__name__)
@@ -381,17 +382,30 @@ def _connect(self):
381382
"""Start paho's network thread, which connects and reconnects if the connection fails or is lost."""
382383
certificates = self._certificates
383384
use_certificate = certificates is not None and certificates.use_certificate()
384-
if use_certificate and certificates.needs_check():
385-
result = self._check_certificate()
385+
tls_context = None
386+
if use_certificate:
387+
try:
388+
tls_context = self._certificate_tls_context()
389+
except Exception as error: # pylint: disable=broad-except
390+
# Not the server's refusal: e.g. the key's passphrase isn't available. Try again later.
391+
logger.error("The device certificate can't be loaded: %s", error)
392+
self._try_again_later()
393+
return
394+
if certificates is not None and tls_context is not None and certificates.needs_check():
395+
result = self._check_certificate(tls_context)
386396
if result == "refused":
387397
certificates.refused()
388398
use_certificate = certificates.use_certificate()
399+
tls_context = None
400+
if use_certificate:
401+
try:
402+
tls_context = self._certificate_tls_context() # Rolled back to the previous certificate.
403+
except Exception as error: # pylint: disable=broad-except
404+
logger.error("The device certificate can't be loaded: %s", error)
405+
self._try_again_later()
406+
return
389407
elif result == "failed":
390-
# The server can't be reached: check again later, waiting twice as long each time.
391-
self._check_wait = min(max(self._check_wait * 2, 1.0), RECONNECT_MAX_DELAY)
392-
self._connect_at = time.monotonic() + self._check_wait
393-
if self.connection_state == ConnectionState.DISCONNECTED:
394-
self.connection_state = ConnectionState.CONNECTING
408+
self._try_again_later()
395409
return
396410
if use_certificate:
397411
# The topics are still under the owner's username. The password isn't needed.
@@ -402,7 +416,7 @@ def _connect(self):
402416
logger.warning("Not connecting to the Dash server without a username and password")
403417
return
404418
logger.debug("Connecting%s..", " with the device certificate" if use_certificate else "")
405-
self._use_client(use_certificate)
419+
self._use_client(tls_context)
406420
self._set_will()
407421
properties = None
408422
if self.offline_delay > 0:
@@ -420,23 +434,28 @@ def _connect(self):
420434

421435
def _certificate_tls_context(self) -> ssl.SSLContext:
422436
"""TLS for port 8885: check the server against the DashIO Server CA, and present the device's certificate."""
423-
context = ssl.create_default_context(cafile=self._certificates.ca_path)
437+
certificates = self._certificates
438+
if certificates is None:
439+
raise ValueError("No device certificate")
440+
context = ssl.create_default_context(cafile=certificates.ca_path)
424441
context.minimum_version = ssl.TLSVersion.TLSv1_2
425-
context.load_cert_chain(self._certificates.cert_path, self._certificates.key_path)
442+
context.load_cert_chain(certificates.cert_path, certificates.key_path, password=certificates.key_passphrase())
426443
return context
427444

428-
def _check_certificate(self) -> str:
445+
def _try_again_later(self):
446+
"""Connect again later, waiting twice as long each time, e.g. when the server can't be reached."""
447+
self._check_wait = min(max(self._check_wait * 2, 1.0), RECONNECT_MAX_DELAY)
448+
self._connect_at = time.monotonic() + self._check_wait
449+
if self.connection_state == ConnectionState.DISCONNECTED:
450+
self.connection_state = ConnectionState.CONNECTING
451+
452+
def _check_certificate(self, context: ssl.SSLContext) -> str:
429453
"""Check that the server accepts a certificate that hasn't been used to log in yet.
430454
431455
With TLS 1.3 the server refuses a client certificate after the handshake, with an alert that paho only
432456
reports as a lost connection, so a refusal couldn't be told from a network failure. Returns "accepted",
433457
"refused", or "failed" when the server couldn't be reached.
434458
"""
435-
try:
436-
context = self._certificate_tls_context()
437-
except (OSError, ssl.SSLError) as error:
438-
logger.warning("The device certificate can't be loaded: %s", error)
439-
return "refused"
440459
try:
441460
with socket.create_connection((self.host, self.cert_port), timeout=10) as sock:
442461
with context.wrap_socket(sock, server_hostname=self.host) as tls:
@@ -478,17 +497,17 @@ def _new_client(self, client_id: str = "", tls_context: ssl.SSLContext | None =
478497
client.reconnect_delay_set(1, CERT_RECONNECT_MAX_DELAY if tls_context is not None else RECONNECT_MAX_DELAY)
479498
return client
480499

481-
def _use_client(self, use_certificate: bool):
500+
def _use_client(self, tls_context: ssl.SSLContext | None):
482501
"""Make a new MQTT client when changing between the password and the certificate login. The broker sets a
483502
certificate login's client ID to d-<device id>, and refuses a password login whose client ID starts with d-."""
484-
if not use_certificate and not self._certificate_login:
503+
if tls_context is None and not self._certificate_login:
485504
return
486505
self._dash_c.loop_stop()
487-
if use_certificate:
488-
self._dash_c = self._new_client(f"d-{self._device_id_list[0]}", self._certificate_tls_context())
506+
if tls_context is not None:
507+
self._dash_c = self._new_client(f"d-{self._device_id_list[0]}", tls_context)
489508
else:
490509
self._dash_c = self._new_client()
491-
self._certificate_login = use_certificate
510+
self._certificate_login = tls_context is not None
492511

493512
def _login_again(self):
494513
"""Disconnect and connect again, e.g. with a new certificate."""
@@ -594,7 +613,7 @@ def __init__(
594613
self.port = port
595614
self.cert_port = cert_port
596615
self.use_ssl = use_ssl
597-
self._certificates = None # The device's DeviceCertificates, if it has them.
616+
self._certificates: DeviceCertificates | None = None # The device's DeviceCertificates, if it has them.
598617
self._certificate_login = False # Whether _dash_c logs in with the device certificate.
599618
self._check_wait = 0.0
600619
self._dash_c = self._new_client()

‎dashio/device_certificates.py‎

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -131,14 +131,28 @@ class DeviceCertificates:
131131
state_callback : Callable[[str], None], optional
132132
Called with the new state, "PASSWORD", "PENDING" or "CERT", when it changes. On CERT, erase the stored Dash
133133
password: a device that kept it would fall back to it when its certificate is revoked.
134+
key_passphrase : str | bytes | Callable[[], str | bytes], optional
135+
Keep the private key encrypted with this passphrase. A function is called each time the key is loaded, so
136+
the passphrase can come from somewhere other than the device's disk, e.g. a systemd credential. A trailing
137+
newline is ignored. A key stored unencrypted is encrypted when it's first loaded with a passphrase. Without
138+
the passphrase the key can't be used, and the device needs a new certificate. Defaults to None: the key is
139+
protected only by the file's permissions.
134140
"""
135141

136-
def __init__(self, path: str, auto_issue: bool = True, ca_file: str | None = None, state_callback: Callable[[str], None] | None = None):
142+
def __init__(
143+
self,
144+
path: str,
145+
auto_issue: bool = True,
146+
ca_file: str | None = None,
147+
state_callback: Callable[[str], None] | None = None,
148+
key_passphrase: str | bytes | Callable[[], str | bytes] | None = None
149+
):
137150
self.path = Path(path)
138151
self.path.mkdir(mode=0o700, parents=True, exist_ok=True)
139152
self.auto_issue = auto_issue
140153
self._ca_file = ca_file
141154
self.state_callback = state_callback
155+
self._key_passphrase = key_passphrase
142156
self.device_id = "" # Set by the Device.
143157
self._lock = threading.RLock()
144158
self._changed = False # The key or certificate changed, so the connection logs in again.
@@ -182,11 +196,41 @@ def _save_state(self):
182196
}
183197
self._write(STATE_FILE, json.dumps(state).encode())
184198

199+
def key_passphrase(self) -> bytes | None:
200+
"""The key's passphrase, or None if the key isn't encrypted. Raises whatever the passphrase function raises."""
201+
passphrase = self._key_passphrase() if callable(self._key_passphrase) else self._key_passphrase
202+
if passphrase is None:
203+
return None
204+
if isinstance(passphrase, str):
205+
passphrase = passphrase.encode()
206+
passphrase = passphrase.rstrip(b"\r\n")
207+
if not passphrase:
208+
raise ValueError("The key passphrase is empty")
209+
return passphrase
210+
211+
def _key_bytes(self, key) -> bytes:
212+
"""The key as PEM, encrypted with the passphrase if there is one."""
213+
passphrase = self.key_passphrase()
214+
encryption = serialization.BestAvailableEncryption(passphrase) if passphrase else serialization.NoEncryption()
215+
return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, encryption)
216+
185217
def _load_key(self, name: str):
186218
try:
187-
return serialization.load_pem_private_key(self._file(name).read_bytes(), password=None)
188-
except (OSError, ValueError, TypeError):
219+
data = self._file(name).read_bytes()
220+
except OSError:
189221
return None
222+
encrypted = data.startswith(b"-----BEGIN ENCRYPTED PRIVATE KEY-----")
223+
try:
224+
passphrase = self.key_passphrase()
225+
if encrypted and passphrase is None:
226+
raise ValueError("the key is encrypted, and there's no key_passphrase")
227+
key = serialization.load_pem_private_key(data, password=passphrase if encrypted else None)
228+
except Exception as error: # pylint: disable=broad-except
229+
logger.error("The device key %s can't be loaded: %s", name, error)
230+
return None
231+
if passphrase is not None and not encrypted:
232+
self._write(name, self._key_bytes(key)) # Encrypt a key stored before there was a passphrase.
233+
return key
190234

191235
def _load_cert(self, name: str = CERT_FILE) -> x509.Certificate | None:
192236
try:
@@ -419,8 +463,8 @@ def make_csr(self, key_type: str = "EC-P256", new_key: bool = False) -> str:
419463
except Exception as error: # pylint: disable=broad-except
420464
raise CertificateError(CRT_KEYGEN_ERR, str(error)) from error
421465
try:
422-
self._write(NEW_KEY_FILE, key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
423-
except OSError as error:
466+
self._write(NEW_KEY_FILE, self._key_bytes(key))
467+
except Exception as error: # pylint: disable=broad-except
424468
raise CertificateError(CRT_STORE_ERR, str(error)) from error
425469
try:
426470
csr = (

‎docs/connections.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,48 @@ dash.add_device(device)
9797
- The server's certificate on port 8885 is checked against the DashIO Server CA, which comes with the library.
9898
- `certificates.state` and `certificates.info()` give the state and the certificate's serial number and expiry. The Dash app can also read them, and provision a certificate, over any connection.
9999

100+
#### Encrypting the key
101+
102+
By default the private key is protected only by its file's permissions: root, or anyone with the device's disk, can read it. `key_passphrase` keeps it encrypted, with a passphrase from somewhere else:
103+
104+
```python
105+
certificates = dashio.DeviceCertificates("certs", key_passphrase=get_passphrase)
106+
```
107+
108+
`key_passphrase` is a string, bytes, or a function returning one, called each time the key is loaded. A trailing newline is ignored. A key already stored unencrypted is encrypted the first time it's loaded with a passphrase. If the passphrase isn't available, the connection logs an error and tries again later, waiting twice as long each time; it doesn't count as the server refusing the certificate. If it's lost, the key can't be used again, and the device needs a new certificate, e.g. by setting its Dash login again from the app.
109+
110+
On Linux, run the device as a systemd service (systemd 250 or later, e.g. Raspberry Pi OS Bookworm) and keep the passphrase as an encrypted systemd credential. Make the passphrase and encrypt it:
111+
112+
```bash
113+
sudo mkdir -p -m 0700 /etc/credstore.encrypted
114+
openssl rand -base64 32 | sudo systemd-creds encrypt --name=dashio-key - /etc/credstore.encrypted/dashio-key
115+
```
116+
117+
Give it to the service, in its unit file:
118+
119+
```ini
120+
[Service]
121+
LoadCredentialEncrypted=dashio-key:/etc/credstore.encrypted/dashio-key
122+
```
123+
124+
systemd decrypts it when the service starts, into a directory only the service can read:
125+
126+
```python
127+
import os
128+
129+
130+
def get_passphrase() -> str:
131+
with open(os.path.join(os.environ["CREDENTIALS_DIRECTORY"], "dashio-key"), encoding="utf-8") as file:
132+
return file.read()
133+
```
134+
135+
How much this protects depends on the hardware:
136+
137+
- **With a TPM** (`systemd-creds has-tpm2`), the credential is sealed to the TPM. Copying the disk to another machine gets neither the passphrase nor the key. Add `--with-key=tpm2` to `systemd-creds encrypt` to refuse to make it without one.
138+
- **Without a TPM**, as on a Raspberry Pi, it's sealed with a key in `/var/lib/systemd/credential.secret`, readable only by root. The key file can't be used by other users, or from a copy of the program's directory or a backup of it, but someone with root or the whole disk can still decrypt it. Full disk encryption adds to this.
139+
140+
Either way, revoking the device in the Dash app cuts off a stolen key.
141+
100142
## TCPConnection
101143

102144
```python

‎skills/python-dashio/SKILL.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ while True:
141141
- **Receive callbacks can reply:** a callback's returned string is sent back to the app.
142142
- **Through the Dash server**, control updates are only published while a Dash app is watching the device (`app_timeout`, 120 s by default); replies, alarms and history always go. A device that seems silent with the app closed is working as designed.
143143
- History for TimeGraph, EventLog and Map: `Device(..., store=dashio.DashStore(path))` keeps it in sqlite and answers the app's history requests. See [storage.md](https://github.com/dashio-connect/python-dashio/blob/master/docs/storage.md).
144-
- **Device certificates:** `Device(..., certificates=dashio.DeviceCertificates(path, state_callback=...))` logs in to the Dash server on port 8885 with the device's own certificate. The device gets one from the server over its password login, then erases the password once the certificate has worked (state `CERT`; erase the stored copy in `state_callback`). A DashConnection with certificates has one device. See [connections.md](https://github.com/dashio-connect/python-dashio/blob/master/docs/connections.md#device-certificates).
144+
- **Device certificates:** `Device(..., certificates=dashio.DeviceCertificates(path, state_callback=...))` logs in to the Dash server on port 8885 with the device's own certificate. The device gets one from the server over its password login, then erases the password once the certificate has worked (state `CERT`; erase the stored copy in `state_callback`). A DashConnection with certificates has one device. `key_passphrase=` keeps the key encrypted; on Linux, supply it from a systemd credential. See [connections.md](https://github.com/dashio-connect/python-dashio/blob/master/docs/connections.md#device-certificates).
145145
- To start a line, track or log again on the device and the Dash server (factory reset, sensor swapped): `control.delete_history()`. For a Map marker that only shows the current position: `map.add_track(dashio.MapTrack("pos", "Here", replace=True))`.
146146

147147
## When the app doesn't show what you expect

0 commit comments

Comments
 (0)