-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimap.go
More file actions
343 lines (293 loc) · 9.68 KB
/
imap.go
File metadata and controls
343 lines (293 loc) · 9.68 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
package main
import (
"bufio"
"bytes"
"crypto/tls"
"flag"
"fmt"
"io"
"log"
"net"
"strings"
"time"
)
var (
imapSTLSPort = flag.Int("imap-port", 6532, "IMAP proxy port (STARTTLS)")
disableIMAPSTARTTLS = flag.Bool("no-imap", false, "Disable IMAP proxy (STARTTLS)")
imapPort = flag.Int("imap-direct-port", 6534, "IMAP proxy port (direct TLS)")
disableIMAP = flag.Bool("no-imap-direct", false, "Disable IMAP proxy (direct TLS)")
)
func imapCommandGet(cReader *bufio.Reader, mcid string, conn net.Conn, debug bool) (end bool, t string, cmd string, part []string) {
for {
line, err := cReader.ReadString('\n')
if err != nil {
if err != io.EOF {
log.Printf("[%s] Error reading from client: %v", mcid, err)
}
return true, "", "", []string{}
}
if debug {
log.Printf("[%s] Client: %s", mcid, strings.TrimSpace(line))
}
// Parse IMAP command
parts := strings.Fields(line)
if len(parts) < 2 {
conn.Write([]byte("* BAD Invalid command\r\n"))
continue
}
tag := parts[0]
command := strings.ToUpper(parts[1])
return false, tag, command, parts
}
}
// handleIMAP handles IMAP protocol specifics
func (mp *MailProxy) handleIMAP(mc *MailConnection, STARTTLS bool) {
HELLO := []byte("* OK i will be launching a court case against apple for waiting for data even with MAIL over TLS/SSL port\r\n")
conn := mc.clientConn
if STARTTLS {
cReader := bufio.NewReader(conn)
// Send initial IMAP greeting
conn.SetDeadline(time.Now().Add(10 * time.Second))
conn.Write(HELLO)
for { // until STARTTLS
end, tag, command, _ := imapCommandGet(cReader, mc.id, conn, mc.debug)
if end {
return
}
if command == "STARTTLS" {
conn.Write([]byte(fmt.Sprintf("%s OK Begin TLS negotiation now\r\n", tag)))
break // Woo!
} else if command == "CAPABILITY" {
// Respond with basic capabilities
// AUTH=PLAIN AUTH=LOGIN
conn.Write([]byte("* CAPABILITY IMAP4rev1 STARTTLS\r\n"))
conn.Write([]byte(fmt.Sprintf("%s OK CAPABILITY completed\r\n", tag)))
} else if command == "NOOP" {
conn.Write([]byte(fmt.Sprintf("%s OK NOOP Fuck Apple\r\n", tag)))
} else if command == "LOGOUT" {
conn.Write([]byte("* BYE LiquidProxy logging out\r\n"))
conn.Write([]byte(fmt.Sprintf("%s OK LOGOUT completed\r\n", tag)))
return
} else {
// Before authentication, reject other commands
conn.Write([]byte(fmt.Sprintf("%s NO Please authenticate first\r\n", tag)))
}
}
}
// Peek at the ClientHello to determine routing
clientHello, err := peekClientHello(conn)
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: conn,
buffer: bytes.NewBuffer(clientHello.raw),
}
tlsConn = tls.Server(replayConn, sConfig)
} else {
// No ClientHello was peeked, proceed normally
tlsConn = tls.Server(conn, 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)
tlsConn.Write(HELLO)
for { // until LOGIN
end, tag, command, parts := imapCommandGet(tReader, mc.id, tlsConn, mc.debug)
if end {
if mc.debug {
log.Printf("[%s] The end...", mc.id)
}
return
}
// Check for authentication commands
if command == "LOGIN" && len(parts) >= 4 {
// Extract username and password
username := strings.Trim(parts[2], "\"")
password := strings.Trim(parts[3], "\"")
// Parse username for server info
if err := mc.parseUsername(username); err != nil {
tlsConn.Write([]byte(fmt.Sprintf("%s NO %v\r\n", tag, err)))
return
}
// Connect to real server
if err := mc.connectToServer(mp.TLSConfig, mp.DefaultRemotePort); err != nil {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Failed to connect to server: %v\r\n", tag, err)))
return
}
// Read server greeting
serverGreeting, err := mc.serverReader.ReadString('\n')
if err != nil {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Failed to read server greeting\r\n", tag)))
return
}
if mc.debug {
log.Printf("[%s] Server: %s", mc.id, strings.TrimSpace(serverGreeting))
}
// Send real login command
realLogin := fmt.Sprintf("%s LOGIN \"%s\" \"%s\"\r\n", tag, mc.realUsername, password)
mc.serverWriter.WriteString(realLogin)
mc.serverWriter.Flush()
// Read response
response, err := mc.readIMAPResponse(tag)
if err != nil {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Authentication failed\r\n", tag)))
return
}
// Forward response to client
tlsConn.Write([]byte(response))
// Check if authentication succeeded
if strings.Contains(response, tag+" OK") {
mc.authenticated = true
if mp.Debug {
log.Printf("[%s] Successfully authenticated to %s", mc.id, mc.targetServer)
}
// Switch to transparent proxy mode
transparentProxy(mc.id, mc.debug, tlsConn, mc.serverConn)
return
}
// Authentication failed
return
} else if command == "AUTHENTICATE" && len(parts) >= 3 {
authType := strings.ToUpper(parts[2])
if authType == "PLAIN" {
// Send continuation response
tlsConn.Write([]byte("+ \r\n"))
// Read base64 encoded credentials
credLine, err := mc.reader.ReadString('\n')
if err != nil {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Authentication failed\r\n", tag)))
return
}
// Decode credentials
decoded, err := decodeBase64(strings.TrimSpace(credLine))
if err != nil {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Invalid credentials encoding\r\n", tag)))
return
}
// AUTH PLAIN format: \0username\0password
parts := strings.Split(decoded, "\x00")
if len(parts) != 3 {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Invalid AUTH PLAIN format\r\n", tag)))
return
}
username := parts[1]
password := parts[2]
// Parse username for server info
if err := mc.parseUsername(username); err != nil {
tlsConn.Write([]byte(fmt.Sprintf("%s NO %v\r\n", tag, err)))
return
}
// Connect to real server
if err := mc.connectToServer(mp.TLSConfig, mp.DefaultRemotePort); err != nil {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Failed to connect to server: %v\r\n", tag, err)))
return
}
// Read server greeting
serverGreeting, err := mc.serverReader.ReadString('\n')
if err != nil {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Failed to read server greeting\r\n", tag)))
return
}
if mc.debug {
log.Printf("[%s] Server: %s", mc.id, strings.TrimSpace(serverGreeting))
}
// Send AUTHENTICATE PLAIN to server
mc.serverWriter.WriteString(fmt.Sprintf("%s AUTHENTICATE PLAIN\r\n", tag))
mc.serverWriter.Flush()
// Read continuation response
contResp, err := mc.serverReader.ReadString('\n')
if err != nil || !strings.HasPrefix(contResp, "+") {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Server rejected authentication\r\n", tag)))
return
}
// Send real credentials
realCreds := encodeBase64(fmt.Sprintf("\x00%s\x00%s", mc.realUsername, password))
mc.serverWriter.WriteString(realCreds + "\r\n")
mc.serverWriter.Flush()
// Read response
response, err := mc.readIMAPResponse(tag)
if err != nil {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Authentication failed\r\n", tag)))
return
}
// Forward response to client
tlsConn.Write([]byte(response))
// Check if authentication succeeded
if strings.Contains(response, tag+" OK") {
mc.authenticated = true
if mp.Debug {
log.Printf("[%s] Successfully authenticated to %s", mc.id, mc.targetServer)
}
// Switch to transparent proxy mode
transparentProxy(mc.id, mc.debug, tlsConn, mc.serverConn)
return
}
// Authentication failed
return
} else {
tlsConn.Write([]byte(fmt.Sprintf("%s NO Unsupported authentication mechanism\r\n", tag)))
}
} else if command == "CAPABILITY" {
// Respond with basic capabilities
// AUTH=PLAIN AUTH=LOGIN
tlsConn.Write([]byte("* CAPABILITY IMAP4rev1 STARTTLS\r\n"))
tlsConn.Write([]byte(fmt.Sprintf("%s OK CAPABILITY completed\r\n", tag)))
} else if command == "NOOP" {
tlsConn.Write([]byte(fmt.Sprintf("%s OK NOOP Fuck Apple\r\n", tag)))
} else if command == "LOGOUT" {
tlsConn.Write([]byte("* BYE LiquidProxy logging out\r\n"))
tlsConn.Write([]byte(fmt.Sprintf("%s OK LOGOUT completed\r\n", tag)))
return
} else {
// Before authentication, reject other commands
tlsConn.Write([]byte(fmt.Sprintf("%s NO Please authenticate first\r\n", tag)))
}
}
}
// readIMAPResponse reads a complete IMAP response for a given tag
func (mc *MailConnection) readIMAPResponse(tag string) (string, error) {
var response strings.Builder
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))
}
response.WriteString(line)
// Check if this is the tagged response
if strings.HasPrefix(line, tag+" ") {
break
}
}
return response.String(), nil
}