Skip to content

Bound the peer text read before authentication - #236

Merged
kahrendt merged 2 commits into
mainfrom
bound-peer-text
Nov 3, 2026
Merged

kahrendt merged 2 commits into
mainfrom
bound-peer-text

Conversation

@kahrendt

@kahrendt kahrendt commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The coherence review from #235 of the allocation series found peer text copied before any length check: the server/error reason (up to the 16 KiB pre-admission cap, unauthenticated), the msg1 psk_category, the pairing fields, and the noise/handshake data itself. This PR reads each in place or refuses it before it is copied.

Change

  • server/error: the reason is parsed into ServerErrorReason (UNSUPPORTED_VERSION, UNSUPPORTED_SUITE, MALFORMED, UNKNOWN), the three reasons messaging.md "server/error" defines. server_error_reason() returns std::optional<ServerErrorReason>, nullopt when no server/error arrived. The reason and an unexpected frame type are logged up to PEER_TEXT_LOG_BYTES (32).
  • msg1 payload: psk_category is parsed from the view inside extract(). A new to_cstr(PskCategory) gives the wire code (lt/pr/sn), which the five category logs now print instead of %d.
  • Pairing fields: b64url_decode_exact<N> (platform/base64.h) decodes nonce_A, pake_msg_1 and server_kc straight into their arrays, replacing as<std::string>() plus a std::vector decode. The three parsers share one shape, so a validate-only call checks the decoded length too, as their docs say. public_key_from_peer_id() uses the same helper.
  • msg1 size: MAX_HANDSHAKE_MSG1_BYTES (ephemeral key + MAX_HANDSHAKE_MESSAGE_BYTES payload + tag = 560) refuses longer noise/handshake data before its buffer is allocated; a static_assert ties it to X25519_KEY_SIZE and AEAD_TAG_SIZE.
  • Full-length reads: the six handshake fields (psk_id, psk_category, data, the reason, type, server_id) are read with | std::string_view("") instead of | "", whose const char* stops at an embedded NUL; a server_id with a NUL suffix was cut back to the real id and accepted.

Tests

  • ServerErrorWhileAwaitingServerInitAborts is a table over every defined reason, unknown text, a non-string and a missing reason, with a non-server/error abort as the nullopt control row (it replaces AbortWithoutServerErrorReportsNoReason).
  • HandshakeDataLongerThanAMsg1IsRefused checks the msg1 cap at and one byte over.
  • The three pairing parser tables gain an over-length row (33/33/65 bytes); over-length input had no test before.
  • NUL-suffixed rows for the reason (UNKNOWN), psk_category (abort), psk_id (Sentinel fallback), type and server_id (refused); each fails with the | "" read.
  • Mutants killed: a reason mapped to UNKNOWN, b64url_decode_exact accepting any decoded size, a wrong output capacity (caught by ASan on the over-length rows), and the msg1 cap moved by one.

The server/error reason, the msg1 psk_category and the pairing fields
were copied out of the peer's frame before any length check.

- server/error's reason is parsed in place into ServerErrorReason
  (UNKNOWN for text messaging.md does not define); the getter returns
  nullopt when no server/error arrived. Logs of the reason and of an
  unexpected type print at most PEER_TEXT_LOG_BYTES.
- psk_category is parsed from the view; to_cstr(PskCategory) gives its
  wire code, which the category logs now print.
- b64url_decode_exact<N> decodes nonce_A, pake_msg_1 and server_kc
  straight into their arrays; the three parsers share one shape, so
  validate-only calls check the decoded length too.
- MAX_HANDSHAKE_MSG1_BYTES refuses noise/handshake data longer than a
  readable message 1 before its buffer is allocated.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Handshake reason parsing truncates strings at embedded NULs, causing undefined reasons to be misclassified as known errors.

4 open issues
What changed in this PR

Closes allocation gaps identified in #235 by bounding peer-controlled input in Sendspin’s authentication and pairing paths before copying or allocating buffers.

Changes:

  • Parse server-error reasons and PSK categories in place, with bounded peer-text logging.
  • Decode pairing fields into fixed arrays and cap Noise message 1 at 560 bytes before allocation.
  • Expand tests for error reasons, handshake size boundaries, and oversized pairing fields.
File Description
tests/​test_noise_transport.cpp Expand error-reason and handshake-size tests.
tests/​test_dynamic_pairing_code.cpp Add oversized pairing-field cases.
src/​record_store.h Add PSK-category wire-string conversion.
src/​protocol.cpp Decode pairing fields directly into fixed arrays.
src/​platform/​base64.h Add an exact-size base64url decoding helper.
src/​noise_handshake.h Represent server-error reasons with a typed enum.
src/​noise_handshake.cpp Bound decoding and logging; parse categories in place.
src/​crypto/​keys.cpp Reuse exact-size decoding for peer keys.
src/​crypto/​constants.h Define the whole-message handshake size cap.
src/​connection.cpp Log typed error reasons and wire-format categories.
src/​connection_manager.cpp Log PSK categories using their wire codes.

Review effort: Max

Comment thread src/noise_handshake.cpp Resolved
Comment thread src/protocol.cpp Resolved
Comment thread tests/test_noise_transport.cpp Resolved
Comment thread tests/test_noise_transport.cpp Resolved
A string_view built from `field | ""` stops at an embedded NUL, so
"malformed\u0000x" read as a defined server/error reason, "lt\u0000x" as
a valid psk_category, and a server_id with a NUL suffix was cut back to
an id the server never sent and accepted. The six handshake fields now
use `| std::string_view("")`, which keeps the full length and a non-null
empty default.

Each field that can carry a NUL gets a row that fails with the old
read; the msg1 cap table's accepting row is marked Control, and the
comment before the msg1-wait server/error test names the frame.
@kahrendt
kahrendt merged commit acb3755 into main Nov 3, 2026
16 checks passed
@kahrendt
kahrendt deleted the bound-peer-text branch November 3, 2026 23:27
kahrendt added a commit that referenced this pull request Nov 4, 2026
## Summary

The allocation series (#225-#236) enforced a rule that was written down
only in `tests/test_allocations.cpp`'s header and in PR bodies.
ESPHome's `operator new` draws only on internal RAM and aborts on
failure, so after `start()` connection setup and message handling
allocate through the fallible `platform_malloc` family, and bounded
values are held inline. This PR states that rule and records where the
code still allocates with `operator new`. Docs only.

## Change

- **`docs/conventions.md`:** "Embedded resource discipline" gains the
rule: `operator new` at construction, `add_*()` and `start()` only;
afterwards `platform_malloc`, whose failure refuses or closes the
connection or drops the message; bounded values inline (`InlineText`,
`InlineVector`, `EnumSet`, `std::array`); peer text bounded where it is
parsed; public `std::string`/`std::vector` types built on the thread
that hands them to the consumer. The Documentation bullet lists the
allocation model among `internals.md`'s contents.
- **`docs/internals.md`:** a new "Memory" section: the three allocators
(`operator new`, `platform_malloc`, noise-c's `calloc`) and how each
fails, what is held inline, a table of the `operator new` allocations
that remain after `start()` with when and on which thread each runs, and
the one-pointer capture the `std::function`s built after `start()` rely
on.
- **`CLAUDE.md`:** the Memory convention names the inline types and
points at the new section; the test build note says what
`sendspin_alloc_tests` counts; both descriptions of `internals.md`
mention memory.
- **`.claude/skills/embedded-review/SKILL.md`:** a new `operator new`
after `start()` is listed in "Memory" or reported as a finding.

## Tests

Docs only. Each claim in the Memory section was checked against the
code; the table is the checklist the remaining allocation groups
(tracked in Sendspin/backlog#92) remove rows from.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants