-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathmain.go
371 lines (314 loc) · 8.49 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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package main
import (
"bytes"
"crypto/tls"
"encoding/binary"
"encoding/json"
"fmt"
"github.com/miekg/dns"
"github.com/valyala/fasthttp"
"golang.org/x/time/rate"
"io"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
)
var (
config *Config
limiter *rate.Limiter
)
// 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
}
// processDNSQuery processes the DNS query and returns a response.
// processDNSQuery processes the DNS query and returns a response.
func processDNSQuery(query []byte) ([]byte, error) {
var msg dns.Msg
err := msg.Unpack(query)
if err != nil {
return nil, err
}
if len(msg.Question) == 0 {
return nil, fmt.Errorf("no DNS question found in the request")
}
domain := msg.Question[0].Name
if ip, ok := findValueByKeyContains(config.Domains, domain); ok {
rr, err := dns.NewRR(domain + " A " + ip)
if err != nil {
return nil, err
}
msg.Answer = append(msg.Answer, rr)
} else {
resp, err := http.Post("https://1.1.1.1/dns-query", "application/dns-message", bytes.NewReader(query))
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
return msg.Pack()
}
// handleDoTConnection handles a single DoT connection.
func handleDoTConnection(conn net.Conn) {
defer conn.Close()
if !limiter.Allow() {
// Log rate limit exceeded
return
}
// Read the first two bytes to determine the length of the DNS message
lengthBuf := make([]byte, 2)
_, err := io.ReadFull(conn, lengthBuf)
if err != nil {
log.Println(err)
return
}
// Parse the length of the DNS message
dnsMessageLength := binary.BigEndian.Uint16(lengthBuf)
// Allocate a buffer of the size indicated by the length and read the DNS message
buffer := make([]byte, dnsMessageLength)
_, err = io.ReadFull(conn, buffer)
if err != nil {
log.Println(err)
return
}
// Process the DNS query and generate a response
response, err := processDNSQuery(buffer) // Process the full message
if err != nil {
log.Println(err)
return
}
// Prepare the response with the length header
responseLength := make([]byte, 2)
binary.BigEndian.PutUint16(responseLength, uint16(len(response)))
// Write the length of the response followed by the response itself
_, err = conn.Write(responseLength)
if err != nil {
log.Println(err)
return
}
_, err = conn.Write(response)
if err != nil {
log.Println(err)
return
}
}
// startDoTServer starts the DNS-over-TLS server.
func startDoTServer() {
// Load TLS credentials
certPrefix := "/etc/letsencrypt/live/" + config.Host + "/"
cer, err := tls.LoadX509KeyPair(certPrefix+"/fullchain.pem", certPrefix+"privkey.pem")
if err != nil {
log.Fatal(err)
}
tlsConfig := &tls.Config{Certificates: []tls.Certificate{cer}}
listener, err := tls.Listen("tcp", ":853", tlsConfig)
if err != nil {
log.Fatal(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Println(err)
continue
}
go handleDoTConnection(conn)
}
}
func serveSniProxy() {
l, err := net.Listen("tcp", ":443")
if err != nil {
log.Fatal(err)
}
for {
conn, err := l.Accept()
if err != nil {
log.Println(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(_ []byte) (int, error) { return 0, io.ErrClosedPipe }
func (conn readOnlyConn) Close() error { return conn.Close() }
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 conn.SetDeadline(t) }
func (conn readOnlyConn) SetReadDeadline(t time.Time) error { return conn.SetReadDeadline(t) }
func (conn readOnlyConn) SetWriteDeadline(t time.Time) error { return conn.SetWriteDeadline(t) }
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.Println(err)
return
}
clientHello, clientHelloBytes, err := peekClientHello(clientConn)
if err != nil {
log.Println(err)
return
}
if strings.TrimSpace(clientHello.ServerName) == "" {
log.Println("empty sni not allowed here")
return
}
if err := clientConn.SetReadDeadline(time.Time{}); err != nil {
log.Println(err)
// HTTP response headers and body
response := "HTTP/1.1 502 OK\r\n" +
"Content-Type: text/plain; charset=utf-8\r\n" +
"Content-Length: 21\r\n" +
"\r\n" +
"nginx, malformed data"
// Write the response to the connection
_, err := clientConn.Write([]byte(response))
if err != nil {
log.Println("Error writing response:", err)
}
return
}
targetHost := strings.ToLower(clientHello.ServerName)
if targetHost == config.Host {
targetHost = "127.0.0.1:8443"
} else {
targetHost = net.JoinHostPort(targetHost, "443")
}
backendConn, err := net.DialTimeout("tcp", targetHost, 5*time.Second)
if err != nil {
log.Println(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()
}
// handleDoHRequest processes the DoH request with rate limiting using fasthttp.
func handleDoHRequest(ctx *fasthttp.RequestCtx) {
if !limiter.Allow() {
ctx.Error("Rate limit exceeded", fasthttp.StatusTooManyRequests)
return
}
body := ctx.PostBody()
dnsResponse, err := processDNSQuery(body)
if err != nil {
ctx.Error("Failed to process DNS query", fasthttp.StatusInternalServerError)
return
}
ctx.SetContentType("application/dns-message")
ctx.SetStatusCode(fasthttp.StatusOK)
ctx.Write(dnsResponse)
}
// runDOHServer starts the DNS-over-HTTPS server using fasthttp.
func runDOHServer() {
server := &fasthttp.Server{
Handler: func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/dns-query":
handleDoHRequest(ctx)
default:
ctx.Error("Unsupported path", fasthttp.StatusNotFound)
}
},
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
if err := server.ListenAndServe("127.0.0.1:8080"); err != nil {
log.Fatalf("Error in DoH Server: %s", err)
}
}
func main() {
err := os.Setenv("GOGC", "50")
if err != nil {
log.Fatal(err)
} // Set GOGC to 50 to make GC more aggressive
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, :853...")
var wg sync.WaitGroup
wg.Add(3)
limiter = rate.NewLimiter(10, 50) // 1 request per second with a burst size of 5
go func() {
runDOHServer()
wg.Done()
}()
go func() {
startDoTServer()
wg.Done()
}()
go func() {
serveSniProxy()
wg.Done()
}()
wg.Wait()
}