Skip to content

fix payload masking for buffers not aligned to 4 bytes - #14

Closed
PrefectSol wants to merge 1 commit into
rbeeli:mainfrom
PrefectSol:fix-unaligned-masking
Closed

PrefectSol wants to merge 1 commit into
rbeeli:mainfrom
PrefectSol:fix-unaligned-masking

Conversation

@PrefectSol

Copy link
Copy Markdown

MaskKey::mask_aligned masks the leading unaligned bytes with the correct key phase
(key_bytes[i & 3]), but the aligned chunks are then XORed with the key vector built from
the unrotated key. When the number of leading bytes is not a multiple of 4, every byte after
the first chunk boundary is masked with the wrong key byte. This affects the SSE2, NEON and
64-bit fallback paths.

In practice the server receives corrupted frames: a text message sent from a buffer whose
address is not 4-byte aligned is rejected with close code 1007 ("bytes are not UTF-8").
Pong payloads masked in place inside the read buffer are affected the same way.

The existing tests do not catch this because they mask twice and compare with the original:
XOR with a consistently wrong key is still an involution.

Fix: rotate the key by the number of leading bytes (mod 4) before building the chunk key.
Added a test that compares against a byte-wise reference for offsets 0..31 and sizes 0..200;
it fails on main and passes with the fix.

@rbeeli

rbeeli commented Nov 18, 2026

Copy link
Copy Markdown
Owner

Thanks for reporting. Fixed in 2f74d01
New version 0.7.4 tagged.

@rbeeli rbeeli closed this Nov 18, 2026
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.

2 participants