-
Notifications
You must be signed in to change notification settings - Fork 0
/
mitmproxxy.go
299 lines (267 loc) · 7.61 KB
/
mitmproxxy.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
package proxymitm
import (
"bufio"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"errors"
"io"
"log"
"math/big"
"net"
"net/http"
"os"
"strconv"
"time"
"golang.org/x/xerrors"
)
func proxy(w http.ResponseWriter, r *http.Request) {
hjk, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Not available http.Hijacker", http.StatusInternalServerError)
return
}
con, _, err := hjk.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer con.Close()
newReq, err := http.NewRequest(r.Method, r.URL.String(), r.Body)
if err != nil {
http.Error(w, "Failed to http.NewRequest()", http.StatusInternalServerError)
return
}
newReq = newReq.WithContext(r.Context())
client := http.Client{}
resp, err := client.Do(newReq)
if err != nil {
http.Error(w, "Failed to http request", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
writer := io.MultiWriter(con, os.Stdout)
resp.Write(writer)
}
var (
internalServerError = []byte("HTTP/1.0 " + strconv.Itoa(http.StatusInternalServerError) + " \r\n\r\n")
)
var _ http.Handler = (*ServerMux)(nil)
type ServerMux struct {
tlsCert tls.Certificate
x509Cert *x509.Certificate
client *http.Client
}
func (mp *ServerMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var newReq *http.Request
// TCP コネクションの確立
// Server 側とはコネクションを張らず、Client に 200 を返す
hjk, ok := w.(http.Hijacker)
if !ok {
log.Println("Failed to hijack")
http.Error(w, "Not available http.Hijacker", http.StatusInternalServerError)
return
}
con, _, err := hjk.Hijack()
if err != nil {
log.Println(xerrors.Errorf("Failed to connect TCP: %w", err))
con.Write(internalServerError)
return
}
defer con.Close()
switch r.Method {
case http.MethodConnect:
//コネクションが張れたため、200 を返す
// ハイジャックをしているため w.WriteHeader 使えない
con.Write([]byte("HTTP/1.0 200 Connection established \r\n\r\n"))
// Client との TLS ハンドシェイク
con, err = mp.tlsHandshake(con, r.URL.Hostname())
if err != nil {
log.Println(xerrors.Errorf("Failed to tls handshake: %w", err))
con.Write(internalServerError)
return
}
defer con.Close()
// データのやりとり
// Clientのリクエストをサーバーへ送信
newReq, err = mp.createRequest(con)
if err != nil {
log.Println(xerrors.Errorf("Failed to create request: %w", err))
con.Write(internalServerError)
return
}
default:
newReq, err = http.NewRequest(r.Method, r.URL.String(), r.Body)
if err != nil {
log.Println(xerrors.Errorf("Failed to create request: %w", err))
http.Error(w, "Failed to http.NewRequest()", http.StatusInternalServerError)
return
}
}
newReq = newReq.WithContext(r.Context())
resp, err := mp.client.Do(newReq)
if err != nil {
log.Println(xerrors.Errorf("Failed to send request: %w", err))
http.Error(w, "Failed to http request", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
writer := io.MultiWriter(con, os.Stdout)
resp.Write(writer)
}
func New(certPath, keyPath string) (*http.Server, error) {
// 自作の認証局の証明書の読み込み
tlsCert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, err
}
// 自作の認証局の証明書で署名された証明書を作成
x509Cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
if err != nil {
return nil, err
}
server := http.Server{
Handler: &ServerMux{
tlsCert: tlsCert,
x509Cert: x509Cert,
client: &http.Client{},
},
}
return &server, nil
}
func mitmx509template(hostName string) *x509.Certificate {
now := time.Now()
return &x509.Certificate{
SerialNumber: big.NewInt(1234),
DNSNames: []string{hostName},
NotBefore: now,
NotAfter: now.AddDate(1, 0, 0),
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature,
}
}
// CreateMitmProxy load pem, and then it return MitmProxy
func CreateMitmProxy(certPath, keyPath string) (*ServerMux, error) {
// 自作の認証局の証明書の読み込み
tlsCert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, err
}
// 自作の認証局の証明書で署名された証明書を作成
x509Cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
if err != nil {
return nil, err
}
return &ServerMux{
tlsCert: tlsCert,
x509Cert: x509Cert,
client: &http.Client{},
}, nil
}
// Handler handle request for mitim
func (mp *ServerMux) handle(w http.ResponseWriter, r *http.Request) {
// TCP コネクションの確立
// Server 側とはコネクションを張らず、Client に 200 を返す
con, err := connectTCP(w)
if err != nil {
con.Write(internalServerError)
log.Println(xerrors.Errorf("Failed to connect TCP: %w", err))
return
}
defer con.Close()
// Client との TLS ハンドシェイク
tlsConn, err := mp.tlsHandshake(con, r.URL.Hostname())
if err != nil {
con.Write(internalServerError)
log.Println(xerrors.Errorf("Failed to tls handshake: %w", err))
return
}
defer tlsConn.Close()
// データのやりとり
// Clientのリクエストをサーバーへ送信
req, err := mp.createRequest(tlsConn)
if err != nil {
tlsConn.Write(internalServerError)
log.Println(xerrors.Errorf("Failed to create request: %w", err))
return
}
// コンテキストも渡す
req = req.WithContext(r.Context())
rsp, err := mp.client.Do(req)
if err != nil {
tlsConn.Write(internalServerError)
log.Println(xerrors.Errorf("Failed to send request: %w", err))
return
}
defer rsp.Body.Close()
// ResponseをClientに返す
writer := io.MultiWriter(tlsConn, os.Stdout)
rsp.Write(writer)
log.Println("end")
}
func connectTCP(w http.ResponseWriter) (net.Conn, error) {
// TCP コネクションの確立
// Server 側とはコネクションを張らず、Client に 200 を返す
hjk, ok := w.(http.Hijacker)
if !ok {
return nil, errors.New("Not available http.Hijacker")
}
con, _, err := hjk.Hijack()
if err != nil {
return nil, err
}
//コネクションが張れたため、200 を返す
// ハイジャックをしているため w.WriteHeader 使えない
con.Write([]byte("HTTP/1.0 200 Connection established \r\n\r\n"))
return con, nil
}
func (mp *ServerMux) tlsHandshake(con net.Conn, hostName string) (*tls.Conn, error) {
// 接続するドメインの証明書を作成する
template := mitmx509template(hostName)
c, pk, err := mp.createX509Certificate(template)
if err != nil {
return nil, err
}
cert := tls.Certificate{
Certificate: [][]byte{c.Raw},
PrivateKey: pk,
}
config := tls.Config{}
config.Certificates = []tls.Certificate{cert}
tlsConn := tls.Server(con, &config)
if err = tlsConn.Handshake(); err != nil {
return nil, err
}
return tlsConn, nil
}
func (mp *ServerMux) createX509Certificate(template *x509.Certificate) (*x509.Certificate, crypto.PrivateKey, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
pub := &priv.PublicKey
cb, err := x509.CreateCertificate(
rand.Reader,
template, mp.x509Cert,
pub, mp.tlsCert.PrivateKey,
)
if err != nil {
return nil, nil, err
}
c, err := x509.ParseCertificate(cb)
if err != nil {
return nil, nil, err
}
return c, priv, nil
}
func (mp *ServerMux) createRequest(tlsConn net.Conn) (*http.Request, error) {
creq, err := http.ReadRequest(bufio.NewReader(tlsConn))
if err != nil {
return nil, err
}
requestURL := "https://" + creq.Host + creq.RequestURI
creq, err = http.NewRequest(creq.Method, requestURL, creq.Body)
if err != nil {
return nil, err
}
return creq, nil
}