forked from bepass-org/smartSNI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
263 lines (220 loc) · 6.13 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
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
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"github.com/miekg/dns"
"golang.org/x/time/rate"
"io"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
)
var config *Config
// Config represents the structure of the configuration file.
type Config struct {
Host string `json:"host"`
Domains map[string]string `json:"domains"`
}
// LoadConfig loads the configuration from a JSON file.
func LoadConfig(filename string) (*Config, error) {
var config Config
cfgBytes, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
err = json.Unmarshal(cfgBytes, &config)
return &config, err
}
func findValueByKeyContains(m map[string]string, substr string) (string, bool) {
for key, value := range m {
if strings.Contains(strings.ToLower(substr), strings.ToLower(key)) {
return value, true
}
}
return "", false // Return empty string and false if no key contains the substring
}
// handleDoHRequest processes the DoH request with rate limiting.
func handleDoHRequest(limiter *rate.Limiter) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !limiter.Allow() {
http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusInternalServerError)
return
}
var msg dns.Msg
err = msg.Unpack(body)
if err != nil {
http.Error(w, "Failed to unpack DNS message", http.StatusBadRequest)
return
}
if len(msg.Question) == 0 {
http.Error(w, "No DNS question found in the request", http.StatusBadRequest)
return
}
domain := msg.Question[0].Name
if ip, ok := findValueByKeyContains(config.Domains, domain); ok {
rr, err := dns.NewRR(domain + " A " + ip)
if err != nil {
http.Error(w, "Failed to create DNS resource record", http.StatusInternalServerError)
return
}
msg.Answer = append(msg.Answer, rr)
} else {
resp, err := http.Post("https://1.1.1.1/dns-query", "application/dns-message", bytes.NewReader(body))
if err != nil {
http.Error(w, "Failed to forward request", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
forwardedBody, _ := io.ReadAll(resp.Body)
w.Header().Set("Content-Type", "application/dns-message")
w.Write(forwardedBody)
return
}
dnsResponse, err := msg.Pack()
if err != nil {
http.Error(w, "Failed to pack DNS response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/dns-message")
w.Write(dnsResponse)
}
}
func serveSniProxy() {
l, err := net.Listen("tcp", ":443")
if err != nil {
log.Fatal(err)
}
for {
conn, err := l.Accept()
if err != nil {
log.Print(err)
continue
}
go handleConnection(conn)
}
}
func peekClientHello(reader io.Reader) (*tls.ClientHelloInfo, io.Reader, error) {
peekedBytes := new(bytes.Buffer)
hello, err := readClientHello(io.TeeReader(reader, peekedBytes))
if err != nil {
return nil, nil, err
}
return hello, peekedBytes, nil
}
type readOnlyConn struct {
reader io.Reader
}
func (conn readOnlyConn) Read(p []byte) (int, error) { return conn.reader.Read(p) }
func (conn readOnlyConn) Write(p []byte) (int, error) { return 0, io.ErrClosedPipe }
func (conn readOnlyConn) Close() error { return nil }
func (conn readOnlyConn) LocalAddr() net.Addr { return nil }
func (conn readOnlyConn) RemoteAddr() net.Addr { return nil }
func (conn readOnlyConn) SetDeadline(t time.Time) error { return nil }
func (conn readOnlyConn) SetReadDeadline(t time.Time) error { return nil }
func (conn readOnlyConn) SetWriteDeadline(t time.Time) error { return nil }
func readClientHello(reader io.Reader) (*tls.ClientHelloInfo, error) {
var hello *tls.ClientHelloInfo
var wg sync.WaitGroup
// Set the wait group for one operation (Handshake)
wg.Add(1)
config := &tls.Config{
GetConfigForClient: func(argHello *tls.ClientHelloInfo) (*tls.Config, error) {
hello = argHello // Capture the ClientHelloInfo
wg.Done() // Indicate that the handshake is complete
return nil, nil
},
}
tlsConn := tls.Server(readOnlyConn{reader: reader}, config)
err := tlsConn.Handshake()
// Wait for the handshake to be captured
wg.Wait()
if hello == nil {
return nil, err
}
return hello, nil
}
func handleConnection(clientConn net.Conn) {
defer clientConn.Close()
if err := clientConn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
log.Print(err)
return
}
clientHello, clientHelloBytes, err := peekClientHello(clientConn)
if err != nil {
log.Print(err)
return
}
if err := clientConn.SetReadDeadline(time.Time{}); err != nil {
log.Print(err)
return
}
targetHost := strings.ToLower(clientHello.ServerName)
if !strings.HasSuffix(targetHost, ".internal.example.com") {
log.Print("Blocking connection to unauthorized backend")
return
}
if targetHost == config.Host {
targetHost = net.JoinHostPort(targetHost, "8443")
} else {
targetHost = net.JoinHostPort(targetHost, "443")
}
backendConn, err := net.DialTimeout("tcp", targetHost, 5*time.Second)
if err != nil {
log.Print(err)
return
}
defer backendConn.Close()
var wg sync.WaitGroup
wg.Add(2)
go func() {
io.Copy(clientConn, backendConn)
clientConn.(*net.TCPConn).CloseWrite()
wg.Done()
}()
go func() {
io.Copy(backendConn, clientHelloBytes)
io.Copy(backendConn, clientConn)
backendConn.(*net.TCPConn).CloseWrite()
wg.Done()
}()
wg.Wait()
}
func runDOHServer() {
limiter := rate.NewLimiter(100, 500) // 1 request per second with a burst size of 5
http.HandleFunc("/dns-query", handleDoHRequest(limiter))
server := &http.Server{
Addr: "127.0.0.1:8080",
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Println(server.ListenAndServe())
}
func main() {
cfg, err := LoadConfig("config.json")
if err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
config = cfg
log.Println("Starting SSNI proxy server on :443...")
var wg sync.WaitGroup
wg.Add(2)
go func() {
runDOHServer()
wg.Done()
}()
go func() {
serveSniProxy()
wg.Done()
}()
wg.Wait()
}