This repository has been archived by the owner on Dec 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 265
/
mail.go
271 lines (233 loc) · 6.68 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
// Package mail provides implementations of the Fleet MailService
package mail
import (
"bytes"
"crypto/tls"
"fmt"
"html/template"
"net"
"net/smtp"
"strings"
"time"
"github.com/kolide/fleet/server/bindata"
"github.com/kolide/fleet/server/kolide"
"github.com/pkg/errors"
)
func NewService() kolide.MailService {
return &mailService{}
}
type mailService struct{}
type sender interface {
sendMail(e kolide.Email, msg []byte) error
}
func Test(mailer kolide.MailService, e kolide.Email) error {
mailBody, err := getMessageBody(e)
if err != nil {
return errors.Wrap(err, "failed to get message body")
}
svc, ok := mailer.(sender)
if !ok {
return nil
}
err = svc.sendMail(e, mailBody)
if err != nil {
return errors.Wrap(err, "sending mail")
}
return nil
}
const (
PortSSL = 465
PortTLS = 587
)
func getMessageBody(e kolide.Email) ([]byte, error) {
body, err := e.Mailer.Message()
if err != nil {
return nil, errors.Wrap(err, "get mailer message")
}
mime := `MIME-version: 1.0;` + "\r\n"
content := `Content-Type: text/html; charset="UTF-8";` + "\r\n"
subject := "Subject: " + e.Subject + "\r\n"
from := "From: " + e.Config.SMTPSenderAddress + "\r\n"
msg := []byte(subject + from + mime + content + "\r\n" + string(body) + "\r\n")
return msg, nil
}
func (m mailService) SendEmail(e kolide.Email) error {
if !e.Config.SMTPConfigured {
return fmt.Errorf("email not configured")
}
msg, err := getMessageBody(e)
if err != nil {
return err
}
return m.sendMail(e, msg)
}
type loginauth struct {
username string
password string
host string
}
func LoginAuth(username, password, host string) smtp.Auth {
return &loginauth{username: username, password: password, host: host}
}
func isLocalhost(name string) bool {
return name == "localhost" || name == "127.0.0.1" || name == "::1"
}
func (l *loginauth) Start(server *smtp.ServerInfo) (proto string, toServer []byte, err error) {
if !server.TLS && !isLocalhost(server.Name) {
return "", nil, errors.New("unencrypted connection")
}
if server.Name != l.host {
return "", nil, errors.New("wrong host name")
}
return "LOGIN", nil, nil
}
func (l *loginauth) Next(fromServer []byte, more bool) (toServer []byte, err error) {
if !more {
return nil, nil
}
prompt := strings.TrimSpace(string(fromServer))
switch prompt {
case "Username:":
return []byte(l.username), nil
case "Password:":
return []byte(l.password), nil
default:
return nil, errors.New("unexpected LOGIN prompt from server")
}
}
func smtpAuth(e kolide.Email) (smtp.Auth, error) {
if e.Config.SMTPAuthenticationType != kolide.AuthTypeUserNamePassword {
return nil, nil
}
var auth smtp.Auth
switch e.Config.SMTPAuthenticationMethod {
case kolide.AuthMethodCramMD5:
auth = smtp.CRAMMD5Auth(e.Config.SMTPUserName, e.Config.SMTPPassword)
case kolide.AuthMethodPlain:
auth = smtp.PlainAuth("", e.Config.SMTPUserName, e.Config.SMTPPassword, e.Config.SMTPServer)
case kolide.AuthMethodLogin:
auth = LoginAuth(e.Config.SMTPUserName, e.Config.SMTPPassword, e.Config.SMTPServer)
default:
return nil, fmt.Errorf("unknown SMTP auth type '%d'", e.Config.SMTPAuthenticationMethod)
}
return auth, nil
}
func (m mailService) sendMail(e kolide.Email, msg []byte) error {
smtpHost := fmt.Sprintf("%s:%d", e.Config.SMTPServer, e.Config.SMTPPort)
auth, err := smtpAuth(e)
if err != nil {
return errors.Wrap(err, "failed to get smtp auth")
}
if e.Config.SMTPAuthenticationMethod == kolide.AuthMethodCramMD5 {
err = smtp.SendMail(smtpHost, auth, e.Config.SMTPSenderAddress, e.To, msg)
if err != nil {
return errors.Wrap(err, "failed to send mail. cramd5 auth method")
}
return nil
}
client, err := dialTimeout(smtpHost)
if err != nil {
return errors.Wrap(err, "could not dial smtp host")
}
defer client.Close()
if e.Config.SMTPEnableStartTLS {
if ok, _ := client.Extension("STARTTLS"); ok {
config := &tls.Config{
ServerName: e.Config.SMTPServer,
InsecureSkipVerify: !e.Config.SMTPVerifySSLCerts,
}
if err = client.StartTLS(config); err != nil {
return errors.Wrap(err, "startTLS error")
}
}
}
if auth != nil {
if err = client.Auth(auth); err != nil {
return errors.Wrap(err, "client auth error")
}
}
if err = client.Mail(e.Config.SMTPSenderAddress); err != nil {
return errors.Wrap(err, "could not issue mail to provided address")
}
for _, recip := range e.To {
if err = client.Rcpt(recip); err != nil {
return errors.Wrap(err, "failed to get recipient")
}
}
writer, err := client.Data()
if err != nil {
return errors.Wrap(err, "getting client data")
}
_, err = writer.Write(msg)
if err != nil {
return errors.Wrap(err, "failed to write")
}
if err = writer.Close(); err != nil {
return errors.Wrap(err, "failed to close writer")
}
if err := client.Quit(); err != nil {
return errors.Wrap(err, "error on client quit")
}
return nil
}
// dialTimeout sets a timeout on net.Dial to prevent email from attempting to
// send indefinitely.
func dialTimeout(addr string) (client *smtp.Client, err error) {
// Ensure that errors are always returned after at least 5s to
// eliminate (some) timing attacks (in which a malicious user tries to
// port scan using the email functionality in Fleet)
c := time.After(5 * time.Second)
defer func() {
if err != nil {
// Wait until timer has elapsed to return anything
<-c
}
}()
conn, err := net.DialTimeout("tcp", addr, 2*time.Second)
if err != nil {
return nil, errors.Wrap(err, "dialing with timeout")
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, errors.Wrap(err, "split host port")
}
// Set a deadline to ensure we time out quickly when there is a TCP
// server listening but it's not an SMTP server (otherwise this seems
// to time out in 20s)
_ = conn.SetDeadline(time.Now().Add(2 * time.Second))
client, err = smtp.NewClient(conn, host)
if err != nil {
return nil, errors.New("SMTP connection error")
}
// Clear deadlines
_ = conn.SetDeadline(time.Time{})
return client, nil
}
// SMTPTestMailer is used to build an email message that will be used as
// a test message when testing SMTP configuration
type SMTPTestMailer struct {
BaseURL template.URL
AssetURL template.URL
}
func (m *SMTPTestMailer) Message() ([]byte, error) {
t, err := getTemplate("server/mail/templates/smtp_setup.html")
if err != nil {
return nil, err
}
var msg bytes.Buffer
if err = t.Execute(&msg, m); err != nil {
return nil, err
}
return msg.Bytes(), nil
}
func getTemplate(templatePath string) (*template.Template, error) {
templateData, err := bindata.Asset(templatePath)
if err != nil {
return nil, err
}
t, err := template.New("email_template").Parse(string(templateData))
if err != nil {
return nil, err
}
return t, nil
}