/
https.go
85 lines (69 loc) · 1.85 KB
/
https.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
package awsmocker
import (
"bufio"
"crypto/tls"
"errors"
"io"
"net"
"net/http"
"net/url"
"regexp"
)
const (
imdsHost4 = "169.254.169.254"
imdsHost6 = "fd00:ec2::254"
)
var (
httpsRegexp = regexp.MustCompile(`^https:\/\/`)
globalTlsConfig = &tls.Config{
InsecureSkipVerify: true,
GetCertificate: func(chi *tls.ClientHelloInfo) (*tls.Certificate, error) {
return globalCertStore.Fetch(chi.ServerName), nil
},
}
)
func (m *mocker) handleHttps(w http.ResponseWriter, r *http.Request) {
hij, ok := w.(http.Hijacker)
if !ok {
panic("httpserver does not support hijacking")
}
proxyClient, _, e := hij.Hijack()
if e != nil {
panic("Cannot hijack connection " + e.Error())
}
// respond with success to acknowledge the proxy request
_, _ = proxyClient.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
// handle the request
go m.handleAwsRequestHttps(proxyClient, r)
}
func (m *mocker) handleAwsRequestHttps(proxyClient net.Conn, r *http.Request) {
rawClientTls := tls.Server(proxyClient, globalTlsConfig)
if err := rawClientTls.Handshake(); err != nil {
m.Warnf("Cannot handshake client %v %v", r.Host, err)
return
}
defer rawClientTls.Close()
clientTlsReader := bufio.NewReader(rawClientTls)
for !isEof(clientTlsReader) {
req, err := http.ReadRequest(clientTlsReader)
if err != nil && !errors.Is(err, io.EOF) {
return
}
if err != nil {
m.Warnf("Cannot read TLS request from mitm'd client %v %v", r.Host, err)
return
}
req.RemoteAddr = r.RemoteAddr
if !httpsRegexp.MatchString(req.URL.String()) {
req.URL, _ = url.Parse("https://" + r.Host + req.URL.String())
}
_, resp := m.handleRequest(req)
origBody := resp.Body
defer origBody.Close()
// defer resp.Body.Close()
resp.Header.Set("Connection", "close")
if err := resp.Write(rawClientTls); err != nil {
m.Warnf("Failed to write response: %s", err)
}
}
}