Repository navigation
Write AEAD tag directly into ciphertext buffer's reserved tail - #217
Conversation
There was a problem hiding this comment.
🟢 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 Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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_seqnow hard-fail on an unexpectedct_len, butdecryptstill onlydebug_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.
decryptallocatesct.len()and truncates byTAG_LEN; once themaxoutsemantics are settled (see inline), that buffer could bept_expectedbytes with notruncate, which is the mirror image of this change. - Unmeasured. There is no
benches/directory, so the win here is inferred rather than measured.RecordProtectionis the per-record hot path and already takes caller-provided buffers;Aead::{encrypt,encrypt_with_seq}return a freshVeceach call, so the remainingvec![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
maxoutnarrowing and the test redundancy are both worth a look.
Avoids a separate tag allocation and copy in Aead::encrypt and Aead::encrypt_with_seq, matching the pattern already used by RecordProtection::encrypt.
c612106 to
dc9f42e
Compare
There was a problem hiding this comment.
🟡 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, whilePK11_AEADOprequires the separate tag pointer to be outside that region (the workingRecordProtectionpath passes the plaintext length). Use the plaintext length asoutput_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.
There was a problem hiding this comment.
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.
encryptreturnsError::Internalon an unexpectedct_len, butdecryptstill has a baredebug_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 asRecordProtection::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-bytememcpyand a possibleVecrealloc inappend. That's clearly non-negative, so no objection, but the threeAeadmethods are the hot path for QUIC header/packet protection and there is currently nothing that would catch a regression here; a small Criterion bench overencrypt/decryptwould 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.
martinthomson
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🔵 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 thect.len()bytes passed asoutput_max. The analogous wrapper explicitly requires the tag not to overlap the output region and passes only the plaintext length asoutput_max(src/aead/recprot.rs:52-54,155). Passpt.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 byPK11_AEADOp(theRecordProtectionpath passes only the plaintext length asoutput_max) and can make the C operation write/read overlapping buffers. Usept.len()foroutput_maxin 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.
There was a problem hiding this comment.
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 forpt.len(); the earlier thread argues forct.len(). I agree withct.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 onlyPK11_AEADOpcall site in the crate wheretaglands inside the declared output window:aead_op's# Safetysays "tagmust not overlap with theoutputregion", andRecordProtection::encryptenforces that withoutput_max = input.len(). Whichever convention wins, please make all five call sites and the safety contract agree — right now a reader auditing thisunsafeblock against the documented contract will conclude it is a bug. - Test coverage of
encrypt_with_seqis still nonzero-seq-free. The newencrypt_with_seq(aad, 0, pt)assertion incheck0exercisesxor_nonceonly at its identity input, so it duplicates whatencryptalready proves against the KAT. The uncovered case —encrypt_with_seqagainst an external vector with a real sequence number — is free from the existing constants (NONCE_BASE+ seq1forquic_server_initial,654_360_564forquic_chacha), mirroring thedecrypt(...)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.
Avoids a separate tag allocation and copy in Aead::encrypt and
Aead::encrypt_with_seq, matching the pattern already used by
RecordProtection::encrypt.