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
|
package smtpclient
import (
"bufio"
"context"
"crypto/tls"
"encoding/base64"
"fmt"
"io"
"net"
"net/textproto"
"strings"
"sync"
"time"
)
type DialContextFunc func(ctx context.Context, network, address string) (net.Conn, error)
type Config struct {
Host string
Port int
Recipient string
EnvelopeFrom string
Username string
Password string
HELO string
TLSServerName string
RequireTLS bool
ImplicitTLS bool
Timeout time.Duration
DryRun bool
}
type Client struct {
cfg Config
dial DialContextFunc
mu sync.Mutex
}
type Message struct {
EnvelopeFrom string
Raw string
}
func New(cfg Config, dial DialContextFunc) *Client {
return &Client{cfg: cfg, dial: dial}
}
func (c *Client) Send(ctx context.Context, msg Message) error {
if c.cfg.DryRun {
return nil
}
c.mu.Lock()
defer c.mu.Unlock()
conn, err := c.connect(ctx)
if err != nil {
return err
}
defer conn.close()
session := conn.session
envelopeFrom := sanitizeEnvelope(c.cfg.EnvelopeFrom)
if envelopeFrom == "" {
envelopeFrom = sanitizeEnvelope(msg.EnvelopeFrom)
}
if _, _, err := session.cmd(250, "MAIL FROM:<%s>\r\n", envelopeFrom); err != nil {
return fmt.Errorf("mail from rejected: %w", err)
}
if _, _, err := session.cmd(250, "RCPT TO:<%s>\r\n", sanitizeEnvelope(c.cfg.Recipient)); err != nil {
return fmt.Errorf("rcpt to rejected: %w", err)
}
if _, _, err := session.cmd(354, "DATA\r\n"); err != nil {
return fmt.Errorf("data rejected: %w", err)
}
if err := writeSMTPData(session.w, msg.Raw); err != nil {
return err
}
if _, _, err := session.read(250); err != nil {
return fmt.Errorf("message rejected: %w", err)
}
_, _, _ = session.cmd(221, "QUIT\r\n")
return nil
}
// Check verifies the complete SOCKS/SMTP/TLS/AUTH path without issuing a mail
// transaction or sending message data.
func (c *Client) Check(ctx context.Context) error {
if c.cfg.DryRun {
return nil
}
c.mu.Lock()
defer c.mu.Unlock()
conn, err := c.connect(ctx)
if err != nil {
return err
}
defer conn.close()
_, _, _ = conn.session.cmd(221, "QUIT\r\n")
return nil
}
type smtpConnection struct {
conn net.Conn
session *session
cancel context.CancelFunc
}
func (c *smtpConnection) close() {
c.cancel()
_ = c.conn.Close()
}
func (c *Client) connect(ctx context.Context) (*smtpConnection, error) {
dial := c.dial
if dial == nil {
dial = (&net.Dialer{}).DialContext
}
timeout := c.cfg.Timeout
if timeout <= 0 {
timeout = 90 * time.Second
}
ctx, cancel := context.WithTimeout(ctx, timeout)
addr := net.JoinHostPort(c.cfg.Host, fmt.Sprintf("%d", c.cfg.Port))
conn, err := dial(ctx, "tcp", addr)
if err != nil {
cancel()
return nil, fmt.Errorf("dial smtp: %w", err)
}
fail := func(err error) (*smtpConnection, error) {
cancel()
_ = conn.Close()
return nil, err
}
if deadline, ok := ctx.Deadline(); ok {
_ = conn.SetDeadline(deadline)
}
if c.cfg.ImplicitTLS {
tlsConn := tls.Client(conn, &tls.Config{
ServerName: c.cfg.TLSServerName,
MinVersion: tls.VersionTLS12,
})
if err := tlsConn.HandshakeContext(ctx); err != nil {
return fail(fmt.Errorf("implicit tls handshake: %w", err))
}
conn = tlsConn
}
session := newSession(conn)
if _, _, err := session.read(220); err != nil {
return fail(fmt.Errorf("smtp greeting: %w", err))
}
if err := session.ehlo(c.cfg.HELO); err != nil {
return fail(err)
}
if c.cfg.RequireTLS && !c.cfg.ImplicitTLS {
if _, _, err := session.cmd(220, "STARTTLS\r\n"); err != nil {
return fail(fmt.Errorf("starttls: %w", err))
}
tlsConn := tls.Client(conn, &tls.Config{
ServerName: c.cfg.TLSServerName,
MinVersion: tls.VersionTLS12,
})
if err := tlsConn.HandshakeContext(ctx); err != nil {
return fail(fmt.Errorf("tls handshake: %w", err))
}
conn = tlsConn
session = newSession(tlsConn)
if err := session.ehlo(c.cfg.HELO); err != nil {
return fail(err)
}
}
if c.cfg.Username != "" || c.cfg.Password != "" {
if c.cfg.Username == "" || c.cfg.Password == "" {
return fail(fmt.Errorf("smtp authentication credentials are incomplete"))
}
if !c.cfg.RequireTLS && !c.cfg.ImplicitTLS {
return fail(fmt.Errorf("smtp authentication requires TLS"))
}
if err := session.authPlain(c.cfg.Username, c.cfg.Password); err != nil {
return fail(err)
}
}
return &smtpConnection{conn: conn, session: session, cancel: cancel}, nil
}
type session struct {
conn net.Conn
tp *textproto.Reader
w *bufio.Writer
}
func newSession(conn net.Conn) *session {
reader := bufio.NewReader(conn)
return &session{
conn: conn,
tp: textproto.NewReader(reader),
w: bufio.NewWriter(conn),
}
}
func (s *session) ehlo(helo string) error {
if helo == "" {
helo = "n2usenet.local"
}
if _, _, err := s.cmd(250, "EHLO %s\r\n", sanitizeAtom(helo)); err != nil {
if _, _, heloErr := s.cmd(250, "HELO %s\r\n", sanitizeAtom(helo)); heloErr != nil {
return fmt.Errorf("ehlo failed: %w", err)
}
}
return nil
}
func (s *session) authPlain(username, password string) error {
if strings.ContainsRune(username, '\x00') || strings.ContainsRune(password, '\x00') {
return fmt.Errorf("smtp authentication credentials contain invalid data")
}
payload := base64.StdEncoding.EncodeToString([]byte("\x00" + username + "\x00" + password))
if _, _, err := s.cmd(235, "AUTH PLAIN %s\r\n", payload); err != nil {
return fmt.Errorf("smtp authentication rejected: %w", err)
}
return nil
}
func (s *session) cmd(expect int, format string, args ...any) (int, string, error) {
if _, err := fmt.Fprintf(s.w, format, args...); err != nil {
return 0, "", err
}
if err := s.w.Flush(); err != nil {
return 0, "", err
}
return s.read(expect)
}
func (s *session) read(expect int) (int, string, error) {
code, msg, err := s.tp.ReadResponse(expect)
if err != nil {
return code, msg, err
}
return code, msg, nil
}
func writeSMTPData(w *bufio.Writer, raw string) error {
raw = strings.ReplaceAll(raw, "\r\n", "\n")
raw = strings.ReplaceAll(raw, "\r", "\n")
for _, line := range strings.Split(raw, "\n") {
if strings.HasPrefix(line, ".") {
line = "." + line
}
if _, err := io.WriteString(w, line+"\r\n"); err != nil {
return fmt.Errorf("write smtp data: %w", err)
}
}
if _, err := io.WriteString(w, ".\r\n"); err != nil {
return fmt.Errorf("write smtp terminator: %w", err)
}
if err := w.Flush(); err != nil {
return fmt.Errorf("flush smtp data: %w", err)
}
return nil
}
func sanitizeEnvelope(v string) string {
v = strings.TrimSpace(v)
v = strings.ReplaceAll(v, "\r", "")
v = strings.ReplaceAll(v, "\n", "")
v = strings.Trim(v, "<>")
return v
}
func sanitizeAtom(v string) string {
v = strings.TrimSpace(v)
v = strings.ReplaceAll(v, "\r", "")
v = strings.ReplaceAll(v, "\n", "")
if v == "" {
return "n2usenet.local"
}
return v
}
|