-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
172 lines (144 loc) · 4.88 KB
/
handlers.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
package app
import (
"bytes"
"fmt"
"net"
"net/mail"
"strings"
"github.com/chrj/smtpd"
"github.com/domodwyer/mailyak/v3"
"github.com/google/uuid"
"go.uber.org/zap"
"github.com/coronon/pingpong-mail/internal/config"
"github.com/coronon/pingpong-mail/internal/dmarc"
"github.com/coronon/pingpong-mail/internal/reply"
"github.com/coronon/pingpong-mail/internal/util"
)
// Check valid recipient (if restricted)
func CheckRecipient(peer smtpd.Peer, addr string) error {
if config.RestrictInboxRegex != nil && !config.RestrictInboxRegex.MatchString(addr) {
zap.S().Debugw("Received email for invalid inbox", "inbox", addr)
return config.ErrInvalidRcpt
}
zap.S().Debugw("Received email for valid inbox", "inbox", addr)
return nil
}
// Initial handler for all incoming mail
func HandleIncoming(peer smtpd.Peer, env smtpd.Envelope) error {
var err error
parsedMail, err := mail.ReadMessage(bytes.NewReader(env.Data))
if err != nil {
zap.S().Debugw("Can't parse email body", "error", err)
return config.ErrCantParseBody
}
// Check subject
zap.S().Debugw("Checking subject",
"subject", parsedMail.Header.Get("Subject"),
"forced", config.Cnf.ForceSubjectPrefix,
)
if config.Cnf.ForceSubjectPrefix != "" &&
!strings.HasPrefix(parsedMail.Header.Get("Subject"), config.Cnf.ForceSubjectPrefix) {
zap.S().Debug("Subject check failed")
return fmt.Errorf("please start your subject with '%v'", config.Cnf.ForceSubjectPrefix)
}
// Detmine sender main domain
senderDomain := util.GetDomainOrFallback(env.Sender, peer.HeloName)
// Determine sender <From:> address
// This is also the address we will reply to -> honouring Reply-To could open
// up attack vectors
fromHeaderAddr, err := util.GetRawFromHeaderAddress(parsedMail.Header.Get("From"))
if err != nil {
zap.S().Debugw("Can't get <From:> address", "error", err)
return err
}
// Determine sender <From:> domain (after the @)
fromHeaderDomain := util.GetDomainOrFallback(fromHeaderAddr, "")
if fromHeaderDomain == "" {
zap.S().Debugw("Can't get <From:> domain", "error", err)
return config.ErrFromHeaderInvalid
}
zap.S().Debugf("Sender domain: %v, From header: %v\n", senderDomain, fromHeaderAddr)
//? To avoid becoming a spammer for people that spoof the sender address for
//? us to reply to, we require a DMARC pass! No DMARC -> no reply!
if config.Cnf.EnableDmarc {
zap.S().Debug("Checking DMARC")
err := dmarc.CheckDmarc(&peer, &env, fromHeaderDomain, senderDomain)
if err != nil {
return err
}
}
// Handle email
zap.S().Debugf("Will handle email :)")
go handleAccepted(parsedMail, env.Recipients[0], fromHeaderAddr)
return nil
}
// Handler for accepted email (passed all checks)
func handleAccepted(email *mail.Message, incomingRcptAddr string, outgoingRcptAddr string) {
// Decide address to reply from
var replyFrom string
if config.Cnf.ReplyAddress != "" {
replyFrom = config.Cnf.ReplyAddress
} else {
replyFrom = incomingRcptAddr
}
// Build new recipients
recipients := make([]string, 1)
recipients[0] = outgoingRcptAddr
// Build response subject
subject := reply.BuildReplySubject(email.Header.Get("Subject"))
// Build response message
body := reply.BuildReplyBody(email)
zap.S().Debugw("Prepared response", "subject", subject, "body", body)
// Build Message-ID
msgUUID, err := uuid.NewRandom()
if err != nil {
zap.S().Debugw("Could not generate random UUID for Message-ID", "error", err)
}
msgID := fmt.Sprintf("<%s@%s>", msgUUID, config.Cnf.ServerName)
// Build response mail
response := mailyak.New("", nil)
response.LocalName(config.Cnf.ServerName)
response.SetHeader("Message-ID", msgID)
response.From(replyFrom)
response.To(outgoingRcptAddr)
response.Subject(subject)
response.Plain().Set(body)
// Find MX server
outgoingRcptDomain := util.GetDomainOrFallback(outgoingRcptAddr, "")
if outgoingRcptDomain == "" {
zap.S().Debugw("Could not determine domain for address", "address", outgoingRcptAddr)
return
}
mxRecords := util.GetMXDomains(outgoingRcptDomain)
if len(mxRecords) == 0 {
return
}
for _, mx := range mxRecords {
for _, port := range config.Cnf.DeliveryPorts {
zap.S().Debugw("Trying to send email",
"from", replyFrom,
"address", outgoingRcptAddr,
"domain", outgoingRcptDomain,
"mx_host", mx.Host,
"mx_pref", mx.Pref,
"port", port,
)
conn, err := net.Dial("tcp", fmt.Sprintf("%v:%v", mx.Host, port))
if err != nil {
zap.S().Debugw("Could not dial", "error", err)
// Attempt other mx:port combination
continue
}
defer func() { _ = conn.Close() }()
//? If sending fails we won't retry as that could be seen as 'spammy'
//? We know that a connection was established as dialing didn't fail
err = mailyak.SmtpExchange(response, conn, mx.Host, true)
if err == nil {
zap.S().Infow("Sent reply", "to", outgoingRcptAddr)
} else {
zap.S().Debugw("Error sending reply", "error", err)
}
return
}
}
}