internal/mailin/authres.go

211 lines · 5503 bytes

  1package mailin
  2
  3import (
  4	"net/mail"
  5	"strings"
  6
  7	"golang.org/x/net/publicsuffix"
  8)
  9
 10// authenticated checks the sender against the mail host's own verdict:
 11// the topmost Authentication-Results header (RFC 8601) whose authserv-id
 12// is authserv. The mail host adds its header above any the message
 13// arrived with, so a lower header claiming the same id is the sender's
 14// and is not read. It returns "" when the header shows dmarc=pass for
 15// the From domain, or dkim=pass with a header.d aligned with it, and the
 16// refusal's reason otherwise.
 17func authenticated(h mail.Header, authserv, from string) string {
 18	_, fromDomain, ok := strings.Cut(strings.ToLower(from), "@")
 19	if !ok || fromDomain == "" {
 20		return "no From domain"
 21	}
 22	for _, v := range h["Authentication-Results"] {
 23		segs := splitResults(tokenize(v))
 24		if len(segs) == 0 || len(segs[0]) == 0 || segs[0][0].kind != tokAtom ||
 25			!strings.EqualFold(segs[0][0].text, authserv) {
 26			continue
 27		}
 28		for _, seg := range segs[1:] {
 29			method, result, props, ok := resinfo(seg)
 30			if !ok || result != "pass" {
 31				continue
 32			}
 33			switch method {
 34			case "dmarc":
 35				if props["header.from"] == fromDomain {
 36					return ""
 37				}
 38			case "dkim":
 39				if aligned(props["header.d"], fromDomain) {
 40					return ""
 41				}
 42			}
 43		}
 44		return "sender not authenticated by " + authserv + " (no DMARC pass or aligned DKIM pass)"
 45	}
 46	return "no Authentication-Results from " + authserv
 47}
 48
 49type tokKind int
 50
 51const (
 52	tokAtom tokKind = iota
 53	tokQuoted
 54	tokEquals
 55	tokSemi
 56)
 57
 58type token struct {
 59	kind tokKind
 60	text string // an atom's text, or a quoted string's content unescaped
 61	// joined marks a token with no whitespace or comment before it, so
 62	// "x"@example.org is one value.
 63	joined bool
 64}
 65
 66// tokenize splits a header value into atoms, quoted strings, "=" and
 67// ";". Comments, nested or not, and whitespace separate tokens and are
 68// dropped; backslash escapes are honoured in both comments and quoted
 69// strings, so nothing inside either can end it early. An unterminated
 70// quoted string or comment runs to the end of the value.
 71func tokenize(s string) []token {
 72	var out []token
 73	joined := false
 74	emit := func(t token) {
 75		t.joined = joined
 76		out = append(out, t)
 77		joined = true
 78	}
 79	for i := 0; i < len(s); {
 80		c := s[i]
 81		switch {
 82		case c == ' ' || c == '\t' || c == '\r' || c == '\n':
 83			joined = false
 84			i++
 85		case c == '(':
 86			i = commentEnd(s, i)
 87			joined = false
 88		case c == '"':
 89			var b strings.Builder
 90			i++
 91			for i < len(s) && s[i] != '"' {
 92				if s[i] == '\\' && i+1 < len(s) {
 93					i++
 94				}
 95				b.WriteByte(s[i])
 96				i++
 97			}
 98			i++ // the closing quote
 99			emit(token{kind: tokQuoted, text: b.String()})
100		case c == '=':
101			emit(token{kind: tokEquals})
102			i++
103		case c == ';':
104			emit(token{kind: tokSemi})
105			i++
106		default:
107			j := i
108			for j < len(s) && !strings.ContainsRune(" \t\r\n()\";=\\", rune(s[j])) {
109				j++
110			}
111			if j == i { // a stray backslash
112				j++
113			}
114			emit(token{kind: tokAtom, text: s[i:j]})
115			i = j
116		}
117	}
118	return out
119}
120
121// commentEnd is the index just past the comment opening at s[i], with
122// nested parentheses and backslash escapes; past the end when unclosed.
123func commentEnd(s string, i int) int {
124	depth := 0
125	for ; i < len(s); i++ {
126		switch s[i] {
127		case '\\':
128			i++
129		case '(':
130			depth++
131		case ')':
132			depth--
133			if depth == 0 {
134				return i + 1
135			}
136		}
137	}
138	return i
139}
140
141// splitResults splits tokens at each ";".
142func splitResults(ts []token) [][]token {
143	segs := [][]token{nil}
144	for _, t := range ts {
145		if t.kind == tokSemi {
146			segs = append(segs, nil)
147			continue
148		}
149		segs[len(segs)-1] = append(segs[len(segs)-1], t)
150	}
151	return segs
152}
153
154// resinfo reads "method[/version]=result" and the "name=value" pairs
155// after it. Method, result and each value must be plain atoms; a quoted
156// value (a reason, or a quoted local part) is kept only as a quoted
157// value and never read as a domain. ok is false when the method does
158// not parse.
159func resinfo(ts []token) (method, result string, props map[string]string, ok bool) {
160	props = map[string]string{}
161	if len(ts) < 3 || ts[0].kind != tokAtom || ts[1].kind != tokEquals || ts[2].kind != tokAtom {
162		return "", "", props, false
163	}
164	method, _, _ = strings.Cut(strings.ToLower(ts[0].text), "/")
165	result = strings.ToLower(ts[2].text)
166	i := 3
167	// A value continues through tokens joined to it: "x"@example.org.
168	for i < len(ts) && ts[i].joined && ts[i].kind != tokEquals {
169		i++
170	}
171	for i < len(ts) {
172		if ts[i].kind != tokAtom || i+2 >= len(ts) || ts[i+1].kind != tokEquals {
173			i++
174			continue
175		}
176		name := strings.ToLower(ts[i].text)
177		v := ts[i+2]
178		j := i + 3
179		plain := v.kind == tokAtom
180		for j < len(ts) && ts[j].joined && ts[j].kind != tokEquals {
181			plain = false
182			j++
183		}
184		// The first value for a name is the one the mail host wrote
185		// beside the result.
186		if _, seen := props[name]; !seen {
187			if plain {
188				props[name] = strings.ToLower(v.text)
189			} else {
190				props[name] = "" // present, but not a plain domain
191			}
192		}
193		i = j
194	}
195	return method, result, props, true
196}
197
198// aligned is DMARC relaxed alignment: the signing domain and the From
199// domain have the same organizational domain (public suffix plus one
200// label). A domain that is itself a public suffix aligns with nothing.
201func aligned(d, from string) bool {
202	if d == "" {
203		return false
204	}
205	od, err := publicsuffix.EffectiveTLDPlusOne(d)
206	if err != nil {
207		return false
208	}
209	of, err := publicsuffix.EffectiveTLDPlusOne(from)
210	return err == nil && od == of
211}