forked from driusan/dkim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signature.go
411 lines (386 loc) · 11.3 KB
/
signature.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package dkim
import (
"bufio"
"bytes"
"fmt"
"io"
"net"
"encoding/base64"
"crypto"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/x509"
"regexp"
"strconv"
"strings"
)
type Signature struct {
Version int
Algorithm string
HeaderCanonicalization, BodyCanonicalization string
Domain, Selector string
Headers []string
BodyHash string
Body string
}
func (s Signature) String() string {
ret := fmt.Sprintf("DKIM-Signature: v=%d", s.Version)
if s.Algorithm != "" {
ret += fmt.Sprintf("; a=%v", s.Algorithm)
}
var h, b string
if s.HeaderCanonicalization != "" {
h = s.HeaderCanonicalization
} else {
h = "simple"
}
if s.BodyCanonicalization != "" {
b = s.BodyCanonicalization
} else {
b = "simple"
}
ret += fmt.Sprintf("; c=%v/%v", h, b)
if s.Domain != "" {
ret += fmt.Sprintf("; d=%v", s.Domain)
}
if s.Selector != "" {
ret += fmt.Sprintf("; s=%v", s.Selector)
}
if len(s.Headers) > 0 {
ret += fmt.Sprintf("; h=%v", strings.Join(s.Headers, ":"))
}
if s.BodyHash != "" {
ret += fmt.Sprintf("; bh=%v", s.BodyHash)
}
// Always include an empty b= tag if one doesn't exist.
ret += fmt.Sprintf("; b=%v", s.Body)
return ret
}
func NewSignature(canon string, selector, domain string, headers []string) (Signature, error) {
sig := Signature{
Version: 1,
Algorithm: "rsa-sha256",
Domain: domain,
HeaderCanonicalization: "simple",
BodyCanonicalization: "simple",
Selector: selector,
Headers: headers,
}
switch canon {
case "simple/simple", "simple":
// nothing
case "relaxed/relaxed", "relaxed", "":
sig.HeaderCanonicalization = "relaxed"
sig.BodyCanonicalization = "relaxed"
case "simple/relaxed":
sig.HeaderCanonicalization = "simple"
sig.BodyCanonicalization = "relaxed"
case "relaxed/simple":
sig.HeaderCanonicalization = "relaxed"
sig.BodyCanonicalization = "simple"
default:
return Signature{}, fmt.Errorf("Bad canonicalization")
}
return sig, nil
}
func (s Signature) Sig() []byte {
decoded, err := base64.StdEncoding.DecodeString(s.Body)
if err != nil {
return nil
}
return decoded
}
type Tag struct {
Name, Value string
}
func splitTags(s []byte) []Tag {
var tgs []Tag
tags := bytes.Split(s, []byte{';'})
for _, t := range tags {
if strings.TrimSpace(string(t)) == "" {
continue
}
splitb := bytes.SplitN(t, []byte{'='}, 2)
tgs = append(tgs, Tag{string(bytes.TrimSpace(splitb[0])), string(splitb[1])})
}
return tgs
}
func ParseSignature(header []byte) *Signature {
splith := bytes.SplitN(header, []byte{':'}, 2)
name := string(splith[0])
if strings.ToLower(name) != "dkim-signature" {
return nil
}
tags := splitTags(splith[1])
var s Signature
for _, t := range tags {
switch t.Name {
case "v":
v, err := strconv.Atoi(t.Value)
if err != nil {
return nil
}
s.Version = v
case "a":
s.Algorithm = t.Value
case "bh":
s.BodyHash = whitespaceRE.ReplaceAllString(t.Value, "")
case "b":
s.Body = whitespaceRE.ReplaceAllString(t.Value, "")
case "c":
switch t.Value {
case "simple", "simple/simple":
s.HeaderCanonicalization = "simple"
s.BodyCanonicalization = "simple"
case "relaxed", "relaxed/relaxed":
s.HeaderCanonicalization = "relaxed"
s.BodyCanonicalization = "relaxed"
case "simple/relaxed":
s.HeaderCanonicalization = "simple"
s.BodyCanonicalization = "relaxed"
case "relaxed/simple":
s.HeaderCanonicalization = "relaxed"
s.BodyCanonicalization = "simple"
default:
return nil
}
case "d":
s.Domain = t.Value
case "h":
s.Headers = strings.Split(whitespaceRE.ReplaceAllString(t.Value, ""), ":")
case "s":
s.Selector = t.Value
// FIXME: Add i, l, q, t, x, z
}
}
return &s
}
type Header struct {
Raw, Relaxed []byte
}
// signatureBase calculates the basic parts of the DKIM signature
// shared by both signing and verifying.
//
// It extracts the mail headers from r and returns them in a map along
// with the signature. The bodyhash returned is already base64 encoded.
//
// Newlines must already be normalized to CRLF in r.
//
// If s is passed, it will be used as the DKIM signature (for signing), otherwise
// the signature will be parsed from the message header (for verification). When
// signing, sig.BodyHash will be populated, and when verifying, it will be compared
func signatureBase(r io.ReadSeeker, s *Signature) (sig *Signature, msg, dkimheader []byte, err error) {
headers := make(map[string][]Header)
for raw, conv, err := ReadSMTPHeaderRelaxed(r); err == nil; raw, conv, err = ReadSMTPHeaderRelaxed(r) {
split := bytes.SplitN(conv, []byte{':'}, 2)
name := string(split[0])
// headers acts as an upside-down stack. We add the oldest ones
// to the start, and consume from the front in dkimMessageBase.
headers[name] = append([]Header{Header{raw, conv}}, headers[name]...)
if name == "dkim-signature" && s == nil {
sig = ParseSignature(raw)
}
}
cbody, err := ReadSMTPBodyRelaxed(r)
if err != nil {
return nil, nil, nil, err
}
sha := sha256.Sum256(cbody[:])
encoded := string(base64.StdEncoding.EncodeToString(sha[:]))
if s != nil {
sig = s
s.BodyHash = encoded
raw := []byte(s.String())
relax := relaxHeader(raw)
headers["dkim-signature"] = append([]Header{{raw, relax}}, headers["dkim-signature"]...)
}
if sig == nil {
return nil, nil, nil, fmt.Errorf("Permanent failure: no DKIM signature")
}
if encoded != sig.BodyHash {
return nil, nil, nil, fmt.Errorf("Permanent failure: body hash does not match")
}
var tohash []byte
for _, h := range sig.Headers {
var hval Header
lh := strings.ToLower(h)
if header, ok := headers[lh]; ok && len(header) > 0 {
// If there is a header, consume it so that if a header
// is included in sig.Headers multiple times the next
// one is correct.
hval = header[0]
headers[lh] = header[1:]
}
switch sig.HeaderCanonicalization {
case "simple":
tohash = append(tohash, hval.Raw...)
case "relaxed":
tohash = append(tohash, hval.Relaxed...)
}
}
var sighead []byte
rawsig, ok := headers["dkim-signature"]
if !ok {
return nil, nil, nil, fmt.Errorf("Permanent failure: No DKIM-Signature")
}
if sig.HeaderCanonicalization == "relaxed" {
sighead = bytes.TrimRight(rawsig[0].Relaxed, "\r\n")
} else {
sighead = bytes.TrimRight(rawsig[0].Raw, "\r\n")
}
return sig, tohash, sighead, nil
}
var bRE = regexp.MustCompile("b=[^;]+")
func SignedHeader(s Signature, r io.ReadSeeker, dst io.Writer, key *rsa.PrivateKey, nl string) error {
if nl != "\n" {
nl = "\r\n"
}
sig, msg, basedkimsig, err := signatureBase(r, &s)
b, err := signDKIMMessage(msg, basedkimsig, s.Algorithm, key)
if err != nil {
return err
}
sig.Body = b
fmt.Fprintf(dst, "%v%v", sig, nl)
return nil
}
// SignMessage signs the message in r with the signature parameters from s and
// the private key key, writing the result with the added DKIM-Signature to
// dst.
func SignMessage(s Signature, r io.ReadSeeker, dst io.Writer, key *rsa.PrivateKey, nl string) error {
if nl != "\n" {
nl = "\r\n"
}
sig, msg, basedkimsig, err := signatureBase(r, &s)
b, err := signDKIMMessage(msg, basedkimsig, s.Algorithm, key)
if err != nil {
return err
}
sig.Body = b
if _, err := r.Seek(0, io.SeekStart); err != nil {
return err
}
linescan := bufio.NewScanner(r)
addedSig := false
for linescan.Scan() {
if err := linescan.Err(); err != nil {
return err
}
line := linescan.Text()
if strings.HasPrefix(line, "From ") {
fmt.Fprintf(dst, "%v%v", line, nl)
continue
}
if !addedSig {
addedSig = true
fmt.Fprintf(dst, "%v%v", sig, nl)
fmt.Fprintf(dst, "%v%v", line, nl)
} else {
fmt.Fprintf(dst, "%v%v", line, nl)
}
}
return nil
}
// signDKIMMessage signs a message that has already been canonicalized according
// to the DKIM standard.
func signDKIMMessage(message, dkimsig []byte, algorithm string, key *rsa.PrivateKey) (b string, err error) {
dkimsig = bRE.ReplaceAll(dkimsig, []byte{'b', '='})
message = append(message, dkimsig...)
switch algorithm {
case "rsa-sha256", "sha256":
hash := sha256.Sum256(message)
v, err := rsa.SignPKCS1v15(nil, key, crypto.SHA256, hash[:])
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(v), nil
case "rsa-sha1", "sha1":
hash := sha1.Sum(message)
v, err := rsa.SignPKCS1v15(nil, key, crypto.SHA1, hash[:])
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(v), nil
}
return "", fmt.Errorf("Permanent failure: unknown algorithm")
}
// dkimVerify verifies that a message verifies with header of dkimsig and a
// signature of sig, using the PublicKey key.
//
// message must already prepared according to the DKIM standard (ie. it must only be the
// headers of the DKIM-Signature field, and they must already be canonicalized). dkimsig
// must also be canonicalized, but does not need to have had the b= tag stripped yet.
//
// This function is mostly for testing with a known key. In general, you should use the
// Verify function which does the same thing, but extracts the public key from the appropriate
// place according to the dkimsig.
func dkimVerify(message, dkimsig []byte, sig []byte, algorithm string, key *rsa.PublicKey) error {
dkimsig = bRE.ReplaceAll(dkimsig, []byte{'b', '='})
message = append(message, dkimsig...)
switch algorithm {
case "rsa-sha256", "sha256":
hash := sha256.Sum256(message)
return rsa.VerifyPKCS1v15(key, crypto.SHA256, hash[:], sig)
case "rsa-sha1", "sha1":
hash := sha1.Sum(message)
return rsa.VerifyPKCS1v15(key, crypto.SHA1, hash[:], sig)
}
return fmt.Errorf("Permanent failure: unknown algorithm")
}
// VerifyWithPublicKey verifies a reader r, but uses the passed public key
// instead of trying to extract the key from the DNS.
func VerifyWithPublicKey(r io.ReadSeeker, key *rsa.PublicKey) error {
sig, msg, sighead, err := signatureBase(r, nil)
if err != nil {
return err
}
if key == nil {
if key, err = lookupKeyFromDNS(sig.Selector + "._domainkey." + sig.Domain); err != nil {
return err
}
}
sighash, err := base64.StdEncoding.DecodeString(sig.Body)
if err != nil {
return fmt.Errorf("Permanent failure: could not decode body")
}
return dkimVerify(msg, sighead, sighash, sig.Algorithm, key)
}
// Verify verifies the message from reader r has a valid DKIM signature.
//
// Newlines in r must already be in CRLF format.
func Verify(r io.ReadSeeker) error {
return VerifyWithPublicKey(r, nil)
}
func DecodeDNSTXT(txt string) (*rsa.PublicKey, error) {
// FIXME: This should check the k tag instead of assuming
// rsa
for _, tag := range splitTags([]byte(txt)) {
if tag.Name == "p" {
decoded, err := base64.StdEncoding.DecodeString(tag.Value)
if err != nil {
continue
}
key, err := x509.ParsePKIXPublicKey(decoded)
if err != nil {
continue
}
if c, ok := key.(*rsa.PublicKey); ok {
return c, nil
}
}
}
return nil, fmt.Errorf("No key found")
}
func lookupKeyFromDNS(loc string) (*rsa.PublicKey, error) {
txt, err := net.LookupTXT(loc)
if err != nil {
return nil, fmt.Errorf("Temporary failure: %v", err)
}
for _, entry := range txt {
if key, err := DecodeDNSTXT(entry); err == nil {
return key, nil
}
}
return nil, fmt.Errorf("Permanent error: no public key found")
}