-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmtp.go
More file actions
367 lines (314 loc) · 9.23 KB
/
smtp.go
File metadata and controls
367 lines (314 loc) · 9.23 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
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
package hostlib
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/smtp"
"strings"
"time"
"github.com/reglet-dev/reglet-host-sdk/netutil"
)
// SMTPConnectRequest contains parameters for an SMTP connection test.
type SMTPConnectRequest struct {
// Host is the SMTP server hostname.
Host string `json:"host"`
// Port is the SMTP server port (typically 25, 465, or 587).
Port int `json:"port"`
// UseTLS indicates whether to use implicit TLS (port 465).
UseTLS bool `json:"use_tls,omitempty"`
// UseSTARTTLS indicates whether to upgrade to TLS via STARTTLS (port 587).
UseSTARTTLS bool `json:"use_starttls,omitempty"`
// Timeout is the connection timeout in milliseconds. Default is 30000 (30s).
Timeout int `json:"timeout_ms,omitempty"`
}
// SMTPConnectResponse contains the result of an SMTP connection test.
type SMTPConnectResponse struct {
// Error contains error information if the connection failed.
Error *SMTPError `json:"error,omitempty"`
// Banner is the SMTP server banner (greeting message).
Banner string `json:"banner,omitempty"`
// TLSVersion is the TLS version if TLS is used.
TLSVersion string `json:"tls_version,omitempty"`
// TLSCipherSuite is the cipher suite used for TLS.
TLSCipherSuite string `json:"tls_cipher_suite,omitempty"`
// TLSServerName is the server name used for TLS (SNI).
TLSServerName string `json:"tls_server_name,omitempty"`
// LatencyMs is the connection latency in milliseconds.
LatencyMs int64 `json:"latency_ms,omitempty"`
// Connected indicates whether the connection was successful.
Connected bool `json:"connected"`
}
// SMTPError represents an SMTP connection error.
type SMTPError struct {
Code string `json:"code"`
Message string `json:"message"`
}
// Error implements the error interface.
func (e *SMTPError) Error() string {
return e.Message
}
// SMTPOption is a functional option for configuring SMTP connection behavior.
type SMTPOption func(*smtpConfig)
type smtpConfig struct {
tlsConfig *tls.Config
timeout time.Duration
ssrfProtection bool
allowPrivate bool
}
func defaultSMTPConfig() smtpConfig {
return smtpConfig{
timeout: 30 * time.Second,
tlsConfig: nil,
}
}
// WithSMTPTimeout sets the SMTP connection timeout.
func WithSMTPTimeout(d time.Duration) SMTPOption {
return func(c *smtpConfig) {
if d > 0 {
c.timeout = d
}
}
}
// WithSMTPTLSConfig sets custom TLS configuration.
func WithSMTPTLSConfig(cfg *tls.Config) SMTPOption {
return func(c *smtpConfig) {
c.tlsConfig = cfg
}
}
// WithSMTPSSRFProtection enables SSRF protection.
// When enabled, private/reserved IPs are blocked unless allowPrivate is true.
// DNS is resolved once and the resolved IP is used for the connection (prevents DNS rebinding).
func WithSMTPSSRFProtection(allowPrivate bool) SMTPOption {
return func(c *smtpConfig) {
c.ssrfProtection = true
c.allowPrivate = allowPrivate
}
}
// PerformSMTPConnect tests SMTP connectivity to the specified server.
// This is a pure Go implementation with no WASM runtime dependencies.
//
// Example usage from a WASM host:
//
// func handleSMTPConnect(req hostfuncs.SMTPConnectRequest) hostfuncs.SMTPConnectResponse {
// return hostfuncs.PerformSMTPConnect(ctx, req)
// }
func PerformSMTPConnect(ctx context.Context, req SMTPConnectRequest, opts ...SMTPOption) SMTPConnectResponse {
cfg := defaultSMTPConfig()
// Check context for default SSRF protection based on capabilities
if allowPrivate, ok := ctx.Value("ssrf_allow_private").(bool); ok {
WithSMTPSSRFProtection(allowPrivate)(&cfg)
}
for _, opt := range opts {
opt(&cfg)
}
// Override config from request if specified
if req.Timeout > 0 {
cfg.timeout = time.Duration(req.Timeout) * time.Millisecond
}
// Validate request
if req.Host == "" {
return SMTPConnectResponse{
Connected: false,
Error: &SMTPError{
Code: "INVALID_REQUEST",
Message: "host is required",
},
}
}
if req.Port <= 0 || req.Port > 65535 {
return SMTPConnectResponse{
Connected: false,
Error: &SMTPError{
Code: "INVALID_REQUEST",
Message: fmt.Sprintf("invalid port: %d", req.Port),
},
}
}
// SSRF Protection: validate and resolve address
originalHost := req.Host
resolvedHost := req.Host
if cfg.ssrfProtection {
addr := fmt.Sprintf("%s:%d", req.Host, req.Port)
var opts []netutil.NetfilterOption
if cfg.allowPrivate {
opts = append(opts, netutil.WithBlockPrivate(false), netutil.WithBlockLocalhost(false))
}
result := netutil.ValidateAddress(addr, opts...)
if !result.Allowed {
return SMTPConnectResponse{
Connected: false,
Error: &SMTPError{
Code: "SSRF_BLOCKED",
Message: result.Reason,
},
}
}
// Use resolved IP for connection to prevent DNS rebinding
if result.ResolvedIP != "" {
resolvedHost = result.ResolvedIP
}
}
// Build address using resolved IP
address := fmt.Sprintf("%s:%d", resolvedHost, req.Port)
// Apply timeout to context
ctx, cancel := context.WithTimeout(ctx, cfg.timeout)
defer cancel()
start := time.Now()
// Connect based on TLS mode
if req.UseTLS {
// Implicit TLS (typically port 465)
return connectWithTLS(ctx, address, originalHost, cfg, start)
}
// Plain connection (may upgrade via STARTTLS)
return connectPlain(ctx, address, originalHost, req.UseSTARTTLS, cfg, start)
}
func connectWithTLS(ctx context.Context, address, host string, cfg smtpConfig, start time.Time) SMTPConnectResponse {
tlsConfig := cfg.tlsConfig
if tlsConfig == nil {
tlsConfig = &tls.Config{
ServerName: host, // Use original hostname for SNI, not resolved IP
MinVersion: tls.VersionTLS12,
}
} else if tlsConfig.ServerName == "" {
tlsConfig.ServerName = host
}
dialer := &net.Dialer{Timeout: cfg.timeout}
conn, err := tls.DialWithDialer(dialer, "tcp", address, tlsConfig)
latency := time.Since(start)
if err != nil {
return SMTPConnectResponse{
Connected: false,
LatencyMs: latency.Milliseconds(),
Error: classifySMTPError(err),
}
}
defer func() { _ = conn.Close() }()
// Read banner
banner, err := readBanner(conn, cfg.timeout)
if err != nil {
return SMTPConnectResponse{
Connected: false,
LatencyMs: latency.Milliseconds(),
Error: &SMTPError{
Code: "READ_BANNER_FAILED",
Message: err.Error(),
},
}
}
state := conn.ConnectionState()
return SMTPConnectResponse{
Connected: true,
Banner: banner,
TLSVersion: tlsVersionString(state.Version),
TLSCipherSuite: tls.CipherSuiteName(state.CipherSuite),
TLSServerName: state.ServerName,
LatencyMs: latency.Milliseconds(),
}
}
func connectPlain(ctx context.Context, address, host string, useSTARTTLS bool, cfg smtpConfig, start time.Time) SMTPConnectResponse {
dialer := &net.Dialer{Timeout: cfg.timeout}
conn, err := dialer.DialContext(ctx, "tcp", address)
latency := time.Since(start)
if err != nil {
return SMTPConnectResponse{
Connected: false,
LatencyMs: latency.Milliseconds(),
Error: classifySMTPError(err),
}
}
defer func() { _ = conn.Close() }()
// Create SMTP client
client, err := smtp.NewClient(conn, host)
if err != nil {
return SMTPConnectResponse{
Connected: false,
LatencyMs: latency.Milliseconds(),
Error: &SMTPError{
Code: "SMTP_CLIENT_FAILED",
Message: err.Error(),
},
}
}
defer func() { _ = client.Quit() }()
var tlsVersion string
var tlsCipherSuite string
var tlsServerName string
// Upgrade to TLS if requested
if useSTARTTLS {
tlsConfig := cfg.tlsConfig
if tlsConfig == nil {
tlsConfig = &tls.Config{
ServerName: host, // Use original hostname for SNI, not resolved IP
MinVersion: tls.VersionTLS12,
}
} else if tlsConfig.ServerName == "" {
tlsConfig.ServerName = host
}
if err := client.StartTLS(tlsConfig); err != nil {
return SMTPConnectResponse{
Connected: false,
LatencyMs: latency.Milliseconds(),
Error: &SMTPError{
Code: "STARTTLS_FAILED",
Message: err.Error(),
},
}
}
// Get TLS version after STARTTLS
state, ok := client.TLSConnectionState()
if ok {
tlsVersion = tlsVersionString(state.Version)
tlsCipherSuite = tls.CipherSuiteName(state.CipherSuite)
tlsServerName = state.ServerName
}
}
return SMTPConnectResponse{
Connected: true,
TLSVersion: tlsVersion,
TLSCipherSuite: tlsCipherSuite,
TLSServerName: tlsServerName,
LatencyMs: latency.Milliseconds(),
}
}
func readBanner(conn net.Conn, timeout time.Duration) (string, error) {
_ = conn.SetReadDeadline(time.Now().Add(timeout))
buf := make([]byte, 512)
n, err := conn.Read(buf)
if err != nil {
return "", err
}
return strings.TrimSpace(string(buf[:n])), nil
}
func classifySMTPError(err error) *SMTPError {
msg := err.Error()
code := "CONNECTION_FAILED"
switch {
case strings.Contains(msg, "timeout"):
code = "TIMEOUT"
case strings.Contains(msg, "refused"):
code = "CONNECTION_REFUSED"
case strings.Contains(msg, "no such host"):
code = "HOST_NOT_FOUND"
case strings.Contains(msg, "certificate"):
code = "TLS_CERTIFICATE_ERROR"
}
return &SMTPError{
Code: code,
Message: msg,
}
}
func tlsVersionString(version uint16) string {
switch version {
case tls.VersionTLS10:
return "TLS 1.0"
case tls.VersionTLS11:
return "TLS 1.1"
case tls.VersionTLS12:
return "TLS 1.2"
case tls.VersionTLS13:
return "TLS 1.3"
default:
return ""
}
}