-
Notifications
You must be signed in to change notification settings - Fork 3
/
proxy.go
337 lines (281 loc) · 7.82 KB
/
proxy.go
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
package main
import (
"errors"
"fmt"
"net"
"regexp"
"flag"
)
type HttpProxyConnection struct {
// Server hostname
server string
// Client and Server connection
cConn, sConn net.Conn
// Buffer for initial read
headBuf []byte
}
type HttpsProxyConnection struct {
// Server hostname
server string
// Client and Server connection
cConn, sConn net.Conn
// Buffer for initial read
tlsBuf []byte
}
func PipeConn(in net.Conn, out net.Conn) {
// Make sure to close both connections in the end
defer in.Close()
defer out.Close()
buf := make([]byte, 2048)
for {
numBytes, err := in.Read(buf)
if err != nil {
Logf(LOG_INFO, "Read error: %v\n", err)
break
}
_, err = out.Write(buf[:numBytes])
if err != nil {
Logf(LOG_INFO, "Write error: %v\n", err)
break
}
}
}
func (http *HttpProxyConnection) ParseHeader() error {
// Regexp to find the Host line and to check for an empty line
reHost := regexp.MustCompile("(?m)^Host: (.+)\r\n")
reHeaderEnd := regexp.MustCompile("\r\n\r\n")
// Buffer to hold the data we read, use 8k as maximum header size
buf := make([]byte, 8192)
pos := 0
for {
// Read new bytes from connection
tmpBuf := make([]byte, len(buf)-pos)
numBytes, err := http.cConn.Read(tmpBuf)
if err != nil {
return errors.New(fmt.Sprintf("Read error (%v)", err))
}
// Store new data in "buf"
copy(buf[pos:], tmpBuf[:numBytes])
pos += numBytes
//Logf(LOG_DEBUG, "Current data:\n%v\n", string(buf[:pos]))
// Try to find the "Host: " header in "buf"
if matches := reHost.FindSubmatch(buf); len(matches) > 0 {
http.server = string(matches[1])
http.headBuf = buf[:pos]
return nil
}
// Check for an empty line (indicates end of header)
if matches := reHeaderEnd.FindSubmatch(buf); len(matches) > 0 {
return errors.New("No Host header found!")
}
// Check if we hit our buffer limit
if len(buf) == pos {
return errors.New("Buffer limit exceeded!")
}
}
}
func (http *HttpProxyConnection) HandleConn() {
Logf(LOG_NOTICE, "Handling new connection from %v\n", http.cConn.RemoteAddr())
var err error
// Extract desired server from HTTP header
if err = http.ParseHeader(); err != nil {
Logf(LOG_NOTICE, "Error getting server: %v\n", err)
http.cConn.Close()
return
}
// TODO(fabi): Figure out what to do if server contains a port number
// Create connection to server
Logf(LOG_INFO, "Connecting to %s:http\n", http.server)
http.sConn, err = net.Dial("tcp", fmt.Sprintf("%s:http", http.server))
if err != nil {
Logf(LOG_NOTICE, "Error connecting to server: %v\n", err)
http.cConn.Close()
return
}
// Send data we read during parsing to server
if _, err = http.sConn.Write(http.headBuf); err != nil {
Logf(LOG_INFO, "Write error: %v\n", err)
http.cConn.Close()
http.sConn.Close()
return
}
// Link both connections together
Logf(LOG_INFO, "Linking client and server connection")
go PipeConn(http.cConn, http.sConn)
go PipeConn(http.sConn, http.cConn)
}
func (https *HttpsProxyConnection) ParseTlsHandshake() error {
// Buffer to hold the data we read, use 8k as maximum size
buf := make([]byte, 8192)
pos := 0
for {
// Read new bytes from connection
tmpBuf := make([]byte, len(buf)-pos)
numBytes, err := https.cConn.Read(tmpBuf)
if err != nil {
return errors.New(fmt.Sprintf("Read error (%v)", err))
}
// Store new data in "buf"
copy(buf[pos:], tmpBuf[:numBytes])
pos += numBytes
// We need the header to start parsing
if pos < 5 {
continue
}
// Check content type
//Logf(LOG_DEBUG, "TLS content type: %d\n", buf[0])
if buf[0] != 0x16 {
return errors.New("Data doesn't look like a TLS handshake!")
}
// We need at least SSL 3
//Logf(LOG_DEBUG, "SSL version: %d.%d\n", buf[1], buf[2])
if buf[1] < 3 {
return errors.New(fmt.Sprintf("Incompatible SSL Version (%d.%d)!", buf[1], buf[2]))
}
// Make sure we have the whole handshake
len := int((buf[3] << 8) + buf[4] + 5)
//Logf(LOG_DEBUG, "need: %d, have:%d\n", len, pos)
if pos < len {
continue
}
readPos := 5
// Check handshake type
if readPos+1 > pos {
return errors.New("Not enough data!")
}
if buf[5] != 0x01 {
return errors.New("Not a handshake client hello!")
}
// Skip Handshake Type, Length, Version, Random
readPos += 38
// Skip Session ID
if readPos+1 > pos {
return errors.New("Not enough data!")
}
readPos += 1 + int(buf[readPos])
// Skip Cipher Suites
if readPos+2 > pos {
return errors.New("Not enough data!")
}
readPos += 2 + int((buf[readPos]<<8)+buf[readPos+1])
// Skip Compression Methods
if readPos+1 > pos {
return errors.New("Not enough data!")
}
readPos += 1 + int(buf[readPos])
// Check for extensions
if pos == readPos {
return errors.New("No TLS extensions!")
}
// Get and skip Extensions Length
if readPos+2 > pos {
return errors.New("Not enough data!")
}
extLen := int((buf[readPos] << 8) + buf[readPos+1])
readPos += 2
// Loop through extensions
for extPos := 0; extPos+4 <= extLen; {
extReadPos := readPos + extPos
len := int((buf[extReadPos+2] << 8) + buf[extReadPos+3])
// Is it a server name extension?
if buf[extReadPos] == 0x00 && buf[extReadPos+1] == 0x00 {
if extReadPos+4+len > pos {
return errors.New("Not enough data!")
}
// Loops through extension fields
for fieldPos := 2; fieldPos+3 < len; {
fieldReadPos := readPos + extPos + 4 + fieldPos
fieldLen := int((buf[fieldReadPos+1] << 8) + buf[fieldReadPos+2])
// Is it a hostname field?
if buf[fieldReadPos] == 0x00 {
if fieldReadPos+3+fieldLen > pos {
return errors.New("Not enough data!")
}
// Woohoo!
https.server = string(buf[fieldReadPos+3 : fieldReadPos+3+fieldLen])
https.tlsBuf = buf[:pos]
return nil
}
fieldPos += 3 + fieldLen
}
// There can only be one server name extension
break
}
extPos += 4 + len
}
return errors.New("No server name found!")
}
}
func (https *HttpsProxyConnection) HandleConn() {
Logf(LOG_NOTICE, "Handling new connection from %v\n", https.cConn.RemoteAddr())
var err error
// Extract desired server from TLS handshake
if err = https.ParseTlsHandshake(); err != nil {
Logf(LOG_NOTICE, "Error getting server: %v\n", err)
https.cConn.Close()
return
}
// TODO(fabi): Figure out what to do if server contains a port number
// Create connection to server
Logf(LOG_INFO, "Connecting to %s:https\n", https.server)
https.sConn, err = net.Dial("tcp", fmt.Sprintf("%s:https", https.server))
if err != nil {
Logf(LOG_NOTICE, "Error connecting to server: %v\n", err)
https.cConn.Close()
return
}
// Send data we read during parsing to server
if _, err = https.sConn.Write(https.tlsBuf); err != nil {
Logf(LOG_INFO, "Write error: %v\n", err)
https.cConn.Close()
https.sConn.Close()
return
}
// Link both connections together
Logf(LOG_INFO, "Linking client and server connection")
go PipeConn(https.cConn, https.sConn)
go PipeConn(https.sConn, https.cConn)
}
func startHttpProxy() {
// Start listener
Logf(LOG_NOTICE, "Listening on :http")
listener, err := net.Listen("tcp", ":http")
if err != nil {
Fatal(err)
}
// Wait for clients
for {
if conn, err := listener.Accept(); err == nil {
newConn := HttpProxyConnection{cConn: conn}
go newConn.HandleConn()
} else {
Logf(LOG_ERR, "Client error: %v\n", err)
}
}
}
func startHttpsProxy() {
// Start listener
Logf(LOG_NOTICE, "Listening on :https")
listener, err := net.Listen("tcp", ":https")
if err != nil {
Fatal(err)
}
// Wait for clients
for {
if conn, err := listener.Accept(); err == nil {
newConn := HttpsProxyConnection{cConn: conn}
go newConn.HandleConn()
} else {
Logf(LOG_ERR, "Client error: %v\n", err)
}
}
}
func main() {
// Parse flags
flag.Parse()
// Start proxy routines
go startHttpProxy()
go startHttpsProxy()
// Block forever
select {}
}