Debian Codegraph @

https.go

raw symbols SCIP
1 package goproxy
2
3 import (
4 "bufio"
5 "crypto/tls"
6 "errors"
7 "fmt"
8 "io"
9 "io/ioutil"
10 "net"
11 "net/http"
12 "net/url"
13 "os"
14 "regexp"
15 "strconv"
16 "strings"
17 "sync"
18 "sync/atomic"
19 )
20
21 type ConnectActionLiteral int
22
23 const (
24 ConnectAccept = iota
25 ConnectReject
26 ConnectMitm
27 ConnectHijack
28 ConnectHTTPMitm
29 ConnectProxyAuthHijack
30 )
31
32 var (
33 OkConnect = &ConnectAction{Action: ConnectAccept, TLSConfig: TLSConfigFromCA(&GoproxyCa)}
34 MitmConnect = &ConnectAction{Action: ConnectMitm, TLSConfig: TLSConfigFromCA(&GoproxyCa)}
35 HTTPMitmConnect = &ConnectAction{Action: ConnectHTTPMitm, TLSConfig: TLSConfigFromCA(&GoproxyCa)}
36 RejectConnect = &ConnectAction{Action: ConnectReject, TLSConfig: TLSConfigFromCA(&GoproxyCa)}
37 httpsRegexp = regexp.MustCompile(`^https:\/\/`)
38 )
39
40 // ConnectAction enables the caller to override the standard connect flow.
41 // When Action is ConnectHijack, it is up to the implementer to send the
42 // HTTP 200, or any other valid http response back to the client from within the
43 // Hijack func
44 type ConnectAction struct {
45 Action ConnectActionLiteral
46 Hijack func(req *http.Request, client net.Conn, ctx *ProxyCtx)
47 TLSConfig func(host string, ctx *ProxyCtx) (*tls.Config, error)
48 }
49
50 func stripPort(s string) string {
51 var ix int
52 if strings.Contains(s, "[") && strings.Contains(s, "]") {
53 //ipv6 : for example : [2606:4700:4700::1111]:443
54
55 //strip '[' and ']'
56 s = strings.ReplaceAll(s, "[", "")
57 s = strings.ReplaceAll(s, "]", "")
58
59 ix = strings.LastIndexAny(s, ":")
60 if ix == -1 {
61 return s
62 }
63 } else {
64 //ipv4
65 ix = strings.IndexRune(s, ':')
66 if ix == -1 {
67 return s
68 }
69
70 }
71 return s[:ix]
72 }
73
74 func (proxy *ProxyHttpServer) dial(network, addr string) (c net.Conn, err error) {
75 if proxy.Tr.Dial != nil {
76 return proxy.Tr.Dial(network, addr)
77 }
78 return net.Dial(network, addr)
79 }
80
81 func (proxy *ProxyHttpServer) connectDial(ctx *ProxyCtx, network, addr string) (c net.Conn, err error) {
82 if proxy.ConnectDialWithReq == nil && proxy.ConnectDial == nil {
83 return proxy.dial(network, addr)
84 }
85
86 if proxy.ConnectDialWithReq != nil {
87 return proxy.ConnectDialWithReq(ctx.Req, network, addr)
88 }
89
90 return proxy.ConnectDial(network, addr)
91 }
92
93 type halfClosable interface {
94 net.Conn
95 CloseWrite() error
96 CloseRead() error
97 }
98
99 var _ halfClosable = (*net.TCPConn)(nil)
100
101 func (proxy *ProxyHttpServer) handleHttps(w http.ResponseWriter, r *http.Request) {
102 ctx := &ProxyCtx{Req: r, Session: atomic.AddInt64(&proxy.sess, 1), Proxy: proxy, certStore: proxy.CertStore}
103
104 hij, ok := w.(http.Hijacker)
105 if !ok {
106 panic("httpserver does not support hijacking")
107 }
108
109 proxyClient, _, e := hij.Hijack()
110 if e != nil {
111 panic("Cannot hijack connection " + e.Error())
112 }
113
114 ctx.Logf("Running %d CONNECT handlers", len(proxy.httpsHandlers))
115 todo, host := OkConnect, r.URL.Host
116 for i, h := range proxy.httpsHandlers {
117 newtodo, newhost := h.HandleConnect(host, ctx)
118
119 // If found a result, break the loop immediately
120 if newtodo != nil {
121 todo, host = newtodo, newhost
122 ctx.Logf("on %dth handler: %v %s", i, todo, host)
123 break
124 }
125 }
126 switch todo.Action {
127 case ConnectAccept:
128 if !hasPort.MatchString(host) {
129 host += ":80"
130 }
131 targetSiteCon, err := proxy.connectDial(ctx, "tcp", host)
132 if err != nil {
133 ctx.Warnf("Error dialing to %s: %s", host, err.Error())
134 httpError(proxyClient, ctx, err)
135 return
136 }
137 ctx.Logf("Accepting CONNECT to %s", host)
138 proxyClient.Write([]byte("HTTP/1.0 200 Connection established\r\n\r\n"))
139
140 targetTCP, targetOK := targetSiteCon.(halfClosable)
141 proxyClientTCP, clientOK := proxyClient.(halfClosable)
142 if targetOK && clientOK {
143 go copyAndClose(ctx, targetTCP, proxyClientTCP)
144 go copyAndClose(ctx, proxyClientTCP, targetTCP)
145 } else {
146 go func() {
147 var wg sync.WaitGroup
148 wg.Add(2)
149 go copyOrWarn(ctx, targetSiteCon, proxyClient, &wg)
150 go copyOrWarn(ctx, proxyClient, targetSiteCon, &wg)
151 wg.Wait()
152 proxyClient.Close()
153 targetSiteCon.Close()
154
155 }()
156 }
157
158 case ConnectHijack:
159 todo.Hijack(r, proxyClient, ctx)
160 case ConnectHTTPMitm:
161 proxyClient.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
162 ctx.Logf("Assuming CONNECT is plain HTTP tunneling, mitm proxying it")
163 targetSiteCon, err := proxy.connectDial(ctx, "tcp", host)
164 if err != nil {
165 ctx.Warnf("Error dialing to %s: %s", host, err.Error())
166 return
167 }
168 for {
169 client := bufio.NewReader(proxyClient)
170 remote := bufio.NewReader(targetSiteCon)
171 req, err := http.ReadRequest(client)
172 if err != nil && err != io.EOF {
173 ctx.Warnf("cannot read request of MITM HTTP client: %+#v", err)
174 }
175 if err != nil {
176 return
177 }
178 req, resp := proxy.filterRequest(req, ctx)
179 if resp == nil {
180 if err := req.Write(targetSiteCon); err != nil {
181 httpError(proxyClient, ctx, err)
182 return
183 }
184 resp, err = http.ReadResponse(remote, req)
185 if err != nil {
186 httpError(proxyClient, ctx, err)
187 return
188 }
189 defer resp.Body.Close()
190 }
191 resp = proxy.filterResponse(resp, ctx)
192 if err := resp.Write(proxyClient); err != nil {
193 httpError(proxyClient, ctx, err)
194 return
195 }
196 }
197 case ConnectMitm:
198 proxyClient.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
199 ctx.Logf("Assuming CONNECT is TLS, mitm proxying it")
200 // this goes in a separate goroutine, so that the net/http server won't think we're
201 // still handling the request even after hijacking the connection. Those HTTP CONNECT
202 // request can take forever, and the server will be stuck when "closed".
203 // TODO: Allow Server.Close() mechanism to shut down this connection as nicely as possible
204 tlsConfig := defaultTLSConfig
205 if todo.TLSConfig != nil {
206 var err error
207 tlsConfig, err = todo.TLSConfig(host, ctx)
208 if err != nil {
209 httpError(proxyClient, ctx, err)
210 return
211 }
212 }
213 go func() {
214 //TODO: cache connections to the remote website
215 rawClientTls := tls.Server(proxyClient, tlsConfig)
216 defer rawClientTls.Close()
217 if err := rawClientTls.Handshake(); err != nil {
218 ctx.Warnf("Cannot handshake client %v %v", r.Host, err)
219 return
220 }
221 clientTlsReader := bufio.NewReader(rawClientTls)
222 for !isEof(clientTlsReader) {
223 req, err := http.ReadRequest(clientTlsReader)
224 var ctx = &ProxyCtx{Req: req, Session: atomic.AddInt64(&proxy.sess, 1), Proxy: proxy, UserData: ctx.UserData}
225 if err != nil && err != io.EOF {
226 return
227 }
228 if err != nil {
229 ctx.Warnf("Cannot read TLS request from mitm'd client %v %v", r.Host, err)
230 return
231 }
232 req.RemoteAddr = r.RemoteAddr // since we're converting the request, need to carry over the original connecting IP as well
233 ctx.Logf("req %v", r.Host)
234
235 if !httpsRegexp.MatchString(req.URL.String()) {
236 req.URL, err = url.Parse("https://" + r.Host + req.URL.String())
237 }
238
239 // Bug fix which goproxy fails to provide request
240 // information URL in the context when does HTTPS MITM
241 ctx.Req = req
242
243 req, resp := proxy.filterRequest(req, ctx)
244 if resp == nil {
245 if req.Method == "PRI" {
246 // Handle HTTP/2 connections.
247
248 // NOTE: As of 1.22, golang's http module will not recognize or
249 // parse the HTTP Body for PRI requests. This leaves the body of
250 // the http2.ClientPreface ("SM\r\n\r\n") on the wire which we need
251 // to clear before setting up the connection.
252 _, err := clientTlsReader.Discard(6)
253 if err != nil {
254 ctx.Warnf("Failed to process HTTP2 client preface: %v", err)
255 return
256 }
257 if !proxy.AllowHTTP2 {
258 ctx.Warnf("HTTP2 connection failed: disallowed")
259 return
260 }
261 tr := H2Transport{clientTlsReader, rawClientTls, tlsConfig.Clone(), host}
262 if _, err := tr.RoundTrip(req); err != nil {
263 ctx.Warnf("HTTP2 connection failed: %v", err)
264 } else {
265 ctx.Logf("Exiting on EOF")
266 }
267 return
268 }
269 if isWebSocketRequest(req) {
270 ctx.Logf("Request looks like websocket upgrade.")
271 proxy.serveWebsocketTLS(ctx, w, req, tlsConfig, rawClientTls)
272 return
273 }
274 if err != nil {
275 if req.URL != nil {
276 ctx.Warnf("Illegal URL %s", "https://"+r.Host+req.URL.Path)
277 } else {
278 ctx.Warnf("Illegal URL %s", "https://"+r.Host)
279 }
280 return
281 }
282 removeProxyHeaders(ctx, req)
283 resp, err = func() (*http.Response, error) {
284 // explicitly discard request body to avoid data races in certain RoundTripper implementations
285 // see https://github.com/golang/go/issues/61596#issuecomment-1652345131
286 defer req.Body.Close()
287 return ctx.RoundTrip(req)
288 }()
289 if err != nil {
290 ctx.Warnf("Cannot read TLS response from mitm'd server %v", err)
291 return
292 }
293 ctx.Logf("resp %v", resp.Status)
294 }
295 resp = proxy.filterResponse(resp, ctx)
296 defer resp.Body.Close()
297
298 text := resp.Status
299 statusCode := strconv.Itoa(resp.StatusCode) + " "
300 if strings.HasPrefix(text, statusCode) {
301 text = text[len(statusCode):]
302 }
303 // always use 1.1 to support chunked encoding
304 if _, err := io.WriteString(rawClientTls, "HTTP/1.1"+" "+statusCode+text+"\r\n"); err != nil {
305 ctx.Warnf("Cannot write TLS response HTTP status from mitm'd client: %v", err)
306 return
307 }
308
309 if resp.Request.Method == "HEAD" {
310 // don't change Content-Length for HEAD request
311 } else {
312 // Since we don't know the length of resp, return chunked encoded response
313 // TODO: use a more reasonable scheme
314 resp.Header.Del("Content-Length")
315 resp.Header.Set("Transfer-Encoding", "chunked")
316 }
317 // Force connection close otherwise chrome will keep CONNECT tunnel open forever
318 resp.Header.Set("Connection", "close")
319 if err := resp.Header.Write(rawClientTls); err != nil {
320 ctx.Warnf("Cannot write TLS response header from mitm'd client: %v", err)
321 return
322 }
323 if _, err = io.WriteString(rawClientTls, "\r\n"); err != nil {
324 ctx.Warnf("Cannot write TLS response header end from mitm'd client: %v", err)
325 return
326 }
327
328 if resp.Request.Method == "HEAD" {
329 // Don't write out a response body for HEAD request
330 } else {
331 chunked := newChunkedWriter(rawClientTls)
332 if _, err := io.Copy(chunked, resp.Body); err != nil {
333 ctx.Warnf("Cannot write TLS response body from mitm'd client: %v", err)
334 return
335 }
336 if err := chunked.Close(); err != nil {
337 ctx.Warnf("Cannot write TLS chunked EOF from mitm'd client: %v", err)
338 return
339 }
340 if _, err = io.WriteString(rawClientTls, "\r\n"); err != nil {
341 ctx.Warnf("Cannot write TLS response chunked trailer from mitm'd client: %v", err)
342 return
343 }
344 }
345 }
346 ctx.Logf("Exiting on EOF")
347 }()
348 case ConnectProxyAuthHijack:
349 proxyClient.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\n"))
350 todo.Hijack(r, proxyClient, ctx)
351 case ConnectReject:
352 if ctx.Resp != nil {
353 if err := ctx.Resp.Write(proxyClient); err != nil {
354 ctx.Warnf("Cannot write response that reject http CONNECT: %v", err)
355 }
356 }
357 proxyClient.Close()
358 }
359 }
360
361 func httpError(w io.WriteCloser, ctx *ProxyCtx, err error) {
362 errStr := fmt.Sprintf("HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s", len(err.Error()), err.Error())
363 if _, err := io.WriteString(w, errStr); err != nil {
364 ctx.Warnf("Error responding to client: %s", err)
365 }
366 if err := w.Close(); err != nil {
367 ctx.Warnf("Error closing client connection: %s", err)
368 }
369 }
370
371 func copyOrWarn(ctx *ProxyCtx, dst io.Writer, src io.Reader, wg *sync.WaitGroup) {
372 if _, err := io.Copy(dst, src); err != nil {
373 ctx.Warnf("Error copying to client: %s", err)
374 }
375 wg.Done()
376 }
377
378 func copyAndClose(ctx *ProxyCtx, dst, src halfClosable) {
379 if _, err := io.Copy(dst, src); err != nil {
380 ctx.Warnf("Error copying to client: %s", err)
381 }
382
383 dst.CloseWrite()
384 src.CloseRead()
385 }
386
387 func dialerFromEnv(proxy *ProxyHttpServer) func(network, addr string) (net.Conn, error) {
388 https_proxy := os.Getenv("HTTPS_PROXY")
389 if https_proxy == "" {
390 https_proxy = os.Getenv("https_proxy")
391 }
392 if https_proxy == "" {
393 return nil
394 }
395 return proxy.NewConnectDialToProxy(https_proxy)
396 }
397
398 func (proxy *ProxyHttpServer) NewConnectDialToProxy(https_proxy string) func(network, addr string) (net.Conn, error) {
399 return proxy.NewConnectDialToProxyWithHandler(https_proxy, nil)
400 }
401
402 func (proxy *ProxyHttpServer) NewConnectDialToProxyWithHandler(https_proxy string, connectReqHandler func(req *http.Request)) func(network, addr string) (net.Conn, error) {
403 u, err := url.Parse(https_proxy)
404 if err != nil {
405 return nil
406 }
407 if u.Scheme == "" || u.Scheme == "http" {
408 if !strings.ContainsRune(u.Host, ':') {
409 u.Host += ":80"
410 }
411 return func(network, addr string) (net.Conn, error) {
412 connectReq := &http.Request{
413 Method: "CONNECT",
414 URL: &url.URL{Opaque: addr},
415 Host: addr,
416 Header: make(http.Header),
417 }
418 if connectReqHandler != nil {
419 connectReqHandler(connectReq)
420 }
421 c, err := proxy.dial(network, u.Host)
422 if err != nil {
423 return nil, err
424 }
425 connectReq.Write(c)
426 // Read response.
427 // Okay to use and discard buffered reader here, because
428 // TLS server will not speak until spoken to.
429 br := bufio.NewReader(c)
430 resp, err := http.ReadResponse(br, connectReq)
431 if err != nil {
432 c.Close()
433 return nil, err
434 }
435 defer resp.Body.Close()
436 if resp.StatusCode != 200 {
437 resp, err := ioutil.ReadAll(resp.Body)
438 if err != nil {
439 return nil, err
440 }
441 c.Close()
442 return nil, errors.New("proxy refused connection" + string(resp))
443 }
444 return c, nil
445 }
446 }
447 if u.Scheme == "https" || u.Scheme == "wss" {
448 if !strings.ContainsRune(u.Host, ':') {
449 u.Host += ":443"
450 }
451 return func(network, addr string) (net.Conn, error) {
452 c, err := proxy.dial(network, u.Host)
453 if err != nil {
454 return nil, err
455 }
456 c = tls.Client(c, proxy.Tr.TLSClientConfig)
457 connectReq := &http.Request{
458 Method: "CONNECT",
459 URL: &url.URL{Opaque: addr},
460 Host: addr,
461 Header: make(http.Header),
462 }
463 if connectReqHandler != nil {
464 connectReqHandler(connectReq)
465 }
466 connectReq.Write(c)
467 // Read response.
468 // Okay to use and discard buffered reader here, because
469 // TLS server will not speak until spoken to.
470 br := bufio.NewReader(c)
471 resp, err := http.ReadResponse(br, connectReq)
472 if err != nil {
473 c.Close()
474 return nil, err
475 }
476 defer resp.Body.Close()
477 if resp.StatusCode != 200 {
478 body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 500))
479 if err != nil {
480 return nil, err
481 }
482 c.Close()
483 return nil, errors.New("proxy refused connection" + string(body))
484 }
485 return c, nil
486 }
487 }
488 return nil
489 }
490
491 func TLSConfigFromCA(ca *tls.Certificate) func(host string, ctx *ProxyCtx) (*tls.Config, error) {
492 return func(host string, ctx *ProxyCtx) (*tls.Config, error) {
493 var err error
494 var cert *tls.Certificate
495
496 hostname := stripPort(host)
497 config := defaultTLSConfig.Clone()
498 ctx.Logf("signing for %s", stripPort(host))
499
500 genCert := func() (*tls.Certificate, error) {
501 return signHost(*ca, []string{hostname})
502 }
503 if ctx.certStore != nil {
504 cert, err = ctx.certStore.Fetch(hostname, genCert)
505 } else {
506 cert, err = genCert()
507 }
508
509 if err != nil {
510 ctx.Warnf("Cannot sign host certificate with provided CA: %s", err)
511 return nil, err
512 }
513
514 config.Certificates = append(config.Certificates, *cert)
515 return config, nil
516 }
517 }