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 pathmail.go
More file actions
387 lines (332 loc) · 8.7 KB
/
Copy pathmail.go
File metadata and controls
387 lines (332 loc) · 8.7 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
package main
import (
"bufio"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"log"
"net"
"strings"
"time"
)
// MailProxy handles IMAP and SMTP proxy connections
type MailProxy struct {
// Protocol type (IMAP or SMTP)
Protocol string
// Listen port
Port int // I am amazed!!! I thought it meant the port as in lightning.
// Default remote port if not specified
DefaultRemotePort int
// TLS config for upstream connections
TLSConfig *tls.Config
// Explaination not needed
ServerTLSConfig *tls.Config
// Enable debug logging
Debug bool
ServerCA tls.Certificate
// On iPhone 4, where "SSL" is STARTTLS forced, you will need this
STARTTLS bool
}
// MailConnection represents a single mail proxy connection
type MailConnection struct {
id string
clientConn net.Conn
serverConn net.Conn
protocol string
targetServer string
realUsername string
authenticated bool
tlsEnabled bool
reader *bufio.Reader
writer *bufio.Writer
serverReader *bufio.Reader
serverWriter *bufio.Writer
debug bool
}
func mailMain(systemRoots *x509.CertPool, ca tls.Certificate, tlsServerConfig *tls.Config) {
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
RootCAs: systemRoots,
}
// Start IMAP proxy
if !*disableIMAP {
imapProxy := &MailProxy{
Protocol: "IMAP",
Port: *imapPort,
DefaultRemotePort: 993,
TLSConfig: tlsConfig,
ServerTLSConfig: tlsServerConfig,
Debug: *debug,
ServerCA: ca,
}
if err := imapProxy.Start(); err != nil {
log.Fatal("Failed to start IMAP proxy:", err)
}
}
if !*disableIMAPSTARTTLS {
imapStartTLSProxy := &MailProxy{
Protocol: "IMAP",
Port: *imapSTLSPort,
DefaultRemotePort: 993,
TLSConfig: tlsConfig,
ServerTLSConfig: tlsServerConfig,
Debug: *debug,
STARTTLS: true,
ServerCA: ca,
}
if err := imapStartTLSProxy.Start(); err != nil {
log.Fatal("Failed to start IMAP proxy:", err)
}
}
// Start SMTP proxy
if !*disableSMTP {
smtpProxy := &MailProxy{
Protocol: "SMTP",
Port: *smtpPort,
DefaultRemotePort: 587,
TLSConfig: tlsConfig,
ServerTLSConfig: tlsServerConfig,
Debug: *debug,
ServerCA: ca,
}
if err := smtpProxy.Start(); err != nil {
log.Fatal("Failed to start SMTP proxy:", err)
}
}
block := ""
if !*disableIMAP {
block += fmt.Sprintf("IMAP(DIRECT):%d, ", *imapPort)
}
if !*disableIMAPSTARTTLS {
block += fmt.Sprintf("IMAP(STARTTLS):%d, ", *imapSTLSPort)
}
if !*disableSMTP {
block += fmt.Sprintf("SMTP:%d, ", *smtpPort)
}
block = strings.TrimRight(block, ", ")
log.Printf("Mail Proxy started (%s)", block)
}
// Start starts the mail proxy listener
func (mp *MailProxy) Start() error {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", mp.Port))
if err != nil {
return fmt.Errorf("failed to start %s proxy on port %d: %w", mp.Protocol, mp.Port, err)
}
go func() {
for {
conn, err := listener.Accept()
if err != nil {
if mp.Debug {
log.Printf("%s proxy accept error: %v", mp.Protocol, err)
}
continue
}
go mp.handleConnection(conn)
}
}()
return nil
}
// handleConnection handles a single client connection
func (mp *MailProxy) handleConnection(clientConn net.Conn) {
// Check if connection is from localhost unless allow-remote-connections is set
if *blockRemoteConnections {
host, _, err := net.SplitHostPort(clientConn.RemoteAddr().String())
if err != nil {
if mp.Debug {
log.Printf("Error parsing remote address: %v", err)
}
clientConn.Close()
return
}
// Check if the connection is from localhost
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
if mp.Debug {
log.Printf("Rejected non-localhost connection from %s", host)
}
clientConn.Close()
return
}
}
connID := fmt.Sprintf("%s-%p", mp.Protocol, clientConn)
mc := &MailConnection{
id: connID,
clientConn: clientConn,
protocol: mp.Protocol,
reader: bufio.NewReader(clientConn),
writer: bufio.NewWriter(clientConn),
debug: mp.Debug,
}
if mc.debug {
log.Printf("[%s] New %s connection from %s", connID, mp.Protocol, clientConn.RemoteAddr())
}
// Handle based on protocol
switch mp.Protocol {
case "IMAP":
if mp.STARTTLS {
if mc.debug {
log.Printf("[%s] It's STARTTLS!", connID)
}
mp.handleIMAP(mc, true)
} else {
if mc.debug {
log.Printf("[%s] It's direct TLS", connID)
}
mp.handleIMAP(mc, false)
}
case "SMTP":
mp.handleSMTP(mc)
default:
log.Fatalf("Something went wrong, the protocol is %s", mp.Protocol)
}
}
// parseUsername extracts the real username and target server from the proxy username
func (mc *MailConnection) parseUsername(username string) error {
// Username format: realuser@domain@server
lastAt := strings.LastIndex(username, "@")
if lastAt == -1 || lastAt == 0 || lastAt == len(username)-1 {
return fmt.Errorf("invalid username format, use: user@domain@server")
}
un := username[:lastAt]
if strings.HasSuffix(un, "@") {
mc.realUsername = strings.TrimRight(un, "@")
} else {
if !strings.HasPrefix(un, "lp:") {
// john@example.com. correct answer is john@@example.com
return fmt.Errorf("Get off of my server :(")
} else {
mc.realUsername = strings.TrimLeft(un, "lp:")
}
}
mc.targetServer = username[lastAt+1:]
// Validate server name
if mc.targetServer == "" || mc.targetServer == "localhost" {
return fmt.Errorf("invalid target server")
}
if mc.debug {
log.Printf("[%s] Parsed username: %s -> server: %s", mc.id, mc.realUsername, mc.targetServer)
}
return nil
}
// connectToServer establishes connection to the real mail server
func (mc *MailConnection) connectToServer(tlsConfig *tls.Config, port int) error {
// Add port if not specified
server := mc.targetServer
if !strings.Contains(server, ":") {
server = fmt.Sprintf("%s:%d", server, port)
}
if mc.debug {
log.Printf("[%s] Connecting to %s", mc.id, server)
}
// For SMTP on port 465, use direct TLS
if mc.protocol == "SMTP" && port == 465 {
var tlsConf *tls.Config
if tlsConfig == nil {
tlsConf = &tls.Config{
ServerName: mc.targetServer,
}
} else {
tlsConf = tlsConfig
tlsConf.ServerName = mc.targetServer
}
conn, err := tls.Dial("tcp", server, tlsConf)
if err != nil {
return err
}
mc.serverConn = conn
mc.tlsEnabled = true
} else {
// For IMAP and SMTP on 587, start with plain connection
conn, err := net.Dial("tcp", server)
if err != nil {
return err
}
mc.serverConn = conn
// For IMAP, always upgrade to TLS immediately
if mc.protocol == "IMAP" {
var tlsConf *tls.Config
if tlsConfig == nil {
tlsConf = &tls.Config{
ServerName: mc.targetServer,
}
} else {
tlsConf = tlsConfig
tlsConf.ServerName = mc.targetServer
}
tlsConn := tls.Client(conn, tlsConf)
if err := tlsConn.Handshake(); err != nil {
conn.Close()
return fmt.Errorf("TLS handshake failed: %w", err)
}
mc.serverConn = tlsConn
mc.tlsEnabled = true
}
}
mc.serverReader = bufio.NewReader(mc.serverConn)
mc.serverWriter = bufio.NewWriter(mc.serverConn)
return nil
}
// transparentProxy switches to transparent proxy mode after authentication
func (mc *MailConnection) transparentProxy(tlsConn *tls.Conn) {
if mc.debug {
log.Printf("[%s] Switching to transparent proxy mode", mc.id)
}
// Verify connections are established
if tlsConn == nil {
if mc.debug {
log.Printf("[%s] ERROR: clientConn is nil in transparentProxy", mc.id)
}
return
}
if mc.serverConn == nil {
if mc.debug {
log.Printf("[%s] ERROR: serverConn is nil in transparentProxy", mc.id)
}
return
}
// For SMTP, we need to rewrite MAIL FROM commands
if mc.protocol == "SMTP" {
mc.transparentSMTPProxy(tlsConn)
return
}
errc := make(chan error, 2)
go func() {
_, err := io.Copy(tlsConn, mc.serverConn)
errc <- err
}()
go func() {
_, err := io.Copy(mc.serverConn, tlsConn)
errc <- err
}()
err2 := <-errc
if mc.debug {
log.Printf("[%s] Close starting", mc.id)
}
tlsConn.CloseWrite()
err1 := <-errc
ignore := func(err error) bool {
if err == nil {
return true
}
s := err.Error()
return strings.Contains(s, "use of closed network connection") ||
strings.Contains(s, "protocol is shutdown") ||
strings.Contains(s, "close_notify") ||
strings.Contains(s, "i/o timeout") ||
err == io.EOF
}
if !ignore(err1) {
log.Printf("[%s] copy error: %v", mc.id, err1)
}
if !ignore(err2) {
log.Printf("[%s] copy error: %v", mc.id, err2)
}
if mc.debug {
log.Printf("[%s] Goodbye!", mc.id)
}
tlsConn.SetDeadline(time.Time{})
mc.serverConn.SetDeadline(time.Time{})
tlsConn.Close()
mc.serverConn.Close()
}