-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathemail.go
More file actions
326 lines (298 loc) · 8.66 KB
/
Copy pathemail.go
File metadata and controls
326 lines (298 loc) · 8.66 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
package reporter
import (
"crypto/tls"
"fmt"
"net"
"net/mail"
"net/smtp"
"strings"
"time"
"golang.org/x/xerrors"
"github.com/future-architect/vuls/config"
"github.com/future-architect/vuls/models"
)
// plainAuth implements smtp.Auth for the PLAIN mechanism without
// stdlib's TLS enforcement, preserving behavioral parity with the
// previously used go-smtp library for TLSMode "None" configurations.
type plainAuth struct {
identity, username, password string
}
func (a *plainAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
if !server.TLS {
advertised := false
for _, mech := range server.Auth {
if strings.EqualFold(mech, "PLAIN") {
advertised = true
break
}
}
if !advertised {
return "", nil, xerrors.New("unencrypted connection: PLAIN auth requires TLS or explicit server advertisement")
}
}
resp := []byte(a.identity + "\x00" + a.username + "\x00" + a.password)
return "PLAIN", resp, nil
}
func (a *plainAuth) Next(_ []byte, more bool) ([]byte, error) {
if more {
return nil, xerrors.New("unexpected server challenge")
}
return nil, nil
}
// loginAuth implements smtp.Auth for the LOGIN mechanism.
type loginAuth struct {
username, password string
}
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
if !server.TLS {
advertised := false
for _, mech := range server.Auth {
if strings.EqualFold(mech, "LOGIN") {
advertised = true
break
}
}
if !advertised {
return "", nil, xerrors.New("unencrypted connection: LOGIN auth requires TLS or explicit server advertisement")
}
}
return "LOGIN", nil, nil
}
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if !more {
return nil, nil
}
prompt := strings.TrimSpace(strings.ToLower(string(fromServer)))
switch {
case strings.Contains(prompt, "username"):
return []byte(a.username), nil
case strings.Contains(prompt, "password"):
return []byte(a.password), nil
default:
return nil, xerrors.Errorf("unexpected server challenge: %q", fromServer)
}
}
// EMailWriter send mail
type EMailWriter struct {
FormatOneEMail bool
FormatOneLineText bool
FormatList bool
Cnf config.SMTPConf
}
// Write results to Email
func (w EMailWriter) Write(rs ...models.ScanResult) (err error) {
var message string
sender := NewEMailSender(w.Cnf)
m := map[string]int{}
for _, r := range rs {
if w.FormatOneEMail {
text, err := formatFullPlainText(r)
if err != nil {
return xerrors.Errorf("Failed to format full plain text. err: %w", err)
}
message += text + "\r\n\r\n"
mm := r.ScannedCves.CountGroupBySeverity()
keys := []string{"Critical", "High", "Medium", "Low", "Unknown"}
for _, k := range keys {
m[k] += mm[k]
}
} else {
var subject string
if len(r.Errors) != 0 {
subject = fmt.Sprintf("%s%s An error occurred while scanning",
w.Cnf.SubjectPrefix, r.ServerInfo())
} else {
subject = fmt.Sprintf("%s%s %s",
w.Cnf.SubjectPrefix,
r.ServerInfo(),
r.ScannedCves.FormatCveSummary())
}
if w.FormatList {
message, err = formatList(r)
if err != nil {
return xerrors.Errorf("Failed to format list. err: %w", err)
}
} else {
message, err = formatFullPlainText(r)
if err != nil {
return xerrors.Errorf("Failed to format full plain text. err: %w", err)
}
}
if w.FormatOneLineText {
message = fmt.Sprintf("One Line Summary\r\n================\r\n%s", formatOneLineSummary(r))
}
if err := sender.Send(subject, message); err != nil {
return err
}
}
}
summary := fmt.Sprintf("Total: %d (Critical:%d High:%d Medium:%d Low:%d ?:%d)",
m["Critical"]+m["High"]+m["Medium"]+m["Low"]+m["Unknown"],
m["Critical"], m["High"], m["Medium"], m["Low"], m["Unknown"])
origmessage := message
if w.FormatOneEMail {
message = fmt.Sprintf("One Line Summary\r\n================\r\n%s", formatOneLineSummary(rs...))
if !w.FormatOneLineText {
message += fmt.Sprintf("\r\n\r\n%s", origmessage)
}
subject := fmt.Sprintf("%s %s",
w.Cnf.SubjectPrefix, summary)
return sender.Send(subject, message)
}
return nil
}
// EMailSender is interface of sending e-mail
type EMailSender interface {
Send(subject, body string) error
}
type emailSender struct {
conf config.SMTPConf
}
func (e *emailSender) dialTLS(addr string, tlsConfig *tls.Config) (*smtp.Client, error) {
conn, err := tls.Dial("tcp", addr, tlsConfig)
if err != nil {
return nil, xerrors.Errorf("Failed to create TLS connection to SMTP server: %w", err)
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
_ = conn.Close()
return nil, xerrors.Errorf("Failed to parse SMTP server address: %w", err)
}
c, err := smtp.NewClient(conn, host)
if err != nil {
_ = conn.Close()
return nil, xerrors.Errorf("Failed to create SMTP client over TLS: %w", err)
}
return c, nil
}
func (e *emailSender) dialStartTLS(addr string, tlsConfig *tls.Config) (*smtp.Client, error) {
c, err := smtp.Dial(addr)
if err != nil {
return nil, xerrors.Errorf("Failed to create connection to SMTP server: %w", err)
}
if err := c.StartTLS(tlsConfig); err != nil {
_ = c.Close()
return nil, xerrors.Errorf("Failed to STARTTLS: %w", err)
}
return c, nil
}
func (e *emailSender) sendMail(smtpServerAddr, message string) (err error) {
emailConf := e.conf
tlsConfig := &tls.Config{
ServerName: emailConf.SMTPAddr,
InsecureSkipVerify: emailConf.TLSInsecureSkipVerify,
}
var c *smtp.Client
switch emailConf.TLSMode {
case "":
switch emailConf.SMTPPort {
case "465":
c, err = e.dialTLS(smtpServerAddr, tlsConfig)
if err != nil {
return err
}
default:
c, err = smtp.Dial(smtpServerAddr)
if err != nil {
return xerrors.Errorf("Failed to create connection to SMTP server: %w", err)
}
if ok, _ := c.Extension("STARTTLS"); ok {
if err := c.StartTLS(tlsConfig); err != nil {
_ = c.Close()
return xerrors.Errorf("Failed to STARTTLS: %w", err)
}
}
}
case "None":
c, err = smtp.Dial(smtpServerAddr)
if err != nil {
return xerrors.Errorf("Failed to create connection to SMTP server: %w", err)
}
case "STARTTLS":
c, err = e.dialStartTLS(smtpServerAddr, tlsConfig)
if err != nil {
return err
}
case "SMTPS":
c, err = e.dialTLS(smtpServerAddr, tlsConfig)
if err != nil {
return err
}
default:
return xerrors.New(`invalid TLS mode. accepts: ["", "None", "STARTTLS", "SMTPS"]`)
}
defer c.Close()
if ok, param := c.Extension("AUTH"); ok {
authList := strings.Fields(param)
auth := e.newAuth(authList)
if auth != nil {
if err = c.Auth(auth); err != nil {
return xerrors.Errorf("Failed to authenticate: %w", err)
}
}
}
if err = c.Mail(emailConf.From); err != nil {
return xerrors.Errorf("Failed to send Mail command: %w", err)
}
for _, to := range emailConf.To {
if err = c.Rcpt(to); err != nil {
return xerrors.Errorf("Failed to send Rcpt command: %w", err)
}
}
w, err := c.Data()
if err != nil {
return xerrors.Errorf("Failed to send Data command: %w", err)
}
_, err = w.Write([]byte(message))
if err != nil {
return xerrors.Errorf("Failed to write EMail message: %w", err)
}
err = w.Close()
if err != nil {
return xerrors.Errorf("Failed to close Writer: %w", err)
}
err = c.Quit()
if err != nil {
return xerrors.Errorf("Failed to close connection: %w", err)
}
return nil
}
func (e *emailSender) Send(subject, body string) (err error) {
emailConf := e.conf
to := strings.Join(emailConf.To[:], ", ")
cc := strings.Join(emailConf.Cc[:], ", ")
mailAddresses := append(emailConf.To, emailConf.Cc...)
if _, err := mail.ParseAddressList(strings.Join(mailAddresses[:], ", ")); err != nil {
return xerrors.Errorf("Failed to parse email addresses: %w", err)
}
headers := make(map[string]string)
headers["From"] = emailConf.From
headers["To"] = to
headers["Cc"] = cc
headers["Subject"] = subject
headers["Date"] = time.Now().Format(time.RFC1123Z)
headers["Content-Type"] = "text/plain; charset=utf-8"
var header strings.Builder
for k, v := range headers {
header.WriteString(fmt.Sprintf("%s: %s\r\n", k, v))
}
if err := e.sendMail(net.JoinHostPort(emailConf.SMTPAddr, emailConf.SMTPPort), fmt.Sprintf("%s\r\n%s", header.String(), body)); err != nil {
return xerrors.Errorf("Failed to send emails: %w", err)
}
return nil
}
// NewEMailSender creates emailSender
func NewEMailSender(cnf config.SMTPConf) EMailSender {
return &emailSender{cnf}
}
func (e *emailSender) newAuth(authList []string) smtp.Auth {
for _, v := range authList {
switch strings.ToUpper(v) {
case "PLAIN":
return &plainAuth{identity: "", username: e.conf.User, password: e.conf.Password}
case "LOGIN":
return &loginAuth{username: e.conf.User, password: e.conf.Password}
}
}
return nil
}