Debian Codegraph @

examples/goproxy-transparent/transparent.go

raw
1 package main
2
3 import (
4 "bufio"
5 "bytes"
6 "context"
7 "flag"
8 "fmt"
9 "log"
10 "net"
11 "net/http"
12 "net/url"
13 "regexp"
14
15 "github.com/elazarl/goproxy"
16 "github.com/inconshreveable/go-vhost"
17 )
18
19 func orPanic(err error) {
20 if err != nil {
21 panic(err)
22 }
23 }
24
25 func main() {
26 verbose := flag.Bool("v", true, "should every proxy request be logged to stdout")
27 http_addr := flag.String("httpaddr", ":3129", "proxy http listen address")
28 https_addr := flag.String("httpsaddr", ":3128", "proxy https listen address")
29 flag.Parse()
30
31 proxy := goproxy.NewProxyHttpServer()
32 proxy.Verbose = *verbose
33 if proxy.Verbose {
34 log.Printf("Server starting up! - configured to listen on http interface %s and https interface %s", *http_addr, *https_addr)
35 }
36
37 proxy.NonproxyHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
38 if req.Host == "" {
39 fmt.Fprintln(w, "Cannot handle requests without Host header, e.g., HTTP 1.0")
40 return
41 }
42 req.URL.Scheme = "http"
43 req.URL.Host = req.Host
44 proxy.ServeHTTP(w, req)
45 })
46 proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
47 HandleConnect(goproxy.AlwaysMitm)
48 proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*:80$"))).
49 HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
50 defer func() {
51 if e := recover(); e != nil {
52 ctx.Logf("error connecting to remote: %v", e)
53 client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n"))
54 }
55 client.Close()
56 }()
57 clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
58
59 remote, err := connectDial(req.Context(), proxy, "tcp", req.URL.Host)
60 orPanic(err)
61 remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote))
62 for {
63 req, err := http.ReadRequest(clientBuf.Reader)
64 orPanic(err)
65 orPanic(req.Write(remoteBuf))
66 orPanic(remoteBuf.Flush())
67 resp, err := http.ReadResponse(remoteBuf.Reader, req)
68 orPanic(err)
69 orPanic(resp.Write(clientBuf.Writer))
70 orPanic(clientBuf.Flush())
71 }
72 })
73
74 go func() {
75 log.Fatalln(http.ListenAndServe(*http_addr, proxy))
76 }()
77
78 // listen to the TLS ClientHello but make it a CONNECT request instead
79 ln, err := net.Listen("tcp", *https_addr)
80 if err != nil {
81 log.Fatalf("Error listening for https connections - %v", err)
82 }
83 for {
84 c, err := ln.Accept()
85 if err != nil {
86 log.Printf("Error accepting new connection - %v", err)
87 continue
88 }
89 go func(c net.Conn) {
90 tlsConn, err := vhost.TLS(c)
91 if err != nil {
92 log.Printf("Error accepting new connection - %v", err)
93 }
94 if tlsConn.Host() == "" {
95 log.Printf("Cannot support non-SNI enabled clients")
96 return
97 }
98 connectReq := &http.Request{
99 Method: "CONNECT",
100 URL: &url.URL{
101 Opaque: tlsConn.Host(),
102 Host: net.JoinHostPort(tlsConn.Host(), "443"),
103 },
104 Host: tlsConn.Host(),
105 Header: make(http.Header),
106 RemoteAddr: c.RemoteAddr().String(),
107 }
108 resp := dumbResponseWriter{tlsConn}
109 proxy.ServeHTTP(resp, connectReq)
110 }(c)
111 }
112 }
113
114 // copied/converted from https.go
115 func dial(ctx context.Context, proxy *goproxy.ProxyHttpServer, network, addr string) (c net.Conn, err error) {
116 if proxy.Tr.DialContext != nil {
117 return proxy.Tr.DialContext(ctx, network, addr)
118 }
119 var d net.Dialer
120 return d.DialContext(ctx, network, addr)
121 }
122
123 // copied/converted from https.go
124 func connectDial(ctx context.Context, proxy *goproxy.ProxyHttpServer, network, addr string) (c net.Conn, err error) {
125 if proxy.ConnectDial == nil {
126 return dial(ctx, proxy, network, addr)
127 }
128 return proxy.ConnectDial(network, addr)
129 }
130
131 type dumbResponseWriter struct {
132 net.Conn
133 }
134
135 func (dumb dumbResponseWriter) Header() http.Header {
136 panic("Header() should not be called on this ResponseWriter")
137 }
138
139 func (dumb dumbResponseWriter) Write(buf []byte) (int, error) {
140 if bytes.Equal(buf, []byte("HTTP/1.0 200 OK\r\n\r\n")) {
141 return len(buf), nil // throw away the HTTP OK response from the faux CONNECT request
142 }
143 return dumb.Conn.Write(buf)
144 }
145
146 func (dumb dumbResponseWriter) WriteHeader(code int) {
147 panic("WriteHeader() should not be called on this ResponseWriter")
148 }
149
150 func (dumb dumbResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
151 return dumb, bufio.NewReadWriter(bufio.NewReader(dumb), bufio.NewWriter(dumb)), nil
152 }