forked from koalabearguo/php-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
430 lines (401 loc) · 8.77 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
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
package main
import (
"bufio"
//"context"
"crypto/tls"
"crypto/x509"
//"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
)
var mux sync.Mutex
const num_connection int = 5
var conn_index int = 0
type proxy struct {
//global config
cfg *config
//prepare static buf
bufpool sync.Pool
//php client
client [num_connection]*client
//ca sign ssl cert for middle intercept
signer *CaSigner
//ca root cert info for middle attack check
cert *x509.Certificate
}
func (prx *proxy) load_ca() []byte {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
ca_path := ""
if prx.cfg.Ca == "" {
ca_path = dir + "/php-proxy.crt"
} else {
ca_path = prx.cfg.Ca
}
raw, err1 := ioutil.ReadFile(ca_path)
if err1 != nil {
return nil
}
log.Print("Load ca cert from " + ca_path + " file")
return raw
}
func (prx *proxy) load_key() []byte {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
key_path := ""
if prx.cfg.Key == "" {
key_path = dir + "/php-proxy.key"
} else {
key_path = prx.cfg.Key
}
raw, err1 := ioutil.ReadFile(key_path)
if err1 != nil {
return nil
}
log.Print("Load ca key from " + key_path + " file")
return raw
}
func (prx *proxy) init_ca() {
//
var use_ca, use_key []byte
prx.signer = NewCaSignerCache(1024)
cert := prx.load_ca()
key := prx.load_key()
if cert != nil && key != nil {
use_ca = cert
use_key = key
log.Print("Using external customize CA file")
} else {
use_ca = CaCert
use_key = CaKey
log.Print("Using internal Php-Proxy CA file")
}
ca, err := tls.X509KeyPair(use_ca, use_key)
if err != nil {
log.Fatal(err)
} else {
prx.signer.Ca = &ca
}
//parse our own php-proxy ca to get info
prx.cert, err = x509.ParseCertificate(ca.Certificate[0])
if err != nil {
log.Fatal(err)
}
//prepare gen google cert for cache(not must)
_ = prx.signer.SignHost("www.google.com")
_ = prx.signer.SignHost("www.youtube.com")
_ = prx.signer.SignHost("www.googlevideo.com")
_ = prx.signer.SignHost("www.gstatic.com")
_ = prx.signer.SignHost("www.ggpht.com")
}
func (prx *proxy) init_proxy() {
//
prx.init_ca()
//
log.Println("HTTP Proxy Listening on " + prx.cfg.Listen)
//connect php server config
for i := 0; i < num_connection; i++ {
prx.client[i] = &client{cfg: prx.cfg}
prx.client[i].cert = prx.cert
prx.client[i].init_client()
}
//
prx.bufpool = sync.Pool{
New: func() interface{} {
return make([]byte, 32*1024)
},
}
//
log.Fatal(http.ListenAndServe(prx.cfg.Listen, prx))
//
}
func (prx *proxy) IOCopy(dst io.Writer, src io.Reader) (written int64, err error) {
//not use tmp mem,use prepared mem
buf := prx.bufpool.Get().([]byte)
written, err = io.CopyBuffer(dst, src, buf)
prx.bufpool.Put(buf)
return written, err
}
var hopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Te",
"Trailers",
"Transfer-Encoding",
"Upgrade",
}
func (prx *proxy) ServePROXY(rw http.ResponseWriter, req *http.Request) {
hijacker, ok := rw.(http.Hijacker)
if !ok {
log.Println("Not Support Hijacking")
}
client, _, err := hijacker.Hijack()
if err != nil {
log.Println(err)
}
defer client.Close()
//
var address string
if strings.Index(req.Host, ":") == -1 { //host port not include,default 80
address = req.Host + ":http"
} else {
address = req.Host
}
server, err := net.Dial("tcp", address)
if err != nil {
log.Println(err)
return
}
defer server.Close()
//
if req.Method == http.MethodConnect {
io.WriteString(client, "HTTP/1.1 200 Connection established\r\n\r\n")
//exchange data
go prx.IOCopy(server, client)
prx.IOCopy(client, server)
return
}
//
for _, h := range hopHeaders {
req.Header.Del(h)
}
//
Req := req
//http proxy keep alive
for true {
err = Req.Write(server)
if err != nil {
return
}
Res, err := http.ReadResponse(bufio.NewReader(server), Req)
if err != nil {
return
}
err = Res.Write(client)
if err != nil {
return
}
Req, err = http.ReadRequest(bufio.NewReader(client))
if err != nil {
return
}
//
for _, h := range hopHeaders {
req.Header.Del(h)
}
//
}
}
func (prx *proxy) isblocked(host string) bool {
hostname := stripPort(host)
hostnamelth := len(hostname)
for key, _ := range gfwlist {
if hostnamelth >= len(key) {
subhost := hostname[(hostnamelth - len(key)):]
if key == subhost {
return true
}
}
}
return false
}
func (prx *proxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
var tlscon *tls.Conn
//
if prx.cfg.Autoproxy && (req.Method == http.MethodConnect || req.Method != http.MethodConnect && req.URL.IsAbs()) {
blocked := prx.isblocked(req.Host)
if blocked == false {
log.Printf("Direct Connect %s", req.Host)
prx.ServePROXY(rw, req)
return
}
}
//
if req.Method != http.MethodConnect && !req.URL.IsAbs() {
//
req.URL.Scheme = "https"
if req.Host == "" {
req.URL.Host = "localhost"
} else {
req.URL.Host = req.Host
}
if prx.cfg.Debug {
log.Printf("Request Host:%s", req.URL.Host)
}
}
//
//Strip ssl
if req.Method == http.MethodConnect {
hijacker, ok := rw.(http.Hijacker)
if !ok {
if req.Body != nil {
req.Body.Close()
}
log.Println("Not Support Hijacking")
return
}
conn, _, err := hijacker.Hijack()
if err != nil {
if req.Body != nil {
req.Body.Close()
}
log.Println(err)
return
}
_, err = io.WriteString(conn, "HTTP/1.1 200 Connection established\r\n\r\n")
if err != nil {
log.Println(err)
conn.Close()
return
}
tlscon, err = prx.handleClientConnectRequest(conn, req.URL.Hostname())
if err != nil {
log.Println(err)
tlscon.Close()
return
}
loConn, err := net.Dial("tcp", prx.cfg.Listen)
if err != nil {
log.Println(err)
tlscon.Close()
return
}
go prx.IOCopy(tlscon, loConn)
prx.IOCopy(loConn, tlscon)
err = tlscon.Close()
if err != nil {
log.Println(err)
}
err = loConn.Close()
if err != nil {
log.Println(err)
}
return
}
//
req_op := &request{cfg: prx.cfg, http_req: req}
//
//parse http request
start := time.Now()
req_op.parse_request()
if prx.cfg.Debug == true {
elapsed := time.Since(start)
log.Println("HTTP POST body Proc Time:", elapsed)
}
//
//connect php server
start = time.Now()
var conn_index_tmp int
mux.Lock()
conn_index_tmp = conn_index
conn_index++
conn_index = conn_index % num_connection
mux.Unlock()
Res, err := prx.client[conn_index_tmp].Do(req_op.cli_req)
if prx.cfg.Debug == true {
elapsed := time.Since(start)
log.Println("HTTP POST Time:", elapsed)
}
if err != nil {
log.Println(err)
if prx.client[conn_index_tmp].tr3 != nil {
prx.client[conn_index_tmp].tr3.Close()
}
origin := req_op.http_req.Header.Get("Origin")
if origin != "" {
rw.Header().Add("Access-Control-Allow-Origin", origin)
rw.Header().Add("Access-Control-Allow-Credentials", "true")
}
http.Error(rw, "empty response", http.StatusBadGateway)
return
}
//
defer Res.Body.Close()
//
proxy_res_data := &response{res: Res, cfg: prx.cfg}
resp := proxy_res_data.parse_response()
if resp == nil {
log.Println("Response is nil")
return
}
defer resp.Body.Close()
for key, values := range resp.Header {
for _, value := range values {
rw.Header().Add(key, value)
if prx.cfg.Debug {
log.Print(key + ":" + value)
}
}
}
//Patch CORS
origin := req_op.http_req.Header.Get("Origin")
if origin != "" && rw.Header().Get("Access-Control-Allow-Origin") == "" {
rw.Header().Add("Access-Control-Allow-Origin", origin)
}
if origin != "" && rw.Header().Get("Access-Control-Allow-Credentials") == "" {
rw.Header().Add("Access-Control-Allow-Credentials", "true")
}
//rw.Header().Set("Set-Cookie", rw.Header().Get("Set-Cookie") + ";HttpOnly;Secure;SameSite=Strict" )
//
rw.WriteHeader(resp.StatusCode)
_, err = prx.IOCopy(rw, resp.Body)
//
if err != nil {
if strings.Contains(err.Error(), io.ErrUnexpectedEOF.Error()) == true {
hijacker, ok := rw.(http.Hijacker)
if !ok {
log.Println("Not Support Hijacking")
}
conn, _, err := hijacker.Hijack()
if err != nil {
log.Println(err)
}
err = conn.Close()
if err != nil {
log.Println(err)
}
} else if strings.Contains(err.Error(), "invalid byte in chunk length") == true {
hijacker, ok := rw.(http.Hijacker)
if !ok {
log.Println("Not Support Hijacking")
}
conn, _, err := hijacker.Hijack()
if err != nil {
log.Println(err)
}
err = conn.Close()
if err != nil {
log.Println(err)
}
} else {
log.Println(err)
}
}
}
func (prx *proxy) handleClientConnectRequest(client net.Conn, host string) (tlscon *tls.Conn, err error) {
//
cer := prx.signer.SignHost(host)
//
config := &tls.Config{
Certificates: []tls.Certificate{*cer},
}
tlscon = tls.Server(client, config)
err = tlscon.Handshake()
if err != nil {
return tlscon, err
}
return tlscon, nil
}