-
Notifications
You must be signed in to change notification settings - Fork 0
/
mitm.go
232 lines (203 loc) · 5.21 KB
/
mitm.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
package mitm
import (
"crypto/tls"
"errors"
"log"
"net"
"net/http"
"net/http/httputil"
"sync"
"time"
)
// Proxy is a forward proxy that substitutes its own certificate
// for incoming TLS connections in place of the upstream server's
// certificate.
type Proxy struct {
// Wrap specifies a function for optionally wrapping upstream for
// inspecting the decrypted HTTP request and response.
Wrap func(upstream http.Handler) http.Handler
// CA specifies the root CA for generating leaf certs for each incoming
// TLS request.
CA *tls.Certificate
// TLSServerConfig specifies the tls.Config to use when generating leaf
// cert using CA.
TLSServerConfig *tls.Config
// TLSClientConfig specifies the tls.Config to use when establishing
// an upstream connection for proxying.
TLSClientConfig *tls.Config
// FlushInterval specifies the flush interval
// to flush to the client while copying the
// response body.
// If zero, no periodic flushing is done.
FlushInterval time.Duration
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == "CONNECT" {
p.serveConnect(w, r)
return
}
rp := &httputil.ReverseProxy{
Director: httpDirector,
FlushInterval: p.FlushInterval,
}
p.Wrap(rp).ServeHTTP(w, r)
}
func (p *Proxy) serveConnect(w http.ResponseWriter, r *http.Request) {
var (
err error
sconn *tls.Conn
name = dnsName(r.Host)
)
if name == "" {
log.Println("cannot determine cert name for " + r.Host)
http.Error(w, "no upstream", 503)
return
}
provisionalCert, err := p.cert(name)
if err != nil {
log.Println("cert", err)
http.Error(w, "no upstream", 503)
return
}
sConfig := new(tls.Config)
if p.TLSServerConfig != nil {
*sConfig = *p.TLSServerConfig
}
sConfig.Certificates = []tls.Certificate{*provisionalCert}
sConfig.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
cConfig := new(tls.Config)
if p.TLSClientConfig != nil {
*cConfig = *p.TLSClientConfig
}
cConfig.ServerName = hello.ServerName
sconn, err = tls.Dial("tcp", r.Host, cConfig)
if err != nil {
log.Println("dial", r.Host, err)
return nil, err
}
return p.cert(hello.ServerName)
}
cconn, err := handshake(w, sConfig)
if err != nil {
log.Println("handshake", r.Host, err)
return
}
defer cconn.Close()
if sconn == nil {
log.Println("could not determine cert name for " + r.Host)
return
}
defer sconn.Close()
od := &oneShotDialer{c: sconn}
rp := &httputil.ReverseProxy{
Director: httpsDirector,
Transport: &http.Transport{DialTLS: od.Dial},
FlushInterval: p.FlushInterval,
}
ch := make(chan int)
wc := &onCloseConn{cconn, func() { ch <- 0 }}
http.Serve(&oneShotListener{wc}, p.Wrap(rp))
<-ch
}
func (p *Proxy) cert(names ...string) (*tls.Certificate, error) {
return genCert(p.CA, names)
}
var okHeader = []byte("HTTP/1.1 200 OK\r\n\r\n")
// handshake hijacks w's underlying net.Conn, responds to the CONNECT request
// and manually performs the TLS handshake. It returns the net.Conn or and
// error if any.
func handshake(w http.ResponseWriter, config *tls.Config) (net.Conn, error) {
raw, _, err := w.(http.Hijacker).Hijack()
if err != nil {
http.Error(w, "no upstream", 503)
return nil, err
}
if _, err = raw.Write(okHeader); err != nil {
raw.Close()
return nil, err
}
conn := tls.Server(raw, config)
err = conn.Handshake()
if err != nil {
conn.Close()
raw.Close()
return nil, err
}
return conn, nil
}
func httpDirector(r *http.Request) {
r.URL.Host = r.Host
r.URL.Scheme = "http"
}
func httpsDirector(r *http.Request) {
r.URL.Host = r.Host
r.URL.Scheme = "https"
}
// dnsName returns the DNS name in addr, if any.
func dnsName(addr string) string {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return ""
}
return host
}
// namesOnCert returns the dns names
// in the peer's presented cert.
func namesOnCert(conn *tls.Conn) []string {
// TODO(kr): handle IP addr SANs.
c := conn.ConnectionState().PeerCertificates[0]
if len(c.DNSNames) > 0 {
// If Subject Alt Name is given,
// we ignore the common name.
// This matches behavior of crypto/x509.
return c.DNSNames
}
return []string{c.Subject.CommonName}
}
// A oneShotDialer implements net.Dialer whos Dial only returns a
// net.Conn as specified by c followed by an error for each subsequent Dial.
type oneShotDialer struct {
c net.Conn
mu sync.Mutex
}
func (d *oneShotDialer) Dial(network, addr string) (net.Conn, error) {
d.mu.Lock()
defer d.mu.Unlock()
if d.c == nil {
return nil, errors.New("closed")
}
c := d.c
d.c = nil
return c, nil
}
// A oneShotListener implements net.Listener whos Accept only returns a
// net.Conn as specified by c followed by an error for each subsequent Accept.
type oneShotListener struct {
c net.Conn
}
func (l *oneShotListener) Accept() (net.Conn, error) {
if l.c == nil {
return nil, errors.New("closed")
}
c := l.c
l.c = nil
return c, nil
}
func (l *oneShotListener) Close() error {
return nil
}
func (l *oneShotListener) Addr() net.Addr {
return l.c.LocalAddr()
}
// A onCloseConn implements net.Conn and calls its f on Close.
type onCloseConn struct {
net.Conn
f func()
}
func (c *onCloseConn) Close() error {
if c.f != nil {
c.f()
c.f = nil
}
return c.Conn.Close()
}