From 68e214c438d949e1fcae7f464e933f620f52207d Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:12:19 +0100 Subject: [PATCH] feat(traffic): add opt-in RFC 1928 SOCKS5 UDP ASSOCIATE relay with per-datagram policy --- intercept/target_dial.go | 140 +++++++++++- server/manager.go | 3 + traffic/socks5.go | 172 +++++++++++---- traffic/socks5_udp.go | 444 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 716 insertions(+), 43 deletions(-) create mode 100644 traffic/socks5_udp.go diff --git a/intercept/target_dial.go b/intercept/target_dial.go index 62007db..850b797 100644 --- a/intercept/target_dial.go +++ b/intercept/target_dial.go @@ -116,9 +116,9 @@ func (i *Interceptor) dialTarget(ctx context.Context, scope TargetScope, toolNam // the URL. func addrTarget(network, addr string) (Target, error) { switch network { - case "tcp", "tcp4", "tcp6": + case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6": default: - return Target{}, fmt.Errorf("network %q is not tcp", network) + return Target{}, fmt.Errorf("network %q is not tcp or udp", network) } host, port, err := net.SplitHostPort(addr) if err != nil { @@ -237,3 +237,139 @@ func (i *Interceptor) DialSOCKS5(ctx context.Context, network, addr string) (net } return i.dialAddrs(ctx, network, ct.ips, t.Port) } + +// PinnedUDP4Resolver returns a per-datagram IPv4 destination resolver that +// enforces the platform's target gate identically to PinnedDialer. When scoped +// is true, a missing or incomplete TargetScope fails closed with +// TARGET_GATE_UNAVAILABLE. +func PinnedUDP4Resolver(toolName string, scoped bool) func(ctx context.Context, addr string) (*net.UDPAddr, error) { + return func(ctx context.Context, addr string) (*net.UDPAddr, error) { + scope, ok := TargetScopeFromContext(ctx) + switch { + case !ok && scoped: + return nil, &dialError{code: TargetGateUnavailable, target: addr, reason: "the target scope of the session did not reach the connection"} + case !ok: + return resolvePlainUDP4(ctx, addr) + case scope.Enabled == nil || !scope.Enabled(): + if scope.Interceptor != nil { + return scope.Interceptor.ResolveUDP4(ctx, addr) + } + return resolvePlainUDP4(ctx, addr) + case scope.Interceptor == nil: + return nil, &dialError{code: TargetGateUnavailable, target: addr, reason: "the session's target scope carries no gate"} + } + return scope.Interceptor.resolveTargetUDP4(ctx, scope, toolName, addr) + } +} + +// ResolveUDP4 enforces the platform's target gate before forwarding a SOCKS5 +// UDP ASSOCIATE datagram, reusing the exact same asset block rules, fresh DNS +// resolution, and TargetScope pin/exemption logic as DialSOCKS5 / PinnedDialer. +// Returns the first verified IPv4 *net.UDPAddr. +func (i *Interceptor) ResolveUDP4(ctx context.Context, addr string) (*net.UDPAddr, error) { + if i == nil { + return resolvePlainUDP4(ctx, addr) + } + if scope, ok := TargetScopeFromContext(ctx); ok && scope.Enabled != nil && scope.Enabled() { + return i.resolveTargetUDP4(ctx, scope, "socks5-udp", addr) + } + t, err := addrTarget("udp4", addr) + if err != nil { + return nil, &dialError{code: TargetGateUnavailable, target: addr, reason: "the address of the datagram could not be read (" + err.Error() + ")"} + } + if i.targets == nil { + return resolvePlainUDP4(ctx, addr) + } + rules, err := i.targets.BlockRules(db.TargetScopeRef{}) + if err != nil { + return nil, &dialError{code: TargetGateUnavailable, target: t.String(), reason: "the asset rules could not be read: " + err.Error()} + } + ct := &checkedTarget{Target: t} + if t.Kind != TargetDomain { + ct.ips, ct.resolver, ct.resolvedAt = []string{t.Host}, literalResolver, time.Now().UTC() + } + if rule, hit := blockRule(rules, ct); hit { + return nil, &dialError{code: TargetRuleBlocked, target: t.String(), reason: fmt.Sprintf("%s is blocked by an asset rule. %s", t, rule.Reason())} + } + if t.Kind == TargetDomain { + c := &targetCheck{i: i, ctx: ctx, tool: "socks5-udp", fresh: true} + c.resolve(ct, true) + if ct.err != nil { + return nil, ct.err + } + if rule, hit := blockRule(rules, ct); hit { + return nil, &dialError{code: TargetRuleBlocked, target: t.String(), reason: fmt.Sprintf("%s is blocked by an asset rule. %s", t, rule.Reason())} + } + } + return firstIPv4UDPAddr(ct.ips, t.Port) +} + +func (i *Interceptor) resolveTargetUDP4(ctx context.Context, scope TargetScope, toolName, addr string) (*net.UDPAddr, error) { + input, _ := json.Marshal(map[string]string{"udp": addr}) + ctx = WithCall(ctx, toolName, input) + t, err := addrTarget("udp4", addr) + if err != nil { + res := undeterminedTarget(ctx, scope, toolName, input, "the address of the datagram could not be read ("+err.Error()+")") + return nil, &dialError{code: res.Code, target: addr, reason: res.Reason} + } + blocked := func(res TargetResult) error { + return &dialError{code: res.Code, target: t.String(), reason: res.Reason} + } + c := &targetCheck{i: i, ctx: ctx, scope: scope, tool: toolName, input: input, fresh: true} + unpinned, res := c.run([]Target{t}) + if res.Code != "" { + return nil, blocked(res) + } + if len(unpinned) > 0 { + scope.WaitBound = 0 + res = i.RequestTargets(ctx, scope, toolName, input, unpinned, nil) + if res.Code == TargetApprovalPending { + res.Reason = notCovered(unpinned[0], scope) + } + return nil, blocked(res) + } + switch ct := c.checked[0]; ct.cover { + case coverDerived, coverNameOnly: + return resolvePlainUDP4(ctx, addr) + default: + return firstIPv4UDPAddr(ct.ips, t.Port) + } +} + +func firstIPv4UDPAddr(ips []string, port int) (*net.UDPAddr, error) { + for _, raw := range ips { + a, err := netip.ParseAddr(raw) + if err == nil && a.Is4() { + return &net.UDPAddr{IP: net.IP(a.AsSlice()), Port: port}, nil + } + } + return nil, &net.AddrError{Err: "no IPv4 address found", Addr: strings.Join(ips, ", ")} +} + +func resolvePlainUDP4(ctx context.Context, addr string) (*net.UDPAddr, error) { + host, portStr, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + port, err := strconv.Atoi(portStr) + if err != nil || port <= 0 || port > 65535 { + return nil, fmt.Errorf("invalid udp port %q", portStr) + } + if ip := net.ParseIP(strings.Trim(host, "[]")); ip != nil { + ip4 := ip.To4() + if ip4 == nil { + return nil, &net.AddrError{Err: "IPv6 UDP destination not supported", Addr: addr} + } + return &net.UDPAddr{IP: ip4, Port: port}, nil + } + ips, err := net.DefaultResolver.LookupIP(ctx, "ip4", host) + if err != nil { + return nil, err + } + for _, ip := range ips { + if ip4 := ip.To4(); ip4 != nil { + return &net.UDPAddr{IP: ip4, Port: port}, nil + } + } + return nil, &net.AddrError{Err: "no IPv4 address found", Addr: addr} +} diff --git a/server/manager.go b/server/manager.go index 47c486c..d15661b 100644 --- a/server/manager.go +++ b/server/manager.go @@ -465,8 +465,11 @@ func NewManager(dir, proxyAddr string) (*Manager, error) { m.reloadRewriteRules() // in place before the proxy accepts a connection if scfg, ok := traffic.SOCKS5ConfigFromEnv(); ok { scfg.DialContext = m.interceptor.DialSOCKS5 + scfg.ResolveUDP4 = m.interceptor.ResolveUDP4 if bound, serr := tr.StartSOCKS5(scfg); serr != nil { log.Printf("[traffic/socks5] disabled: %v", serr) + } else if scfg.EnableUDP { + log.Printf("[traffic/socks5] opt-in SOCKS5 CONNECT + UDP ASSOCIATE listener on %s", bound) } else { log.Printf("[traffic/socks5] opt-in SOCKS5 CONNECT listener on %s", bound) } diff --git a/traffic/socks5.go b/traffic/socks5.go index 5508d54..bf7aacd 100644 --- a/traffic/socks5.go +++ b/traffic/socks5.go @@ -31,15 +31,26 @@ const ( // Setting a non-empty address also enables the listener unless // ARTEX_SOCKS5_ENABLED is explicitly false/0/off/no. SOCKS5AddrEnv = "ARTEX_SOCKS5_ADDR" + // SOCKS5UDPEnabledEnv turns on RFC 1928 UDP ASSOCIATE (IPv4 first) on the + // SOCKS5 listener when set to 1/true/on/yes. Off by default: when off, + // UDP ASSOCIATE is refused with reply 0x07 and no UDP relay socket is opened. + // Setting ARTEX_SOCKS5_UDP_ENABLED=1 also enables the SOCKS5 listener on + // ARTEX_SOCKS5_ADDR (or DefaultSOCKS5Addr) unless ARTEX_SOCKS5_ENABLED is + // explicitly false/0/off/no. + SOCKS5UDPEnabledEnv = "ARTEX_SOCKS5_UDP_ENABLED" - DefaultSOCKS5Addr = "127.0.0.1:1080" - DefaultSOCKS5MaxConcurrent = 64 - DefaultSOCKS5MaxBytesPerDir = 4 * 1024 * 1024 - DefaultSOCKS5PreviewBytes = blobPreview - DefaultSOCKS5IdleTimeout = 2 * time.Minute - DefaultSOCKS5HandshakeTimeout = 10 * time.Second - DefaultSOCKS5DialTimeout = 30 * time.Second - DefaultSOCKS5PaceTimeout = paceWaitMax + DefaultSOCKS5Addr = "127.0.0.1:1080" + DefaultSOCKS5MaxConcurrent = 64 + DefaultSOCKS5MaxBytesPerDir = 4 * 1024 * 1024 + DefaultSOCKS5PreviewBytes = blobPreview + DefaultSOCKS5IdleTimeout = 2 * time.Minute + DefaultSOCKS5HandshakeTimeout = 10 * time.Second + DefaultSOCKS5DialTimeout = 30 * time.Second + DefaultSOCKS5PaceTimeout = paceWaitMax + DefaultSOCKS5UDPMaxDatagrams = 1000 + DefaultSOCKS5UDPMaxBytes = 4 * 1024 * 1024 + DefaultSOCKS5UDPIdleTimeout = 2 * time.Minute + DefaultSOCKS5UDPMaxDatagramSize = 65535 ) // RFC 1928 / RFC 1929 protocol constants. @@ -97,6 +108,24 @@ type SOCKS5Config struct { // OnRecord, when non-nil, receives each completed raw TCP capture. // When nil and attached to a Traffic store, the store's raw-TCP recorder runs. OnRecord func(RawTCPCapture) + + // EnableUDP opts into RFC 1928 UDP ASSOCIATE (IPv4 first, P4.1c). + // Off by default: when false, UDP ASSOCIATE returns 0x07. + EnableUDP bool + // UDPMaxDatagrams caps total forwarded datagrams (c2s + s2c) per UDP association (default 1000). + UDPMaxDatagrams int + // UDPMaxBytes caps total forwarded payload bytes (c2s + s2c) per UDP association (default 4 MiB). + UDPMaxBytes int64 + // UDPIdleTimeout closes a UDP association after no forwarded datagrams move (default 2m). + UDPIdleTimeout time.Duration + // UDPPreviewBytes caps inline preview per stored UDP datagram before blob spill (default PreviewBytes / 8 KiB). + UDPPreviewBytes int + // ResolveUDP4 enforces the target gate and resolves each UDP datagram destination + // to a verified IPv4 *net.UDPAddr before forwarding. Defaults to intercept.PinnedUDP4Resolver("socks5-udp", false). + ResolveUDP4 func(ctx context.Context, addr string) (*net.UDPAddr, error) + // OnRecordUDP, when non-nil, receives each forwarded UDP datagram capture. + // When nil and attached to a Traffic store, the store's raw-UDP recorder runs. + OnRecordUDP func(RawUDPCapture) } // RawTCPCapture is the completed metadata and bounded directional payloads of @@ -114,11 +143,22 @@ type RawTCPCapture struct { Paced bool } -// SOCKS5ConfigFromEnv parses ARTEX_SOCKS5_ENABLED and ARTEX_SOCKS5_ADDR. -// Returns (cfg, false) when disabled (the default). +// SOCKS5ConfigFromEnv parses ARTEX_SOCKS5_ENABLED, ARTEX_SOCKS5_ADDR, and +// ARTEX_SOCKS5_UDP_ENABLED. Returns (cfg, false) when disabled (the default). func SOCKS5ConfigFromEnv() (SOCKS5Config, bool) { rawEnabled := strings.ToLower(strings.TrimSpace(os.Getenv(SOCKS5EnabledEnv))) rawAddr := strings.TrimSpace(os.Getenv(SOCKS5AddrEnv)) + rawUDP := strings.ToLower(strings.TrimSpace(os.Getenv(SOCKS5UDPEnabledEnv))) + + enableUDP := false + switch rawUDP { + case "", "0", "false", "off", "no": + enableUDP = false + case "1", "true", "on", "yes": + enableUDP = true + default: + log.Printf("[traffic] %s=%q is not a boolean; leaving SOCKS5 UDP disabled", SOCKS5UDPEnabledEnv, rawUDP) + } switch rawEnabled { case "0", "false", "off", "no": @@ -128,12 +168,16 @@ func SOCKS5ConfigFromEnv() (SOCKS5Config, bool) { if addr == "" { addr = DefaultSOCKS5Addr } - return SOCKS5Config{Addr: addr}, true + return SOCKS5Config{Addr: addr, EnableUDP: enableUDP}, true case "": - if rawAddr == "" { + if rawAddr == "" && !enableUDP { return SOCKS5Config{}, false } - return SOCKS5Config{Addr: rawAddr}, true + addr := rawAddr + if addr == "" { + addr = DefaultSOCKS5Addr + } + return SOCKS5Config{Addr: addr, EnableUDP: enableUDP}, true default: log.Printf("[traffic] %s=%q is not a boolean; leaving SOCKS5 disabled", SOCKS5EnabledEnv, rawEnabled) return SOCKS5Config{}, false @@ -168,6 +212,21 @@ func (c SOCKS5Config) withDefaults() SOCKS5Config { if c.DialContext == nil { c.DialContext = intercept.PinnedDialer("socks5", false) } + if c.UDPMaxDatagrams <= 0 { + c.UDPMaxDatagrams = DefaultSOCKS5UDPMaxDatagrams + } + if c.UDPMaxBytes <= 0 { + c.UDPMaxBytes = DefaultSOCKS5UDPMaxBytes + } + if c.UDPIdleTimeout <= 0 { + c.UDPIdleTimeout = DefaultSOCKS5UDPIdleTimeout + } + if c.UDPPreviewBytes <= 0 { + c.UDPPreviewBytes = c.PreviewBytes + } + if c.ResolveUDP4 == nil { + c.ResolveUDP4 = intercept.PinnedUDP4Resolver("socks5-udp", false) + } return c } @@ -181,10 +240,10 @@ type socks5Server struct { wg sync.WaitGroup mu sync.Mutex - active map[net.Conn]struct{} + active map[io.Closer]struct{} } -// StartSOCKS5 binds and starts the opt-in RFC 1928 SOCKS5 CONNECT listener on t. +// StartSOCKS5 binds and starts the opt-in RFC 1928 SOCKS5 listener on t. // Returns the actual bound address (useful when cfg.Addr uses port 0). func (t *Traffic) StartSOCKS5(cfg SOCKS5Config) (string, error) { cfg = cfg.withDefaults() @@ -198,7 +257,7 @@ func (t *Traffic) StartSOCKS5(cfg SOCKS5Config) (string, error) { ln: ln, sem: make(chan struct{}, cfg.MaxConcurrent), stop: make(chan struct{}), - active: map[net.Conn]struct{}{}, + active: map[io.Closer]struct{}{}, } t.socksMu.Lock() if t.socks != nil { @@ -224,6 +283,14 @@ func (t *Traffic) SOCKS5Addr() string { return t.socks.ln.Addr().String() } +// SOCKS5UDPEnabled reports whether the running SOCKS5 listener accepts RFC 1928 +// UDP ASSOCIATE requests. +func (t *Traffic) SOCKS5UDPEnabled() bool { + t.socksMu.Lock() + defer t.socksMu.Unlock() + return t.socks != nil && t.socks.cfg.EnableUDP +} + func (s *socks5Server) Close() error { var closeErr error s.once.Do(func() { @@ -248,7 +315,7 @@ func (s *socks5Server) stopping() bool { } } -func (s *socks5Server) trackConn(c net.Conn) bool { +func (s *socks5Server) trackConn(c io.Closer) bool { s.mu.Lock() defer s.mu.Unlock() if s.stopping() { @@ -258,7 +325,7 @@ func (s *socks5Server) trackConn(c net.Conn) bool { return true } -func (s *socks5Server) untrackConn(c net.Conn) { +func (s *socks5Server) untrackConn(c io.Closer) { s.mu.Lock() delete(s.active, c) s.mu.Unlock() @@ -302,11 +369,15 @@ func (s *socks5Server) handleConn(client net.Conn) { return } - host, port, rep := readSOCKS5Request(client) + cmd, atyp, host, port, rep := readSOCKS5Request(client, s.cfg.EnableUDP) if rep != socks5RepSuccess { _ = writeSOCKS5Reply(client, rep, nil) return } + if cmd == socks5CmdUDPAssociate { + s.handleUDPAssociate(client, atyp, host, port) + return + } // 2. Enforce max concurrent streams before touching policy or dialing. select { @@ -458,16 +529,16 @@ func readSOCKS5UserPass(conn net.Conn) (paced bool, ok bool) { return string(uname) == egress.PaceUser, true } -func readSOCKS5Request(conn net.Conn) (host string, port int, rep byte) { +func readSOCKS5Request(conn net.Conn, enableUDP bool) (cmd byte, atyp byte, host string, port int, rep byte) { var hdr [4]byte if _, err := io.ReadFull(conn, hdr[:]); err != nil { - return "", 0, socks5RepGeneralFailure + return 0, 0, "", 0, socks5RepGeneralFailure } if hdr[0] != socks5Version || hdr[2] != 0x00 { - return "", 0, socks5RepGeneralFailure + return 0, 0, "", 0, socks5RepGeneralFailure } - cmd := hdr[1] - atyp := hdr[3] + cmd = hdr[1] + atyp = hdr[3] // Read the address + port before rejecting unsupported commands so the stream // stays cleanly framed if the peer reads our reply. @@ -475,56 +546,75 @@ func readSOCKS5Request(conn net.Conn) (host string, port int, rep byte) { case socks5AtypIPv4: var ip [4]byte if _, err := io.ReadFull(conn, ip[:]); err != nil { - return "", 0, socks5RepGeneralFailure + return cmd, atyp, "", 0, socks5RepGeneralFailure } host = net.IP(ip[:]).String() case socks5AtypDomain: var l [1]byte if _, err := io.ReadFull(conn, l[:]); err != nil { - return "", 0, socks5RepGeneralFailure + return cmd, atyp, "", 0, socks5RepGeneralFailure } if l[0] == 0 { - return "", 0, socks5RepGeneralFailure + return cmd, atyp, "", 0, socks5RepGeneralFailure } dom := make([]byte, int(l[0])) if _, err := io.ReadFull(conn, dom); err != nil { - return "", 0, socks5RepGeneralFailure + return cmd, atyp, "", 0, socks5RepGeneralFailure } host = strings.TrimSpace(string(dom)) if host == "" { - return "", 0, socks5RepGeneralFailure + return cmd, atyp, "", 0, socks5RepGeneralFailure } case socks5AtypIPv6: var ip [16]byte if _, err := io.ReadFull(conn, ip[:]); err != nil { - return "", 0, socks5RepGeneralFailure + return cmd, atyp, "", 0, socks5RepGeneralFailure } host = net.IP(ip[:]).String() default: - return "", 0, socks5RepAtypNotSupported + return cmd, atyp, "", 0, socks5RepAtypNotSupported } var pbuf [2]byte if _, err := io.ReadFull(conn, pbuf[:]); err != nil { - return "", 0, socks5RepGeneralFailure + return cmd, atyp, "", 0, socks5RepGeneralFailure } port = int(binary.BigEndian.Uint16(pbuf[:])) - if cmd != socks5CmdConnect { - return "", 0, socks5RepCmdNotSupported + switch cmd { + case socks5CmdConnect: + if port <= 0 || port > 65535 { + return cmd, atyp, "", 0, socks5RepGeneralFailure + } + return cmd, atyp, host, port, socks5RepSuccess + case socks5CmdUDPAssociate: + if !enableUDP { + return cmd, atyp, "", 0, socks5RepCmdNotSupported + } + // P4.1c covers IPv4 first; IPv6 UDP ASSOCIATE is rejected explicitly. + if atyp == socks5AtypIPv6 { + return cmd, atyp, "", 0, socks5RepAtypNotSupported + } + return cmd, atyp, host, port, socks5RepSuccess + default: + return cmd, atyp, "", 0, socks5RepCmdNotSupported } - if port <= 0 || port > 65535 { - return "", 0, socks5RepGeneralFailure - } - return host, port, socks5RepSuccess } func writeSOCKS5Reply(conn net.Conn, rep byte, bindAddr net.Addr) error { var bndIP net.IP var bndPort int - if tcpAddr, ok := bindAddr.(*net.TCPAddr); ok && tcpAddr != nil { - bndIP = tcpAddr.IP - bndPort = tcpAddr.Port + switch a := bindAddr.(type) { + case *net.TCPAddr: + if a != nil { + bndIP = a.IP + bndPort = a.Port + } + case *net.UDPAddr: + if a != nil { + bndIP = a.IP + bndPort = a.Port + } } var out []byte if ip4 := bndIP.To4(); ip4 != nil { diff --git a/traffic/socks5_udp.go b/traffic/socks5_udp.go new file mode 100644 index 0000000..bdc5ec2 --- /dev/null +++ b/traffic/socks5_udp.go @@ -0,0 +1,444 @@ +package traffic + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "log" + "net" + "net/url" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/Autumn-27/artex/egress" +) + +var ( + errSOCKS5UDPShortPacket = errors.New("short SOCKS5 UDP packet") + errSOCKS5UDPBadReserved = errors.New("non-zero SOCKS5 UDP RSV field") + errSOCKS5UDPFragmented = errors.New("SOCKS5 UDP fragmentation (FRAG != 0) is not supported") + errSOCKS5UDPUnsupportedAtyp = errors.New("unsupported SOCKS5 UDP address type (IPv4/domain only)") + errSOCKS5UDPBadDestination = errors.New("invalid SOCKS5 UDP destination address or port") +) + +var fallbackUDPAssocSeq atomic.Int64 + +// RawUDPCapture holds one forwarded UDP datagram observed on a SOCKS5 UDP +// ASSOCIATE relay. Each datagram is recorded individually as it arrives with +// no fragmentation reassembly. +type RawUDPCapture struct { + AssociationID string + Host string + Port int + Direction string // "c2s" | "s2c" + Timestamp time.Time + Payload []byte +} + +// parseSOCKS5UDPHeader parses an RFC 1928 §7 UDP request header. +// +// +----+------+------+----------+----------+----------+ +// |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA | +// +----+------+------+----------+----------+----------+ +// | 2 | 1 | 1 | Variable | 2 | Variable | +// +----+------+------+----------+----------+----------+ +// +// Fragmentation reassembly is intentionally unsupported: any datagram with +// FRAG != 0 returns errSOCKS5UDPFragmented and must be dropped per RFC 1928 §7. +// P4.1c covers IPv4 destinations (ATYP=0x01) and domain names resolved to IPv4 +// (ATYP=0x03); IPv6 (ATYP=0x04) is rejected with errSOCKS5UDPUnsupportedAtyp. +func parseSOCKS5UDPHeader(pkt []byte) (atyp byte, host string, port int, payload []byte, err error) { + if len(pkt) < 4 { + return 0, "", 0, nil, errSOCKS5UDPShortPacket + } + if pkt[0] != 0x00 || pkt[1] != 0x00 { + return 0, "", 0, nil, errSOCKS5UDPBadReserved + } + if pkt[2] != 0x00 { + return 0, "", 0, nil, errSOCKS5UDPFragmented + } + atyp = pkt[3] + off := 4 + switch atyp { + case socks5AtypIPv4: + if len(pkt) < off+4+2 { + return atyp, "", 0, nil, errSOCKS5UDPShortPacket + } + ip := net.IPv4(pkt[off], pkt[off+1], pkt[off+2], pkt[off+3]).To4() + if ip == nil || ip.IsUnspecified() { + return atyp, "", 0, nil, errSOCKS5UDPBadDestination + } + host = ip.String() + off += 4 + case socks5AtypDomain: + if len(pkt) < off+1 { + return atyp, "", 0, nil, errSOCKS5UDPShortPacket + } + domLen := int(pkt[off]) + off++ + if domLen == 0 || len(pkt) < off+domLen+2 { + return atyp, "", 0, nil, errSOCKS5UDPShortPacket + } + host = strings.TrimSpace(string(pkt[off : off+domLen])) + if host == "" { + return atyp, "", 0, nil, errSOCKS5UDPBadDestination + } + off += domLen + default: + return atyp, "", 0, nil, errSOCKS5UDPUnsupportedAtyp + } + + port = int(binary.BigEndian.Uint16(pkt[off : off+2])) + off += 2 + if port <= 0 || port > 65535 { + return atyp, "", 0, nil, errSOCKS5UDPBadDestination + } + return atyp, host, port, pkt[off:], nil +} + +// buildSOCKS5UDPPacket wraps an IPv4 upstream reply datagram in an RFC 1928 §7 +// UDP header (RSV=0x0000, FRAG=0x00, ATYP=0x01). +func buildSOCKS5UDPPacket(srcIP net.IP, srcPort int, payload []byte) ([]byte, error) { + ip4 := srcIP.To4() + if ip4 == nil || srcPort <= 0 || srcPort > 65535 { + return nil, errSOCKS5UDPBadDestination + } + out := make([]byte, 10+len(payload)) + out[0] = 0x00 + out[1] = 0x00 + out[2] = 0x00 + out[3] = socks5AtypIPv4 + copy(out[4:8], ip4) + binary.BigEndian.PutUint16(out[8:10], uint16(srcPort)) + copy(out[10:], payload) + return out, nil +} + +func (s *socks5Server) newUDPAssociationID(started time.Time) string { + var n int64 + if s.t != nil { + n = s.t.seq.Add(1) + } else { + n = fallbackUDPAssocSeq.Add(1) + } + return fmt.Sprintf("udpa-%d-%04d", started.UnixMilli(), n%10000) +} + +func (s *socks5Server) handleUDPAssociate(client net.Conn, reqAtyp byte, reqHost string, reqPort int) { + // 1. Enforce max concurrent sessions before allocating UDP sockets. + select { + case s.sem <- struct{}{}: + defer func() { <-s.sem }() + default: + _ = writeSOCKS5Reply(client, socks5RepGeneralFailure, nil) + return + } + + // 2. Bind client-facing IPv4 UDP relay socket on the TCP local interface IP. + bindIP := net.IPv4(127, 0, 0, 1) + if ltcp, ok := client.LocalAddr().(*net.TCPAddr); ok && ltcp != nil { + if ip4 := ltcp.IP.To4(); ip4 != nil && !ip4.IsUnspecified() { + bindIP = ip4 + } + } + relayConn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: bindIP, Port: 0}) + if err != nil { + _ = writeSOCKS5Reply(client, socks5RepGeneralFailure, nil) + return + } + if !s.trackConn(relayConn) { + _ = relayConn.Close() + _ = writeSOCKS5Reply(client, socks5RepGeneralFailure, nil) + return + } + defer s.untrackConn(relayConn) + defer relayConn.Close() + + // 3. Bind upstream IPv4 UDP socket for forwarding to verified targets. + upstreamConn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: 0}) + if err != nil { + _ = writeSOCKS5Reply(client, socks5RepGeneralFailure, nil) + return + } + if !s.trackConn(upstreamConn) { + _ = upstreamConn.Close() + _ = writeSOCKS5Reply(client, socks5RepGeneralFailure, nil) + return + } + defer s.untrackConn(upstreamConn) + defer upstreamConn.Close() + + // Clear handshake deadline and send BND.ADDR + BND.PORT on TCP control conn. + _ = client.SetDeadline(time.Time{}) + relayAddr := relayConn.LocalAddr().(*net.UDPAddr) + if err := writeSOCKS5Reply(client, socks5RepSuccess, relayAddr); err != nil { + return + } + + // Determine allowed client UDP source IP/port. + var expectedClientIP net.IP + expectedClientPort := 0 + if reqAtyp == socks5AtypIPv4 { + if ip := net.ParseIP(reqHost).To4(); ip != nil && !ip.IsUnspecified() { + expectedClientIP = ip + } + if reqPort > 0 && reqPort <= 65535 { + expectedClientPort = reqPort + } + } + if expectedClientIP == nil { + if rtcp, ok := client.RemoteAddr().(*net.TCPAddr); ok && rtcp != nil { + expectedClientIP = rtcp.IP.To4() + } + } + + assocID := s.newUDPAssociationID(time.Now().UTC()) + + baseCtx := context.Background() + if s.cfg.BaseContext != nil { + if ctx := s.cfg.BaseContext(); ctx != nil { + baseCtx = ctx + } + } + assocCtx, assocCancel := context.WithCancel(baseCtx) + var closeOnce sync.Once + closeAssoc := func() { + closeOnce.Do(func() { + assocCancel() + _ = relayConn.Close() + _ = upstreamConn.Close() + _ = client.Close() + }) + } + defer closeAssoc() + + // Close association when server stops. + stopWatchDone := make(chan struct{}) + go func() { + select { + case <-s.stop: + closeAssoc() + case <-assocCtx.Done(): + } + close(stopWatchDone) + }() + defer func() { <-stopWatchDone }() + + // Idle timer bounds inactive associations. + var idleTimer *time.Timer + if s.cfg.UDPIdleTimeout > 0 { + idleTimer = time.AfterFunc(s.cfg.UDPIdleTimeout, closeAssoc) + defer idleTimer.Stop() + } + touchIdle := func() { + if idleTimer != nil { + idleTimer.Reset(s.cfg.UDPIdleTimeout) + } + } + + var ( + assocMu sync.Mutex + clientUDPAddr *net.UDPAddr + allowedPeers = map[string]string{} // resolved "ip:port" -> logical dst host + datagramCount int + byteCount int64 + ) + + // consumeBudget reserves one datagram + payload length against the + // association's bounds. Returns false if either limit would be exceeded. + consumeBudget := func(payloadLen int) bool { + assocMu.Lock() + defer assocMu.Unlock() + if datagramCount+1 > s.cfg.UDPMaxDatagrams || byteCount+int64(payloadLen) > s.cfg.UDPMaxBytes { + return false + } + datagramCount++ + byteCount += int64(payloadLen) + return true + } + + var wg sync.WaitGroup + wg.Add(3) + + // Goroutine 1: tie association lifetime strictly to the TCP control connection. + go func() { + defer wg.Done() + var discard [64]byte + for { + if _, err := client.Read(discard[:]); err != nil { + closeAssoc() + return + } + } + }() + + // Goroutine 2: client -> upstream UDP relay (c2s). + go func() { + defer wg.Done() + buf := make([]byte, DefaultSOCKS5UDPMaxDatagramSize) + for { + n, from, err := relayConn.ReadFromUDP(buf) + if err != nil { + return + } + if !s.acceptClientUDPSource(from, expectedClientIP, expectedClientPort, &assocMu, &clientUDPAddr) { + continue + } + + _, dstHost, dstPort, payload, err := parseSOCKS5UDPHeader(buf[:n]) + if err != nil { + // Malformed header, FRAG != 0, or unsupported ATYP: drop datagram. + continue + } + + // Copy payload before forwarding/recording so buf can be reused safely. + payloadCopy := append([]byte(nil), payload...) + targetAddr := net.JoinHostPort(dstHost, strconv.Itoa(dstPort)) + + // Enforce per-datagram destination policy (target gate + egress governor) + // BEFORE forwarding. A denied destination drops that datagram cleanly. + dstUDPAddr, err := s.resolveAndPaceUDP4(assocCtx, targetAddr) + if err != nil { + continue + } + + if !consumeBudget(len(payloadCopy)) { + closeAssoc() + return + } + + assocMu.Lock() + allowedPeers[dstUDPAddr.String()] = dstHost + assocMu.Unlock() + + if _, err := upstreamConn.WriteToUDP(payloadCopy, dstUDPAddr); err != nil { + if assocCtx.Err() != nil { + return + } + continue + } + touchIdle() + s.recordUDPCapture(RawUDPCapture{ + AssociationID: assocID, + Host: dstHost, + Port: dstPort, + Direction: "c2s", + Timestamp: time.Now().UTC(), + Payload: payloadCopy, + }) + } + }() + + // Goroutine 3: upstream -> client UDP relay (s2c). + go func() { + defer wg.Done() + buf := make([]byte, DefaultSOCKS5UDPMaxDatagramSize) + for { + n, from, err := upstreamConn.ReadFromUDP(buf) + if err != nil { + return + } + assocMu.Lock() + origHost, allowed := allowedPeers[from.String()] + cli := clientUDPAddr + assocMu.Unlock() + if !allowed || cli == nil { + // Drop unsolicited UDP packets from destinations this association + // has not sent an allowed datagram to. + continue + } + + payloadCopy := append([]byte(nil), buf[:n]...) + if !consumeBudget(len(payloadCopy)) { + closeAssoc() + return + } + + wrapped, err := buildSOCKS5UDPPacket(from.IP, from.Port, payloadCopy) + if err != nil { + continue + } + if _, err := relayConn.WriteToUDP(wrapped, cli); err != nil { + if assocCtx.Err() != nil { + return + } + continue + } + touchIdle() + s.recordUDPCapture(RawUDPCapture{ + AssociationID: assocID, + Host: origHost, + Port: from.Port, + Direction: "s2c", + Timestamp: time.Now().UTC(), + Payload: payloadCopy, + }) + } + }() + + wg.Wait() +} + +func (s *socks5Server) acceptClientUDPSource(from *net.UDPAddr, expectedIP net.IP, expectedPort int, mu *sync.Mutex, pinned **net.UDPAddr) bool { + if from == nil || from.IP == nil { + return false + } + fromIP4 := from.IP.To4() + if fromIP4 == nil { + return false + } + if expectedIP != nil && !fromIP4.Equal(expectedIP) { + return false + } + if expectedPort > 0 && from.Port != expectedPort { + return false + } + mu.Lock() + defer mu.Unlock() + if *pinned == nil { + *pinned = &net.UDPAddr{IP: append(net.IP(nil), fromIP4...), Port: from.Port} + return true + } + return (*pinned).IP.Equal(fromIP4) && (*pinned).Port == from.Port +} + +func (s *socks5Server) resolveAndPaceUDP4(assocCtx context.Context, targetAddr string) (*net.UDPAddr, error) { + // 1. Target gate + fresh DNS resolution (IPv4). + resCtx, resCancel := context.WithTimeout(assocCtx, s.cfg.DialTimeout) + defer resCancel() + dstAddr, err := s.cfg.ResolveUDP4(resCtx, targetAddr) + if err != nil { + return nil, err + } + if dstAddr == nil || dstAddr.IP == nil || dstAddr.IP.To4() == nil || dstAddr.Port <= 0 { + return nil, errSOCKS5UDPBadDestination + } + + // 2. Egress governor (same egress.Do path as HTTP / SOCKS5 TCP / transparent TCP). + govCtx, govCancel := context.WithTimeout(assocCtx, s.cfg.PaceTimeout) + defer govCancel() + targetURL := &url.URL{Scheme: "udp", Host: targetAddr} + _, err = egress.Do(egress.Current(), govCtx, targetURL, func() (struct{}, error) { + return struct{}{}, nil + }) + if err != nil { + return nil, err + } + return dstAddr, nil +} + +func (s *socks5Server) recordUDPCapture(rec RawUDPCapture) { + if s.cfg.OnRecordUDP != nil { + s.cfg.OnRecordUDP(rec) + return + } + // Commit 2 wires SQLite raw_udp_datagrams persistence here. + if s.t != nil && s.t.db != nil { + log.Printf("[traffic/socks5-udp] recorded datagram assoc=%s dir=%s dst=%s:%d bytes=%d", + rec.AssociationID, rec.Direction, rec.Host, rec.Port, len(rec.Payload)) + } +}