-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_spf.go
388 lines (342 loc) · 10 KB
/
parse_spf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package main
import (
"bytes"
"net/netip"
"regexp"
"strconv"
"strings"
"github.com/miekg/dns"
)
type spfMechanism uint8
const (
spfMechanismAll spfMechanism = iota + 1
spfMechanismInclude
spfMechanismA
spfMechanismMx
spfMechanismPtr
spfMechanismIp4
spfMechanismIp6
spfMechanismExists
)
var spfMechanismMap = map[string]spfMechanism{
"all": spfMechanismAll,
"include": spfMechanismInclude,
"a": spfMechanismA,
"mx": spfMechanismMx,
"ptr": spfMechanismPtr,
"ip4": spfMechanismIp4,
"ip6": spfMechanismIp6,
"exists": spfMechanismExists,
}
type spfQualifier uint8
const (
spfQualifierPass spfQualifier = iota + 1
spfQualifierFail
spfQualifierSoftfail
spfQualifierNeutral
)
var spfQualifierMap = map[byte]spfQualifier{
'+': spfQualifierPass,
'-': spfQualifierFail,
'~': spfQualifierSoftfail,
'?': spfQualifierNeutral,
}
type spfModifierType uint8
const (
spfModifierTypeRedirect spfModifierType = iota + 1
spfModifierTypeExplanation
spfModifierTypeUnknown
)
const (
// ( "%{" macro-letter transformers *delimiter "}" ) / "%%" / "%_" / "%-"
// c/r/t excluded, explanation-string only
macroExpand = `%{[slodiphv][0-9]*r?[-.+,/_=]*}|%[%_-]`
// ( *alphanum ALPHA *alphanum ) / ( 1*alphanum "-" *( alphanum / "-" ) alphanum )
topLabel = `(?i:[a-z0-9]*[a-z][a-z0-9]*|[a-z0-9]+-[a-z0-9-]*[a-z0-9])`
// ( "." toplabel [ "." ] ) / macro-expand
domainEnd = `(?:\.` + topLabel + `\.?|` + macroExpand + `)`
// *( macro-expand / macro-literal )
macroString = `(?:` + macroExpand + `|[!-$&-~])*`
ipv4Cidr = `/(?:3[0-2]|[12]?[0-9])`
ipv6Cidr = `/(?:12[0-8]|(?:1[01]|[1-9])?[0-9])`
dualCidr = `(?P<v4cidr>` + ipv4Cidr + `)?(?:/(?P<v6cidr>` + ipv6Cidr + `))?`
)
var (
patternName = compileExactMatch(`(?i)[a-z][a-z0-9_.-]*`)
patternMacroString = compileExactMatch(macroString)
patternIPv4CIDR = compileExactMatch(ipv4Cidr)
patternIPv6CIDR = compileExactMatch(ipv6Cidr)
patternDualCidr = compileExactMatch(dualCidr)
patternRecord = compileExactMatch(`v=spf1(?P<terms>(?: +[^ ]+)+)? *`)
patternDirective = compileExactMatch(`(?P<qualifier>[+?~-]?)(?P<mechanism>(?i)i(?:nclude|p[46])|a(?:ll)?|exists|ptr|mx)(?P<remainder>.*)`)
patternDomainSpec = compileExactMatch(macroString + domainEnd)
)
var (
patternDualCidrMap = getPatternNameMap(patternDualCidr)
patternRecordMap = getPatternNameMap(patternRecord)
patternDirectiveMap = getPatternNameMap(patternDirective)
)
type spfData struct {
terms []any
names []string
spfNames []string
anyUnknown bool
}
type spfDirective struct {
name string // cannot be empty, if it exists; check existence with domain == ""
address netip.Addr
isMacroName bool
qualifier spfQualifier
mechanism spfMechanism
v4cidr uint8
v6cidr uint8
hasV4Cidr bool
hasV6Cidr bool
}
type spfModifier struct {
key string // only for spfModifierTypeUnknown
spec string
modType spfModifierType
isMacroName bool
}
func parseSPF(txt []byte) (ret spfData, err error) {
matches := patternRecord.FindSubmatch(txt)
if matches == nil {
return ret, Error{s: "invalid SPF record, unable to find version v=spf1 at beginning"}
}
if err = ret.parseTerms(matches[patternRecordMap["terms"]]); err != nil {
return spfData{}, err
}
if err = ret.extractData(); err != nil {
return spfData{}, err
}
return ret, err
}
func (data *spfData) extractData() error {
extractDataL:
for _, term := range data.terms {
var name string
var isMacro, isSPFName bool
switch termT := term.(type) {
case spfDirective:
name = termT.name
isMacro = termT.isMacroName
isSPFName = termT.mechanism == spfMechanismInclude
case spfModifier:
switch termT.modType {
case spfModifierTypeRedirect, spfModifierTypeExplanation:
name = termT.spec
isMacro = termT.isMacroName
isSPFName = termT.modType == spfModifierTypeRedirect
case spfModifierTypeUnknown:
data.anyUnknown = true
continue extractDataL // don't try anything with unknown modifiers
}
default:
panic("unknown modifier")
}
if len(name) == 0 {
continue
}
if isMacro {
var ok bool
if name, ok = macroToConstantDomain(name); !ok {
continue
}
}
name = strings.ToLower(name)
if isSPFName {
data.spfNames = append(data.spfNames, name)
} else {
data.names = append(data.names, name)
}
}
return nil
}
func macroToConstantDomain(macro string) (constant string, ok bool) {
index := strings.LastIndexByte(macro, '%')
constSectionStart := strings.IndexByte(macro[index:], '.') + index
if constSectionStart == len(macro)-1 { // matched final "." in fqdn
return "", false
}
return macro[constSectionStart+1:], true
}
func (spf *spfData) parseTerms(txt []byte) (err error) {
for _, field := range bytes.Fields(txt) {
var parsed bool
if parsed, err = spf.tryParseDirective(field); err != nil {
return err
}
if !parsed {
if err = spf.parseModifier(field); err != nil {
return err
}
}
}
return nil
}
func (spf *spfData) tryParseDirective(txt []byte) (parsed bool, err error) {
directive := bytes.SplitN(txt, []byte{' '}, 2)[0]
directiveParts := patternDirective.FindSubmatch(directive)
if directiveParts == nil {
return false, nil
}
qualifier := directiveParts[patternDirectiveMap["qualifier"]]
mechanism := bytes.ToLower(directiveParts[patternDirectiveMap["mechanism"]])
remainder := directiveParts[patternDirectiveMap["remainder"]]
if err = spf.parseDirective(qualifier, mechanism, remainder); err != nil {
return false, err
}
return true, nil
}
func (spf *spfData) parseDirective(qualifierB, mechanismB, remainderB []byte) (err error) {
directive := spfDirective{qualifier: spfQualifierPass, mechanism: spfMechanismMap[string(mechanismB)]}
if len(qualifierB) != 0 {
directive.qualifier = spfQualifierMap[qualifierB[0]]
}
colonI := bytes.IndexByte(remainderB, ':')
slashI := bytes.IndexByte(remainderB, '/')
var domainNet, cidr []byte
if slashI != -1 {
cidr = remainderB[slashI:]
}
if colonI != -1 {
end := len(remainderB)
if slashI != -1 {
end = slashI
}
domainNet = remainderB[colonI+1 : end]
}
switch directive.mechanism { // handle domainNet
case spfMechanismAll:
if len(remainderB) > 0 {
return Error{s: "unexpected data after `all` directive"}
}
case spfMechanismInclude, spfMechanismA, spfMechanismMx, spfMechanismPtr, spfMechanismExists:
if len(domainNet) == 0 {
switch directive.mechanism {
case spfMechanismInclude, spfMechanismExists:
return Error{s: "missing required domain in `include`/`exists`"}
}
} else {
if !patternDomainSpec.Match(domainNet) {
return Error{s: "invalid domain-spec"}
}
directive.isMacroName = bytes.ContainsRune(domainNet, '%')
directive.name = dns.Fqdn(string(domainNet))
}
case spfMechanismIp4, spfMechanismIp6:
if directive.address, err = netip.ParseAddr(string(domainNet)); err != nil {
return err
}
var matchingType bool
switch directive.mechanism {
case spfMechanismIp4:
matchingType = directive.address.Is4()
case spfMechanismIp6:
matchingType = directive.address.Is6()
}
if !matchingType {
return Error{s: "mismatching IP type in `ip4`/`ip6` directive"}
}
}
if len(cidr) > 0 {
switch directive.mechanism { // handle cidr
case spfMechanismAll, spfMechanismInclude, spfMechanismPtr, spfMechanismExists:
return Error{s: "unexpected cidr in `all`/`include`/`ptr`/`exists` directive"}
case spfMechanismA, spfMechanismMx:
matches := patternDualCidr.FindSubmatch(cidr)
if matches == nil {
return Error{s: "invalid dual-cidr in `a`/`mx` directive"}
}
if v4cidr := matches[patternDualCidrMap["v4cidr"]]; len(v4cidr) > 0 {
if directive.v4cidr, err = parseCidrNum(v4cidr); err != nil {
return err
}
directive.hasV4Cidr = true
}
if v6cidr := matches[patternDualCidrMap["v4cidr"]]; len(v6cidr) > 0 {
if directive.v6cidr, err = parseCidrNum(v6cidr); err != nil {
return err
}
directive.hasV6Cidr = true
}
case spfMechanismIp4:
if !patternIPv4CIDR.Match(cidr) {
return Error{s: "invalid ip4 cidr"}
}
if directive.v4cidr, err = parseCidrNum(cidr); err != nil {
return err
}
directive.hasV4Cidr = true
case spfMechanismIp6:
if !patternIPv6CIDR.Match(cidr) {
return Error{s: "invalid ip6 cidr"}
}
if directive.v6cidr, err = parseCidrNum(cidr); err != nil {
return err
}
directive.hasV6Cidr = true
}
}
spf.terms = append(spf.terms, directive)
return nil
}
func (spf *spfData) parseModifier(txt []byte) error {
modifier := spfModifier{}
modifierParts := bytes.SplitN(txt, []byte{'='}, 2)
if len(modifierParts) != 2 {
return Error{s: "unexpected sequence in SPF record, not directive or modifier"}
}
key := modifierParts[0]
spec := modifierParts[1]
switch string(bytes.ToLower(key)) {
case "redirect":
modifier.modType = spfModifierTypeRedirect
case "exp":
modifier.modType = spfModifierTypeExplanation
default:
modifier.modType = spfModifierTypeUnknown
}
switch modifier.modType {
case spfModifierTypeRedirect, spfModifierTypeExplanation:
if !patternDomainSpec.Match(spec) {
return Error{s: "invalid domain spec"}
}
case spfModifierTypeUnknown:
if !patternName.Match(key) {
return Error{s: "invalid unknown-modifier name"}
}
if !patternMacroString.Match(spec) {
return Error{s: "invalid macro string in unknown-modifier"}
}
modifier.key = string(key)
default:
panic("unknown modifier")
}
modifier.spec = dns.Fqdn(string(spec))
modifier.isMacroName = bytes.ContainsRune(spec, '%')
spf.terms = append(spf.terms, modifier)
return nil
}
func getPatternNameMap(pattern *regexp.Regexp) map[string]int {
names := pattern.SubexpNames()
ret := make(map[string]int, len(names)-1) // assumes all matches are named
for i, key := range names {
if key == "" {
continue
}
if _, ok := ret[key]; ok {
panic("duplicate key: " + key)
}
ret[key] = i
}
return ret
}
func parseCidrNum(b []byte) (uint8, error) {
unum, err := strconv.ParseUint(string(b[1:]), 10, 8)
return uint8(unum), err
}
func compileExactMatch(pattern string) *regexp.Regexp {
return regexp.MustCompile(`^` + pattern + `$`)
}