-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
213 lines (193 loc) · 5.66 KB
/
main.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
package main
import (
"bufio"
"context"
"crypto/tls"
"github.com/redis/go-redis/v9"
"io"
"log"
"net"
"net/http"
"net/url"
"strings"
)
var ctx = context.Background()
func handleHttpsTunneling(w http.ResponseWriter, r *http.Request, rdb *redis.Client, config Configuration) {
log.Println("[*] Tunneling to:", r.Host)
w.WriteHeader(http.StatusOK)
// Hijack the connection to the client
hijacker, allowed := w.(http.Hijacker)
if !allowed {
http.Error(w, "HTTP/1.1 400 Internal Server Error", http.StatusInternalServerError)
return
}
srcConn, _, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
// Create a TLS connection
clientTLSConfig := &tls.Config{
Certificates: []tls.Certificate{*config.cert},
GetCertificate: func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
return config.cert, nil
},
InsecureSkipVerify: true,
}
clientTLSConn := tls.Server(srcConn, clientTLSConfig)
defer func(clientTLSConn *tls.Conn) {
err := clientTLSConn.Close()
if err != nil {
log.Println("[-] Failed closing clientTLSConn:", err.Error())
}
}(clientTLSConn)
err = clientTLSConn.Handshake()
if err != nil {
http.Error(w, "TLS handshake failed", http.StatusInternalServerError)
return
}
// Read the request from the client
reader := bufio.NewReader(clientTLSConn)
req, err := http.ReadRequest(reader)
if err != nil {
log.Println("[-] Failed reading request:", err.Error())
http.Error(w, "Failed to read request", http.StatusInternalServerError)
return
}
// if the request is a GET request, check if it is cached in Redis
// and return the cached response if it is
if req.Method == http.MethodGet {
val, err := rdb.Get(ctx, getRedisKey(req)).Result()
if err == nil {
log.Println("[*] Cache hit:", req.Host+req.URL.Path)
_, err := clientTLSConn.Write([]byte(val))
if err != nil {
log.Println("[-] Failed writing cached response:", err.Error())
}
return
}
log.Println("[*] Cache miss:", req.URL.Host+req.URL.Path)
}
// Forward the request to the target server
req.URL = &url.URL{
Scheme: "https",
Host: req.Host,
Path: req.URL.Path,
}
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Read the response
body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Println("[-] Failed closing response Body:", err.Error())
}
}(resp.Body)
buffer := &strings.Builder{}
buffer.Write(getResponseStatusLine(resp.StatusCode))
copyHeader(buffer, resp.Header)
buffer.Write([]byte("\r\n"))
buffer.Write(body)
// Write the response to the client
_, err = clientTLSConn.Write([]byte(buffer.String()))
if err != nil {
log.Println("[-] Failed writing response:", err.Error())
return
}
// If the request is a GET request, cache the response
if req.Method == http.MethodGet {
rdb.Set(ctx, getRedisKey(req), []byte(buffer.String()), config.redisExpiration)
}
}
func handleHttp(w http.ResponseWriter, req *http.Request, rdb *redis.Client, config Configuration) {
log.Println("[*] Fetching from upstream:", req.URL)
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Println("[-] Failed closing response Body:", err.Error())
}
}(resp.Body)
buffer := &strings.Builder{}
buffer.Write(getResponseStatusLine(resp.StatusCode))
copyHeader(buffer, resp.Header)
buffer.Write([]byte("\r\n"))
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Println("[-] Failed reading response Body:", err.Error())
return
}
buffer.Write(body)
_, err = w.Write([]byte(buffer.String()))
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
log.Println("[-] Failed copying response Body:", err.Error())
return
}
err = rdb.Set(ctx, getRedisKey(req), []byte(buffer.String()), config.redisExpiration).Err()
if err != nil {
log.Println("[-] Failed caching response Body:", err.Error())
}
}
func handleCachedHttp(w http.ResponseWriter, req *http.Request, rdb *redis.Client, config Configuration) {
val, err := rdb.Get(ctx, getRedisKey(req)).Result()
if err != nil {
log.Println("[-] Cache miss:", err.Error())
handleHttp(w, req, rdb, config)
return
}
log.Println("[*] Cache hit:", req.URL)
_, err = w.Write([]byte(val))
if err != nil {
log.Println("[-] Failed writing cached response:", err.Error())
}
}
func startProxy(config Configuration) {
hostAddr := net.JoinHostPort(config.listenHostname, config.listenPort)
rdb := redis.NewClient(&redis.Options{
Addr: net.JoinHostPort(config.redisHostname, config.redisPort),
Username: config.redisUsername,
Password: config.redisPassword,
DB: config.redisDB,
})
server := http.Server{
Addr: hostAddr,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("[*] Received connection from:", r.RemoteAddr)
switch r.Method {
case http.MethodConnect:
handleHttpsTunneling(w, r, rdb, config)
return
case http.MethodGet:
handleCachedHttp(w, r, rdb, config)
return
default:
handleHttp(w, r, rdb, config)
}
}),
TLSConfig: nil,
}
log.Println("[*] Listening on: ", hostAddr)
err := server.ListenAndServe()
if err != nil {
log.Fatalln("[-] Cannot listen on ", hostAddr, " : ", err.Error())
}
}
func main() {
config, err := getConfiguration()
if err != nil {
log.Fatalln("[-] Configuration error: ", err.Error())
}
startProxy(*config)
}