-
-
Notifications
You must be signed in to change notification settings - Fork 350
/
proxy.go
163 lines (129 loc) · 3.73 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
package proxy
import (
"context"
"crypto"
"crypto/tls"
"crypto/x509"
"fmt"
"log"
"net"
"net/http"
"net/http/httputil"
"github.com/dstotijn/hetty/pkg/scope"
)
type contextKey int
const ReqIDKey contextKey = 0
// Proxy implements http.Handler and offers MITM behaviour for modifying
// HTTP requests and responses.
type Proxy struct {
certConfig *CertConfig
handler http.Handler
// TODO: Add mutex for modifier funcs.
reqModifiers []RequestModifyMiddleware
resModifiers []ResponseModifyMiddleware
scope *scope.Scope
}
// NewProxy returns a new Proxy.
func NewProxy(ca *x509.Certificate, key crypto.PrivateKey) (*Proxy, error) {
certConfig, err := NewCertConfig(ca, key)
if err != nil {
return nil, err
}
p := &Proxy{
certConfig: certConfig,
reqModifiers: make([]RequestModifyMiddleware, 0),
resModifiers: make([]ResponseModifyMiddleware, 0),
}
p.handler = &httputil.ReverseProxy{
Director: p.modifyRequest,
ModifyResponse: p.modifyResponse,
ErrorHandler: errorHandler,
}
return p, nil
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodConnect {
p.handleConnect(w, r)
return
}
p.handler.ServeHTTP(w, r)
}
func (p *Proxy) UseRequestModifier(fn ...RequestModifyMiddleware) {
p.reqModifiers = append(p.reqModifiers, fn...)
}
func (p *Proxy) UseResponseModifier(fn ...ResponseModifyMiddleware) {
p.resModifiers = append(p.resModifiers, fn...)
}
func (p *Proxy) modifyRequest(r *http.Request) {
// Fix r.URL for HTTPS requests after CONNECT.
if r.URL.Scheme == "" {
r.URL.Host = r.Host
r.URL.Scheme = "https"
}
// Setting `X-Forwarded-For` to `nil` ensures that http.ReverseProxy doesn't
// set this header.
r.Header["X-Forwarded-For"] = nil
fn := nopReqModifier
for i := len(p.reqModifiers) - 1; i >= 0; i-- {
fn = p.reqModifiers[i](fn)
}
fn(r)
}
func (p *Proxy) modifyResponse(res *http.Response) error {
fn := nopResModifier
for i := len(p.resModifiers) - 1; i >= 0; i-- {
fn = p.resModifiers[i](fn)
}
return fn(res)
}
// handleConnect hijacks the incoming HTTP request and sets up an HTTP tunnel.
// During the TLS handshake with the client, we use the proxy's CA config to
// create a certificate on-the-fly.
func (p *Proxy) handleConnect(w http.ResponseWriter, r *http.Request) {
hj, ok := w.(http.Hijacker)
if !ok {
log.Printf("[ERROR] handleConnect: ResponseWriter is not a http.Hijacker (type: %T)", w)
writeError(w, r, http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
clientConn, _, err := hj.Hijack()
if err != nil {
log.Printf("[ERROR] Hijacking client connection failed: %v", err)
writeError(w, r, http.StatusServiceUnavailable)
return
}
defer clientConn.Close()
// Secure connection to client.
clientConn, err = p.clientTLSConn(clientConn)
if err != nil {
log.Printf("[ERROR] Securing client connection failed: %v", err)
return
}
clientConnNotify := ConnNotify{clientConn, make(chan struct{})}
l := &OnceAcceptListener{clientConnNotify.Conn}
err = http.Serve(l, p)
if err != nil && err != ErrAlreadyAccepted {
log.Printf("[ERROR] Serving HTTP request failed: %v", err)
}
<-clientConnNotify.closed
}
func (p *Proxy) clientTLSConn(conn net.Conn) (*tls.Conn, error) {
tlsConfig := p.certConfig.TLSConfig()
tlsConn := tls.Server(conn, tlsConfig)
if err := tlsConn.Handshake(); err != nil {
tlsConn.Close()
return nil, fmt.Errorf("handshake error: %v", err)
}
return tlsConn, nil
}
func errorHandler(w http.ResponseWriter, r *http.Request, err error) {
if err == context.Canceled {
return
}
log.Printf("[ERROR]: Proxy error: %v", err)
w.WriteHeader(http.StatusBadGateway)
}
func writeError(w http.ResponseWriter, r *http.Request, code int) {
http.Error(w, http.StatusText(code), code)
}