Repository navigation
Add a certificate-capable DTLS client that can offer max_fragment_length - #129
QuiteYellow wants to merge 9 commits into
Conversation
The record layer, the handshake reassembler, the cookie exchange and the retransmission timer are identical whatever credential a session carries, and every defect fixed in them has been fixed once. A second engine for the certificate path would have duplicated exactly the code those fixes live in: the insert-only reassembly cap (#125), the repeated-HelloVerifyRequest answer whose absence is the shape localthings#504 describes, the ordering in recv() that hands back buffered data ahead of a stored failure (#125), and the uint48 record sequence. So the shared half moves to _dtls_base._DtlsClientBase, and _dtls_psk keeps the PSK half: the ciphersuite, the CBC transform, the ServerKeyExchange parse and the client flight. A subclass supplies the offered suites, the hello extensions, the client flight, and any handshake message the shared state machine leaves to it. This is a move. The ranges were lifted out of the file by script, so the moved code is byte-identical, and the names the record-layer and hostile-input tests reach for are re-exported from _dtls_psk so their imports stand. The PSK path should behave as it did. It is hardware-validated on @KRZ303's oven and it carries the engine's whole test suite, so the evidence is that the 1343 tests on 7f96fdf pass with only these two files modified: the 331 record-layer cases, the hostile-input suite and the OpenSSL interop tests included.
The washer and dryer on #20 leave the network for about ten seconds whenever they have to put a handshake flight on the wire that will not fit one frame, and theirs will not, so they never finish a handshake. Measured on both units on 2026-10-25, three probes each in the order no-extension, extension, no-extension: all four no-extension arms took the unit off the network for 9.2 to 10.5 seconds and ended with it ARP-probing its own address, and both extension arms drew the appliance's whole flight in four datagrams of 525 bytes or less with no loss. The post-check runs third, after a working arm, so the drop tracks the extension and not the position in the run. No Python binding of OpenSSL can send that extension. OpenSSL itself can, with `openssl s_client -maxfraglen`, so the library is not the limit: cryptography 50.0.1 exposes neither SSL_CTX_set_tlsext_max_fragment_length nor the SSL_CTX_ctrl the macro goes through, its OpenSSL is linked statically into _rust.abi3.so with those symbols hidden, and the only SSL_CTX_ctrl that resolves in-process belongs to a different OpenSSL, which does not own the context held here. DtlsCertClient speaks one ciphersuite, 0xC02B, on the shared base. The wire profile is the one measured for this cohort in #33 and confirmed against #20's appliances: P-256 only, the ordered signature offer RSA+SHA256, ECDSA+SHA256, RSA+SHA1, ECDSA+SHA1, and no session ticket. Outbound handshake fragmentation lives here, because a PSK flight is small enough to never need it, and a negotiated length binds this client as much as the peer. Trust is decided nowhere in the engine. It checks that the ServerKeyExchange signature was made by the key in the leaf the peer presented, which is what binds the ephemeral parameters to that certificate, and hands the chain to a caller-supplied callback for everything else. The role, UUID and CA rules belong to SamsungServerProfile and are not restated. Validated on a Samsung dryer and oven, 2026-10-26, with the bridge stopped. Three arms per appliance from one credential and one source port: pyOpenSSL as production runs it, this engine with no extension, and this engine offering 512. dryer A pyOpenSSL 560 ms, GET /oic/d 2.05, 153 B dryer B engine, no MFL 664 ms, GET /oic/d 2.05, 153 B dryer C engine, MFL 512 706 ms, GET /oic/d 2.05, 153 B, MFL negotiated oven A pyOpenSSL 716 ms, GET /oic/d 2.05, 149 B oven B engine, no MFL 872 ms, GET /oic/d 2.05, 149 B oven C engine, MFL 512 770 ms, GET /oic/d 2.05, 149 B, MFL negotiated The engine reads the same resource in the same time as the path it stands beside, and arm C does it while the dryer fragments its flight to fit 512 bytes. The dryer reproduces across two clean runs, and it is the unit that matters, because its flight is a single over-MTU datagram. On the happy path, then, the engine measures as no worse. What remains open is the case it was built for: both of these appliances complete a handshake on pyOpenSSL today and the units on #20 do not, so neither of mine can speak for them. Arm C on the oven is one pass in two attempts, and the oven echoes the extension without applying it to its flight anyway. Hardware found the defect that mattered. Every arm on both appliances failed at "server leaf certificate did not parse" until OpenSSL took over reading the leaf's public key. `cryptography`'s `load_der_x509_certificate` refuses both appliances' factory leaves, while the pyOpenSSL path completes against the very same certificate. #33 recorded that asymmetry on an HW-S61B and a TU7x and reads the subject through OpenSSL for it, and an engine that parses the chain itself meets the same wall from the other side. It was written down as the item most likely to bite, and it bit. Six more defects came out before hardware, each with a test: four from a self-audit pass against this project's own fixed-defect history, two from the hostile-input cases. They are listed in the register under local-tools/cert-engine/. Offline it completes a handshake against OpenSSL acting as the server and carries application data both ways over the AES-GCM records, on the dependency floor and on current.
The hook a credential answers to bring its own engine was private, and both downstream consumers of it said the same thing. @mbillow declined to ship LocalThings on it, on mbillow/localthings#504: the library documents it as private and "not a supported public extension API", and a contract test only tells us after a release has broken it. @fredrikbae, who has a working max_fragment_length fork running two heat pumps in service, declined to open a PR for the same reason. So it becomes DtlsConnectionProvider.create_dtls_connection, returning a DtlsConnection, both in the published contract. #120 named this as the next step when it put construction behind one hook per caller. DtlsConnection states the whole surface this package drives, which is eight methods: the handshake driver takes bio_write, bio_read, do_handshake and the two timeout verbs, the session adds send and recv, and both the session and the diagnostic call shutdown to free the appliance's peer entry. set_connect_state and set_ciphertext_mtu are absent because a factory hands back a connection already in client state with its MTU applied. The two DTLSv1_ names keep pyOpenSSL's capitalisation, since one driver drives both and cannot hold two spellings. configure_context stays in the provider contract, so a provider still satisfies AuthenticationProvider, the session's isinstance gate keeps its meaning, and the context path stays open. Nothing here requires the new method, so a third-party AuthenticationProvider that has not grown one is unaffected. The private name is still consulted, and warns. A fork shipped against it and runs in production; breaking that in the release that fixes the fragility would be a strange way to fix it. An alternative was on the table and is worth recording. @mbillow suggested selecting the engine by an argument, max_fragment_length=1024 on the session. That would put engine construction back inside the session, which is the isinstance branching #120 removed from three sites. His requirement was a supported interface rather than that mechanism, and this meets it. ## And what a negotiated fragment length implies These appliances cannot send a record larger than a negotiated max_fragment_length. Measured by @fredrikbae on a TP1X board and reported on mbillow/localthings#504: a response over the limit never arrives and the session is unusable afterwards, which on those boards covers the full /oic/res, the /device/0 batch and /information/vs/0. Block2 is no escape, because the board ignores a smaller SZX on block 0. An integration needs two things the library had no way to say. DtlsCoapSession.negotiated_fragment_length reports the limit in force. None covers three different situations on purpose. There may be no session, the engine may not negotiate a length, or the server may have declined to echo one. A caller that needs to tell those apart can ask before connecting. FragmentLimitTimeoutError is raised when a read gives up on its first block while a limit is in force. It subclasses SessionTimeoutError, so existing handlers are untouched, the way HandshakePeerCleanupError did in v0.1.15, and it carries the limit. Its claim is deliberately narrow, and the docstring states the limit of it so a caller reads it there. The library knows two facts: the first block drew nothing, and a limit was negotiated. An appliance that has powered its radio down produces the same silence. What separates them is whether smaller resources on the same device still answer. That belongs to the caller, so the error carries the limit and leaves the reason open. A timeout on a later block stays an ordinary SessionTimeoutError. Blocks were arriving, so the representation fits and the deadline was the binding constraint. That is @fredrikbae's own discriminator: block 0 means nothing started, a higher block means it ran out of time. These two land together because they are entangled in one file: the session's dispatch and its reporting both sit in dtls_session.py, and splitting them left the first commit importing a helper the second one added. They are also the same request. @mbillow asked for the seam and for both of these in one comment.
FragmentingCertificateAuth answers the public seam: same credentials, same server profile, same trust rules as CertificateAuth, with the handshake on _dtls_cert.DtlsCertClient so the ClientHello can offer max_fragment_length. Nothing in this package selects it, and the default certificate path is untouched. The default offer is 1024. The ceiling is whatever leaves the appliance's own flight inside one Ethernet frame, and the same figure caps every response it can send back, so the largest workable value is the right one. @fredrikbae measured both ends of that on a TP1X board: 512 draws a largest datagram of 525 B, 1024 draws 1037 B, and 2048 would put it past the MTU. A smaller offer only costs reads, and this client asks for 1024-byte Block2 blocks (coap.py BLOCK_SZX = 6). server_profile is optional, as it is on CertificateAuth, and means the same thing. Without one the peer's chain is verified against the bundled OCF root and nothing further is pinned, which is what a profileless pyOpenSSL context does. With one, the profile's role, subject and UUID checks apply on top. Nothing per-appliance is configured. The client certificate's subject UUID is a constant. It does not rotate. A profile pins the appliance's hardware leaf UUID, which is a separate identity and differs between units. from_files and from_memory are overridden only to carry max_fragment_length, which the inherited factories have no parameter for. Verification calls the profile. The anchors are the bundled OCF root plus any additional CA it carries. The leaf check is SamsungServerProfile._verify_peer. OpenSSL parses the certificates, because Samsung's factory leaves do not survive a cryptography reparse that OpenSSL has already accepted (#33).
DTLS_FRAGMENT_LENGTH routes the bridge's handshake through this package's own certificate engine, the only path that can send the extension. Unset or 0 is the pyOpenSSL path these appliances have always used, byte for byte. Off by default on purpose. Both appliances this bridge runs against already complete a handshake, so the extension buys them nothing, and they are also the whole of the engine's hardware evidence. The appliances that need it are the ones dropping off the network mid-handshake. None of those is here. Only the four RFC 6066 sizes are accepted. Reach for 1024. A value that parses and cannot be offered, 500 say, stops the process at startup, which is the contract the other knobs here keep. One behavioural difference to know about. A negotiated fragment length bounds application records as well as handshake ones. A write above the value therefore raises. The bridge writes at two sites only: clock_sync.py, and the command path in bridge.py. Both send small CBOR maps. test_bridge_write_attempts' fake SharedConfig gains the new field. It stands in for the real one, so it carries every attribute the bridge reads; a getattr default in the bridge would have hidden config drift instead.
QuiteYellow-reviewer
left a comment
There was a problem hiding this comment.
A fresh-context review at 8aaa251, with every finding re-checked by a second independent pass. It found one bug, one risk to fix before this leaves draft, one open question, and some stale docs.
- The diagnostic enforces trust when it gets
FragmentingCertificateAuth(inline ondtls_probe.py). This is the one I'd fix first, because the failure leaves a half-open peer on the appliance. - Block1 does not fit under a negotiated length of 512 or 1024 (inline on
_dtls_cert.py). The bridge's own writes are small, so the demo is fine; a library caller posting a larger body is not. - "Same trust rules" may not hold for EKU (inline on
auth.py). This one is a question. - Stale "has met no appliance" text (inline on
docs/certificates.md). Also, the module docstring attests/test_fragmenting_certificate_auth.py:5-6says "a session with no profile cannot be built at all", and the test at:52-65in the same file builds one and asserts_mfl == 1024. - Nit: the deprecation warning will rarely surface (inline on
auth.py).
Checked and not raised: no smaller Block2 SZX under MFL (347a0ca records that the board ignores a smaller SZX on block 0), GCM nonce reuse on retransmit (byte-identical resend, and it predates this PR), and the 713aebf extraction (a scripted comparison shows a byte-identical move).
Not read in this review: most of test_dtls_cert_hostile.py, all of test_dtls_cert_interop.py, and the generated docs/api.md.
|
Reviewed It covers my boards. The two Thermia Aura S3 units ( Four things, most important first. 1. After an oversized read, the session is dead, and the 2. A server that doesn't echo the extension. My engine refuses the handshake in that case. Yours carries on, and 3. 4. Inbound cap. Neither engine enforces The attributions in Next, I can run |
|
Thank you for the review, @fredrikbae. Your third point is fixed in If you run the branch against your units, |
F1: the diagnostic now builds FragmentingCertificateAuth through a hook that leaves the chain to the peer. An untrusted chain reaches the appliance, and the result reports the appliance's alert. F1b: when the certificate engine refuses the peer before its flight, it keeps one epoch-zero fatal handshake_failure, and the handshake driver sends it. pyOpenSSL connections have no such hook and are unchanged. F2: under a negotiated fragment length, post() sizes each message to fit, and starts Block1 at the largest SZX that fits. A request that cannot fit raises ValueError before anything is sent. F3: the engine verifies the server chain for the SSL-server purpose. The pyOpenSSL path refuses a clientAuth-only leaf, measured on the floor and on current, and the engine accepted it. F4: the docs and the provider docstring now name the dryer and oven validation of 2026-10-26, in place of "has met no appliance". F5: the legacy hook warns with FutureWarning, and a bad max_fragment_length raises at construction. Add BEHAVIOUR.md with the decisions above. Publish-Approved: 2026-11-13T16:30:00+00:00
QuiteYellow-reviewer
left a comment
There was a problem hiding this comment.
Automated review at 7019f84. Follow-up to the review at 8aaa251.
Not run: no hardware. CI passes 8 of 8 at this head.
All five earlier points are fixed. F1, F2 and F3 have new tests, and the tests fail at 8aaa251. Four new points follow, all inline:
BEHAVIOUR.md:12states a wider rule than the code keeps. Only three refusals send the new alert. This one is a risk.- A docstring still names
DeprecationWarning. - The
post()docstring omits the block-countValueError. - Nit: the purpose binding is called without a lookup.
R1: both pure-Python engines send the abandon alert at every refusal of a server message before their own flight, not only at the three client-flight refusals. A fatal alert from the peer, a local limit, and the server Finished check still end the handshake with no alert. Measured on a dryer: after a refusal at the server Certificate, a retry from the same local port completed at once with the alert (2 of 2). Without it, the dryer resent its old flight to every new ClientHello from that port for more than 10 minutes. N1: the session docstring names FutureWarning for the legacy hook. N2: the post() docstring names the ValueError for a body that needs more than 1024 blocks. N3: an OpenSSL binding that cannot set the server purpose raises at construction, with the reason. From @fredrikbae's review: the FragmentLimitTimeoutError docstring says to check smaller resources on a fresh session, and the negotiated_fragment_length docstring says to compare it with the length offered after connect(). BEHAVIOUR.md records the alert, the cases with no alert, and why the engines do not refuse an inbound record over the negotiated length. Publish-Approved: 2026-11-13T18:45:00+00:00
|
@fredrikbae, your points 1 and 2 are in Point 4 stays out of this PR, as you suggested. I'm happy to revisit a size limit on incoming records when hardware needs it. One data point for then: my oven echoes the extension and still sends its handshake flight in records longer than the negotiated length, so a strict check would fail that handshake. |
The bridge demo's fragment length moves to a follow-up PR, set per appliance from the start. A negotiated length caps every response: on 2026-11-13 a dryer at 1024 could not send /device/0, so a process-wide value would break the appliances that do not need it. This PR keeps the library: the engine, the seam and the session changes. The demo files are back to their state at the base, 7f96fdf. Publish-Approved: 2026-11-13T20:05:00+00:00
The docstring said a read asks for 1024-byte blocks on its first block. The first request of a read carries no Block2 option, so the appliance chooses the block size, and nothing in the client lowers it to the negotiated length. The test of the library log line read only its source text, so a change of level or logger kept it passing while the script lost every alert name. A test now runs the real DtlsCoapSession.connect() over a fake connection that fails with an alert, and checks that the script names it. With the library's warning demoted to info, that test fails. The liveness check now counts any answer from the plaintext directory, not only one that lists a secure port, so an appliance that answers with no port no longer reads as gone from the network. Alert 22 is named record_overflow. Every exit after the prompt prints the reminder to re-enable the integration, and Ctrl-C exits 130. 16 tests pass on Python 3.11 to 3.14 and on 3.11 at the dependency floor, with the library installed from b40b720. Publish-Approved: 2026-11-14T17:45:00+00:00
The appliance firmware sends block 0 of a read at 1024 bytes. Under a negotiated length of 512 or 1024 that response does not fit a record, and the session is lost. A GET that asks for a smaller block 0 gets no reply. In TizenRT's iotivity_1.2-rel fork that request takes the first-block branch, which stores the asked size under the token and client port for 60 s but does not reach the handler (cablockwisetransfer.c:483-490, :1045-1064). A plain GET on the same token then gets block 0 at the stored size (:2405-2436, :1575). So get() now sends a NON primer, Block2 NUM 0 at the largest size that fits, then the plain GET. If a server answers the primer itself, that answer is block 0 and no plain GET is sent. With no length in force, or one that a 1024-byte block fits, nothing changes. Measured on a dryer on 2026-11-19, in one session at a length of 1024: /device/0, 4607 bytes, came back as 9 blocks of 512 bytes in 2.2 s, and the bridge polled with no errors afterwards. Limit: the firmware never splits a body of 1024 bytes or less, so such a body over the length still raises FragmentLimitTimeoutError. Use 1024, not 512. Publish-Approved: 2026-11-20T10:15:00+00:00
|
@fredrikbae, before the run you offered: the branch now has
|
Draft, for review before it goes anywhere near a release.
A certificate-capable DTLS client of this package's own, because the appliances on #20 leave the network for about ten seconds whenever they have to put a handshake flight on the wire that will not fit one Ethernet frame, and theirs will not. Offering
max_fragment_lengthstops it. The OpenSSL bindings this package depends on cannot send that extension.Why this needs an engine of its own
openssl s_client -maxfraglenworks, so OpenSSL itself supports the extension and the Python bindings are where it stops.cryptography50.0.1 publishes neitherSSL_CTX_set_tlsext_max_fragment_lengthnor theSSL_CTX_ctrlthat macro goes through, and it links OpenSSL statically into_rust.abi3.sowith those symbols hidden. The onlySSL_CTX_ctrlthat resolves in-process belongs to a different OpenSSL, which owns none of the contexts here. Other bindings may expose it; these two are the ones this package has.The four commits
_dtls_base. A move, lifted by script, leaving one copy of the record layer, reassembler, cookie exchange and retransmission timer. On main as it then stood (7f96fdf), the 1343 tests pass with only_dtls_base.pyand_dtls_psk.pytouched._dtls_cert.DtlsCertClient— suite0xC02B, AES-GCM records, a verified ServerKeyExchange signature, outbound handshake fragmentation, and the extension.FragmentingCertificateAuth, opt-in, on that seam.The bridge demo that a fifth commit added has moved to a follow-up PR, which sets the length per appliance. The 1024 item under Open says why.
Hardware
A Samsung dryer and oven, 2026-10-26, bridge stopped. Three arms per appliance from one credential and one source port: pyOpenSSL as production runs it, this engine with no extension, and this engine offering 512.
GET /oic/dThe dryer reproduces across two clean runs, and it is the unit that matters, because its flight is a single over-MTU datagram.
On the happy path the engine measures as no worse. What stays open is the case it was built for: both of these appliances complete a handshake on pyOpenSSL already and the units on #20 do not, so neither of mine speaks for them.
Hardware found one defect that no offline test could have. Every arm failed at
server leaf certificate did not parseuntil OpenSSL took over reading the leaf's public key:cryptographyrefuses both appliances' factory leaves while the pyOpenSSL path completes against the very same certificate, which is the asymmetry #33 recorded on an HW-S61B. The interop tests mint their own chains withcryptography, so both ends agree and the gap stays hidden.Six more came out before hardware, each with a test: four from a self-audit pass against this project's own fixed-defect history, two from the hostile-input cases.
The seam, and why not an argument
@mbillow declined to ship LocalThings on
_create_dtls_connection(mbillow/localthings#504) because the library documents it as private, and a contract test only reports a break after a release. @fredrikbae declined to open a PR for a working MFL fork for the same reason. So it is nowDtlsConnectionProvider.create_dtls_connectionreturning aDtlsConnection, both published, with the private name still consulted behind aFutureWarningso his fork keeps running.Selecting the engine by an argument was the other option and would have put construction back inside the session, which is the branching #120 removed from three sites.
Credit
@fredrikbae measured the figures the 1024 default rests on and the finding this branch had missed: a response over the negotiated length never arrives, with Block2 no help because the board ignores a smaller SZX on block 0. @mochman confirmed the mechanism on a washer, a dryer and a TP1X_REF_21K.
Open
/oic/dread 2.05 every time./device/0never arrived at 512, and the session was dead afterwards.f74a26ehas not run on them yet./oic/d. The dryer took a 1098-byte write as three Block1 blocks of 512 bytes and answered 4.04; the path did not exist, so nothing was written. It could not send/device/0then, because the firmware sends block 0 at 1024 bytes.f74a26efixes that on this dryer. Under a negotiated length,get()first sends a NON GET for block 0 at the largest size that fits. The firmware does not answer it, but it keeps the size, and the plain GET that follows on the same token comes back in blocks of that size./device/0(4607 bytes) came back as nine 512-byte blocks at 1024 on 2026-11-19, and again on 2026-11-20 with the check script from Check the primed read with pr129_check.py, on #20 units and TP1X boards #138. The commit message has the path through the firmware source. So the length suits only an appliance that cannot work without it, and a single value for every appliance on a network would break the rest. The oven timed out twice at 1024 in one run and completed in the next; the first run did not record the wire, so that cause is unknown.7019f84, and the follow-ups from the re-review ine2f0957.diagnose_dtls_handshakeno longer enforces trust when it getsFragmentingCertificateAuth. When either pure-Python engine, certificate or PSK, refuses a server message before its own flight, it now sends an epoch-zero fatalhandshake_failure. On my dryer that alert frees the peer: after a refusal at the server's Certificate, a retry from the same source port completed in under 600 ms, twice. With the alert suppressed, the dryer answered every new ClientHello from that port with its old flight, and the port was still refused ten minutes later. Only the certificate engine has sent it to an appliance. Under a negotiated length,post()sizes every message to fit and uses Block1 at the largest block size that fits, which the dryer accepted at 512.cablockwisetransfer.c:66-81). At 1024 that leaves a few tens of bytes. The per-href and backoff work that avoids such reads belongs to the integration.0xC023is in the adapter's accepted list iniotivity_1.2-rel, and the server picks by its own preference, so a probe has to offer that suite alone. If it is accepted,_dtls_psk._Transformalready implements that record layer and_GcmTransformbecomes optional.State
CI passed 8 of 8 at
f74a26e, on its merge withmain: 1572 tests on 3.11 through 3.14 and on the 3.11 dependency floor, share-safety clean, wheel and sdist built.mainhas moved 21 commits past this branch's base, and merging it in is conflict-free.The 1024 run is done. Failing a review, the fallback is to merge on the happy-path evidence alone and say so in the release notes. Nothing in the package selects the engine, so only a caller that asks for it gets it.