Skip to content

Write AEAD tag directly into ciphertext buffer's reserved tail - #217

Merged
larseggert merged 2 commits into
mainfrom
aead-encrypt-tag-inplace
Sep 14, 2026
Merged

larseggert merged 2 commits into
mainfrom
aead-encrypt-tag-inplace

Conversation

@larseggert

Copy link
Copy Markdown
Collaborator

Avoids a separate tag allocation and copy in Aead::encrypt and
Aead::encrypt_with_seq, matching the pattern already used by
RecordProtection::encrypt.

Copilot AI balanced review requested due to automatic review settings September 13, 2026 12:55

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.

🟢 Approval recommended

No unresolved review issues were identified.

Pull request overview

Updates AEAD encryption to write authentication tags directly into the reserved ciphertext buffer tail, avoiding allocation and copying.

Changes:

  • Writes tags in-buffer for both encryption paths.
  • Validates ciphertext length.
  • Adds tamper-detection tests.
File summaries
File Summary
src/aead/mod.rs Implements in-buffer tag output and authentication tests.
Review details
  • Files reviewed: 1/1 changed files
  • Comments generated: 0
  • Review effort level: Lite (auto)

Note

Copilot is running an experiment and ran this review at Lite.


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@codecov-commenter

codecov-commenter commented Sep 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.91304% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.74%. Comparing base (95cbf42) to head (bab78ab).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
src/aead/mod.rs 73.91% 2 Missing and 4 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #217      +/-   ##
==========================================
+ Coverage   73.57%   73.74%   +0.16%     
==========================================
  Files          28       28              
  Lines        3315     3325      +10     
  Branches     3315     3325      +10     
==========================================
+ Hits         2439     2452      +13     
- Misses        662      664       +2     
+ Partials      214      209       -5     
Flag Coverage Δ
freebsd 73.74% <73.91%> (+0.16%) ⬆️
linux 73.74% <73.91%> (+0.16%) ⬆️
macos 73.74% <73.91%> (+0.16%) ⬆️
windows 73.74% <73.91%> (+0.16%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions github-actions Bot 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.

Nice simplification — one 16-byte allocation plus a memcpy removed per Aead::encrypt/encrypt_with_seq, and the resulting code is shorter than what it replaces.

Soundness of the new unsafe looks fine to me: ct_ptr is derived once, nothing re-borrows ct across the FFI call, ct_ptr.add(pt.len()) stays inside the pt.len() + TAG_LEN allocation, and the tag region is disjoint from the declared output region (the invariant recprot::aead_op documents in its # Safety block). Replacing the debug_assert_eq! with a returned error is the right call for an FFI-reported length.

A few whole-PR observations beyond the inline comments:

  • Consistency with decrypt. encrypt/encrypt_with_seq now hard-fail on an unexpected ct_len, but decrypt still only debug_assert_eq!s and then truncates, so a short read from NSS silently yields a truncated plaintext in release builds. Worth converting in the same PR while the reasoning is fresh.
  • Follow-on allocation win. decrypt allocates ct.len() and truncates by TAG_LEN; once the maxout semantics are settled (see inline), that buffer could be pt_expected bytes with no truncate, which is the mirror image of this change.
  • Unmeasured. There is no benches/ directory, so the win here is inferred rather than measured. RecordProtection is the per-record hot path and already takes caller-provided buffers; Aead::{encrypt,encrypt_with_seq} return a fresh Vec each call, so the remaining vec![0; …] dominates the tag copy this removes. Fine as a cleanup — just worth not over-claiming in the commit message.
  • Re: the Copilot review above (0 comments, approval recommended) — I disagree that there's nothing to flag; the maxout narrowing and the test redundancy are both worth a look.

Comment thread src/aead/mod.rs Resolved
Comment thread src/aead/mod.rs Resolved
Comment thread src/aead/mod.rs Resolved
Comment thread src/aead/mod.rs Resolved
Avoids a separate tag allocation and copy in Aead::encrypt and
Aead::encrypt_with_seq, matching the pattern already used by
RecordProtection::encrypt.
@larseggert
larseggert force-pushed the aead-encrypt-tag-inplace branch from c612106 to dc9f42e Compare September 13, 2026 17:29
Copilot AI review requested due to automatic review settings September 13, 2026 17:29

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

Fix the output-region length passed in both encryption paths so the tag does not overlap it.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

src/aead/mod.rs:357

  • This has the same overlap issue as the other encryption path: ct.len() declares the output region through the tag, while PK11_AEADOp requires the separate tag pointer to be outside that region (the working RecordProtection path passes the plaintext length). Use the plaintext length as output_max.
                c_int_len(ct.len())?,
  • Files reviewed: 1/1 changed files
  • Comments generated: 1
  • Review effort level: Lite (auto)

Note

Copilot is running an experiment and ran this review at Lite.

Comment thread src/aead/mod.rs Resolved

@github-actions github-actions Bot 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.

Drops the separate tag allocation in Aead::encrypt/encrypt_with_seq by pointing PK11_AEADOp's tag parameter at the reserved tail of ct, and upgrades the ct_len debug_assert to a hard error. The pointer arithmetic is in bounds (ct.len() == pt.len() + TAG_LEN), both pointers share ct_ptr's provenance so there's no Stacked-Borrows hazard, and the output length is now always exactly pt.len() + TAG_LEN rather than ct_len + TAG_LEN — strictly tighter. The pt.len() == 0 case (quic_retry) makes tag == out, which the existing KAT covers.

Resolved from my previous review: maxout is back to c_int_len(ct.len()).

Two whole-PR observations not worth inline comments:

  • Encrypt and decrypt now disagree on how much they trust NSS. encrypt returns Error::Internal on an unexpected ct_len, but decrypt still has a bare debug_assert_eq!(len, pt_expected) (L403) and hands back a short plaintext in release builds. If the stricter check is worth having on the encrypt side, it is worth more on the decrypt side, where the value is returned to a caller that may size-check it. Same shape as RecordProtection::decrypt_in_place, which does check.
  • Savings are unmeasured and the crate has no benches/. Per call this removes one 16-byte allocation plus a 16-byte memcpy and a possible Vec realloc in append. That's clearly non-negative, so no objection, but the three Aead methods are the hot path for QUIC header/packet protection and there is currently nothing that would catch a regression here; a small Criterion bench over encrypt/decrypt would make this class of change self-justifying. (Tracking that separately would be fine.)

Three comments from my previous review still look unaddressed on dc9f42e — the c_int comparison, the encrypt/encrypt_with_seq duplication, and the coverage value of the two new tamper tests — so I've left them to that thread rather than repeating them here.

Comment thread src/aead/mod.rs Resolved

@martinthomson martinthomson left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not sure about the testing, which seems duplicative.

One way to save on code, but increase coverage is to run *_seq calls for encrypt and decrypt in parallel within check0, validating that the same call with sequence number zero produces the same output as the non-seq variant. That's close to what the bot suggested.

That function could also pick up tampering detection in the same way. After successful decryption, a tampered copy of the ciphertext could be run against decrypt calls of both variants.

That doesn't cover non-zero sequence numbers, but there's a limit to what you need to test.

Comment thread src/aead/mod.rs Resolved
Comment thread src/aead/mod.rs Resolved
Copilot AI review requested due to automatic review settings September 14, 2026 05:54

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.

🔵 Needs a closer look

Both encryption paths must limit output_max to pt.len() before approval.

Review details

Suppressed comments (2)

src/aead/mod.rs:316

  • This makes the tag pointer overlap the output region advertised to PK11_AEADOp: ct_ptr.add(pt.len()) is inside the ct.len() bytes passed as output_max. The analogous wrapper explicitly requires the tag not to overlap the output region and passes only the plaintext length as output_max (src/aead/recprot.rs:52-54,155). Pass pt.len() as the output maximum here so the reserved tail is outside the ciphertext output region.
                ct_ptr.add(pt.len()),
                c_int_len(TAG_LEN)?,

src/aead/mod.rs:359

  • As in the other encryption path, the tag pointer is inside the ct.len()-byte output range passed immediately above. That violates the non-overlap contract used by PK11_AEADOp (the RecordProtection path passes only the plaintext length as output_max) and can make the C operation write/read overlapping buffers. Use pt.len() for output_max in this call as well.
                ct_ptr.add(pt.len()),
                c_int_len(TAG_LEN)?,
  • Files reviewed: 1/1 changed files
  • Comments generated: 0 new
  • Review effort level: Lite (auto)

Note

Copilot is running an experiment and ran this review at Lite.

@github-actions github-actions Bot 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.

Narrow, well-scoped change: saves one 16-byte allocation plus a 16-byte copy per encrypt/encrypt_with_seq, and upgrades a debug_assert_eq! to a real error. Deriving both out and tag from a single ct.as_mut_ptr() is the right call — one provenance covering the whole allocation — and reading ct.len() afterwards only borrows the Vec header, so ct_ptr stays valid.

Resolved since my earlier pass: the redundant map_err(|_| Error::IntegerOverflow) is gone (Error: From<TryFromIntError>, per @martinthomson's r4002326567), and maxout is back to ct.len().

Two things that apply PR-wide rather than to a single line:

  • Conflicting advice on maxout (r4000319421 vs. r3999690051). Copilot asks for pt.len(); the earlier thread argues for ct.len(). I agree with ct.len() — it is the honest size of the buffer, and it is what NSS's non-message-mode fallback needs to avoid the very scratch buffer this PR removes. But that makes this the only PK11_AEADOp call site in the crate where tag lands inside the declared output window: aead_op's # Safety says "tag must not overlap with the output region", and RecordProtection::encrypt enforces that with output_max = input.len(). Whichever convention wins, please make all five call sites and the safety contract agree — right now a reader auditing this unsafe block against the documented contract will conclude it is a bug.
  • Test coverage of encrypt_with_seq is still nonzero-seq-free. The new encrypt_with_seq(aad, 0, pt) assertion in check0 exercises xor_nonce only at its identity input, so it duplicates what encrypt already proves against the KAT. The uncovered case — encrypt_with_seq against an external vector with a real sequence number — is free from the existing constants (NONCE_BASE + seq 1 for quic_server_initial, 654_360_564 for quic_chacha), mirroring the decrypt(...) calls already there. See r3999691658.

Also still open: encrypt and encrypt_with_seq are now byte-identical apart from the generator and nonce (r3999690857). Duplicated raw-pointer FFI is the kind of thing that drifts; recprot::aead_op is already 90% of the shared helper.

Comment thread src/aead/mod.rs Resolved
Comment thread src/aead/mod.rs Resolved
@larseggert
larseggert added this pull request to the merge queue Sep 14, 2026
Merged via the queue into main with commit c4fc2b0 Sep 14, 2026
53 of 57 checks passed
@larseggert
larseggert deleted the aead-encrypt-tag-inplace branch September 25, 2026 07:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants