-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmail.go
3797 lines (2807 loc) · 110 KB
/
mail.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
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2024 Andrew Hodel
LICENSE MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package gomail
import (
"crypto/rsa"
"crypto/x509"
"time"
mrand "math/rand"
"unsafe"
"encoding/pem"
"crypto/sha256"
"crypto/rand"
"crypto/tls"
"crypto"
"hash"
"errors"
"context"
"fmt"
"net"
"net/mail"
"bytes"
"strings"
"strconv"
"io"
"encoding/base64"
"mime/quotedprintable"
"os"
"github.com/andrewhodel/go-ip-ac"
)
type mail_from_func func(string, string, string, string, *bool) (bool, string)
type rcpt_to_func func(string, string, *bool) (bool, string)
type headers_func func(map[string]string, string, *bool) bool
type full_message_func func(*[]byte, *map[string]string, *[]map[string]string, *[][]byte, *bool, *string, *bool, *string, *[]string)
type pop3_auth_func func(string, string, string, string) bool
type pop3_stat_func func(string) (int, int)
type pop3_list_func func(string) (int, []int, []int)
type pop3_retr_func func(string, int) string
type pop3_dele_func func(string, int) (bool, string)
type imap4_auth_func func(string, string, string) (bool)
type imap4_list_func func(string, []string, string, string) ([]string)
type imap4_select_func func(string, string) (int, []string, int, int, int)
type imap4_fetch_func func(string, []string, []string) ([]Email)
type imap4_store_func func(string, string, string, string, string) (bool)
type imap4_close_func func(string) (bool)
type imap4_search_func func(string, string) (string)
type Config struct {
SmtpTLSPorts []int64 `json:"smtpTLSPorts"`
SmtpNonTLSPorts []int64 `json:"smtpNonTLSPorts"`
SmtpMaxEmailSize uint64 `json:"smtpMaxEmailSize"`
Imap4Port int64 `json:"imap4Port"`
Pop3Port int64 `json:"pop3Port"`
SslKey string `json:"sslKey"`
SslCert string `json:"sslCert"`
SslCa string `json:"sslCa"`
LoadCertificatesFromFiles bool `json:"loadCertificatesFromFiles"`
Fqdn string `json:"fqdn"`
IdleTimeout int `json:"idleTimeout"`
}
type Email struct {
Uid int
InternalDate time.Time
Flags []string
Body []byte
Headers map[string]string
Rfc822Size int
Mailbox string
}
type SendResp struct {
ReplyCode int
TLSInfo string
}
type OutboundMail struct {
SendingHost string
Username string
Password string
ReceivingHostTlsConfig *tls.Config
ReceivingHost string
Port int
From mail.Address
To []mail.Address
Cc []mail.Address
Bcc []mail.Address
Subj string
Body []byte
DkimPrivateKey []byte
DkimDomain string
DkimSigningAlgo string
DkimExpireSeconds int
Headers map[string]string
FirstSendFailure time.Time
RequireTLS bool
RequireServerNameOfReceivingAddresses bool
STARTTLS_ServerName string
}
type Esmtp struct {
Name string
Parts []string
}
func ParseTags(b []byte) (map[string]string, []string) {
// converts " a=asdf; b=afsdf" to
// v["a"] = "asdf"
// v["b"] = "afsdf"
// all the values, out of order
var tags = make(map[string]string, 0)
// the order of the tags
var order = make([]string, 0)
var tag_found = false
var tag []byte
var value []byte
i := 0
for {
if (i == len(b)) {
break
}
if (tag_found == true) {
// add to the value
if (b[i] == ';' || i == len(b)-1) {
// value end or end of data found
if (b[i] != ';') {
// last character is part of the value
value = append(value, b[i])
}
//fmt.Println("tag", string(tag), string(value))
// add the tag to tags
tags[string(tag)] = string(value)
order = append(order, string(tag))
tag_found = false
tag = nil
value = nil
i = i + 1
continue
} else {
value = append(value, b[i])
}
} else {
// add to the tag
if (b[i] == '=') {
// separator found
tag_found = true
i = i + 1
continue
} else {
// do not add tabs or spaces in the tag name
if (b[i] != 9 && b[i] != ' ') {
tag = append(tag, b[i])
}
}
}
i = i + 1
}
return tags, order
}
// execute and respond to a command
func smtpExecCmd(ip_ac ipac.Ipac, using_tls bool, conn net.Conn, tls_config tls.Config, config Config, c []byte, auth_login *string, auth_password *string, login_status *int, authed *bool, esmtp_authed *bool, mail_from *string, rcpt_to_addresses *[]string, parse_data *bool, sent_cmds *int, login *[]byte, ip string, mail_from_func mail_from_func, rcpt_to_func rcpt_to_func, headers_func headers_func, full_message_func full_message_func) {
//fmt.Printf("smtp smtpExecCmd: %s\n", c)
if (!(*authed)) {
(*sent_cmds) += 1
}
if ((*login_status) == 1) {
// decode base64 encoded password
dec, dec_err := base64.StdEncoding.DecodeString(string(c))
if (dec_err == nil) {
// split the parts by a null character
var null_delimited_parts = bytes.Split(dec, []byte{0})
if (len(null_delimited_parts) == 1) {
(*auth_password) = string(dec)
} else if (len(null_delimited_parts) == 2) {
(*auth_login) = string(null_delimited_parts[0])
(*auth_password) = string(null_delimited_parts[1])
} else if (len(null_delimited_parts) == 3) {
(*auth_login) = string(null_delimited_parts[0])
(*auth_password) = string(null_delimited_parts[2])
}
}
// set login_status to 0
(*login_status) = 0
// send a 235 response
conn.Write([]byte("235 OK\r\n"))
} else if (bytes.Index(c, []byte("STARTTLS")) == 0 && using_tls == false) {
conn.Write([]byte("220 Ready to start TLS\r\n"))
// upgrade to TLS
var tlsConn *tls.Conn
tlsConn = tls.Server(conn, &tls_config)
// run a handshake
tlsConn.Handshake()
// convert tlsConn to a net.Conn type
conn = net.Conn(tlsConn)
//fmt.Println("upgraded to TLS with STARTTLS")
// the upgraded conn object is only available in the local scope
// start a new smtpHandleClient in the existing go subroutine
smtpHandleClient(ip_ac, false, true, conn, tls_config, ip, config, mail_from_func, rcpt_to_func, headers_func, full_message_func)
} else if (bytes.Index(c, []byte("EHLO")) == 0 || bytes.Index(c, []byte("HELO")) == 0) {
//fmt.Printf("EHLO command\n")
// multi line replies to an SMTP client
// use the same code with a dash after it
// and no dash on the last line
// to know where the reply ends
// respond with 250-
// supported SMTP extensions
conn.Write([]byte("250-" + config.Fqdn + "\r\n"))
conn.Write([]byte("250-SIZE 14680064\r\n"))
conn.Write([]byte("250-8BITMIME\r\n"))
conn.Write([]byte("250-AUTH PLAIN\r\n"))
if (using_tls == false) {
// start tls
conn.Write([]byte("250-STARTTLS\r\n"))
}
conn.Write([]byte("250-ENHANCEDSTATUSCODES\r\n"))
conn.Write([]byte("250-PIPELINING\r\n"))
//conn.Write([]byte("250-CHUNKING\r\n")) // this is BDAT CHUNKING, the BDAT command must be supported
conn.Write([]byte("250-SMTPUTF8\r\n"))
// respond without the - to request the next command
// " OK" is required by clients like Mozilla Thunderbird
conn.Write([]byte("250 OK\r\n"))
} else if (bytes.Index(c, []byte("AUTH PLAIN")) == 0) {
var auth_parts = bytes.Split(c, []byte(" "))
if (len(auth_parts) == 3) {
// password sent in this command as the third parameter
// decode the base64 password
dec, dec_err := base64.StdEncoding.DecodeString(string(auth_parts[2]))
if (dec_err == nil) {
// split the parts by a null character
var null_delimited_parts = bytes.Split(dec, []byte{0})
if (len(null_delimited_parts) == 1) {
(*auth_password) = string(dec)
} else if (len(null_delimited_parts) == 2) {
(*auth_login) = string(null_delimited_parts[0])
(*auth_password) = string(null_delimited_parts[1])
} else if (len(null_delimited_parts) == 3) {
(*auth_login) = string(null_delimited_parts[0])
(*auth_password) = string(null_delimited_parts[2])
}
}
// respond with 235
conn.Write([]byte("235 OK\r\n"))
} else {
// password sent as next command (on next line)
// set login_status to 1 to parse that next line
(*login_status) = 1
// respond with 334
conn.Write([]byte("334 OK\r\n"))
}
} else if (bytes.Index(c, []byte("MAIL FROM:")) == 0) {
//fmt.Printf("MAIL FROM command\n")
i1 := bytes.Index(c, []byte("<"))
i2 := bytes.Index(c, []byte(">"))
s := make([]byte, 0)
if (i1 > -1 && i2 > -1) {
s = c[i1+1:i2]
}
//fmt.Printf("send address (between %d and %d): %s\n", i1, i2, s)
(*mail_from) = string(s)
var mail_from_authed, mail_from_error_string = mail_from_func(string(s), ip, (*auth_login), (*auth_password), esmtp_authed)
if (mail_from_authed == false) {
// invalid auth
ipac.ModifyAuth(&ip_ac, 1, ip)
if (mail_from_error_string == "") {
// use default response, 221
conn.Write([]byte("221 not authorized\r\n"))
} else {
// use mail_from_error_string
conn.Write([]byte(mail_from_error_string + "\r\n"))
}
conn.Close()
} else {
conn.Write([]byte("250 AUTH\r\n"))
//conn.Write([]byte("250 OK\r\n"))
}
} else if (bytes.Index(c, []byte("RCPT TO:")) == 0) {
//fmt.Printf("RCPT TO:\n")
i1 := bytes.Index(c, []byte("<"))
i2 := bytes.Index(c, []byte(">"))
s := make([]byte, 0)
if (i1 > -1 && i2 > -1) {
//fmt.Printf("found < and > in: '%s'\n", c)
s = c[i1+1:i2]
}
_ = s
//fmt.Printf("rcpt address (between %d and %d): %s\n", i1, i2, s)
(*rcpt_to_addresses) = append((*rcpt_to_addresses), string(s))
var rcpt_to_error_string string
(*authed), rcpt_to_error_string = rcpt_to_func(string(s), ip, esmtp_authed)
if ((*authed) == true) {
conn.Write([]byte("250 OK\r\n"))
} else {
// invalid auth
ipac.ModifyAuth(&ip_ac, 1, ip)
if (rcpt_to_error_string == "") {
// 550 to indicate no mailbox found
conn.Write([]byte("550 mailbox not available\r\n"))
} else {
// use rcpt_to_error_string
conn.Write([]byte(rcpt_to_error_string + "\r\n"))
}
conn.Close()
}
} else if (bytes.Index(c, []byte("DATA")) == 0) {
//fmt.Printf("DATA command\n")
if ((*authed)) {
// valid auth
ipac.ModifyAuth(&ip_ac, 2, ip)
(*parse_data) = true
conn.Write([]byte("354 End data with <CR><LF>.<CR><LF>\r\n"))
//fmt.Println("DATA received, replied with 354")
} else {
// invalid auth
ipac.ModifyAuth(&ip_ac, 1, ip)
// 221 <domain>
// service closing transmission channel
conn.Write([]byte("221 not authorized\r\n"))
conn.Close()
}
} else if (bytes.Index(c, []byte("RSET")) == 0) {
//fmt.Printf("RSET command\n")
conn.Write([]byte("250 OK\r\n"))
//fmt.Println("RSET received, replied with 250")
} else if (bytes.Index(c, []byte("QUIT")) == 0) {
//fmt.Printf("QUIT command\n")
conn.Write([]byte("221 Bye\r\n"))
conn.Close()
} else {
// 502 command not implemented
conn.Write([]byte("502 COMMAND NOT IMPLEMENTED\r\n"))
}
}
func smtpHandleClient(ip_ac ipac.Ipac, is_new bool, using_tls bool, conn net.Conn, tls_config tls.Config, ip string, config Config, mail_from_func mail_from_func, rcpt_to_func rcpt_to_func, headers_func headers_func, full_message_func full_message_func) {
//fmt.Printf("new SMTP connection from %s\n", ip)
if (is_new == true) {
conn.Write([]byte("220 " + config.Fqdn + " go-mail\r\n"))
}
authed := false
esmtp_authed := false
auth_login := ""
auth_password := ""
login_status := 0
parse_data := false
mail_from := ""
var rcpt_to_addresses []string
login := make([]byte, 0)
var parts_headers = make([]map[string]string, 0)
var parts = make([][]byte, 0)
sent_cmds := 0
sent_bytes := 0
smtp_data := make([]byte, 0)
last_parse_data_block_position := 0
for {
// create an idle timeout
conn.SetDeadline(time.Now().Add(time.Duration(int(time.Second) * config.IdleTimeout)))
if (authed == false && sent_cmds > 3) {
// should be authorized
conn.Write([]byte("221 unauthenticated send limit exceeded\r\n"))
conn.Close()
break
}
if (authed == false && sent_bytes > 400) {
// disconnect unauthed connections that have sent more than N bytes
conn.Write([]byte("221 unauthenticated send limit exceeded\r\n"))
conn.Close()
break
}
buf := make([]byte, 1400)
n, err := conn.Read(buf)
sent_bytes += n
if err != nil {
//fmt.Printf("server: conn: read: %s\n", err)
// close connection
conn.Close()
break
}
//fmt.Printf("smtp read length: %d\n", n)
//fmt.Print(string(buf))
// set buf to read length
buf = buf[:n]
// add buf to smtp_data
for l := range buf {
smtp_data = append(smtp_data, buf[l])
}
if (uint64(len(smtp_data)) > config.SmtpMaxEmailSize) {
//fmt.Println("smtp data too big from ", ip)
conn.Write([]byte("221 send limit exceeded\r\n"))
conn.Close()
break
}
if (parse_data == false) {
if (bytes.Index(smtp_data, []byte("\r\n")) == -1) {
// not a valid command
//fmt.Println("no valid command, waiting for more data")
continue
}
// commands end with \r\n and can be at most 512 bytes
// remove each and send to smtpExecCmd()
var s = bytes.Split(smtp_data, []byte("\r\n"))
for r := range s {
if (parse_data == true) {
// time to parse the data
break
}
var line = s[r]
if (len(line) > 0) {
// do not send an empty line to smtpExecCmd()
smtpExecCmd(ip_ac, using_tls, conn, tls_config, config, line, &auth_login, &auth_password, &login_status, &authed, &esmtp_authed, &mail_from, &rcpt_to_addresses, &parse_data, &sent_cmds, &login, ip, mail_from_func, rcpt_to_func, headers_func, full_message_func)
}
if (len(smtp_data) + 2 >= len(line) && len(smtp_data) >= 2 && len(line) + 2 <= len(smtp_data)) {
// remove the line from smtp_data
smtp_data = smtp_data[len(line) + 2:len(smtp_data)]
}
}
}
if (parse_data == true) {
// connection has already been authenticated
// this is data sent after the client sends DATA and the server responds with 354
// to make fast modifications
// instead of iterating through 500MB of data each time 1400 bytes is added
var lp_start = last_parse_data_block_position - 10
if (lp_start < 0) {
// the start position is 0 at least
lp_start = 0
}
smtp_data_edit_block := smtp_data[lp_start:len(smtp_data)]
// RFC-5321 section 4.5.2. Transparency
// Before sending a line of mail text, the SMTP client checks the first character of the line. If it is a period, one additional period is inserted at the beginning of the line.
smtp_data_edit_block = bytes.ReplaceAll(smtp_data_edit_block, []byte("\r\n.."), []byte("\r\n."))
smtp_data = smtp_data[0:lp_start]
for db := range(smtp_data_edit_block) {
smtp_data = append(smtp_data, smtp_data_edit_block[db])
}
// gather data until <CR><LF>.<CR><LF>
// indicating the end of this email (body, attachments and anything else received already)
data_block_end := bytes.Index(smtp_data_edit_block, []byte("\r\n.\r\n"))
if (data_block_end > -1) {
// if the data_block_end was found, set the offset position
data_block_end += lp_start
}
//fmt.Println("data_block_end", data_block_end)
// keep track of the previous/last position in smtp_data
last_parse_data_block_position = len(smtp_data)-1
if (data_block_end > -1) {
// this is the end of all the DATA
//fmt.Printf("smtp parse_data: (%d)\n######\n%s\n######\n", len(smtp_data), smtp_data[0:data_block_end])
//fmt.Printf("<CR><LF>.<CR><LF> found at: %d of %d\n", data_block_end, len(smtp_data))
// validate DKIM without the \r\n.\r\n
smtp_data = smtp_data[0:data_block_end]
boundary := ""
// parse the headers
headers := make(map[string]string)
// keep an ordered list also
real_headers := make([]string, 0)
var headers_sent = false
// decode quoted-printable body parts
var decode_qp = false
// limit the number of DKIM lookups
var dkim_lookups = 0
var validate_dkim = false
var dkim_public_key = ""
var dkim_valid = false
var dkim_done = false
var dkim_hp map[string]string
v := make([]byte, 0)
i := -1
for {
i = i + 1
//fmt.Println(i, len(smtp_data), data_block_end)
if (i >= len(smtp_data)) {
break
}
//fmt.Printf("i=%d, c=%c\n", i, smtp_data[i])
if (smtp_data[i] == []byte("\n")[0] && smtp_data[i-1] == []byte("\r")[0]) {
// this is at \r\n
// remove the \r from v
v = v[:len(v)-1]
//fmt.Println("LINE:", len(v), string(v))
if (len(v) == 0) {
// empty line indicates body or new block start
if (headers_sent == false) {
// send the headers for validation
authed = headers_func(headers, ip, &esmtp_authed)
if (authed == false) {
conn.Write([]byte("221 not authorized\r\n"))
conn.Close()
return
}
// only send them once
headers_sent = true
}
//fmt.Printf("email body or new block start at %d\n", i)
//fmt.Println("validate_dkim", validate_dkim)
//fmt.Println("dkim_done", dkim_done)
// skip the newline
i = i + 1
if (validate_dkim == true && dkim_done == false) {
// this needs to happen once the email is fully processed and only once
// the email is in smtp_data
dkim_done = true
//fmt.Println("DKIM signing algorithm:", dkim_hp["a"])
var dkim_expired = false
if (dkim_hp["x"] != "") {
// make sure header is not expired
i, err := strconv.ParseInt(dkim_hp["x"], 10, 64)
if err != nil {
// invalid data in x tag
dkim_expired = true
} else {
expire_time := time.Unix(i, 0)
if (expire_time.Unix() < time.Now().Unix()) {
dkim_expired = true
}
}
}
//fmt.Println("dkim_expired", dkim_expired)
// the domain in the from header
var valid_domain_1 = ""
var d1p = strings.Split(headers["from"], "@")
if (len(d1p) == 2) {
valid_domain_1 = strings.TrimRight(d1p[1], ">")
}
// the domain in the MAIL FROM command
var valid_domain_2 = ""
var d2p = strings.Split(mail_from, "@")
if (len(d2p) == 2) {
valid_domain_2 = d2p[1]
}
if (dkim_expired == true) {
//fmt.Println("DKIM header is expired")
headers["go-mail-dkim-validation-errors"] = headers["go-mail-dkim-validation-errors"] + "(header is expired)"
} else if (dkim_hp["a"] != "rsa-sha256") {
//fmt.Println("unsupported DKIM signing algorithm", dkim_hp["a"])
headers["go-mail-dkim-validation-errors"] = headers["go-mail-dkim-validation-errors"] + "(unsupported signing algorithm)"
} else {
if (dkim_hp["d"] != valid_domain_1 && dkim_hp["d"] != valid_domain_2) {
// the d= tag value (domain specified in the DKIM header) is not the same domain as the reply-to address
//fmt.Println("DKIM d= domain", dkim_hp["d"], "does not match the from address", headers["from"], "or the MAIL FROM address", mail_from)
headers["go-mail-dkim-validation-warnings"] = headers["go-mail-dkim-validation-warnings"] + "(d= domain does not match the from header domain or the SMTP MAIL FROM domain)"
}
// finish parsing the DKIM headers
// replace whitespace in b= and bh=
// space, tab, \r and \n
dkim_hp["b"] = strings.ReplaceAll(dkim_hp["b"], " ", "")
dkim_hp["b"] = strings.ReplaceAll(dkim_hp["b"], string(9), "")
dkim_hp["b"] = strings.ReplaceAll(dkim_hp["b"], string(10), "")
dkim_hp["b"] = strings.ReplaceAll(dkim_hp["b"], string(13), "")
dkim_hp["bh"] = strings.ReplaceAll(dkim_hp["bh"], " ", "")
dkim_hp["bh"] = strings.ReplaceAll(dkim_hp["bh"], string(9), "")
dkim_hp["bh"] = strings.ReplaceAll(dkim_hp["bh"], string(10), "")
dkim_hp["bh"] = strings.ReplaceAll(dkim_hp["bh"], string(13), "")
// bh= is the body hash, if the l= field exists it specifies the length of the body that was hashed
//fmt.Println("DKIM header bh=", dkim_hp["bh"])
// make sure the bh tag from the DKIM headers is the same as the actual body hash (only the length specified if l= exists)
/*
rfc6376 - DKIM
3.5. The DKIM-Signature Header Field
c= Message canonicalization (plain-text; OPTIONAL, default is
"simple/simple"). This tag informs the Verifier of the type of
canonicalization used to prepare the message for signing. It
consists of two names separated by a "slash" (%d47) character,
corresponding to the header and body canonicalization algorithms,
respectively. These algorithms are described in Section 3.4. If
only one algorithm is named, that algorithm is used for the header
and "simple" is used for the body. For example, "c=relaxed" is
treated the same as "c=relaxed/simple".
In better explanation, `header_canon_algorith/body_canon_algorithm` with `simple/simple` being default
*/
var canon_algos = strings.Split(dkim_hp["c"], "/")
if (len(canon_algos) == 0) {
// is no algorithms are defined, use simple for the header and body
canon_algos = append(canon_algos, "simple")
canon_algos = append(canon_algos, "simple")
} else if (len(canon_algos) == 1) {
// if only one algorithm is defined, it is used for the header and simple is used for the body
canon_algos = append(canon_algos, "simple")
}
var canonicalized_body []byte
var canonicalized_body_hash_base64 string
if (canon_algos[1] == "simple") {
// simple body canonicalization
/*
3.4.3. The "simple" Body Canonicalization Algorithm
The "simple" body canonicalization algorithm ignores all empty lines
at the end of the message body. An empty line is a line of zero
length after removal of the line terminator. If there is no body or
no trailing CRLF on the message body, a CRLF is added. It makes no
other changes to the message body. In more formal terms, the
"simple" body canonicalization algorithm converts "*CRLF" at the end
of the body to a single "CRLF".
remove all \r\n at the end then add \r\n (\r\n is CRLF)
*/
if (dkim_hp["l"] != "") {
// length specified
optional_body_length, optional_body_length_err := strconv.ParseInt(dkim_hp["l"], 10, 64)
if (optional_body_length >= 0 && int(optional_body_length) <= data_block_end && optional_body_length_err == nil) {
// valid length
canonicalized_body = bytes.TrimRight(smtp_data[i:data_block_end], "\r\n")
} else {
// invalid optional body length
// dkim will not validate unless the bh= tag hash was created with an empty canonicalized body
}
} else {
// no length specified
canonicalized_body = bytes.TrimRight(smtp_data[i:data_block_end], "\r\n")
}
canonicalized_body = append(canonicalized_body, '\r')
canonicalized_body = append(canonicalized_body, '\n')
} else if (canon_algos[1] == "relaxed") {
// relaxed body canonicalization
/*
3.4.4. The "relaxed" Body Canonicalization Algorithm
The "relaxed" body canonicalization algorithm MUST apply the
following steps (a) and (b) in order:
a. Reduce whitespace:
* Ignore all whitespace at the end of lines. Implementations
MUST NOT remove the CRLF at the end of the line.
* Reduce all sequences of WSP within a line to a single SP
character.
b. Ignore all empty lines at the end of the message body. "Empty
line" is defined in Section 3.4.3. If the body is non-empty but
does not end with a CRLF, a CRLF is added. (For email, this is
only possible when using extensions to SMTP or non-SMTP transport
mechanisms.)
*/
canonicalized_body = smtp_data[i:data_block_end]
// remove whitespace at the end of lines
for true {
if (bytes.Index(canonicalized_body, []byte("\t\r\n")) > -1) {
// replace trn with rn
canonicalized_body = bytes.Replace(canonicalized_body, []byte("\t\r\n"), []byte("\r\n"), 1)
} else if (bytes.Index(canonicalized_body, []byte(" \r\n")) > -1) {
// replace nrn with rn
canonicalized_body = bytes.Replace(canonicalized_body, []byte(" \r\n"), []byte("\r\n"), 1)
} else {
break
}
}
// replace wsp sequences with a single space
for true {
if (bytes.Index(canonicalized_body, []byte("\t")) > -1) {
// replace all \t with space
canonicalized_body = bytes.ReplaceAll(canonicalized_body, []byte("\t"), []byte(" "))
} else if (bytes.Index(canonicalized_body, []byte(" ")) > -1) {
// replace " " with space
canonicalized_body = bytes.Replace(canonicalized_body, []byte(" "), []byte(" "), 1)
} else {
// no more wsp characters
break
}
}
// 3.4.4 step b
if (len(canonicalized_body) > 0) {
// the body is non-empty
if (len(canonicalized_body) >= 2) {
if (canonicalized_body[len(canonicalized_body)-2] != '\r' && canonicalized_body[len(canonicalized_body)-1] != '\n') {
// the body does not end with a CRLF
// add a CRLF
canonicalized_body = append(canonicalized_body, '\r')
canonicalized_body = append(canonicalized_body, '\n')
}
} else {
// the body is not long enough to end with a CRLF
// add a CRLF
canonicalized_body = append(canonicalized_body, '\r')
canonicalized_body = append(canonicalized_body, '\n')
}
}
}
// get the checksum from the canonicalized body
var canonicalized_body_sha256_sum = sha256.Sum256(canonicalized_body)
// convert [32]byte to []byte
var formatted_canonicalized_body_sha256_sum []byte
for b := range canonicalized_body_sha256_sum {
formatted_canonicalized_body_sha256_sum = append(formatted_canonicalized_body_sha256_sum, canonicalized_body_sha256_sum[b])
}
// as base64
canonicalized_body_hash_base64 = base64.StdEncoding.EncodeToString(formatted_canonicalized_body_sha256_sum)
if (canonicalized_body_hash_base64 != dkim_hp["bh"]) {
/*
fmt.Println("DKIM canonicalized_body_hash_base64 does not equal the bh= tag value")
fmt.Println("canonicalization algorithms", canon_algos)
fmt.Println("bh=", dkim_hp["bh"])
fmt.Println("canonicalized_body_hash_base64", canonicalized_body_hash_base64)
*/
headers["go-mail-dkim-validation-errors"] = headers["go-mail-dkim-validation-errors"] + "(canonicalized body hash encoded as base64 does not equal the bh= tag value)"
} else if (dkim_public_key == "") {
// no dkim_public_key was found in DNS
headers["go-mail-dkim-validation-errors"] = headers["go-mail-dkim-validation-errors"] + "(no DKIM public key was found in DNS using query domain " + dkim_hp["s"] + "._domainkey." + dkim_hp["d"] + ")"
} else {
// body hash in the headers is the same as the calculated body hash
// valid
//fmt.Println("DKIM bh= tag matches hash of body content with length optionally specified by l= tag")
// the DKIM public key of the sending domain is in dkim_public_key
// b= is the signature of the headers and body
//fmt.Println("signature base64 b=", dkim_hp["b"])
// this string as dkim_public_key causes an error "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDdpuAU4byvZtkEoQ8ZRl4ppDrI DDyDsrad7SdKlfvN/2C3TGAw9Tb+wuHw8oTO4QAMA5lnVzLryrcC6oJI/5vjPUM+ JwM2h7FRcXbFsWHhfIFpXdjjyYifdzT+oZ3ALHHs7UqxlHy1gOz0qXL4BC9ohs2m IstCvZWjvxdMmf50FQIDAQAB"
// get the public key as an x509 object
var dkim_public_x509_key rsa.PublicKey
un64, un64_err := base64.StdEncoding.DecodeString(dkim_public_key)
var x509_error_string = ""
if (un64_err == nil) {
pk, pk_err := x509.ParsePKIXPublicKey(un64)
if (pk_err == nil) {
if pk, ok := pk.(*rsa.PublicKey); ok {
dkim_public_x509_key = *pk
}
} else {
x509_error_string = pk_err.Error()
}
} else {
x509_error_string = un64_err.Error()
}
if (dkim_public_x509_key.N == nil || x509_error_string != "") {
headers["go-mail-dkim-validation-errors"] = headers["go-mail-dkim-validation-errors"] + "(an invalid DKIM public key (" + dkim_public_key + ") was found in DNS using query domain " + dkim_hp["s"] + "._domainkey." + dkim_hp["d"] + " failing with error: " + x509_error_string + ")"
} else {
// create the canonicalized header string based on the field specified in the h= tag
// remove spaces from each field
dkim_hp["h"] = strings.ReplaceAll(dkim_hp["h"], " ", "")
// lowercase all field names
dkim_hp["h"] = strings.ToLower(dkim_hp["h"])
var canon_h = strings.Split(dkim_hp["h"], ":")
// remove duplicates
var d = 0
for {
if (d >= len(canon_h)) {
// last entry
break
}
for dd := len(canon_h)-1; dd >= 0; dd-- {
if (canon_h[dd] == canon_h[d] && dd != d) {
// remove duplicate value
//fmt.Println("remove duplicate", dd, canon_h[dd], len(canon_h))
canon_h = append(canon_h[:dd], canon_h[dd+1:]...)
}
}
d += 1
}
var canonicalized_header_string = ""
if (canon_algos[0] == "simple") {
// simple header canonicalization
} else if (canon_algos[0] == "relaxed") {
// relaxed header canonicalization
for h := range canon_h {
var h_name = canon_h[h]
//fmt.Println("h_name", h_name)
var is_real = false
for r := range real_headers {
if (real_headers[r] == h_name) {
is_real = true
break
}
}
if (is_real == true) {
// add each header specified in the h= tag with the valid format
// lowercase key values and no spaces on either side of :
canonicalized_header_string = canonicalized_header_string + h_name + ":" + headers[h_name] + "\r\n"
}