-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
1925 lines (1770 loc) · 68.6 KB
/
server.go
File metadata and controls
1925 lines (1770 loc) · 68.6 KB
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
package proxy
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nemirovsky/sluice/internal/audit"
"github.com/nemirovsky/sluice/internal/channel"
"github.com/nemirovsky/sluice/internal/policy"
"github.com/nemirovsky/sluice/internal/store"
"github.com/nemirovsky/sluice/internal/vault"
"github.com/things-go/go-socks5"
"github.com/things-go/go-socks5/statute"
)
// dnsTimeout bounds how long a single DNS lookup can block. The go-socks5
// library passes context.Background() into the resolver, so we cannot rely
// on external cancellation. This timeout prevents a stuck system resolver
// from holding a request goroutine indefinitely.
const dnsTimeout = 10 * time.Second
// connectTimeout bounds how long a single outbound TCP connect can block.
// Without this, a client can point the proxy at a black-holed IP and hold
// a goroutine/socket until the kernel TCP timeout expires (typically 2+
// minutes on Linux). This limits the resource impact of such requests.
const connectTimeout = 30 * time.Second
// byteDetectTimeout is how long to wait for the client's first bytes during
// byte-level protocol detection on non-standard ports. Kept short to minimize
// latency for server-first protocols where the client never sends first.
const byteDetectTimeout = 200 * time.Millisecond
// Config holds configuration for creating a new SOCKS5 proxy server.
type Config struct {
ListenAddr string
Policy *policy.Engine
Audit *audit.FileLogger
Broker *channel.Broker
Provider vault.Provider // nil = no credential injection
Resolver *vault.BindingResolver // nil = no credential injection
VaultDir string // CA cert storage dir (defaults to ~/.sluice)
Store *store.Store // nil = in-memory only (no persistence)
WSBlockRules []WSBlockRuleConfig // WebSocket content deny rules
WSRedactRules []WSRedactRuleConfig // WebSocket content redact rules
QUICBlockRules []QUICBlockRuleConfig // QUIC/HTTP3 content deny rules
QUICRedactRules []QUICRedactRuleConfig // QUIC/HTTP3 content redact rules
DNSResolver string // upstream DNS resolver for intercepted queries (default: 8.8.8.8:53)
SelfBypass []string // host:port addresses to auto-allow without policy evaluation (sluice's own listeners)
}
// Server wraps a SOCKS5 server with policy enforcement and audit logging.
type Server struct {
listener net.Listener
socks *socks5.Server
rules *policyRuleSet
dnsResolver *policyResolver
injector *Injector
injectorLn net.Listener
sshJump *SSHJumpHost
mailProxy *MailProxy
udpRelay *UDPRelay
dnsInterceptor *DNSInterceptor
quicProxy *QUICProxy
resolver atomic.Pointer[vault.BindingResolver]
closed atomic.Bool
serving atomic.Bool
activeConns sync.WaitGroup
}
type contextKey string
const (
ctxKeyProtocol contextKey = "protocol"
ctxKeyEngine contextKey = "engine"
ctxKeyFallbackAddrs contextKey = "fallbackAddrs"
ctxKeyFQDN contextKey = "fqdn"
ctxKeySNIDeferred contextKey = "sniDeferred" // true when policy check deferred for SNI peeking
)
// ProtocolFromContext retrieves the detected protocol from the request context.
func ProtocolFromContext(ctx context.Context) Protocol {
if v, ok := ctx.Value(ctxKeyProtocol).(Protocol); ok {
return v
}
return ProtoGeneric
}
// isPrivateIP checks whether an IP is in a private, loopback, link-local,
// or unspecified range. These addresses should not be reachable via DNS
// rebinding of allow-listed hostnames unless explicitly allowed by policy.
func isPrivateIP(ip net.IP) bool {
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() ||
ip.IsLinkLocalMulticast() || ip.IsUnspecified()
}
// isTLSPort returns true for ports that typically carry TLS traffic.
func isTLSPort(port int) bool {
switch port {
case 443, 8443, 993, 995, 465:
return true
default:
return false
}
}
// policyResolver performs DNS resolution only for destinations that could be
// allowed by policy. Definitely-denied destinations return nil IP (no DNS
// lookup) to prevent leaks. For potentially-allowed destinations, DNS failures
// return an error so go-socks5 sends a hostUnreachable reply instead of the
// ruleFailure that would result from failing inside Allow().
type policyResolver struct {
engine *atomic.Pointer[policy.Engine]
audit *audit.FileLogger
broker *channel.Broker
}
func (r *policyResolver) Resolve(ctx context.Context, name string) (context.Context, net.IP, error) {
dest := strings.TrimRight(name, ".")
eng := r.engine.Load()
// Store engine snapshot in context so Allow() evaluates against the
// same policy version, preventing a SIGHUP reload from splitting a
// single request across two different policy snapshots.
ctx = context.WithValue(ctx, ctxKeyEngine, eng)
// Only treat Ask rules as potentially-allowed when an approval broker
// is configured. Without a broker, Ask verdicts become Deny, so
// resolving DNS would leak queries for destinations that will be denied.
includeAsk := r.broker != nil
if !eng.CouldBeAllowed(dest, includeAsk) {
// Definitely denied on all ports: skip DNS to prevent leaks.
// Allow() will deny the connection with ruleFailure.
return ctx, nil, nil
}
// Destination might be allowed: resolve DNS. The context from
// go-socks5 is context.Background() and is never cancelled, so we
// add our own timeout to bound stalled system resolver lookups.
// Failures return an error so go-socks5 sends hostUnreachable
// (more accurate than ruleFailure).
dnsCtx, dnsCancel := context.WithTimeout(ctx, dnsTimeout)
defer dnsCancel()
addrs, err := net.DefaultResolver.LookupIPAddr(dnsCtx, dest)
if err != nil {
log.Printf("[DENY] DNS resolution failed for %s: %v", dest, err)
if r.audit != nil {
if logErr := r.audit.Log(audit.Event{
Destination: dest,
Verdict: policy.Deny.String(),
Reason: "dns resolution failed",
}); logErr != nil {
log.Printf("audit log write error: %v", logErr)
}
}
return ctx, nil, fmt.Errorf("resolve %s: %w", dest, err)
}
if len(addrs) == 0 {
log.Printf("[DENY] DNS resolution returned no addresses for %s", dest)
if r.audit != nil {
if logErr := r.audit.Log(audit.Event{
Destination: dest,
Verdict: policy.Deny.String(),
Reason: "dns resolution failed",
}); logErr != nil {
log.Printf("audit log write error: %v", logErr)
}
}
return ctx, nil, fmt.Errorf("resolve %s: no addresses found", dest)
}
// The go-socks5 NameResolver interface returns a single IP, so we
// pass the first address and store any remaining addresses in the
// context as fallbacks. The custom Dial function tries them in order
// if the primary address is unreachable, providing resilience on
// dual-stack hosts where the preferred address family may be unusable.
// The system resolver already applies RFC 6724 destination address
// selection, so addrs[0] is the best first choice.
if len(addrs) > 1 {
fallback := make([]net.IP, len(addrs)-1)
for i, a := range addrs[1:] {
fallback[i] = a.IP
}
ctx = context.WithValue(ctx, ctxKeyFallbackAddrs, fallback)
}
return ctx, addrs[0].IP, nil
}
type policyRuleSet struct {
engine *atomic.Pointer[policy.Engine]
reloadMu *sync.Mutex // serializes engine swaps and dynamic rule mutations
audit *audit.FileLogger
broker *channel.Broker
store *store.Store
selfBypass map[string]bool // host:port addresses that bypass policy (sluice's own listeners)
dnsInterceptor *DNSInterceptor // reverse DNS cache for IP -> hostname recovery
}
func (r *policyRuleSet) Allow(ctx context.Context, req *socks5.Request) (context.Context, bool) {
// BIND is not implemented; ASSOCIATE is handled by go-socks5's built-in
// UDP relay. Return true for both so go-socks5 reaches its own handler
// instead of sending ruleFailure. Per-datagram policy enforcement for
// UDP ASSOCIATE will be added via a custom associate handler.
if req.Command != statute.CommandConnect {
return ctx, true
}
dest := req.DestAddr.FQDN
ipOnly := false // true when SOCKS5 CONNECT had no FQDN
if dest == "" {
if req.DestAddr.IP != nil {
ipStr := req.DestAddr.IP.String()
port := req.DestAddr.Port
// For TLS ports, always defer to SNI extraction (happy path).
// SNI from the TLS ClientHello is more reliable than the DNS
// reverse cache because it comes directly from the client and
// doesn't expire. DNS cache is used only for non-TLS protocols.
if isTLSPort(port) {
dest = ipStr
ipOnly = true
} else if r.dnsInterceptor != nil {
if hostname := r.dnsInterceptor.ReverseLookup(ipStr); hostname != "" {
dest = hostname
} else {
dest = ipStr
ipOnly = true
}
} else {
dest = ipStr
ipOnly = true
}
} else {
return ctx, false
}
}
// Strip trailing dot from FQDN to canonicalize DNS names.
// In DNS, "example.com." and "example.com" are equivalent.
// Without this, a SOCKS5 client can bypass deny rules by
// appending a dot to the hostname.
dest = strings.TrimRight(dest, ".")
port := req.DestAddr.Port
// Self-bypass: auto-allow connections to sluice's own listener
// addresses (health/MCP server) without policy evaluation. This
// prevents the agent's MCP HTTP connection from being blocked or
// triggering approval when routed through the SOCKS5 proxy.
if len(r.selfBypass) > 0 {
target := net.JoinHostPort(dest, strconv.Itoa(port))
if r.selfBypass[target] {
log.Printf("[BYPASS] %s (self)", target)
proto := DetectProtocol(port)
ctx = context.WithValue(ctx, ctxKeyProtocol, proto)
ctx = context.WithValue(ctx, ctxKeyFQDN, dest)
return ctx, true
}
}
// Use the engine snapshot from Resolve() (stored in context) to ensure
// consistent policy evaluation within a single request. For IP-based
// requests where Resolve() was not called, load fresh from the pointer.
eng, _ := ctx.Value(ctxKeyEngine).(*policy.Engine)
if eng == nil {
eng = r.engine.Load()
}
verdict := eng.Evaluate(dest, port)
// SNI deferral: when the destination is an IP with no DNS reverse cache
// hit and the port is typically TLS, defer the policy check to the custom
// connect handler which will peek the TLS ClientHello for SNI. This lets
// hostname-based allow rules match even when tun2proxy sends raw IPs.
if ipOnly && verdict != policy.Allow && verdict != policy.Deny && isTLSPort(port) {
log.Printf("[SNI-DEFER] %s:%d (deferring policy for SNI peek)", dest, port)
proto := DetectProtocol(port)
ctx = context.WithValue(ctx, ctxKeyProtocol, proto)
ctx = context.WithValue(ctx, ctxKeyFQDN, dest)
ctx = context.WithValue(ctx, ctxKeySNIDeferred, true)
ctx = context.WithValue(ctx, ctxKeyEngine, eng)
return ctx, true
}
// Determine the effective outcome.
allowed := false
effectiveVerdict := verdict
var reason string
switch verdict {
case policy.Allow:
allowed = true
case policy.Ask:
if r.broker == nil {
effectiveVerdict = policy.Deny
reason = "ask treated as deny (no approval broker)"
log.Printf("[ASK->DENY] %s:%d (no approval broker)", dest, port)
} else {
log.Printf("[ASK] %s:%d (waiting for Telegram approval)", dest, port)
timeout := time.Duration(eng.TimeoutSec) * time.Second
proto := DetectProtocol(port)
resp, err := r.broker.Request(dest, port, proto.String(), timeout)
if err != nil {
effectiveVerdict = policy.Deny
reason = fmt.Sprintf("approval timeout: %v", err)
log.Printf("[ASK->DENY] %s:%d (timeout: %v)", dest, port, err)
} else {
switch resp {
case channel.ResponseAllowOnce:
allowed = true
effectiveVerdict = policy.Allow
reason = "user approved once"
log.Printf("[ASK->ALLOW] %s:%d (user approved once)", dest, port)
case channel.ResponseAlwaysAllow:
allowed = true
effectiveVerdict = policy.Allow
reason = "user approved always"
log.Printf("[ASK->ALLOW+SAVE] %s:%d (user approved always)", dest, port)
// Hold reloadMu to prevent a concurrent SIGHUP from swapping
// the engine between the store write and recompile.
r.reloadMu.Lock()
func() {
defer r.reloadMu.Unlock()
if r.store != nil {
if _, storeErr := r.store.AddRule("allow", store.RuleOpts{Destination: dest, Ports: []int{port}, Source: "approval"}); storeErr != nil {
log.Printf("[WARN] failed to persist allow rule for %s:%d: %v", dest, port, storeErr)
}
if newEng, recompErr := policy.LoadFromStore(r.store); recompErr != nil {
log.Printf("[WARN] failed to recompile engine after always-allow: %v", recompErr)
} else if valErr := newEng.Validate(); valErr != nil {
log.Printf("[WARN] engine validation failed after always-allow: %v", valErr)
} else {
r.engine.Store(newEng)
}
} else {
if err := r.engine.Load().AddDynamicAllow(dest, port); err != nil { //nolint:staticcheck // backward compat fallback when no store
log.Printf("[WARN] failed to add dynamic allow rule for %s:%d: %v", dest, port, err)
}
}
}()
case channel.ResponseAlwaysDeny:
effectiveVerdict = policy.Deny
reason = "user denied always"
log.Printf("[ASK->DENY+SAVE] %s:%d (user denied always)", dest, port)
r.reloadMu.Lock()
func() {
defer r.reloadMu.Unlock()
if r.store != nil {
if _, storeErr := r.store.AddRule("deny", store.RuleOpts{Destination: dest, Ports: []int{port}, Source: "approval"}); storeErr != nil {
log.Printf("[WARN] failed to persist deny rule for %s:%d: %v", dest, port, storeErr)
}
if newEng, recompErr := policy.LoadFromStore(r.store); recompErr != nil {
log.Printf("[WARN] failed to recompile engine after always-deny: %v", recompErr)
} else if valErr := newEng.Validate(); valErr != nil {
log.Printf("[WARN] engine validation failed after always-deny: %v", valErr)
} else {
r.engine.Store(newEng)
}
}
}()
default:
effectiveVerdict = policy.Deny
reason = "user denied"
log.Printf("[ASK->DENY] %s:%d (user denied)", dest, port)
}
}
}
}
// DNS rebinding check for FQDN connections. The policyResolver
// already resolved the IP, so we verify it is not restricted.
if allowed && req.DestAddr.FQDN != "" && req.DestAddr.IP != nil {
resolvedIP := req.DestAddr.IP.String()
if eng.IsRestricted(resolvedIP, port) {
allowed = false
effectiveVerdict = policy.Deny
reason = fmt.Sprintf("resolved IP %s is restricted", resolvedIP)
log.Printf("[DENY] %s resolved to restricted IP %s", req.DestAddr.FQDN, resolvedIP)
} else if isPrivateIP(req.DestAddr.IP) && eng.Evaluate(resolvedIP, port) != policy.Allow {
allowed = false
effectiveVerdict = policy.Deny
reason = fmt.Sprintf("resolved IP %s is private and not allowed by policy", resolvedIP)
log.Printf("[DENY] %s resolved to private IP %s (DNS rebinding protection)", req.DestAddr.FQDN, resolvedIP)
}
}
// Filter fallback addresses through the same rebinding/policy checks
// so the Dial function only tries addresses that would be allowed.
if allowed && req.DestAddr.FQDN != "" {
if fallbacks, ok := ctx.Value(ctxKeyFallbackAddrs).([]net.IP); ok {
approved := make([]net.IP, 0, len(fallbacks))
for _, ip := range fallbacks {
ipStr := ip.String()
if eng.IsRestricted(ipStr, port) {
continue
}
if isPrivateIP(ip) && eng.Evaluate(ipStr, port) != policy.Allow {
continue
}
approved = append(approved, ip)
}
ctx = context.WithValue(ctx, ctxKeyFallbackAddrs, approved)
}
}
// Single audit entry reflecting the final outcome.
if r.audit != nil {
if err := r.audit.Log(audit.Event{
Destination: dest,
Port: port,
Verdict: effectiveVerdict.String(),
Reason: reason,
}); err != nil {
log.Printf("audit log write error: %v", err)
}
}
if allowed {
proto := DetectProtocol(port)
ctx = context.WithValue(ctx, ctxKeyProtocol, proto)
ctx = context.WithValue(ctx, ctxKeyFQDN, dest)
}
return ctx, allowed
}
// New creates a new SOCKS5 proxy server bound to the configured listen address.
func New(cfg Config) (*Server, error) {
if cfg.Policy == nil {
return nil, fmt.Errorf("policy engine is required")
}
ln, err := net.Listen("tcp", cfg.ListenAddr)
if err != nil {
return nil, fmt.Errorf("listen: %w", err)
}
srv := &Server{listener: ln}
// Initialize credential injection handlers when a vault provider is
// configured. The resolver may be nil at startup (no bindings yet) and
// set later via StoreResolver after SIGHUP or Telegram mutations.
if cfg.Resolver != nil {
srv.resolver.Store(cfg.Resolver)
}
if cfg.Provider != nil {
injErr := srv.setupInjection(cfg, ln)
if injErr != nil {
// When bindings exist (resolver is set), injection infrastructure
// is required. Hard-fail so the operator fixes the issue.
if cfg.Resolver != nil {
_ = ln.Close()
return nil, injErr
}
// No bindings yet. Degrade to policy-only mode so network
// governance still works. Injection can be enabled by fixing
// the underlying issue (e.g. CA dir permissions) and restarting.
log.Printf("credential injection disabled (no bindings): %v", injErr)
}
}
enginePtr := new(atomic.Pointer[policy.Engine])
enginePtr.Store(cfg.Policy)
reloadMu := new(sync.Mutex)
var bypassSet map[string]bool
if len(cfg.SelfBypass) > 0 {
bypassSet = make(map[string]bool, len(cfg.SelfBypass))
for _, addr := range cfg.SelfBypass {
bypassSet[addr] = true
}
}
// Create UDP relay and DNS interceptor for UDP ASSOCIATE sessions.
srv.udpRelay = NewUDPRelay(enginePtr, cfg.Audit)
srv.dnsInterceptor = NewDNSInterceptor(enginePtr, cfg.Audit, cfg.DNSResolver)
rules := &policyRuleSet{engine: enginePtr, reloadMu: reloadMu, audit: cfg.Audit, broker: cfg.Broker, store: cfg.Store, selfBypass: bypassSet, dnsInterceptor: srv.dnsInterceptor}
dnsRes := &policyResolver{engine: enginePtr, audit: cfg.Audit, broker: cfg.Broker}
srv.rules = rules
srv.dnsResolver = dnsRes
srv.socks = socks5.NewServer(
socks5.WithRule(rules),
socks5.WithResolver(dnsRes),
socks5.WithDial(srv.dial),
socks5.WithConnectHandle(srv.handleConnect),
socks5.WithAssociateHandle(srv.handleAssociate),
)
return srv, nil
}
// setupInjection initializes the credential injection infrastructure (HTTPS
// MITM, SSH jump host, mail proxy). Returns an error if any component fails.
// The caller decides whether the error is fatal based on whether bindings exist.
func (s *Server) setupInjection(cfg Config, _ net.Listener) error {
vaultDir := cfg.VaultDir
if vaultDir == "" {
home, homeErr := os.UserHomeDir()
if homeErr != nil {
return fmt.Errorf("determine home dir for CA: %w", homeErr)
}
vaultDir = filepath.Join(home, ".sluice")
}
caCert, _, caErr := LoadOrCreateCA(vaultDir)
if caErr != nil {
return fmt.Errorf("load CA: %w", caErr)
}
certPath := filepath.Join(vaultDir, "ca-cert.pem")
if expiring, expiryErr := IsCACertExpiring(certPath, 30*24*time.Hour); expiryErr == nil && expiring {
log.Printf("WARNING: CA certificate at %s expires within 30 days. Delete and restart to regenerate.", certPath)
}
// Generate a random auth token so only our SOCKS5 dial function
// can use the injector listener. Without this, any local process
// that discovers the port could bypass policy and audit logging.
tokenBytes := make([]byte, 16)
if _, tokenErr := rand.Read(tokenBytes); tokenErr != nil {
return fmt.Errorf("generate injector auth token: %w", tokenErr)
}
authToken := hex.EncodeToString(tokenBytes)
// Create WebSocket proxy for frame-level inspection when configured.
var wsProxy *WSProxy
if len(cfg.WSBlockRules) > 0 || len(cfg.WSRedactRules) > 0 {
var wsErr error
wsProxy, wsErr = NewWSProxy(cfg.Provider, &s.resolver, cfg.WSBlockRules, cfg.WSRedactRules)
if wsErr != nil {
return fmt.Errorf("create ws proxy: %w", wsErr)
}
} else {
// Create WSProxy with empty rules for phantom token replacement.
wsProxy, _ = NewWSProxy(cfg.Provider, &s.resolver, nil, nil)
}
s.injector = NewInjector(cfg.Provider, &s.resolver, caCert, authToken, wsProxy)
// Populate the OAuth token URL index from credential metadata so
// the response handler can detect OAuth token endpoints from startup.
if cfg.Store != nil {
if metas, metaErr := cfg.Store.ListCredentialMeta(); metaErr == nil {
s.injector.UpdateOAuthIndex(metas)
} else {
log.Printf("[INJECT-OAUTH] failed to load credential meta for index: %v", metaErr)
}
}
injLn, injErr := net.Listen("tcp", "127.0.0.1:0")
if injErr != nil {
return fmt.Errorf("injector listener: %w", injErr)
}
s.injectorLn = injLn
go http.Serve(injLn, s.injector.Proxy) //nolint:errcheck // best-effort
// SSH jump host for credential-injected SSH connections.
hostKey, hkErr := GenerateSSHHostKey()
if hkErr != nil {
_ = injLn.Close()
s.injectorLn = nil
s.injector = nil
return fmt.Errorf("generate SSH host key: %w", hkErr)
}
s.sshJump = NewSSHJumpHost(cfg.Provider, hostKey)
// Mail proxy for IMAP/SMTP credential injection. Pass the CA cert
// so implicit TLS ports (993, 465) can be handled via TLS MITM.
s.mailProxy = NewMailProxy(cfg.Provider, &caCert)
// QUIC proxy for HTTP/3 MITM credential injection over UDP.
qp, qpErr := NewQUICProxy(caCert, cfg.Provider, &s.resolver, cfg.Audit, cfg.QUICBlockRules, cfg.QUICRedactRules)
if qpErr != nil {
log.Printf("QUIC proxy disabled: %v", qpErr)
} else {
s.quicProxy = qp
go func() {
if listenErr := qp.ListenAndServe("127.0.0.1:0"); listenErr != nil {
log.Printf("[QUIC] listener stopped: %v", listenErr)
}
}()
}
log.Printf("credential injection enabled (%s)", cfg.Provider.Name())
return nil
}
// bindingIsMetaOnly returns true when all protocols in the binding are
// meta-protocols (tcp/udp). A meta-protocol binding matches a family of
// specific protocols rather than identifying one, so the ResolveProtocolHint
// fast path should still be attempted to find a more specific binding.
func bindingIsMetaOnly(b vault.Binding) bool {
if len(b.Protocols) == 0 {
return false
}
for _, p := range b.Protocols {
if !vault.IsMetaProtocol(p) {
return false
}
}
return true
}
// dial is the custom dialer for go-socks5. When a credential binding matches
// the destination, the connection is routed through the appropriate injection
// handler (HTTPS MITM, SSH jump host, or mail proxy). Otherwise it falls
// through to a direct TCP connection with DNS fallback support.
func (s *Server) dial(ctx context.Context, network, addr string) (net.Conn, error) {
if r := s.resolver.Load(); r != nil {
fqdn, _ := ctx.Value(ctxKeyFQDN).(string)
if fqdn != "" {
_, portStr, _ := net.SplitHostPort(addr)
port, _ := strconv.Atoi(portStr)
proto := ProtocolFromContext(ctx)
// Use protocol-aware resolution so the correct binding is
// selected when multiple bindings exist for the same host:port
// with different protocols (e.g. one for SSH, one for HTTPS).
binding, ok := r.ResolveForProtocol(fqdn, port, proto.String())
if !ok {
// No protocol-specific or protocol-agnostic binding
// matched. Fall back to any dest+port binding and adopt
// its protocol when unambiguous. ResolveProtocolHint
// scans ALL bindings for this dest+port and returns false
// when multiple single-protocol bindings disagree,
// preventing order-dependent protocol selection.
binding, ok = r.Resolve(fqdn, port)
if ok && len(binding.Protocols) == 1 {
if hint, hok := r.ResolveProtocolHint(fqdn, port); hok {
if parsed, perr := ParseProtocol(hint); perr == nil {
proto = parsed
}
}
}
}
// When protocol is still generic (non-standard port) and
// resolution returned a protocol-agnostic or meta-protocol
// binding, check if a specific-protocol binding exists for
// this dest+port. Without this, the agnostic/meta fallback
// from ResolveForProtocol masks protocol-specific bindings
// and the connection falls through to the timeout-sensitive
// byte-detection path instead of using the fast hint path.
if ok && proto == ProtoGeneric && (len(binding.Protocols) == 0 || bindingIsMetaOnly(binding)) {
if hint, hok := r.ResolveProtocolHint(fqdn, port); hok {
if parsed, perr := ParseProtocol(hint); perr == nil {
proto = parsed
}
if specific, sok := r.ResolveForProtocol(fqdn, port, hint); sok {
binding = specific
}
}
}
if ok {
// hostAddr uses the FQDN for TLS SNI and SSH known_hosts
// verification. addr (the go-socks5 dial target) uses the
// policy-approved resolved IP for the actual TCP connection,
// preventing DNS rebinding between policy evaluation and dial.
hostAddr := net.JoinHostPort(fqdn, portStr)
// Build address list from primary + policy-approved fallbacks
// so injection handlers have the same dual-stack resilience
// as the non-injected direct connection path.
dialAddrs := []string{addr}
if fallbacks, ok := ctx.Value(ctxKeyFallbackAddrs).([]net.IP); ok {
for _, ip := range fallbacks {
dialAddrs = append(dialAddrs, net.JoinHostPort(ip.String(), portStr))
}
}
switch proto {
case ProtoHTTP, ProtoHTTPS:
if s.injector != nil {
// Pin the policy-approved IPs so goproxy's
// transport dials them instead of re-resolving.
// Each connection gets a unique pin ID to avoid
// races between concurrent same-host connections.
ips := make([]string, len(dialAddrs))
for i, a := range dialAddrs {
ip, _, _ := net.SplitHostPort(a)
ips[i] = ip
}
pinID := generatePinID()
s.injector.PinIPs(pinID, ips)
conn, err := dialThroughInjector(s.injectorLn.Addr().String(), fqdn, port, s.injector.authToken, pinID)
if err != nil {
s.injector.UnpinIPs(pinID)
return nil, err
}
return &pinnedConn{Conn: conn, injector: s.injector, pinID: pinID}, nil
}
case ProtoSSH:
if s.sshJump != nil {
return dialWithHandler(func(agentConn net.Conn, ready chan<- error) {
if err := s.sshJump.HandleConnection(agentConn, dialAddrs, hostAddr, binding, ready); err != nil {
log.Printf("[SSH] handler error: %v", err)
}
})
}
case ProtoIMAP, ProtoSMTP:
if s.mailProxy != nil {
return dialWithHandler(func(agentConn net.Conn, ready chan<- error) {
if err := s.mailProxy.HandleConnection(agentConn, dialAddrs, hostAddr, binding, proto, ready); err != nil {
log.Printf("[MAIL] handler error: %v", err)
}
})
}
}
// Non-standard port with binding: use byte-level detection
// to determine the correct injection handler. Port-based
// detection returned ProtoGeneric (or ProtoTCP from a
// binding hint), so peek the client's first bytes to
// identify the actual protocol.
if proto == ProtoGeneric || proto == ProtoTCP {
bnd := binding // capture for closure
return dialWithHandler(func(agentConn net.Conn, ready chan<- error) {
s.handleWithDetection(agentConn, ready, &bnd, fqdn, port, hostAddr, dialAddrs)
})
}
}
}
}
// Route unbound HTTP/HTTPS through the injector when available so
// phantom tokens are stripped from requests to hosts without bindings.
// Without this, requests bypassing the binding-match block above
// would go direct and leak SLUICE_PHANTOM:* tokens upstream.
if s.injector != nil {
_, portStr, _ := net.SplitHostPort(addr)
port, _ := strconv.Atoi(portStr)
proto := DetectProtocol(port)
switch proto {
case ProtoHTTP, ProtoHTTPS:
fqdn, _ := ctx.Value(ctxKeyFQDN).(string)
if fqdn == "" {
host, _, _ := net.SplitHostPort(addr)
fqdn = host
}
ips := []string{}
if ip, _, err := net.SplitHostPort(addr); err == nil {
ips = append(ips, ip)
}
if fallbacks, ok := ctx.Value(ctxKeyFallbackAddrs).([]net.IP); ok {
for _, ip := range fallbacks {
ips = append(ips, ip.String())
}
}
pinID := generatePinID()
s.injector.PinIPs(pinID, ips)
conn, err := dialThroughInjector(s.injectorLn.Addr().String(), fqdn, port, s.injector.authToken, pinID)
if err != nil {
s.injector.UnpinIPs(pinID)
// Fall through to direct connection below.
} else {
return &pinnedConn{Conn: conn, injector: s.injector, pinID: pinID}, nil
}
case ProtoGeneric:
// Non-standard port without binding: use byte-level
// detection to catch HTTPS/HTTP for phantom stripping.
fqdn, _ := ctx.Value(ctxKeyFQDN).(string)
if fqdn == "" {
host, _, _ := net.SplitHostPort(addr)
fqdn = host
}
unboundAddrs := []string{addr}
if fallbacks, ok := ctx.Value(ctxKeyFallbackAddrs).([]net.IP); ok {
for _, ip := range fallbacks {
unboundAddrs = append(unboundAddrs, net.JoinHostPort(ip.String(), portStr))
}
}
hostAddr := net.JoinHostPort(fqdn, portStr)
return dialWithHandler(func(agentConn net.Conn, ready chan<- error) {
s.handleWithDetection(agentConn, ready, nil, fqdn, port, hostAddr, unboundAddrs)
})
}
}
// No credential binding or unsupported protocol: direct connection.
d := &net.Dialer{Timeout: connectTimeout}
conn, err := d.DialContext(ctx, network, addr)
if err == nil {
return conn, nil
}
// Try policy-approved fallback addresses from DNS resolution.
fallbacks, _ := ctx.Value(ctxKeyFallbackAddrs).([]net.IP)
if len(fallbacks) == 0 {
return nil, err
}
_, portStr, splitErr := net.SplitHostPort(addr)
if splitErr != nil {
return nil, err
}
for _, ip := range fallbacks {
fbAddr := net.JoinHostPort(ip.String(), portStr)
if fbConn, fbErr := d.DialContext(ctx, network, fbAddr); fbErr == nil {
return fbConn, nil
}
}
return nil, err
}
// handleWithDetection peeks the agent's first bytes to detect the protocol
// and routes through the appropriate injection handler. Used for connections
// on non-standard ports where port-based detection returned ProtoGeneric.
// The binding parameter is nil for unbound connections (phantom stripping only).
func (s *Server) handleWithDetection(
agentConn net.Conn,
ready chan<- error,
binding *vault.Binding,
fqdn string,
port int,
hostAddr string,
dialAddrs []string,
) {
defer func() { _ = agentConn.Close() }()
// Signal ready immediately: byte detection requires reading client
// data, which only arrives after the SOCKS5 CONNECT succeeds. Any
// handler failures after this point close the connection, surfacing
// as an application-layer error rather than a SOCKS5 failure.
ready <- nil
// Read first bytes with a deadline. For client-first protocols (TLS,
// SSH, HTTP), data arrives quickly. For server-first or idle
// connections, the deadline fires and we fall through to direct relay.
peekBuf := make([]byte, 4)
_ = agentConn.SetReadDeadline(time.Now().Add(byteDetectTimeout))
n, _ := io.ReadFull(agentConn, peekBuf)
_ = agentConn.SetReadDeadline(time.Time{})
proto := DetectFromClientBytes(peekBuf[:n])
// Replay peeked bytes before the rest of the stream.
var peekReader io.Reader = agentConn
if n > 0 {
peekReader = io.MultiReader(bytes.NewReader(peekBuf[:n]), agentConn)
}
peekConn := &bufferedConn{Reader: peekReader, Conn: agentConn}
if proto != ProtoGeneric {
log.Printf("[DETECT] %s byte detection -> %s", hostAddr, proto)
}
// Re-resolve binding with detected protocol: the initial resolution in
// dial() used "generic" (non-standard port), so a meta-protocol binding
// (e.g. protocols=["tcp"]) may have been selected over a more specific
// one (e.g. protocols=["ssh"]). Now that byte detection revealed the
// actual protocol, re-resolve to pick the most specific binding.
if proto != ProtoGeneric && binding != nil {
if r := s.resolver.Load(); r != nil {
if specific, ok := r.ResolveForProtocol(fqdn, port, proto.String()); ok {
binding = &specific
}
}
}
switch proto {
case ProtoHTTPS, ProtoHTTP:
if s.injector != nil {
ips := make([]string, 0, len(dialAddrs))
for _, a := range dialAddrs {
if ip, _, err := net.SplitHostPort(a); err == nil {
ips = append(ips, ip)
}
}
pinID := generatePinID()
s.injector.PinIPs(pinID, ips)
defer s.injector.UnpinIPs(pinID)
injConn, err := dialThroughInjector(s.injectorLn.Addr().String(), fqdn, port, s.injector.authToken, pinID)
if err != nil {
log.Printf("[DETECT] injector failed for %s: %v", hostAddr, err)
if binding != nil {
// Fail closed for bound connections: credential
// injection is required and phantom tokens must not
// leak upstream. Unlike the standard bound path
// (which returns an error before CONNECT succeeds),
// the detection path has already signaled ready, so
// this drops the connection at the application layer.
return
}
relayDirect(peekConn, dialAddrs)
return
}
bidirectionalRelay(peekConn, injConn)
return
}
case ProtoSSH:
if s.sshJump != nil && binding != nil {
// Pass nil for ready: SOCKS5 CONNECT already succeeded (see
// comment above), so the handler's readiness signal is unused.
// Both HandleConnection implementations guard with
// "if ready != nil" before sending.
if err := s.sshJump.HandleConnection(peekConn, dialAddrs, hostAddr, *binding, nil); err != nil {
log.Printf("[SSH] handler error for %s: %v", hostAddr, err)
}
return
}
case ProtoIMAP, ProtoSMTP:
if s.mailProxy != nil && binding != nil {
if err := s.mailProxy.HandleConnection(peekConn, dialAddrs, hostAddr, *binding, proto, nil); err != nil {
log.Printf("[MAIL] handler error for %s: %v", hostAddr, err)
}
return
}
}
// Server-first detection: when no client bytes arrived (timeout),
// the remote might be a server-first protocol (SMTP, IMAP). Connect
// upstream and peek the server's first bytes to find out. Only attempt
// this when a binding and mail proxy exist, since server-first detection
// can only route through the mail proxy and the upstream probe is wasted
// without a binding to inject.
if n == 0 && binding != nil && s.mailProxy != nil {
s.handleServerFirstDetection(peekConn, binding, hostAddr, dialAddrs)
return
}
relayDirect(peekConn, dialAddrs)
}
// serverDetectTimeout bounds how long to wait for the server's first bytes
// during server-first protocol detection (SMTP banner, IMAP greeting).
const serverDetectTimeout = 500 * time.Millisecond
// handleServerFirstDetection connects upstream and peeks the server's first
// bytes to detect server-first protocols (SMTP, IMAP). If a match is found
// and a binding exists, the connection is routed through the mail proxy.
// Otherwise, the server's pre-read bytes are relayed and the connection
// continues as a direct relay.
func (s *Server) handleServerFirstDetection(
agentConn net.Conn,
binding *vault.Binding,
hostAddr string,
dialAddrs []string,
) {
d := &net.Dialer{Timeout: connectTimeout}
var upstream net.Conn
var err error
for _, addr := range dialAddrs {
upstream, err = d.Dial("tcp", addr)
if err == nil {
break
}
}
if err != nil {
log.Printf("[DETECT] server-first upstream dial failed for %s: %v", hostAddr, err)
return
}
// Peek server's first bytes with a short deadline.
serverBuf := make([]byte, 8)
_ = upstream.SetReadDeadline(time.Now().Add(serverDetectTimeout))
sn, _ := io.ReadFull(upstream, serverBuf)
_ = upstream.SetReadDeadline(time.Time{})
serverProto := DetectFromServerBytes(serverBuf[:sn])
if serverProto != ProtoGeneric {
log.Printf("[DETECT] %s server byte detection -> %s", hostAddr, serverProto)
}
// Re-resolve binding with detected server protocol (same rationale as
// the client-byte re-resolution in handleWithDetection).
if serverProto != ProtoGeneric && binding != nil {
if r := s.resolver.Load(); r != nil {
if host, portStr, err := net.SplitHostPort(hostAddr); err == nil {
if p, err := strconv.Atoi(portStr); err == nil {
if specific, ok := r.ResolveForProtocol(host, p, serverProto.String()); ok {
binding = &specific
}
}
}
}
}
if (serverProto == ProtoIMAP || serverProto == ProtoSMTP) && s.mailProxy != nil && binding != nil {
// Close probe connection. The mail proxy establishes its own
// upstream connection to manage STARTTLS and AUTH interception.
_ = upstream.Close()
// Pass nil for ready: SOCKS5 CONNECT already succeeded in the
// parent handleWithDetection call.
if err := s.mailProxy.HandleConnection(agentConn, dialAddrs, hostAddr, *binding, serverProto, nil); err != nil {
log.Printf("[MAIL] handler error for %s: %v", hostAddr, err)
}
return
}
// No server-first protocol match or no mail proxy/binding available.
// Relay with pre-read server bytes prepended to the upstream stream.
var upstreamReader io.Reader = upstream
if sn > 0 {
upstreamReader = io.MultiReader(bytes.NewReader(serverBuf[:sn]), upstream)
}
upConn := &bufferedConn{Reader: upstreamReader, Conn: upstream}