-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
1510 lines (1274 loc) ยท 49.2 KB
/
server.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Server component of the Sultry proxy system.
//
// This component is responsible for:
// 1. Establishing connections to target servers
// 2. Handling TLS handshakes with targets
// 3. Relaying data between client component and targets
// 4. Managing out-of-band (OOB) communication for SNI concealment
//
// The server component plays a crucial role in the SNI concealment strategy:
// - It receives ClientHello messages from the client component via HTTP
// - It connects to the real target server and forwards the ClientHello
// - It relays the ServerHello and subsequent handshake messages back to the client
// - After handshake completion, it helps establish a direct connection for data transfer
//
// By handling the TLS handshake through HTTP, this approach conceals the SNI
// information from network monitors/firewalls that might be inspecting the traffic
// between the client and the proxy server.
package main
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"strings"
"sync"
"time"
)
// SessionState represents the state of a TLS session.
type SessionState struct {
TargetConn net.Conn
HandshakeComplete bool
LastActivity time.Time
ServerResponses [][]byte
ClientMessages [][]byte
ResponseQueue chan []byte
Adopted bool
ServerMsgIndex int // Index into ServerResponses for direct access
mu sync.Mutex // Protects all fields in this struct
}
// Global session store
var (
sessions = make(map[string]*SessionState)
sessionsMu sync.Mutex
)
func server(config *Config) {
// Configure more verbose logging
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
log.Println("๐ Starting Sultry server component...")
log.Println("๐ Configuration:", fmt.Sprintf("%+v", *config))
// Set up HTTP handlers for different endpoints
http.HandleFunc("/", legacyServe) // Legacy endpoint for backward compatibility
http.HandleFunc("/handshake", handleHandshake) // New endpoint for handshake messages
http.HandleFunc("/appdata", handleAppData) // New endpoint for application data
http.HandleFunc("/complete_handshake", handleCompleteHandshake)
http.HandleFunc("/adopt_connection", handleAdoptConnection)
http.HandleFunc("/get_target_info", handleGetTargetInfo) // New endpoint for getting target server information
http.HandleFunc("/release_connection", handleReleaseConnection) // New endpoint for releasing connections
http.HandleFunc("/get_response", handleGetResponse) // New endpoint for getting server responses
http.HandleFunc("/send_data", handleSendData) // New endpoint for sending client data
http.HandleFunc("/create_connection", handleCreateConnection) // New endpoint for simplified SNI concealment
// Log all registered routes
log.Println("๐ Registered HTTP handlers:")
log.Println(" - / (Legacy endpoint)")
log.Println(" - /handshake (Handshake message handler)")
log.Println(" - /appdata (Application data handler)")
log.Println(" - /complete_handshake (Handshake completion handler)")
log.Println(" - /adopt_connection (Connection adoption handler)")
log.Println(" - /get_target_info (Target info handler)")
log.Println(" - /release_connection (Connection release handler)")
log.Println(" - /get_response (Response retrieval handler)")
log.Println(" - /send_data (Data sending handler)")
log.Println(" - /create_connection (SNI resolution handler)")
// Start cleanup goroutine
go cleanupInactiveSessions()
log.Println("๐น TLS Relay service listening on port", config.RelayPort)
log.Println("โ
Server ready to accept connections")
log.Fatal(http.ListenAndServe(":"+fmt.Sprint(config.RelayPort), nil))
}
// Legacy handler for backward compatibility
func legacyServe(w http.ResponseWriter, r *http.Request) {
var req ClientHelloRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
clientHello := req.Data
sni := req.SNI
if len(clientHello) == 0 {
http.Error(w, "ClientHello data is required", http.StatusBadRequest)
return
}
log.Println("๐น Performing TLS handshake with real server for:", sni)
// Forward the ClientHello to the real target
serverHello, err := forwardClientHello(clientHello, sni)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to fetch ServerHello: %v", err), http.StatusInternalServerError)
return
}
w.Write(serverHello)
}
// Handler for new handshake messages
func handleHandshake(w http.ResponseWriter, r *http.Request) {
var req HandshakeMessageRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
sessionID := req.SessionID
clientMsg := req.Data
sni := req.SNI
if len(clientMsg) == 0 {
http.Error(w, "Client message data is required", http.StatusBadRequest)
return
}
// Check if this is a new session
sessionsMu.Lock()
session, exists := sessions[sessionID]
sessionsMu.Unlock()
if !exists {
// This is a new session, initialize it
log.Printf("๐น Initiating new TLS handshake session %s for SNI: %s", sessionID, sni)
err = handleOOBRequest(sessionID, clientMsg, sni)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to initialize handshake: %v", err), http.StatusInternalServerError)
return
}
// Get the first server response (ServerHello)
sessionsMu.Lock()
session = sessions[sessionID]
sessionsMu.Unlock()
if session == nil {
http.Error(w, "Session initialization failed", http.StatusInternalServerError)
return
}
// Wait for the first response from the server
select {
case serverResponse := <-session.ResponseQueue:
w.Write(serverResponse)
case <-time.After(30 * time.Second):
http.Error(w, "Timeout waiting for server response", http.StatusGatewayTimeout)
}
return
}
// This is an existing session, forward the client message
isComplete, err := handleClientMessage(sessionID, clientMsg)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to process client message: %v", err), http.StatusInternalServerError)
return
}
// If the handshake is complete, return an empty response to signal completion
if isComplete {
w.Write([]byte{})
return
}
// Wait for the server's response
select {
case serverResponse := <-session.ResponseQueue:
w.Write(serverResponse)
case <-time.After(30 * time.Second):
http.Error(w, "Timeout waiting for server response", http.StatusGatewayTimeout)
}
}
// Handler for application data
func handleAppData(w http.ResponseWriter, r *http.Request) {
var req AppDataRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
sessionID := req.SessionID
data := req.Data
if len(data) == 0 {
http.Error(w, "Application data is required", http.StatusBadRequest)
return
}
// Check if the session exists
sessionsMu.Lock()
session, exists := sessions[sessionID]
sessionsMu.Unlock()
if !exists || !session.HandshakeComplete {
http.Error(w, "Invalid session or handshake not complete", http.StatusBadRequest)
return
}
// Forward the application data to the target with timeout
session.TargetConn.SetWriteDeadline(time.Now().Add(10 * time.Second))
_, err = session.TargetConn.Write(data)
session.TargetConn.SetWriteDeadline(time.Time{})
if err != nil {
http.Error(w, fmt.Sprintf("Failed to write application data: %v", err), http.StatusInternalServerError)
return
}
// Application data was sent successfully
session.LastActivity = time.Now()
w.WriteHeader(http.StatusOK)
}
// Initialize a new OOB handshake session
func handleOOBRequest(sessionID string, clientHello []byte, sni string) error {
// Connect to the target server with optimized settings
// Use a dialer with timeout for better connection performance
dialer := &net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 30 * time.Second,
}
targetConn, err := dialer.Dial("tcp", sni+":443")
if err != nil {
log.Printf("โ Failed to connect to %s: %v", sni, err)
return fmt.Errorf("failed to connect to %s: %w", sni, err)
}
if tcpConn, ok := targetConn.(*net.TCPConn); ok {
// Optimize TCP settings for TLS handshake performance
tcpConn.SetNoDelay(true) // Disable Nagle's algorithm
tcpConn.SetKeepAlive(true)
tcpConn.SetKeepAlivePeriod(30 * time.Second)
tcpConn.SetReadBuffer(32768) // 32KB read buffer
tcpConn.SetWriteBuffer(32768) // 32KB write buffer
}
log.Printf("๐ Connected to target server via SNI-concealed channel: %s", sni)
// Create a new session
session := &SessionState{
TargetConn: targetConn,
HandshakeComplete: false,
LastActivity: time.Now(),
ServerResponses: make([][]byte, 0),
ResponseQueue: make(chan []byte, 100), // Much larger buffer
}
// Store the session
sessionsMu.Lock()
sessions[sessionID] = session
sessionsMu.Unlock()
// Send ClientHello to target
_, err = targetConn.Write(clientHello)
if err != nil {
log.Printf("โ Failed to send ClientHello to target: %v", err)
return fmt.Errorf("failed to send ClientHello to target: %w", err)
}
log.Printf("๐น Sent ClientHello to target server for session: %s", sessionID)
// Start reading responses from target
go handleTargetResponses(sessionID, targetConn)
return nil
}
// In handleTargetResponses function in server.go:
func handleTargetResponses(sessionID string, targetConn net.Conn) {
defer func() {
log.Printf("๐น Closing target connection for session %s", sessionID)
targetConn.Close()
}()
// Use a larger buffer for more reliable handshake processing
buffer := make([]byte, 1048576) // Increase buffer size to 1MB for large TLS records
// When session is adopted, we should stop processing in this function
var directConnStarted bool = false
// We don't want to send ChangeCipherSpec during this phase anymore
// It's better to let the normal TLS handshake complete naturally
for {
// Check if the session has been adopted and hijacked to a direct connection
sessionsMu.Lock()
session, exists := sessions[sessionID]
sessionAdopted := exists && session.Adopted
sessionsMu.Unlock()
if sessionAdopted && !directConnStarted {
// Session has been adopted, but direct connection hasn't been fully established yet
log.Printf("๐น Session %s is adopted, waiting for direct connection setup...", sessionID)
directConnStarted = true
// We'll continue reading data for a short time to make sure the transition is smooth
// After this cycle, we'll keep checking if the session still exists
} else if sessionAdopted && directConnStarted {
// Check if the session still exists - if not, direct relay is fully taking over
sessionsMu.Lock()
_, stillExists := sessions[sessionID]
sessionsMu.Unlock()
if !stillExists {
log.Printf("๐น Session %s has been transferred to direct relay, stopping target reader", sessionID)
return
}
}
// Read response from target server with reasonable timeout
targetConn.SetReadDeadline(time.Now().Add(30 * time.Second))
n, err := targetConn.Read(buffer)
targetConn.SetReadDeadline(time.Time{}) // Reset the deadline after read
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
log.Printf("โ ๏ธ Read timeout from target server for session %s, continuing", sessionID)
continue
} else if err != io.EOF {
log.Printf("โ ERROR reading from target: %v", err)
} else {
log.Printf("๐น Target server closed connection for session %s", sessionID)
}
// IMPORTANT: Signal any waiting clients about connection close
sessionsMu.Lock()
session, exists := sessions[sessionID]
if exists && !session.Adopted {
// Send empty response to unblock any waiting clients
select {
case session.ResponseQueue <- []byte{}:
// Signaled waiting client
default:
// No clients waiting, that's OK
}
}
sessionsMu.Unlock()
break
}
// Store and forward the response data
responseData := buffer[:n]
sessionsMu.Lock()
session, exists = sessions[sessionID]
if exists {
// Always keep track of server responses
session.ServerResponses = append(session.ServerResponses, responseData)
// Always log what we received
if !session.Adopted {
session.ResponseQueue <- responseData
log.Printf("๐น Queued handshake response (%d bytes) for session %s", len(responseData), sessionID)
} else {
// When adopted, don't queue to ResponseQueue, but log what was received
// This data will be handled by the direct connection
log.Printf("๐น Session %s is adopted, target sent %d bytes (handled by direct connection)",
sessionID, len(responseData))
// Check first few bytes of response data to help debug
if len(responseData) > 0 {
if len(responseData) >= 5 {
recordType := responseData[0]
// Only interpret as TLS record if it's a valid TLS record type (20-24)
if recordType >= 20 && recordType <= 24 {
version := (uint16(responseData[1]) << 8) | uint16(responseData[2])
length := (uint16(responseData[3]) << 8) | uint16(responseData[4])
log.Printf("๐น Target TLS record: Type=%d, Version=0x%04x, Length=%d",
recordType, version, length)
log.Printf("๐น First 16 bytes: %x", responseData[:min(16, len(responseData))])
} else {
// This is likely application data
log.Printf("๐น Target application data: %d bytes", len(responseData))
}
} else {
log.Printf("๐น Short data: %x", responseData)
}
}
}
}
sessionsMu.Unlock()
}
}
// Handle a message from the client
func handleClientMessage(sessionID string, message []byte) (bool, error) {
sessionsMu.Lock()
session, exists := sessions[sessionID]
sessionsMu.Unlock()
if !exists {
return false, fmt.Errorf("session %s not found", sessionID)
}
// Update last activity
session.LastActivity = time.Now()
// Forward the message to the target with timeout
session.TargetConn.SetWriteDeadline(time.Now().Add(10 * time.Second))
_, err := session.TargetConn.Write(message)
session.TargetConn.SetWriteDeadline(time.Time{})
if err != nil {
log.Printf("โ Failed to write client message to target: %v", err)
return false, fmt.Errorf("failed to write client message: %w", err)
}
// Analyze if this message completes the handshake
_, isComplete := analyzeHandshakeStatus(message)
// Mark the handshake as complete if determined
if isComplete {
session.HandshakeComplete = true
}
return isComplete, nil
}
// Analyze if a message is part of the handshake and if it completes the handshake
func analyzeHandshakeStatus(data []byte) (isHandshake bool, isComplete bool) {
if len(data) < 5 {
return false, false
}
recordType := data[0]
// TLS handshake record type is 22
isHandshake = (recordType == 22)
// Don't try to detect handshake completion by record inspection
// Instead, rely on receiving application data or the client's explicit signal
return isHandshake, false // Never auto-complete based on record inspection
}
// Periodic cleanup of inactive sessions
func cleanupInactiveSessions() {
for {
time.Sleep(60 * time.Second)
sessionsMu.Lock()
now := time.Now()
for sessionID, session := range sessions {
// Clean up sessions inactive for more than 10 minutes
if now.Sub(session.LastActivity) > 10*time.Minute {
log.Printf("๐งน Cleaning up inactive session %s", sessionID)
if session.TargetConn != nil {
session.TargetConn.Close()
}
delete(sessions, sessionID)
}
}
sessionsMu.Unlock()
}
}
// Legacy function for backward compatibility
func forwardClientHello(clientHelloData []byte, sni string) ([]byte, error) {
log.Println("๐น Starting TLS handshake with:", sni)
// Connect to the target server
conn, err := net.Dial("tcp", sni+":443")
if err != nil {
log.Printf("โ Failed to connect to %s: %v", sni, err)
return nil, fmt.Errorf("failed to connect to %s: %w", sni, err)
}
defer conn.Close()
log.Println("๐น Connected to:", sni)
// Analyze the ClientHello data
recordType, version, msgLen, err := parseRecordHeader(clientHelloData)
if err != nil {
return nil, err
}
log.Printf("๐น ClientHello details: RecordType=%d, Version=0x%x, Length=%d",
recordType, version, msgLen)
// Check if it's a valid TLS handshake message
if recordType != 22 { // 22 is the value for Handshake
return nil, fmt.Errorf("not a handshake message (type=%d)", recordType)
}
// Forward the ClientHello as-is
_, err = conn.Write(clientHelloData)
if err != nil {
log.Printf("โ Failed to write ClientHello: %v", err)
return nil, fmt.Errorf("failed to write ClientHello: %w", err)
}
log.Println("๐น Sent ClientHello to server, waiting for response")
// Read the ServerHello response
// First, read the TLS record header (5 bytes)
recordHeader := make([]byte, 5)
_, err = conn.Read(recordHeader)
if err != nil {
log.Printf("โ Failed to read ServerHello header: %v", err)
return nil, fmt.Errorf("failed to read ServerHello header: %w", err)
}
// Parse the record header to determine message length
responseType := recordHeader[0]
responseVer := binary.BigEndian.Uint16(recordHeader[1:3])
responseLen := binary.BigEndian.Uint16(recordHeader[3:5])
log.Printf("๐น ServerHello response: Type=%d, Version=0x%x, Length=%d",
responseType, responseVer, responseLen)
// Read the actual handshake message
serverHelloData := make([]byte, responseLen)
_, err = conn.Read(serverHelloData)
if err != nil {
log.Printf("โ Failed to read ServerHello data: %v", err)
return nil, fmt.Errorf("failed to read ServerHello data: %w", err)
}
// Combine the record header and message data for a complete response
completeResponse := append(recordHeader, serverHelloData...)
log.Printf("๐น Successfully received ServerHello (%d bytes)", len(completeResponse))
// Format a human-readable response for debugging
info := fmt.Sprintf(`{
"tls_record_type": %d,
"tls_version": "0x%x",
"response_length": %d,
"server_name": "%s",
"raw_data_length": %d
}`, responseType, responseVer, responseLen, sni, len(completeResponse))
log.Printf("๐น Server response info: %s", info)
// Return the raw ServerHello data
return completeResponse, nil
}
// Parse the TLS record header
func parseRecordHeader(data []byte) (byte, uint16, uint16, error) {
if len(data) < 5 {
return 0, 0, 0, fmt.Errorf("data too short for TLS record header")
}
recordType := data[0]
version := binary.BigEndian.Uint16(data[1:3])
length := binary.BigEndian.Uint16(data[3:5])
return recordType, version, length, nil
}
// Add to server.go
func handleCompleteHandshake(w http.ResponseWriter, r *http.Request) {
var req struct {
SessionID string `json:"session_id"`
Action string `json:"action"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
sessionsMu.Lock()
session, exists := sessions[req.SessionID]
sessionsMu.Unlock()
if !exists {
http.Error(w, "Session not found", http.StatusNotFound)
return
}
// Mark handshake as complete
session.HandshakeComplete = true
log.Printf("โ
Handshake explicitly marked complete for session %s", req.SessionID)
w.WriteHeader(http.StatusOK)
}
// Handler for connection adoption requests - critical for TLS proxying
func handleAdoptConnection(w http.ResponseWriter, r *http.Request) {
// Read the JSON request body
var req struct {
SessionID string `json:"session_id"`
Protocol string `json:"protocol,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, fmt.Sprintf("Invalid request: %v", err), http.StatusBadRequest)
return
}
sessionID := req.SessionID
if sessionID == "" {
http.Error(w, "Session ID is required", http.StatusBadRequest)
return
}
// Get the session
sessionsMu.Lock()
session, exists := sessions[sessionID]
sessionsMu.Unlock()
if !exists || session.TargetConn == nil {
http.Error(w, fmt.Sprintf("Session %s not found or invalid", sessionID), http.StatusNotFound)
return
}
log.Printf("๐น Adoption request received for session %s", sessionID)
// Check if handshake is complete
if !session.HandshakeComplete {
log.Printf("โ Handshake not complete for session %s, rejecting adoption", sessionID)
http.Error(w, fmt.Sprintf("Handshake not complete for session %s", sessionID), http.StatusBadRequest)
return
}
log.Printf("โ
Handshake confirmed complete for session %s", sessionID)
// Hijack the HTTP connection
hj, ok := w.(http.Hijacker)
if !ok {
log.Printf("โ Server doesn't support hijacking for session %s", sessionID)
http.Error(w, "Server doesn't support hijacking", http.StatusInternalServerError)
return
}
log.Printf("๐น Hijacking HTTP connection for session %s", sessionID)
clientConn, bufrw, err := hj.Hijack()
if err != nil {
log.Printf("โ Hijacking failed for session %s: %v", sessionID, err)
http.Error(w, fmt.Sprintf("Hijacking failed: %v", err), http.StatusInternalServerError)
return
}
log.Printf("โ
Successfully hijacked HTTP connection for session %s", sessionID)
// Mark session as adopted - use mutex to prevent race conditions
session.mu.Lock()
session.Adopted = true
session.mu.Unlock()
log.Printf("โ
Session %s marked as adopted", sessionID)
// Send HTTP 200 OK
log.Printf("๐น Sending 200 OK response for session %s", sessionID)
// Detect TLS version from ServerHello - for logging only
tlsVersion := "TLSv1.2" // Default
session.mu.Lock()
if len(session.ServerResponses) > 0 && len(session.ServerResponses[0]) >= 5 {
ver := (uint16(session.ServerResponses[0][1]) << 8) | uint16(session.ServerResponses[0][2])
switch ver {
case 0x0303:
tlsVersion = "TLSv1.2" // TLS 1.2 record version
case 0x0304:
tlsVersion = "TLSv1.3" // TLS 1.3 record version
}
log.Printf("๐น Detected TLS version in use: %s (0x%04x)", tlsVersion, ver)
}
session.mu.Unlock()
// This is the initial HTTP response to the CONNECT request, which happens BEFORE the TLS handshake
// So it's safe to send HTTP here
responseStr := "HTTP/1.1 200 OK\r\n" +
"Connection: keep-alive\r\n" +
"X-Proxy-Status: Direct-Connection-Established\r\n" +
"\r\n"
if _, err := bufrw.WriteString(responseStr); err != nil {
log.Printf("โ ERROR writing response: %v", err)
return
}
if err := bufrw.Flush(); err != nil {
log.Printf("โ ERROR flushing buffer: %v", err)
return
}
// Ensure the response buffer is fully flushed
if err := bufrw.Flush(); err != nil {
log.Printf("โ ERROR flushing buffer for session %s: %v", sessionID, err)
return
}
log.Printf("โ
Sent 200 OK response for session %s", sessionID)
// Set proper TCP options for improved performance
if tcpConn, ok := session.TargetConn.(*net.TCPConn); ok {
tcpConn.SetNoDelay(true)
tcpConn.SetKeepAlive(true)
tcpConn.SetKeepAlivePeriod(30 * time.Second)
tcpConn.SetReadBuffer(1048576) // 1MB buffer
tcpConn.SetWriteBuffer(1048576) // 1MB buffer
}
if tcpConn, ok := clientConn.(*net.TCPConn); ok {
tcpConn.SetNoDelay(true)
tcpConn.SetKeepAlive(true)
tcpConn.SetKeepAlivePeriod(30 * time.Second)
tcpConn.SetReadBuffer(1048576) // 1MB buffer
tcpConn.SetWriteBuffer(1048576) // 1MB buffer
}
// For HTTP/2, we need a passthrough relay approach
// Don't attempt to read ANY data here as it breaks the TLS protocol state
log.Printf("๐น Starting pure passthrough relay without HTTP/2 preface detection")
// For HTTP/2 to work, we must not interfere with the TLS sequence at all
// Any attempt to read data here breaks the cryptographic MAC sequence
log.Printf("๐น Using pure relay mode, letting the protocol flow naturally")
// Extract the SNI for logging purposes
session.mu.Lock()
var sni string = "unknown"
if len(session.ClientMessages) > 0 {
// Extract SNI
extractedSNI, err := extractSNIFromClientHello(session.ClientMessages[0])
if err == nil && extractedSNI != "" {
sni = extractedSNI
}
// Check for HTTP/2 support - just for logging
if bytes.Contains(session.ClientMessages[0], []byte("h2")) {
log.Printf("๐น Detected HTTP/2 ALPN in ClientHello message")
}
}
session.mu.Unlock()
// Don't send an initial GET request - let the client send its own request
log.Printf("๐น Waiting for client to send HTTP request for: %s", sni)
log.Printf("โ
Connection ready for bidirectional relay (session %s)", sessionID)
// Start bidirectional relay in a separate goroutine
go func() {
log.Printf("โ
Starting bidirectional relay for session %s", sessionID)
// CRITICAL FIX: DON'T forward pending TLS handshake responses after connection adoption
// This would corrupt the TLS MAC sequence and cause "decryption failed or bad record mac" errors
session.mu.Lock()
if len(session.ServerResponses) > 0 && session.ServerMsgIndex < len(session.ServerResponses) {
log.Printf("๐น Found %d pending TLS handshake responses - NOT forwarding to avoid corruption",
len(session.ServerResponses)-session.ServerMsgIndex)
// Update the index to mark as consumed, but don't actually send them
session.ServerMsgIndex = len(session.ServerResponses)
}
session.mu.Unlock()
// Skip manually trying to complete the TLS handshake with signals
// This was causing connection issues - we'll let the data relay handle it
log.Printf("๐น Proceeding directly to HTTP data relay")
// Instead of artificial delay, let's ensure proper protocol state management
// Flush any pending operations to ensure TLS state is properly synchronized
// The key is not manipulating the TLS state once handshake is complete
// Phase 2: Direct communication with maintained TLS state
// Get the negotiated TLS version for logging
tlsVersionStr := "TLS-Unknown"
session.mu.Lock()
if len(session.ServerResponses) > 0 && len(session.ServerResponses[0]) >= 5 {
ver := (uint16(session.ServerResponses[0][1]) << 8) | uint16(session.ServerResponses[0][2])
switch ver {
case 0x0303:
tlsVersionStr = "TLSv1.2"
case 0x0304:
tlsVersionStr = "TLSv1.3"
default:
tlsVersionStr = fmt.Sprintf("TLS-0x%04x", ver)
}
}
session.mu.Unlock()
// CRITICAL: Don't send any HTTP response at this point!
// The TLS handshake is already complete and sending unencrypted HTTP over
// an encrypted TLS connection will break the state machine
log.Printf("๐น Using TLS version: %s in pure relay mode", tlsVersionStr)
log.Printf("๐น Phase 1 complete: SNI concealment handshake successful")
log.Printf("๐น Phase 2 beginning: Direct client-server communication")
// Instead of direct fetch, we'll use a pure bidirectional relay with the existing connection
// This maintains TLS state and allows the client to communicate directly with the server
// No need to start a new connection - we already have a valid, authenticated TLS connection
// Just set up the relay between client and target server
// Enable graceful shutdown behavior to handle connection resets
log.Printf("๐น Enabling graceful shutdown behavior to handle connection resets")
defer func() {
if r := recover(); r != nil {
log.Printf("โ PANIC in bidirectional relay: %v", r)
}
// Close connections
if session.TargetConn != nil {
session.TargetConn.Close()
}
if clientConn != nil {
clientConn.Close()
}
log.Printf("โ
Connections closed for session %s", sessionID)
// Clean up session
sessionsMu.Lock()
delete(sessions, sessionID)
sessionsMu.Unlock()
}()
// Start bidirectional relay immediately without direct fetch
log.Printf("๐น Starting pure bidirectional relay for phase 2 communication")
// Use wait group for the two copy operations
var wg sync.WaitGroup
wg.Add(2)
// Client -> Target with enhanced progress logging
go func() {
defer wg.Done()
// Use a much larger buffer to handle large TLS records and HTTP requests
buffer := make([]byte, 1048576) // 1MB buffer
var totalBytes int64
for {
// Read from client with longer timeout
clientConn.SetReadDeadline(time.Now().Add(120 * time.Second))
nr, err := clientConn.Read(buffer)
clientConn.SetReadDeadline(time.Time{})
if err != nil {
if err == io.EOF || strings.Contains(err.Error(), "use of closed") {
log.Printf("๐น Client closed connection (normal)")
} else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
log.Printf("๐น Client read timeout, continuing...")
continue
} else {
log.Printf("โ Server side: Client->Target relay error: %v", err)
}
break
}
if nr > 0 {
// Log application data details
log.Printf("๐น SERVER DATA: Client->Target: Read %d bytes", nr)
if nr >= 5 {
recordType := buffer[0]
// Only interpret as TLS record if it's a valid TLS record type (20-24)
if recordType >= 20 && recordType <= 24 {
version := (uint16(buffer[1]) << 8) | uint16(buffer[2])
length := (uint16(buffer[3]) << 8) | uint16(buffer[4])
log.Printf("๐น SERVER DATA: Client->Target TLS record: Type=%d, Version=0x%04x, Length=%d",
recordType, version, length)
log.Printf("๐น SERVER DATA: First 16 bytes: %x", buffer[:min(16, nr)])
} else {
// This is likely application data
log.Printf("๐น SERVER DATA: Client->Target application data: %d bytes", nr)
}
}
// Write to target with timeout
session.TargetConn.SetWriteDeadline(time.Now().Add(10 * time.Second))
nw, err := session.TargetConn.Write(buffer[:nr])
session.TargetConn.SetWriteDeadline(time.Time{})
if err != nil {
log.Printf("โ Server side: Client->Target relay error writing: %v", err)
break
}
if nw != nr {
log.Printf("โ ๏ธ Server side: Short write to target %d/%d bytes", nw, nr)
} else {
log.Printf("โ
Server side: Client->Target: Successfully forwarded %d bytes", nw)
}
totalBytes += int64(nw)
}
}
log.Printf("๐น Server side: Client->Target relay finished: %d bytes total", totalBytes)
}()
// Target -> Client with enhanced progress logging
go func() {
defer wg.Done()
// Use a much larger buffer to handle large TLS records and HTTP responses
buffer := make([]byte, 1048576) // 1MB buffer
var totalBytes int64
for {
// Read from target with longer timeout
session.TargetConn.SetReadDeadline(time.Now().Add(120 * time.Second))
nr, err := session.TargetConn.Read(buffer)
session.TargetConn.SetReadDeadline(time.Time{})
if err != nil {
if err == io.EOF || strings.Contains(err.Error(), "use of closed") {
log.Printf("๐น Target closed connection (normal)")
} else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
log.Printf("๐น Target read timeout, continuing...")
continue
} else {
log.Printf("โ Server side: Target->Client relay error: %v", err)
}
break
}
if nr > 0 {
// Try to detect if this is HTTP response data
if nr > 10 && bytes.HasPrefix(buffer[:nr], []byte("HTTP/1.")) {
log.Printf("๐น SERVER DATA: Received HTTP response from target: %d bytes", nr)
// Get the status line
statusLine := ""
for i, b := range buffer[:min(100, nr)] {
if b == '\n' {
statusLine = string(buffer[:i])
break
}
}
log.Printf("๐น HTTP RESPONSE: %s", statusLine)
// Try to find response body
bodyStart := bytes.Index(buffer[:nr], []byte("\r\n\r\n"))
if bodyStart > 0 {
bodyStart += 4 // Skip \r\n\r\n
bodyLen := nr - bodyStart
if bodyLen > 0 {
log.Printf("๐น HTTP BODY: %d bytes", bodyLen)
previewLen := min(100, bodyLen)
log.Printf("๐น BODY PREVIEW: %s", string(buffer[bodyStart:bodyStart+previewLen]))
}
}
} else {
// Regular TLS data
log.Printf("๐น SERVER DATA: Target->Client: Read %d bytes", nr)
if nr >= 5 {
recordType := buffer[0]
// Only interpret as TLS record if it's a valid TLS record type (20-24)
if recordType >= 20 && recordType <= 24 {
version := (uint16(buffer[1]) << 8) | uint16(buffer[2])
length := (uint16(buffer[3]) << 8) | uint16(buffer[4])
log.Printf("๐น SERVER DATA: Target->Client TLS record: Type=%d, Version=0x%04x, Length=%d",
recordType, version, length)
log.Printf("๐น SERVER DATA: First 16 bytes: %x", buffer[:min(16, nr)])
} else {
// This is likely application data
log.Printf("๐น SERVER DATA: Target->Client application data: %d bytes", nr)
}
}
}
// Write to client with better error handling
clientConn.SetWriteDeadline(time.Now().Add(10 * time.Second))
nw, err := clientConn.Write(buffer[:nr])
clientConn.SetWriteDeadline(time.Time{})
if err != nil {
if strings.Contains(err.Error(), "broken pipe") ||
strings.Contains(err.Error(), "use of closed") {
log.Printf("โน๏ธ Client connection closed, stopping relay gracefully")
return
}
log.Printf("โ Server side: Target->Client relay error writing: %v", err)
break
}
if nw != nr {
log.Printf("โ ๏ธ Server side: Short write to client %d/%d bytes", nw, nr)
} else {
log.Printf("โ
Server side: Target->Client: Successfully forwarded %d bytes", nw)
}
totalBytes += int64(nw)
}
}
log.Printf("๐น Server side: Target->Client relay finished: %d bytes total", totalBytes)