mailer: quote recipients, cap header lines, refuse encoded controls
Task 6 review, mailer hardening: - validRequest writes each recipient out again as an addr-spec, its local part quoted by net/mail's rule, and refuses one that does not parse back to itself: "a b"@x no longer reaches SES as a b@x. - headerBlock refuses a header line over 998 characters before its line ending (RFC 5322 2.1.1), field or continuation. - headerBlock decodes the RFC 2047 encoded words (B and Q) of From, Sender, Reply-To, To, Cc and Subject, unfolded, and refuses one that decodes to a control character (C0 but tab, DEL, C1, U+2028/9) or that does not decode. A charset Go does not know is read as raw bytes; ESC is allowed only in ISO-2022. The reported From, which decodes to "cafe\r\nBcc: victim@example.com", is now a 400 before SES. Census: the internal/mailer envelope is re-proposed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+247
−7
internal/mailer/hygiene.go+75 −4internal/mailer/hygiene_test.go+81 −0internal/mailer/send.go+29 −2internal/mailer/send_test.go+61 −0internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv+1 −1
diff --git a/internal/mailer/hygiene.go b/internal/mailer/hygiene.go| index cb84cece9..81567786e 100644 |
| --- a/internal/mailer/hygiene.go |
| +++ b/internal/mailer/hygiene.go |
| @@ -3,6 +3,9 @@ package mailer |
| import ( |
| "bytes" |
| "errors" |
| + "io" |
| + "mime" |
| + "regexp" |
| "strings" |
| ) |
| @@ -46,22 +49,37 @@ var errHeaderSyntax = errors.New("mailer: malformed header block") |
| // the first line) nor a field name of printable ASCII (RFC 5322 ftext, |
| // 33-126 without the colon) immediately followed by ":". So "From :" |
| // and "From\t:", which a lenient reader takes as From and net/mail |
| -// keys as "From ", are refused rather than guessed at. |
| +// keys as "From ", are refused rather than guessed at; |
| +// - a line longer than 998 characters before its line ending (RFC 5322 |
| +// §2.1.1), which a relay may fold or cut where it likes (Task 6 review); |
| +// - in From, Sender, Reply-To, To, Cc or Subject, an RFC 2047 encoded |
| +// word (B or Q) that does not decode, or that decodes to a control |
| +// character: CR, LF, NUL and the rest (cleanEncodedWords). A reader |
| +// that decodes the display name and writes it out again would |
| +// otherwise write the decoded line break as a new header field. |
| func headerBlock(raw []byte) ([]byte, error) { |
| header, _, ok := splitHeader(raw) |
| if !ok { |
| return nil, errNoSeparator |
| } |
| first := true |
| + // The field being read, by lowercased name, and its unfolded value. |
| + var name string |
| + var value []byte |
| + field := func() bool { return !decodedFields[name] || cleanEncodedWords(string(value)) } |
| for i := 0; i < len(header); { |
| j := bytes.IndexByte(header[i:], '\n') |
| line := bytes.TrimSuffix(header[i:i+j], []byte{'\r'}) |
| i += j + 1 |
| - value := line |
| + if len(line) > maxLine { |
| + return nil, errHeaderSyntax |
| + } |
| + rest := line |
| if line[0] == ' ' || line[0] == '\t' { |
| if first { |
| return nil, errHeaderSyntax |
| } |
| + value = append(value, line...) |
| } else { |
| c := bytes.IndexByte(line, ':') |
| if c <= 0 { |
| @@ -72,18 +90,71 @@ func headerBlock(raw []byte) ([]byte, error) { |
| return nil, errHeaderSyntax |
| } |
| } |
| - value = line[c+1:] |
| + if !first && !field() { |
| + return nil, errHeaderSyntax |
| + } |
| + rest = line[c+1:] |
| + name, value = strings.ToLower(string(line[:c])), append([]byte(nil), rest...) |
| } |
| - for _, b := range value { |
| + for _, b := range rest { |
| if (b < 0x20 && b != '\t') || b == 0x7f { |
| return nil, errHeaderSyntax |
| } |
| } |
| first = false |
| } |
| + if !first && !field() { |
| + return nil, errHeaderSyntax |
| + } |
| return header, nil |
| } |
| +// maxLine is RFC 5322 §2.1.1's limit on a line, without its CRLF. |
| +const maxLine = 998 |
| + |
| +// encodedWord is the shape of an RFC 2047 encoded word, B or Q, in any |
| +// case: what is left of one after decoding is one that did not decode. |
| +var encodedWord = regexp.MustCompile(`=\?[^?\s]+\?[bBqQ]\?[^?\s]*\?=`) |
| + |
| +// decodedFields are the header fields whose encoded words a reader is |
| +// known to decode (RFC 2047 §5): the address fields' display names, and |
| +// the subject. Lowercased. |
| +var decodedFields = map[string]bool{"from": true, "sender": true, "reply-to": true, "to": true, "cc": true, "subject": true} |
| + |
| +// cleanEncodedWords reports whether every RFC 2047 encoded word in an |
| +// unfolded field value decodes, B or Q, and decodes to no control |
| +// character: no C0 control but tab, no DEL, no C1 control and no Unicode |
| +// line or paragraph separator. A charset Go does not know is decoded as |
| +// its raw bytes, so a CR, LF or NUL in it is still seen; ESC is allowed in |
| +// an ISO-2022 charset, whose shifts are written with it. A word that does |
| +// not decode (mime leaves it as it was) is refused too: a lenient reader |
| +// may decode it, skipping what Go would not. A value with no "=?" has no |
| +// encoded word, and is clean. |
| +func cleanEncodedWords(v string) bool { |
| + if !strings.Contains(v, "=?") { |
| + return true |
| + } |
| + iso2022 := false |
| + d := mime.WordDecoder{CharsetReader: func(charset string, in io.Reader) (io.Reader, error) { |
| + if strings.HasPrefix(strings.ToLower(charset), "iso-2022-") { |
| + iso2022 = true |
| + } |
| + return in, nil |
| + }} |
| + text, err := d.DecodeHeader(v) |
| + if err != nil || encodedWord.MatchString(text) { |
| + return false |
| + } |
| + for _, r := range text { |
| + switch { |
| + case r == '\t', r == 0x1b && iso2022: |
| + case r < 0x20, r == 0x7f, r >= 0x80 && r <= 0x9f, r == 0x2028, r == 0x2029: |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| // strippedField reports whether a header field of this name never reaches |
| // SES (design §5, Header hygiene): Bcc, and every X-SES-* field. SMTP |
| // honours X-SES-TENANT, X-SES-CONFIGURATION-SET and X-SES-MESSAGE-TAGS, and |
diff --git a/internal/mailer/hygiene_test.go b/internal/mailer/hygiene_test.go| index 95e482f49..2e14214df 100644 |
| --- a/internal/mailer/hygiene_test.go |
| +++ b/internal/mailer/hygiene_test.go |
| @@ -114,3 +114,84 @@ func TestOneFromRefusesMalformedHeaderBlocks(t *testing.T) { |
| t.Fatalf("a well-formed message: %q %v", got, ok) |
| } |
| } |
| + |
| +// Task 6 review: an encoded word (RFC 2047, B or Q) in From, Sender, |
| +// Reply-To, To, Cc or Subject that decodes to a control character is |
| +// refused: a reader that decodes a display name and writes it out again |
| +// would write its CRLF as a new field. So is one that does not decode. |
| +func TestHeaderBlockRefusesEncodedControls(t *testing.T) { |
| + const from = "docs@app.example" |
| + msg := func(fields ...string) []byte { |
| + return []byte(strings.Join(fields, "\r\n") + "\r\n\r\nbody\r\n") |
| + } |
| + for name, raw := range map[string][]byte{ |
| + // The review's repro: "café\r\nBcc: victim@example.com". |
| + "B, CRLF in From's name": msg("From: =?utf-8?b?Y2Fmw6kNCkJjYzogdmljdGltQGV4YW1wbGUuY29t?= <" + from + ">"), |
| + "Q, CRLF in From's name": msg("From: =?utf-8?q?caf=C3=A9=0D=0ABcc:_victim@example.com?= <" + from + ">"), |
| + "Q, upper-case markers": msg("From: =?UTF-8?Q?a=0Ab?= <" + from + ">"), |
| + "Q, LF in Subject": msg("From: "+from, "Subject: =?utf-8?q?hi=0ABcc:_v@example.com?="), |
| + "B, NUL in Subject": msg("From: "+from, "Subject: =?utf-8?b?aGkAdGhlcmU=?="), |
| + "Q, CR in To": msg("From: "+from, "To: =?utf-8?q?x=0Dy?= <x@example.org>"), |
| + "Q, LF in Cc": msg("From: "+from, "Cc: =?utf-8?q?x=0Ay?= <y@example.org>"), |
| + "Q, LF in Reply-To": msg("From: "+from, "reply-to: =?utf-8?q?x=0Ay?= <y@example.org>"), |
| + "Q, LF in Sender": msg("From: "+from, "SENDER: =?utf-8?q?x=0Ay?= <y@example.org>"), |
| + "Q, DEL": msg("From: "+from, "Subject: =?utf-8?q?x=7Fy?="), |
| + "Q, a C1 control": msg("From: "+from, "Subject: =?utf-8?q?x=C2=85y?="), |
| + "Q, latin-1 NEL": msg("From: "+from, "Subject: =?iso-8859-1?q?x=85y?="), |
| + "Q, line separator": msg("From: "+from, "Subject: =?utf-8?q?x=E2=80=A8y?="), |
| + "Q, unknown charset CR": msg("From: "+from, "Subject: =?x-unknown?q?x=0Dy?="), |
| + "B, ESC outside ISO-2022": msg("From: "+from, "Subject: =?utf-8?b?eBt5?="), |
| + "a folded encoded word": msg("From: "+from, "Subject: hello", " =?utf-8?q?x=0Ay?="), |
| + "B that does not decode": msg("From: "+from, "Subject: =?utf-8?b?!!!?="), |
| + "B a lenient reader reads as CRLF": msg("From: "+from, "Subject: =?utf-8?b?DQo*?="), |
| + "Q with a bad escape": msg("From: "+from, "Subject: =?utf-8?q?=ZZ?="), |
| + "the last field": msg("From: "+from, "To: x@example.org", "Subject: =?utf-8?q?x=0Ay?="), |
| + } { |
| + if _, err := headerBlock(raw); err == nil { |
| + t.Errorf("%s: headerBlock admitted %q", name, raw) |
| + } |
| + if got, ok := oneFrom(raw, from); ok { |
| + t.Errorf("%s: oneFrom admitted %q", name, got) |
| + } |
| + } |
| + for name, raw := range map[string][]byte{ |
| + "B, a UTF-8 name": msg("From: =?utf-8?b?Y2Fmw6k=?= <" + from + ">"), |
| + "Q, a UTF-8 name": msg("From: =?utf-8?q?caf=C3=A9?= <" + from + ">"), |
| + "Q, a tab": msg("From: "+from, "Subject: =?utf-8?q?a=09b?="), |
| + "ISO-2022-JP's ESC": msg("From: "+from, "Subject: =?iso-2022-jp?b?GyRCJEokcyQrGyhC?="), |
| + "no encoded word": msg("From: Docs <"+from+">", "Subject: =? not a word"), |
| + "a folded subject": msg("From: "+from, "Subject: =?utf-8?q?caf=C3=A9?=", " =?utf-8?q?_au_lait?="), |
| + } { |
| + if _, err := headerBlock(raw); err != nil { |
| + t.Errorf("%s: headerBlock refused %q: %v", name, raw, err) |
| + } |
| + if got, ok := oneFrom(raw, from); !ok || got != from { |
| + t.Errorf("%s: oneFrom %q %v", name, got, ok) |
| + } |
| + } |
| +} |
| + |
| +// Task 6 review: a header line over 998 characters before its line ending |
| +// (RFC 5322 §2.1.1) is refused, whether a field or a continuation, CRLF or |
| +// LF; the body is not the header's to judge. |
| +func TestHeaderBlockLineLimit(t *testing.T) { |
| + const from = "docs@app.example" |
| + subject := func(n int) string { return "Subject: " + strings.Repeat("a", n-len("Subject: ")) } |
| + for name, c := range map[string]struct { |
| + raw string |
| + admit bool |
| + }{ |
| + "998, CRLF": {"From: " + from + "\r\n" + subject(998) + "\r\n\r\nb\r\n", true}, |
| + "999, CRLF": {"From: " + from + "\r\n" + subject(999) + "\r\n\r\nb\r\n", false}, |
| + "998, LF": {"From: " + from + "\n" + subject(998) + "\n\nb\n", true}, |
| + "999, LF": {"From: " + from + "\n" + subject(999) + "\n\nb\n", false}, |
| + "999, a continuation": {"From: " + from + "\r\nSubject: s\r\n " + strings.Repeat("a", 998) + "\r\n\r\nb\r\n", false}, |
| + "999, the first line": {"From: " + from + strings.Repeat(" ", 999-len("From: "+from)) + "\r\n\r\nb\r\n", false}, |
| + "a long body line is fine": {"From: " + from + "\r\n\r\n" + strings.Repeat("b", 5000) + "\r\n", true}, |
| + } { |
| + _, err := headerBlock([]byte(c.raw)) |
| + if (err == nil) != c.admit { |
| + t.Errorf("%s: headerBlock err %v, want admitted %v", name, err, c.admit) |
| + } |
| + } |
| +} |
diff --git a/internal/mailer/send.go b/internal/mailer/send.go| index 09e57c4b8..9a496f476 100644 |
| --- a/internal/mailer/send.go |
| +++ b/internal/mailer/send.go |
| @@ -265,7 +265,11 @@ func (m *Mailer) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // address with no display name, and a raw message within the limit. The |
| // agent checked most of it; the mailer does not rely on that. It returns |
| // the parsed recipient addresses, which are what SES is given (review |
| -// round 1, Task 5 P3), never the strings as they came. |
| +// round 1, Task 5 P3), never the strings as they came. Each is written |
| +// out again as an addr-spec, its local part quoted where RFC 5322 needs |
| +// it (Task 6 review): net/mail's Address drops the quotes, so "a b"@x |
| +// would go out as a b@x. One that does not parse back to itself is |
| +// refused. |
| func validRequest(req mailsubmit.SendRequest) ([]string, bool) { |
| if !release.ValidAccount(req.Account) || !release.ValidApp(req.App) || !validHost(req.Host) { |
| return nil, false |
| @@ -279,11 +283,34 @@ func validRequest(req mailsubmit.SendRequest) ([]string, bool) { |
| if err != nil || a.Name != "" || !strings.Contains(a.Address, "@") { |
| return nil, false |
| } |
| - to = append(to, a.Address) |
| + spec, ok := addrSpec(a.Address) |
| + if !ok { |
| + return nil, false |
| + } |
| + to = append(to, spec) |
| } |
| return to, true |
| } |
| +// addrSpec is address (net/mail's unquoted local@domain) written as an |
| +// RFC 5322 addr-spec, by net/mail's own quoting rule, when that parses |
| +// back to the same address with no display name. |
| +func addrSpec(address string) (string, bool) { |
| + spec := (&mail.Address{Address: address}).String() |
| + spec, ok := strings.CutPrefix(spec, "<") |
| + if !ok { |
| + return "", false |
| + } |
| + if spec, ok = strings.CutSuffix(spec, ">"); !ok { |
| + return "", false |
| + } |
| + back, err := mail.ParseAddress(spec) |
| + if err != nil || back.Name != "" || back.Address != address { |
| + return "", false |
| + } |
| + return spec, true |
| +} |
| + |
| // validHost is a hostname a record key may be built from: no path |
| // separators, no traversal. |
| func validHost(h string) bool { |
diff --git a/internal/mailer/send_test.go b/internal/mailer/send_test.go| index c91018ffb..245ff2083 100644 |
| --- a/internal/mailer/send_test.go |
| +++ b/internal/mailer/send_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "errors" |
| "net/http" |
| + "net/mail" |
| "strconv" |
| "strings" |
| "sync" |
| @@ -585,3 +586,63 @@ func TestMailerRefusesMalformedRequests(t *testing.T) { |
| t.Fatalf("SES called %d times", h.ses.n()) |
| } |
| } |
| + |
| +// Task 6 review: a recipient whose local part needs quoting goes to SES |
| +// quoted, as net/mail parsed it, and every recipient given to SES parses |
| +// back to the address the request named. |
| +func TestMailerRecipientsKeepTheirQuoting(t *testing.T) { |
| + for in, want := range map[string]string{ |
| + "x@example.org": "x@example.org", |
| + "x.y+tag@example.org": "x.y+tag@example.org", |
| + `"a b"@example.org`: `"a b"@example.org`, |
| + `"a\"b"@example.org`: `"a\"b"@example.org`, |
| + `"x..y"@example.org`: `"x..y"@example.org`, |
| + `"a@b"@example.org`: `"a@b"@example.org`, |
| + "<x@example.org>": "x@example.org", |
| + `"Bcc: y"@example.org`: `"Bcc: y"@example.org`, |
| + } { |
| + got, ok := validRequest(mailsubmit.SendRequest{Account: tAcct, App: tApp, Host: tHost, From: tFrom, |
| + To: []string{in}, Raw: []byte(message(tFrom))}) |
| + if !ok || len(got) != 1 || got[0] != want { |
| + t.Errorf("%s: %q %v, want %q", in, got, ok, want) |
| + continue |
| + } |
| + first, err1 := mail.ParseAddress(in) |
| + back, err2 := mail.ParseAddress(got[0]) |
| + if err1 != nil || err2 != nil || back.Address != first.Address { |
| + t.Errorf("%s: %q does not round-trip: %v %v %v", in, got[0], back, err1, err2) |
| + } |
| + } |
| + |
| + h := newHarness(t) |
| + got := h.send(h.request(func(r *mailsubmit.SendRequest) { r.To = []string{`"a b"@example.org`, "x@example.org"} })) |
| + if got.status != http.StatusOK { |
| + t.Fatalf("send: %+v", got) |
| + } |
| + if to := h.ses.last().Destination.ToAddresses; len(to) != 2 || to[0] != `"a b"@example.org` || to[1] != "x@example.org" { |
| + t.Fatalf("SES was given %q", to) |
| + } |
| +} |
| + |
| +// Task 6 review: the encoded From the review reported, which decodes to |
| +// "café\r\nBcc: victim@example.com", is a 400 before SES. |
| +func TestMailerRefusesEncodedHeaderInjection(t *testing.T) { |
| + h := newHarness(t) |
| + for _, from := range []string{ |
| + "=?utf-8?b?Y2Fmw6kNCkJjYzogdmljdGltQGV4YW1wbGUuY29t?=", |
| + "=?utf-8?q?caf=C3=A9=0D=0ABcc:_victim@example.com?=", |
| + } { |
| + raw := "From: " + from + " <" + tFrom + ">\r\nTo: x@example.org\r\nSubject: hi\r\n\r\nbody\r\n" |
| + got := h.send(h.request(func(r *mailsubmit.SendRequest) { r.Raw = []byte(raw) })) |
| + if got.status != http.StatusBadRequest || got.ans.Code != mailsubmit.CodeBadRequest { |
| + t.Errorf("%s: %+v, want 400 bad_request", from, got) |
| + } |
| + } |
| + if h.ses.n() != 0 { |
| + t.Fatalf("SES called %d times", h.ses.n()) |
| + } |
| + raw := "From: =?utf-8?b?Y2Fmw6k=?= <" + tFrom + ">\r\nTo: x@example.org\r\nSubject: hi\r\n\r\nbody\r\n" |
| + if got := h.send(h.request(func(r *mailsubmit.SendRequest) { r.Raw = []byte(raw) })); got.status != http.StatusOK { |
| + t.Fatalf("a clean encoded name: %+v", got) |
| + } |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv b/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv| index 6ba30caac..468c9f688 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv |
| @@ -95,7 +95,7 @@ internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve- |
| @coverage internal/host/units 63a333f0bb4a354fdde9802089f4ec6794cdfbf774c20fbd48cffab805cd022c |
| @coverage internal/hostenv 6c96c4abe8548fe3cf12d3a220de3e2917c3edfa5320b1662ea76bdf364d24b5 |
| @coverage internal/instancectl 811493ad636a21f5f8e7f2336e8e58055fd2a83f53dd71ef689cd90232e7d3df |
| -@coverage internal/mailer 2f20d6b5968e8e4264fc183865a671d3d89db274e79eb207df06ecf7c31cf186 |
| +@coverage internal/mailer 5ffd93e2e875a9ccbfb2ac72e2527cb0b9c47360e8b917c527057f5409d685c6 |
| @coverage internal/mailsubmit 519123e15891e0802427595306d8caca1fd7f4f861ae1a2ec70e1c10f012e263 |
| @coverage internal/mailwire 0242392c670a0f61b875056b0d79576ccb69c2e29f56735cbb191e7d038222a0 |
| @coverage internal/moves 9390702695d308a327f5572f4ff5967718141c5d385dff7671ff1e2c825ef407 |