fix(email): strip CR/LF in imap_quote to prevent IMAP command injection#135
fix(email): strip CR/LF in imap_quote to prevent IMAP command injection#135guanlan wants to merge 1 commit into
Conversation
RFC 3501 prohibits CR and LF inside IMAP quoted strings. Previously, user-controlled inputs (from_contains, subject_contains, login credentials) were passed through imap_quote() without removing newline characters, allowing an attacker to inject arbitrary IMAP commands by embedding \r\n in those fields. Fix: sanitize the input by stripping \r and \n before escaping and quoting. Add two unit tests: - test_imap_quote_strips_crlf_injection: verifies newlines are removed - test_imap_quote_escapes_backslash_and_quote: verifies existing escape behaviour is preserved
There was a problem hiding this comment.
Note
RFC 3501 also prohibits NUL bytes (%x00) in quoted strings. While NUL cannot inject IMAP commands (unlike CR/LF), it could cause truncation in servers that use C-style string handling. Consider adding null-byte stripping in a follow-up if this fits your threat model.
TL;DR — Strip \r and \n from strings passed through imap_quote() to prevent injected IMAP commands via search parameters and other user-controlled inputs.
Key changes
- Strip CR/LF before IMAP quoting — removes
\rand\nfrom the value inimap_quote()per RFC 3501, then escapes\and"as before - Add injection and escape tests — two unit tests verifying the CR/LF injection payload is neutralized and existing escape logic is preserved
Summary | 1 file | 1 commit | base: main ← fix/imap-command-injection
The change adds a sanitization step that removes CR and LF before the standard IMAP quoting logic, closing the command injection vector via user-controlled from_contains or subject_contains parameters. All four call sites (LOGIN, SELECT, FROM, SUBJECT) already use imap_quote, so they are automatically protected. The stripping-before-escaping order is correct (the byte values for \r and \n don't overlap with \ or "), and the test coverage is appropriate.
Big Pickle (free) | 𝕏

Summary
imap_quote()was escaping backslashes and double-quotes but not stripping carriage returns or newlines. RFC 3501 forbids CR and LF inside IMAP quoted strings, and their presence allows an attacker to inject arbitrary IMAP commands via user-controlled input (e.g. thefrom_containsorsubject_containssearch parameters).Example attack vector
This would cause
imap_quoteto produce a string that, when embedded in aUID SEARCHcommand, sends an extraSTOREcommand to the IMAP server.Fix
Sanitize the input in
imap_quoteby removing\rand\nbefore escaping:Tests
Two new unit tests added:
test_imap_quote_strips_crlf_injection— verifies CR and LF are removed from quoted outputtest_imap_quote_escapes_backslash_and_quote— verifies existing escape logic is unaffectedAll 347 tests pass.
Need help on this PR? Tag
@codesmithwith what you need.