-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdkim.go
More file actions
872 lines (759 loc) · 24.3 KB
/
Copy pathdkim.go
File metadata and controls
872 lines (759 loc) · 24.3 KB
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
package auth
import (
"bytes"
"crypto"
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"net"
"os"
"sort"
"strings"
"time"
)
// DKIMSigner handles outbound DKIM signing.
type DKIMSigner struct {
Domain string
Selector string
PrivateKey crypto.Signer
Algorithm string // "ed25519" or "rsa"
}
// NewDKIMSigner loads the private key from a file and creates a signer.
func NewDKIMSigner(domain, selector, keyPath, algorithm string) (*DKIMSigner, error) {
keyData, err := os.ReadFile(keyPath)
if err != nil {
return nil, fmt.Errorf("reading DKIM key: %w", err)
}
return NewDKIMSignerFromPEM(domain, selector, keyData, algorithm)
}
// NewDKIMSignerFromPEM creates a signer from PEM-encoded private key data.
// This is used for per-domain DKIM keys stored in the database.
func NewDKIMSignerFromPEM(domain, selector string, pemData []byte, algorithm string) (*DKIMSigner, error) {
block, _ := pem.Decode(pemData)
if block == nil {
return nil, fmt.Errorf("no PEM block found in DKIM key")
}
var signer crypto.Signer
switch algorithm {
case "ed25519":
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("parsing ed25519 private key: %w", err)
}
edKey, ok := key.(ed25519.PrivateKey)
if !ok {
return nil, fmt.Errorf("key is not ed25519")
}
signer = edKey
case "rsa":
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
// Try PKCS1 as fallback
key2, err2 := x509.ParsePKCS1PrivateKey(block.Bytes)
if err2 != nil {
return nil, fmt.Errorf("parsing RSA key: %w (PKCS8: %v)", err2, err)
}
signer = key2
} else {
rsaKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("key is not RSA")
}
signer = rsaKey
}
default:
return nil, fmt.Errorf("unsupported DKIM algorithm: %s", algorithm)
}
return &DKIMSigner{
Domain: domain,
Selector: selector,
PrivateKey: signer,
Algorithm: algorithm,
}, nil
}
// GenerateDKIMKeyPair generates a DKIM key pair and returns PEM-encoded strings.
// Returns: privateKeyPEM, publicKeyPEM, dnsRecordValue, error
func GenerateDKIMKeyPair(algorithm string) (string, string, string, error) {
switch algorithm {
case "ed25519":
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return "", "", "", fmt.Errorf("generating ed25519 key: %w", err)
}
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return "", "", "", fmt.Errorf("marshaling private key: %w", err)
}
privPEM := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}))
pubBytes, err := x509.MarshalPKIXPublicKey(pub)
if err != nil {
return "", "", "", fmt.Errorf("marshaling public key: %w", err)
}
pubPEM := string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubBytes}))
pubB64 := base64.StdEncoding.EncodeToString(pubBytes)
dnsRecord := fmt.Sprintf("v=DKIM1; k=ed25519; p=%s", pubB64)
return privPEM, pubPEM, dnsRecord, nil
case "rsa":
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return "", "", "", fmt.Errorf("generating RSA key: %w", err)
}
privBytes, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return "", "", "", fmt.Errorf("marshaling RSA private key: %w", err)
}
privPEM := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}))
pubBytes, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
return "", "", "", fmt.Errorf("marshaling RSA public key: %w", err)
}
pubPEM := string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubBytes}))
pubB64 := base64.StdEncoding.EncodeToString(pubBytes)
dnsRecord := fmt.Sprintf("v=DKIM1; k=rsa; p=%s", pubB64)
return privPEM, pubPEM, dnsRecord, nil
default:
return "", "", "", fmt.Errorf("unsupported algorithm: %s", algorithm)
}
}
// Sign adds a DKIM-Signature header to the message and returns the signed message.
func (s *DKIMSigner) Sign(message []byte) ([]byte, error) {
// Parse headers from message
headers, bodyOffset, err := parseMessageHeaders(message)
if err != nil {
return nil, fmt.Errorf("parsing headers: %w", err)
}
// Extract body
body := message[bodyOffset:]
// Canonicalize body (relaxed canonicalization)
bodyCanonBytes := bodyHashFunc(false, body) // false = not simple, so relaxed
bh := base64.StdEncoding.EncodeToString(bodyCanonBytes)
// Headers to sign (in order)
signHeaders := []string{"from", "to", "subject", "date", "message-id"}
var signedHeaderNames []string
// Find which headers are present in the message
for _, sh := range signHeaders {
for _, h := range headers {
if strings.EqualFold(h.key, sh) {
signedHeaderNames = append(signedHeaderNames, sh)
break
}
}
}
// Build DKIM-Signature header (without b= value)
algo := "ed25519-sha256"
if s.Algorithm == "rsa" {
algo = "rsa-sha256"
}
timestamp := time.Now().Unix()
expiration := timestamp + 7*86400 // 7 days
dkimHeader := fmt.Sprintf(
"DKIM-Signature: v=1; a=%s; c=relaxed/relaxed; d=%s; s=%s; t=%d; x=%d; h=%s; bh=%s; b=",
algo, s.Domain, s.Selector, timestamp, expiration,
strings.Join(signedHeaderNames, ":"), bh,
)
// Build canonical header data for signing (like RFC 6376 specifies)
var dataToSign bytes.Buffer
for _, sh := range signedHeaderNames {
for _, h := range headers {
if strings.EqualFold(h.key, sh) {
// Convert raw bytes to string for canonicalization
rawStr := strings.TrimSpace(h.key) + ":" + h.value
canonical, _ := relaxedCanonicalHeader(rawStr)
dataToSign.WriteString(canonical)
dataToSign.WriteString("\r\n")
break
}
}
}
// Add DKIM-Signature header itself (without b= value, no trailing CRLF on last header)
dkimCanonical, _ := relaxedCanonicalHeader(dkimHeader)
dataToSign.WriteString(dkimCanonical)
// Sign
hash := sha256.Sum256(dataToSign.Bytes())
var sig []byte
switch key := s.PrivateKey.(type) {
case ed25519.PrivateKey:
sig = ed25519.Sign(key, hash[:])
case *rsa.PrivateKey:
var err error
sig, err = rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, hash[:])
if err != nil {
return nil, fmt.Errorf("RSA signing: %w", err)
}
default:
return nil, fmt.Errorf("unsupported key type")
}
sigB64 := base64.StdEncoding.EncodeToString(sig)
fullDKIMHeader := dkimHeader + sigB64
// Prepend DKIM-Signature to message
var result bytes.Buffer
result.WriteString(fullDKIMHeader)
result.WriteString("\r\n")
result.Write(message)
return result.Bytes(), nil
}
// VerifyDKIM performs basic DKIM verification on an inbound message.
// VerifyDKIM verifies a DKIM signature on an email message.
// Returns: (status, detail) where status is "pass", "fail", or "none"
func VerifyDKIM(message []byte) (string, string) {
// Parse the message into headers and body using proper line-ending preservation
hdrs, bodyOffset, err := parseMessageHeaders(message)
if err != nil {
return "none", "malformed headers"
}
// Debug: dump raw header section to see if Content-Type boundary is present
headerEnd := bytes.Index(message, []byte("\r\n\r\n"))
if headerEnd < 0 {
headerEnd = bytes.Index(message, []byte("\n\n"))
}
if headerEnd < 0 {
headerEnd = len(message)
}
// Find the ACTUAL Content-Type header (not the h= list in DKIM-Signature)
// Look for CR/LF at start (to avoid matching "h=Content-Type:" in DKIM-Signature)
rawHeaders := message[:headerEnd]
ctidx := -1
// Search for \r\nContent-Type: or \nContent-Type: (actual header with line break)
ctidx = bytes.Index(rawHeaders, []byte("\r\nContent-Type:"))
if ctidx >= 0 {
ctidx += 2 // Skip the \r\n
} else {
// Try with just LF
ctidx = bytes.Index(rawHeaders, []byte("\nContent-Type:"))
if ctidx >= 0 {
ctidx += 1 // Skip the \n
} else {
// Maybe Content-Type is the first header
if bytes.HasPrefix(rawHeaders, []byte("Content-Type:")) {
ctidx = 0
}
}
}
if ctidx >= 0 {
// Find the end of this header (next line that doesn't start with space/tab)
ctEnd := ctidx
for ctEnd < len(rawHeaders) {
if rawHeaders[ctEnd] == '\n' {
ctEnd++
if ctEnd < len(rawHeaders) && (rawHeaders[ctEnd] == ' ' || rawHeaders[ctEnd] == '\t') {
ctEnd++
continue
}
break
}
ctEnd++
}
rawContentType := rawHeaders[ctidx:ctEnd]
// Replace the parsed Content-Type header with the raw one from the message
// This ensures the boundary parameter is included for DKIM verification
for i, h := range hdrs {
if strings.EqualFold(h.key, "content-type") {
// Extract the value from the raw bytes (after the colon)
colonIdx := bytes.IndexByte(rawContentType, ':')
var valueStr string
if colonIdx >= 0 {
fullValue := rawContentType[colonIdx+1:]
// Unfold: replace CRLF+space/tab with space
unfolded := string(fullValue)
unfolded = strings.ReplaceAll(unfolded, "\r\n ", " ")
unfolded = strings.ReplaceAll(unfolded, "\r\n\t", " ")
unfolded = strings.ReplaceAll(unfolded, "\n ", " ")
unfolded = strings.ReplaceAll(unfolded, "\n\t", " ")
valueStr = strings.TrimSpace(unfolded)
}
// Replace with the raw header (trimmed of trailing CRLF)
rawTrimmed := bytes.TrimRight(rawContentType, "\r\n")
hdrs[i] = &headerRaw{
key: "Content-Type",
lkey: "content-type",
value: valueStr,
raw: rawTrimmed, // Use the raw bytes with boundary
}
break
}
}
}
// Find DKIM-Signature header
var dkimSig *headerRaw
for _, h := range hdrs {
if strings.EqualFold(h.key, "dkim-signature") {
dkimSig = h
break
}
}
if dkimSig == nil {
return "none", "no DKIM-Signature header"
}
// Parse DKIM tags
tags := parseDKIMTags(dkimSig.value)
domain := tags["d"]
selector := tags["s"]
algo := tags["a"]
headersToVerify := tags["h"]
bodyHashB64 := tags["bh"]
sigB64 := tags["b"]
canonMethod := tags["c"]
if domain == "" || selector == "" || sigB64 == "" {
return "fail", "missing required DKIM tags"
}
// Parse canonicalization (default: simple/simple)
headerSimple := true
bodySimple := true
if canonMethod != "" {
parts := strings.Split(canonMethod, "/")
if len(parts) >= 1 {
headerSimple = strings.EqualFold(strings.TrimSpace(parts[0]), "simple")
}
if len(parts) >= 2 {
bodySimple = strings.EqualFold(strings.TrimSpace(parts[1]), "simple")
}
}
// Extract body and verify body hash
body := message[bodyOffset:]
bodyHash := bodyHashFunc(bodySimple, body)
expectedBH := base64.StdEncoding.EncodeToString(bodyHash)
if bodyHashB64 != expectedBH {
return "fail", "body hash mismatch"
}
// Get public key from DNS
pubKeyRecord := fmt.Sprintf("%s._domainkey.%s", selector, domain)
txtRecords, err := net.LookupTXT(pubKeyRecord)
if err != nil {
return "fail", fmt.Sprintf("DNS lookup failed: %v", err)
}
if len(txtRecords) == 0 {
return "fail", "no DKIM public key in DNS"
}
var pubKeyB64 string
for _, txt := range txtRecords {
dkimTags := parseDKIMTags(txt)
if pubKeyB64 = dkimTags["p"]; pubKeyB64 != "" {
break
}
}
if pubKeyB64 == "" {
return "fail", "no public key in DNS record"
}
pubKeyBytes, err := base64.StdEncoding.DecodeString(pubKeyB64)
if err != nil {
return "fail", "invalid public key encoding"
}
// Build the data to be signed. Use MOX's approach:
// Store headers in reverse order map, then pull from them as needed.
revHdrs := make(map[string][]*headerRaw)
for _, h := range hdrs {
lkey := strings.ToLower(h.key)
// Prepend to list (reverse order)
revHdrs[lkey] = append([]*headerRaw{h}, revHdrs[lkey]...)
}
var dataToSign bytes.Buffer
headersToSign := strings.Split(headersToVerify, ":")
for _, headerName := range headersToSign {
headerName = strings.TrimSpace(headerName)
lkey := strings.ToLower(headerName)
hdrsForKey := revHdrs[lkey]
if len(hdrsForKey) == 0 {
continue
}
// Take first from list and remove it
h := hdrsForKey[0]
revHdrs[lkey] = hdrsForKey[1:]
// Canonicalize header
hval := string(h.raw)
if !headerSimple {
hval, _ = relaxedCanonicalHeader(hval)
}
dataToSign.WriteString(hval)
dataToSign.WriteString("\r\n")
}
// Add DKIM-Signature header with b= value removed
dkimVerifySig := stripDKIMBValue(string(dkimSig.raw))
if !headerSimple {
dkimVerifySig, _ = relaxedCanonicalHeader(dkimVerifySig)
}
// No trailing CRLF on last header per RFC 6376 section 3.5
dataToSign.WriteString(dkimVerifySig)
// Compute final hash
hash := sha256.Sum256(dataToSign.Bytes())
sigBytes, err := base64.StdEncoding.DecodeString(sigB64)
if err != nil {
return "fail", "invalid signature encoding"
}
// Determine algorithm and verify
switch {
case strings.Contains(algo, "ed25519"):
key, err := x509.ParsePKIXPublicKey(pubKeyBytes)
if err == nil {
if edPub, ok := key.(ed25519.PublicKey); ok {
if ed25519.Verify(edPub, hash[:], sigBytes) {
return "pass", "DKIM signature valid"
}
}
} else if len(pubKeyBytes) == ed25519.PublicKeySize {
if ed25519.Verify(ed25519.PublicKey(pubKeyBytes), hash[:], sigBytes) {
return "pass", "DKIM signature valid"
}
}
return "fail", "DKIM signature invalid"
case strings.Contains(algo, "rsa"):
key, err := x509.ParsePKIXPublicKey(pubKeyBytes)
if err != nil {
return "fail", "cannot parse RSA public key"
}
rsaPub, ok := key.(*rsa.PublicKey)
if !ok {
return "fail", "key is not RSA"
}
if err := rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, hash[:], sigBytes); err != nil {
return "fail", "DKIM signature invalid"
}
return "pass", "DKIM signature valid"
}
return "fail", fmt.Sprintf("unsupported algorithm: %s", algo)
}
// GetDKIMDomain extracts the DKIM signing domain (d= tag) from a DKIM-Signature header.
// Returns empty string if no DKIM-Signature is found.
func GetDKIMDomain(message []byte) string {
hdrs, _, err := parseMessageHeaders(message)
if err != nil {
return ""
}
// Find DKIM-Signature header
for _, h := range hdrs {
if strings.EqualFold(h.key, "dkim-signature") {
// Parse DKIM tags
tags := parseDKIMTags(h.value)
return tags["d"]
}
}
return ""
}
// GenerateDKIMKeys generates a new Ed25519 key pair for DKIM signing and writes to files.
// Deprecated: use GenerateDKIMKeyPair for per-domain keys stored in DB.
func GenerateDKIMKeys(keyDir string) error {
privPEM, pubPEM, dnsRecord, err := GenerateDKIMKeyPair("ed25519")
if err != nil {
return err
}
if err := os.MkdirAll(keyDir, 0700); err != nil {
return fmt.Errorf("creating key directory: %w", err)
}
if err := os.WriteFile(keyDir+"/dkim_private.pem", []byte(privPEM), 0600); err != nil {
return fmt.Errorf("writing private key: %w", err)
}
if err := os.WriteFile(keyDir+"/dkim_public.pem", []byte(pubPEM), 0644); err != nil {
return fmt.Errorf("writing public key: %w", err)
}
if err := os.WriteFile(keyDir+"/dkim_dns_record.txt", []byte(dnsRecord+"\n"), 0644); err != nil {
return fmt.Errorf("writing DNS record: %w", err)
}
return nil
}
// --- Helper functions ---
type headerRaw struct {
key string // Original case
lkey string // Lowercase key
value string // Value (unfolded)
raw []byte // Complete header including key, colon, and original formatting
}
// parseMessageHeaders parses headers from a message, preserving CRLF structure.
// Returns headers slice and byte offset where body starts.
func parseMessageHeaders(message []byte) ([]*headerRaw, int, error) {
// Find header/body boundary
headerEnd := bytes.Index(message, []byte("\r\n\r\n"))
if headerEnd == -1 {
headerEnd = bytes.Index(message, []byte("\n\n"))
if headerEnd == -1 {
return nil, 0, fmt.Errorf("no header/body boundary found")
}
// For \n\n boundary, body starts after
return parseHeadersFromBytes(message[:headerEnd]), headerEnd + 2, nil
}
// Parse headers with proper CRLF preservation
hdrs := parseHeadersFromBytes(message[:headerEnd])
return hdrs, headerEnd + 4, nil
}
func parseHeadersFromBytes(headerBytes []byte) []*headerRaw {
var hdrs []*headerRaw
i := 0
for i < len(headerBytes) {
// Check for empty line (end of headers)
if i+1 <= len(headerBytes) && headerBytes[i] == '\r' && i+1 < len(headerBytes) && headerBytes[i+1] == '\n' {
break
}
if headerBytes[i] == '\n' {
break
}
// Read this complete header line (including continuations)
lineStart := i
// Scan to end of FIRST line
for i < len(headerBytes) {
if i+1 < len(headerBytes) && headerBytes[i] == '\r' && headerBytes[i+1] == '\n' {
i += 2
break
}
if headerBytes[i] == '\n' {
i += 1
break
}
i++
}
// Now i is at the start of the next line (or EOF)
// Keep scanning through continuation lines (lines starting with space/tab)
// and update lineEnd to include them
lineEnd := i
for i < len(headerBytes) && (headerBytes[i] == ' ' || headerBytes[i] == '\t') {
// Skip the leading whitespace
i++
// Scan to end of this continuation line
for i < len(headerBytes) {
if i+1 < len(headerBytes) && headerBytes[i] == '\r' && headerBytes[i+1] == '\n' {
i += 2
lineEnd = i
break
}
if headerBytes[i] == '\n' {
i += 1
lineEnd = i
break
}
i++
}
}
// Extract the complete header INCLUDING all continuations
rawLine := headerBytes[lineStart:lineEnd]
// Trim trailing line endings for processing
line := bytes.TrimRight(rawLine, "\r\n")
if len(line) == 0 {
break
}
// Find colon
colonIdx := bytes.IndexByte(line, ':')
if colonIdx == -1 {
continue
}
keyPart := strings.TrimSpace(string(line[:colonIdx]))
// Extract value from the complete folded header
// Find the colon in rawLine to get the full value including continuations
colonIdxRaw := bytes.IndexByte(rawLine, ':')
var valuePart string
if colonIdxRaw >= 0 {
// Get everything after colon, including continuation lines
fullValue := rawLine[colonIdxRaw+1:]
// Unfold: replace CRLF+space/tab with space
valueStr := string(fullValue)
valueStr = strings.ReplaceAll(valueStr, "\r\n ", " ")
valueStr = strings.ReplaceAll(valueStr, "\r\n\t", " ")
valueStr = strings.ReplaceAll(valueStr, "\n ", " ")
valueStr = strings.ReplaceAll(valueStr, "\n\t", " ")
valuePart = strings.TrimSpace(valueStr)
}
// For DKIM, we need to store the header with internal folding preserved
// but WITHOUT the trailing line ending
rawLineForDKIM := bytes.TrimRight(rawLine, "\r\n")
hdrs = append(hdrs, &headerRaw{
key: keyPart,
lkey: strings.ToLower(keyPart),
value: valuePart,
raw: rawLineForDKIM, // Store WITHOUT trailing CRLF, but with internal folding
})
}
return hdrs
}
// bodyHashFunc calculates body hash according to RFC 6376
// Returns []byte specifically (not [32]byte)
func bodyHashFunc(simpleCanon bool, body []byte) []byte {
if simpleCanon {
return bodyHashSimple(body)
}
return bodyHashRelaxed(body)
}
// bodyHashSimple implements simple body canonicalization (RFC 6376 section 3.7.1)
// Ensure body ends with exactly one trailing CRLF
func bodyHashSimple(body []byte) []byte {
// Normalize line endings to CRLF (RFC 6376 requires CRLF)
// First, convert all CRLF to LF, then CR to LF, then LF to CRLF
body = bytes.ReplaceAll(body, []byte("\r\n"), []byte("\n"))
body = bytes.ReplaceAll(body, []byte("\r"), []byte("\n"))
body = bytes.ReplaceAll(body, []byte("\n"), []byte("\r\n"))
// Trim all CRLF/LF from end
body = bytes.TrimRight(body, "\r\n")
if len(body) == 0 {
h := sha256.Sum256([]byte("\r\n"))
return h[:]
}
// Add exactly one CRLF
result := append(body, '\r', '\n')
h := sha256.Sum256(result)
return h[:]
}
// bodyHashRelaxed implements relaxed body canonicalization (RFC 6376 section 3.7.2)
func bodyHashRelaxed(body []byte) []byte {
// Normalize line endings to CRLF (RFC 6376 requires CRLF)
// First, convert all CRLF to LF, then CR to LF, then LF to CRLF
body = bytes.ReplaceAll(body, []byte("\r\n"), []byte("\n"))
body = bytes.ReplaceAll(body, []byte("\r"), []byte("\n"))
body = bytes.ReplaceAll(body, []byte("\n"), []byte("\r\n"))
// Split into lines
lines := bytes.Split(body, []byte("\n"))
var processed [][]byte
for _, line := range lines {
// Remove trailing \r if present
if len(line) > 0 && line[len(line)-1] == '\r' {
line = line[:len(line)-1]
}
// Remove trailing whitespace
line = bytes.TrimRight(line, " \t")
// Collapse internal whitespace
if len(line) > 0 {
line = collapseWSP(line)
}
processed = append(processed, line)
}
// Remove all trailing empty lines
for len(processed) > 0 && len(processed[len(processed)-1]) == 0 {
processed = processed[:len(processed)-1]
}
if len(processed) == 0 {
h := sha256.Sum256([]byte("\r\n"))
return h[:]
}
// Rejoin with CRLF
result := bytes.Join(processed, []byte("\r\n"))
result = append(result, '\r', '\n')
h := sha256.Sum256(result)
return h[:]
}
// collapseWSP replaces sequences of space/tab with a single space
func collapseWSP(line []byte) []byte {
var result []byte
prev := byte(0)
for _, b := range line {
if b == ' ' || b == '\t' {
if prev != ' ' {
result = append(result, ' ')
prev = ' '
}
} else {
result = append(result, b)
prev = b
}
}
return result
}
// relaxedCanonicalHeader returns a relaxed canonical form of a header.
// From RFC 6376 section 3.7.2:
// - Ignore all whitespace at end of lines
// - Reduce all sequences of WSP within a line to a single SP
// Returns with CRLF if present in original, without if not.
func relaxedCanonicalHeader(header string) (string, error) {
// Split on first colon
idx := strings.Index(header, ":")
if idx == -1 {
return "", fmt.Errorf("invalid header: no colon")
}
key := strings.ToLower(strings.TrimSpace(header[:idx]))
value := header[idx+1:]
// Unfold (remove line breaks with continuations)
// RFC 5322: folded headers have CRLF/LF followed by space/tab
// Remove the CRLF+continuation but keep semantic separation
value = strings.ReplaceAll(value, "\r\n ", " ")
value = strings.ReplaceAll(value, "\r\n\t", " ")
value = strings.ReplaceAll(value, "\n ", " ")
value = strings.ReplaceAll(value, "\n\t", " ")
// Replace sequences of WSP with single space
value = collapseWhitespace(value)
// Trim leading and trailing whitespace from value
value = strings.Trim(value, " \t")
return key + ":" + value, nil
}
// collapseWhitespace replaces sequences of space/tab with single space
func collapseWhitespace(s string) string {
var result []byte
prev := byte(0)
for i := 0; i < len(s); i++ {
c := s[i]
if c == ' ' || c == '\t' {
if prev != ' ' {
result = append(result, ' ')
prev = ' '
}
} else {
result = append(result, c)
prev = c
}
}
return string(result)
}
// stripDKIMBValue removes the value from the "b=" field in a DKIM-Signature header.
// Returns the header with "b=" but no value.
func stripDKIMBValue(header string) string {
// Find "b="
bIdx := strings.Index(header, "b=")
if bIdx == -1 {
// No b= field, return as-is
return header
}
// Find the end of the b= value (next semicolon or end of line)
rest := header[bIdx+2:]
semiIdx := strings.IndexByte(rest, ';')
if semiIdx == -1 {
// b= goes to the end, remove everything after
return header[:bIdx+2]
}
// b= value ends at semicolon
return header[:bIdx+2] + rest[semiIdx:]
}
// minInt returns the minimum of two integers
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
func parseDKIMTags(s string) map[string]string {
tags := make(map[string]string)
// Remove all newlines and folding (RFC 5322: folded headers use CRLF+SPACE/TAB)
s = strings.ReplaceAll(s, "\r\n", "")
s = strings.ReplaceAll(s, "\n", "")
s = strings.ReplaceAll(s, "\r", "")
// Also remove standalone tabs (from folded lines)
s = strings.ReplaceAll(s, "\t", "")
// Split on semicolons
parts := strings.Split(s, ";")
for _, part := range parts {
part = strings.TrimSpace(part)
if part == "" {
continue
}
idx := strings.IndexByte(part, '=')
if idx == -1 {
continue
}
key := strings.TrimSpace(part[:idx])
value := strings.TrimSpace(part[idx+1:])
// For the h= tag (header list), clean up spaces around colons
// For other values, remove internal whitespace completely
if strings.ToLower(key) == "h" {
// Remove ALL spaces from h= value, then let Split handle it
// This handles cases like "from: to: subject:" correctly
value = strings.ReplaceAll(value, " ", "")
} else {
// Remove internal whitespace from other values
value = strings.Join(strings.Fields(value), "")
}
tags[key] = value
}
return tags
}
func stripDKIMB(header string) string {
// This function name is misleading - just use stripDKIMBValue
return stripDKIMBValue(header)
}
// Ensure sorted unused
var _ = sort.Strings