This repository was archived by the owner on May 5, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmtp.go
More file actions
677 lines (576 loc) · 17.5 KB
/
Copy pathsmtp.go
File metadata and controls
677 lines (576 loc) · 17.5 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
package main
import (
"bufio"
"bytes"
"crypto/tls"
"flag"
"fmt"
"io"
"log"
"regexp"
"strings"
)
var (
smtpPort = flag.Int("smtp-port", 6533, "SMTP proxy port")
disableSMTP = flag.Bool("no-smtp", false, "Disable SMTP proxy")
)
// handleSMTP handles SMTP protocol specifics
func (mp *MailProxy) handleSMTP(mc *MailConnection) {
// Peek at the ClientHello to determine routing
clientHello, err := peekClientHello(mc.clientConn)
if err != nil {
log.Printf("[%s] Error on peeking handshake: %s", mc.id, err)
return
}
if clientHello.isModernClient && *blockModernConnections {
return
}
var sConfig *tls.Config
// Create TLS server config
if mp.ServerTLSConfig == nil {
sConfig = new(tls.Config)
} else {
sConfig = mp.ServerTLSConfig
}
//sConfig.Certificates = []tls.Certificate{sConfig.RootCAs}
sConfig.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
return &mp.ServerCA, nil
}
// Create a connection that can replay the ClientHello
var tlsConn *tls.Conn
if clientHello != nil {
// We have already read the ClientHello, so we need to create a special connection
// that will replay it when the TLS handshake starts
replayConn := &replayConn{
Conn: mc.clientConn,
buffer: bytes.NewBuffer(clientHello.raw),
}
tlsConn = tls.Server(replayConn, sConfig)
} else {
// No ClientHello was peeked, proceed normally
tlsConn = tls.Server(mc.clientConn, sConfig)
}
// Perform TLS handshake
err = tlsConn.Handshake()
if err != nil {
log.Printf("[%s] Error on handshake: %s", mc.id, err)
return
}
if mc.debug {
log.Printf("[%s] Handshake finish", mc.id)
}
tReader := bufio.NewReader(tlsConn)
// Send initial SMTP greeting
greeting := "220 localhost LiquidProxy SMTP server ready\r\n"
tlsConn.Write([]byte(greeting))
// Process commands until we get authentication
for {
line, err := tReader.ReadString('\n')
if err != nil {
if err != io.EOF {
log.Printf("[%s] Error reading from client: %v", mc.id, err)
}
return
}
if mc.debug {
log.Printf("[%s] Client: %s", mc.id, strings.TrimSpace(line))
}
// Parse SMTP command
command := strings.ToUpper(strings.Fields(line)[0])
switch command {
case "EHLO", "HELO":
// Respond with capabilities
domain := "localhost"
if len(strings.Fields(line)) > 1 {
domain = strings.Fields(line)[1]
}
if command == "EHLO" {
tlsConn.Write([]byte(fmt.Sprintf("250-localhost Hello %s\r\n", domain)))
tlsConn.Write([]byte("250-AUTH PLAIN LOGIN\r\n"))
tlsConn.Write([]byte("250-8BITMIME\r\n"))
tlsConn.Write([]byte("250 OK\r\n"))
} else {
tlsConn.Write([]byte(fmt.Sprintf("250 localhost Hello %s\r\n", domain)))
}
case "AUTH":
// Parse AUTH command
authParts := strings.Fields(line)
if len(authParts) < 2 {
tlsConn.Write([]byte("501 Syntax error\r\n"))
continue
}
authType := strings.ToUpper(authParts[1])
if authType == "LOGIN" {
// Handle AUTH LOGIN
tlsConn.Write([]byte("334 VXNlcm5hbWU6\r\n")) // Base64 for "Username:"
// Read username
userLine, err := tReader.ReadString('\n')
if err != nil {
return
}
username, err := decodeBase64(strings.TrimSpace(userLine))
if err != nil {
tlsConn.Write([]byte("501 Invalid username encoding\r\n"))
return
}
// Parse username for server info
if err := mc.parseUsername(username); err != nil {
tlsConn.Write([]byte(fmt.Sprintf("535 %v\r\n", err)))
return
}
tlsConn.Write([]byte("334 UGFzc3dvcmQ6\r\n")) // Base64 for "Password:"
// Read password
passLine, err := tReader.ReadString('\n')
if err != nil {
return
}
password, err := decodeBase64(strings.TrimSpace(passLine))
if err != nil {
tlsConn.Write([]byte("501 Invalid password encoding\r\n"))
return
}
// Connect and authenticate
if mc.debug {
log.Printf("[%s] Attempting to connect to server on port 587", mc.id)
}
if err := mc.connectToServer(mp.TLSConfig, 587); err != nil {
if mc.debug {
log.Printf("[%s] Failed to connect on port 587: %v, trying port 465", mc.id, err)
}
// Try port 465 if 587 fails
if err := mc.connectToServer(mp.TLSConfig, 465); err != nil {
if mc.debug {
log.Printf("[%s] Failed to connect on port 465: %v", mc.id, err)
}
tlsConn.Write([]byte("535 Failed to connect to server\r\n"))
return
}
}
// Perform SMTP authentication with real server
if mc.debug {
log.Printf("[%s] Starting SMTP authentication with %s", mc.id, mc.targetServer)
}
if err := mc.authenticateSMTP(authType, mc.realUsername, password, mp.TLSConfig); err != nil {
if mc.debug {
log.Printf("[%s] SMTP authentication failed: %v", mc.id, err)
}
tlsConn.Write([]byte("535 Authentication failed\r\n"))
return
}
if mc.debug {
log.Printf("[%s] SMTP authentication succeeded, sending 235 to client", mc.id)
}
tlsConn.Write([]byte("235 Authentication successful\r\n"))
if mc.debug {
log.Printf("[%s] Successfully sent 235 response to client", mc.id)
}
mc.authenticated = true
if mp.Debug {
log.Printf("[%s] Successfully authenticated to %s", mc.id, mc.targetServer)
}
// Switch to transparent proxy mode
if mc.debug {
log.Printf("[%s] About to switch to transparent proxy mode", mc.id)
}
mc.transparentSMTPProxy(tlsConn)
if mc.debug {
log.Printf("[%s] Returned from transparentProxy()", mc.id)
}
return
} else if authType == "PLAIN" {
// Handle AUTH PLAIN
var credentials string
if len(authParts) > 2 {
// Credentials provided inline
credentials = authParts[2]
} else {
// Request credentials
tlsConn.Write([]byte("334 \r\n"))
credLine, err := tReader.ReadString('\n')
if err != nil {
return
}
credentials = strings.TrimSpace(credLine)
}
// Decode and parse credentials
decoded, err := decodeBase64(credentials)
if err != nil {
tlsConn.Write([]byte("501 Invalid credentials encoding\r\n"))
return
}
// AUTH PLAIN format: \0username\0password
parts := strings.Split(decoded, "\x00")
if len(parts) != 3 {
tlsConn.Write([]byte("501 Invalid AUTH PLAIN format\r\n"))
return
}
username := parts[1]
password := parts[2]
// Parse username for server info
if err := mc.parseUsername(username); err != nil {
tlsConn.Write([]byte(fmt.Sprintf("535 %v\r\n", err)))
return
}
// Connect and authenticate
if mc.debug {
log.Printf("[%s] Attempting to connect to server on port 587", mc.id)
}
if err := mc.connectToServer(mp.TLSConfig, 587); err != nil {
if mc.debug {
log.Printf("[%s] Failed to connect on port 587: %v, trying port 465", mc.id, err)
}
// Try port 465 if 587 fails
if err := mc.connectToServer(mp.TLSConfig, 465); err != nil {
if mc.debug {
log.Printf("[%s] Failed to connect on port 465: %v", mc.id, err)
}
tlsConn.Write([]byte("535 Failed to connect to server\r\n"))
return
}
}
// Perform SMTP authentication with real server
if mc.debug {
log.Printf("[%s] Starting SMTP authentication with %s", mc.id, mc.targetServer)
}
if err := mc.authenticateSMTP(authType, mc.realUsername, password, mp.TLSConfig); err != nil {
if mc.debug {
log.Printf("[%s] SMTP authentication failed: %v", mc.id, err)
}
tlsConn.Write([]byte("535 Authentication failed\r\n"))
return
}
if mc.debug {
log.Printf("[%s] SMTP authentication succeeded, sending 235 to client", mc.id)
}
tlsConn.Write([]byte("235 Authentication successful\r\n"))
/*if err :=; err != nil {
if mc.debug {
log.Printf("[%s] Error flushing 235 response: %v", mc.id, err)
}
return
}*/
if mc.debug {
log.Printf("[%s] Successfully sent 235 response to client", mc.id)
}
mc.authenticated = true
if mp.Debug {
log.Printf("[%s] Successfully authenticated to %s", mc.id, mc.targetServer)
}
// Switch to transparent proxy mode
if mc.debug {
log.Printf("[%s] About to switch to transparent proxy mode", mc.id)
}
mc.transparentSMTPProxy(tlsConn)
if mc.debug {
log.Printf("[%s] Returned from transparentProxy()", mc.id)
}
return
} else {
tlsConn.Write([]byte("504 Unrecognized authentication type\r\n"))
}
case "QUIT":
tlsConn.Write([]byte("221 Bye\r\n"))
return
case "NOOP":
tlsConn.Write([]byte("250 OK\r\n"))
case "RSET":
tlsConn.Write([]byte("250 OK\r\n"))
default:
// Before authentication, reject other commands
tlsConn.Write([]byte("530 Please authenticate first\r\n"))
}
}
}
// authenticateSMTP performs SMTP authentication with the real server
func (mc *MailConnection) authenticateSMTP(authType, username, password string, tlsConfig *tls.Config) error {
// Read server greeting
greeting, err := mc.serverReader.ReadString('\n')
if err != nil {
return err
}
if mc.debug {
log.Printf("[%s] Server: %s", mc.id, strings.TrimSpace(greeting))
}
// Send EHLO
mc.serverWriter.WriteString("EHLO localhost\r\n")
mc.serverWriter.Flush()
// Read EHLO response and check for STARTTLS
hasSTARTTLS := false
for {
line, err := mc.serverReader.ReadString('\n')
if err != nil {
return err
}
if mc.debug {
log.Printf("[%s] Server: %s", mc.id, strings.TrimSpace(line))
}
// Check for STARTTLS support
if !mc.tlsEnabled && strings.Contains(line, "STARTTLS") {
hasSTARTTLS = true
}
// Check if this is the last line
if len(line) >= 4 && line[3] == ' ' {
break
}
}
// If STARTTLS is supported and we're not already using TLS, upgrade the connection
if hasSTARTTLS && !mc.tlsEnabled {
// Send STARTTLS command
mc.serverWriter.WriteString("STARTTLS\r\n")
mc.serverWriter.Flush()
response, err := mc.serverReader.ReadString('\n')
if err != nil {
return err
}
if mc.debug {
log.Printf("[%s] STARTTLS response: %s", mc.id, strings.TrimSpace(response))
}
if !strings.HasPrefix(response, "220") {
return fmt.Errorf("STARTTLS failed: %s", response)
}
// Upgrade connection
var tlsConf *tls.Config
// CRITICAL: Copy the TLS config to get RootCAs for Snow Leopard
if tlsConfig != nil {
tlsConf = tlsConfig
tlsConf.ServerName = mc.targetServer
} else {
tlsConf = &tls.Config{
ServerName: mc.targetServer,
}
if mc.debug {
log.Printf("[%s] WARNING: No TLS config provided for STARTTLS!", mc.id)
}
}
if mc.debug {
log.Printf("[%s] Starting TLS handshake with %s", mc.id, mc.targetServer)
}
tlsConn := tls.Client(mc.serverConn, tlsConf)
if err := tlsConn.Handshake(); err != nil {
if mc.debug {
log.Printf("[%s] TLS handshake failed: %v", mc.id, err)
}
return fmt.Errorf("TLS handshake failed: %w", err)
}
mc.serverConn = tlsConn
mc.serverReader = bufio.NewReader(mc.serverConn)
mc.serverWriter = bufio.NewWriter(mc.serverConn)
mc.tlsEnabled = true
if mc.debug {
log.Printf("[%s] TLS connection established successfully", mc.id)
}
// Send EHLO again after STARTTLS
if mc.debug {
log.Printf("[%s] Sending EHLO after STARTTLS", mc.id)
}
mc.serverWriter.WriteString("EHLO localhost\r\n")
if err := mc.serverWriter.Flush(); err != nil {
if mc.debug {
log.Printf("[%s] Error flushing EHLO after STARTTLS: %v", mc.id, err)
}
return fmt.Errorf("failed to send EHLO after STARTTLS: %w", err)
}
// Read EHLO response again
if mc.debug {
log.Printf("[%s] Reading EHLO response after STARTTLS", mc.id)
}
for {
line, err := mc.serverReader.ReadString('\n')
if err != nil {
if mc.debug {
log.Printf("[%s] Error reading EHLO response after STARTTLS: %v", mc.id, err)
}
return err
}
if mc.debug {
log.Printf("[%s] Server: %s", mc.id, strings.TrimSpace(line))
}
if len(line) >= 4 && line[3] == ' ' {
break
}
}
}
// Perform authentication
if authType == "LOGIN" {
if mc.debug {
log.Printf("[%s] Sending AUTH LOGIN", mc.id)
}
mc.serverWriter.WriteString("AUTH LOGIN\r\n")
mc.serverWriter.Flush()
// Read username prompt
response, err := mc.serverReader.ReadString('\n')
if err != nil {
if mc.debug {
log.Printf("[%s] Error reading AUTH LOGIN response: %v", mc.id, err)
}
return err
}
if mc.debug {
log.Printf("[%s] AUTH LOGIN response: %s", mc.id, strings.TrimSpace(response))
}
if !strings.HasPrefix(response, "334") {
return fmt.Errorf("AUTH LOGIN failed: %s", response)
}
// Send username
if mc.debug {
log.Printf("[%s] Sending username", mc.id)
}
mc.serverWriter.WriteString(encodeBase64(username) + "\r\n")
mc.serverWriter.Flush()
// Read password prompt
response, err = mc.serverReader.ReadString('\n')
if err != nil {
if mc.debug {
log.Printf("[%s] Error reading password prompt: %v", mc.id, err)
}
return err
}
if mc.debug {
log.Printf("[%s] Password prompt response: %s", mc.id, strings.TrimSpace(response))
}
if !strings.HasPrefix(response, "334") {
return fmt.Errorf("AUTH LOGIN failed: %s", response)
}
// Send password
if mc.debug {
log.Printf("[%s] Sending password", mc.id)
}
mc.serverWriter.WriteString(encodeBase64(password) + "\r\n")
mc.serverWriter.Flush()
} else if authType == "PLAIN" {
// Encode credentials
credentials := encodeBase64(fmt.Sprintf("\x00%s\x00%s", username, password))
if mc.debug {
log.Printf("[%s] Sending AUTH PLAIN", mc.id)
}
mc.serverWriter.WriteString(fmt.Sprintf("AUTH PLAIN %s\r\n", credentials))
mc.serverWriter.Flush()
}
// Read authentication response
response, err := mc.serverReader.ReadString('\n')
if err != nil {
if mc.debug {
log.Printf("[%s] Error reading authentication response: %v", mc.id, err)
}
return err
}
if mc.debug {
log.Printf("[%s] Authentication response: %s", mc.id, strings.TrimSpace(response))
}
if !strings.HasPrefix(response, "235") {
return fmt.Errorf("authentication failed: %s", response)
}
return nil
}
// transparentSMTPProxy handles SMTP-specific transparent proxying with MAIL FROM rewriting
func (mc *MailConnection) transparentSMTPProxy(tlsConn *tls.Conn) {
if mc.debug {
log.Printf("[%s] Entered transparentSMTPProxy", mc.id)
}
// Server to client - log responses if debug enabled
go func() {
if mc.debug {
log.Printf("[%s] Starting server-to-client relay goroutine", mc.id)
}
scanner := bufio.NewScanner(mc.serverConn)
for scanner.Scan() {
line := scanner.Text()
if mc.debug {
log.Printf("[%s] Server response: %s", mc.id, line)
}
tlsConn.Write([]byte(line + "\r\n"))
/*if err :=; err != nil {
if mc.debug {
log.Printf("[%s] Error flushing server response to client: %v", mc.id, err)
}
break
}*/
}
if err := scanner.Err(); err != nil && mc.debug {
log.Printf("[%s] Server scanner error: %v", mc.id, err)
}
if mc.debug {
log.Printf("[%s] Server-to-client relay goroutine exiting", mc.id)
}
tlsConn.Close()
}()
// Client to server - rewrite MAIL FROM commands
if mc.debug {
log.Printf("[%s] Starting client-to-server relay loop", mc.id)
log.Printf("[%s] clientConn type: %T", mc.id, tlsConn)
log.Printf("[%s] serverConn type: %T", mc.id, mc.serverConn)
}
scanner := bufio.NewScanner(tlsConn)
for scanner.Scan() {
line := scanner.Text()
if mc.debug {
log.Printf("[%s] Client command: %s", mc.id, line)
}
// Check if this is a MAIL FROM command
upperLine := strings.ToUpper(line)
if strings.HasPrefix(upperLine, "MAIL FROM:") {
// Extract the email address
fromMatch := regexp.MustCompile(`<([^>]+)>`).FindStringSubmatch(line)
if len(fromMatch) > 1 {
email := fromMatch[1]
// Check if it contains our proxy suffix
if strings.Contains(email, "@imap.mail.me.com") || strings.Contains(email, "@smtp.mail.me.com") {
// Extract the real email (everything before the last @)
lastAt := strings.LastIndex(email, "@")
if lastAt > 0 {
realEmail := email[:lastAt]
// Rewrite the command
line = strings.Replace(line, email, realEmail, 1)
if mc.debug {
log.Printf("[%s] Rewritten MAIL FROM: %s", mc.id, line)
}
}
}
}
}
// Also check for From: header in email data
if strings.HasPrefix(line, "From:") {
// Look for email addresses with our proxy suffix
fromMatch := regexp.MustCompile(`<([^>]+@(?:imap|smtp)\.mail\.[^>]+)>`).FindAllStringSubmatch(line, -1)
for _, match := range fromMatch {
if len(match) > 1 {
email := match[1]
// Extract the real email (everything before the last @)
lastAt := strings.LastIndex(email, "@")
if lastAt > 0 {
realEmail := email[:lastAt]
// Rewrite the From header
line = strings.Replace(line, email, realEmail, 1)
if mc.debug {
log.Printf("[%s] Rewritten From header: %s", mc.id, line)
}
}
}
}
}
// Send the (possibly rewritten) command to server
mc.serverWriter.WriteString(line + "\r\n")
if err := mc.serverWriter.Flush(); err != nil {
if mc.debug {
log.Printf("[%s] Error flushing client command to server: %v", mc.id, err)
}
break
}
// Check for QUIT command
if strings.ToUpper(strings.TrimSpace(line)) == "QUIT" {
if mc.debug {
log.Printf("[%s] Received QUIT command, exiting relay loop", mc.id)
}
// Read final response and close
mc.serverReader.ReadString('\n')
break
}
}
if err := scanner.Err(); err != nil && mc.debug {
log.Printf("[%s] Client scanner error: %v", mc.id, err)
}
if mc.debug {
log.Printf("[%s] Client-to-server relay loop exited", mc.id)
}
tlsConn.Close()
}