From 3161801878b1da51a79b1ac675f9758eb655d27d Mon Sep 17 00:00:00 2001 From: GlobalTechInfo Date: Sat, 17 Oct 2026 17:49:58 +0500 Subject: [PATCH] Add SOCKS5 UDP ASSOCIATE UDP is what a TCP-only proxy breaks: DNS lookups fall back to TCP, QUIC stalls, and Telegram is largely unusable. readRequest now reports the command it saw, and handleClient hands UDP ASSOCIATE to a new relay. The relay opens one socket per destination, wraps replies back to the client, and hangs its lifetime off the TCP control connection, since RFC 1928 makes closing that the end of the association. Tier limits, data accounting and bandwidth pacing apply exactly as they do on the TCP path. Three things worth calling out: - The relay socket is bound on "udp4"/"udp6" chosen from the client's family. net.ListenUDP("udp", IPv4zero) returns a dual-stack IPv6 socket whose LocalAddr reads back as [::], so the associate reply was advertising IPv6 to an IPv4 client. Verified against a real DNS query. - Destinations are capped at 64 per association. Each one is a socket, a goroutine and two 64KB buffers, and the TCP connection limit cannot see them, so one control connection could otherwise ask for an unbounded number. - The generated reality-client.json now offers UDP, since UDP survives the REALITY chain. Confirmed end to end: DNS over UDP through xray. Fragments are dropped rather than reassembled and UDP carries no credentials of its own; authentication happens once on the control connection, which is also why the relay socket cannot be found without it. --- .env.example | 5 + README.md | 27 ++- config.json | 1 + main.go | 61 ++++-- reality.go | 2 +- reality_test.go | 5 + udp.go | 424 ++++++++++++++++++++++++++++++++++++++++++ udp_test.go | 478 ++++++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 987 insertions(+), 16 deletions(-) create mode 100644 udp.go create mode 100644 udp_test.go diff --git a/.env.example b/.env.example index 55639dd..6424e8b 100644 --- a/.env.example +++ b/.env.example @@ -26,6 +26,11 @@ READ_TIMEOUT_SECONDS=30 WRITE_TIMEOUT_SECONDS=30 IDLE_TIMEOUT_SECONDS=300 +# ─── UDP ─────────────────────────────────────────────────────────────────── +# SOCKS5 UDP ASSOCIATE. This is what Telegram, QUIC and DNS-over-UDP need. +# Set false to allow TCP connections only. +UDP_ENABLED=true + # ─── Security ────────────────────────────────────────────────────────────── SECURITY_HEADERS_ENABLED=true diff --git a/README.md b/README.md index e95bc4f..65bf066 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Deploys on any PaaS, including the ones that expose only a single HTTP endpoint. ## Features - **SOCKS5 Protocol** - Full SOCKS5 proxy support with username/password authentication +- **SOCKS5 UDP** - `UDP ASSOCIATE` relay for Telegram, QUIC and DNS-over-UDP, on the SOCKS5 port and through REALITY - **Single-Port Multiplexing** - SOCKS5, TLS, dashboards and the tunnel share one port, so it runs on Render/Koyeb/Heroku/Northflank where raw TCP never reaches the app - **WebSocket Tunnel** - Carries SOCKS5 over an HTTP upgrade for platforms whose edge terminates TLS; ships with a matching client - **REALITY** - Xray front door that presents a real website's certificate to an active prober; sessions still land in the SOCKS5 pipeline @@ -139,6 +140,7 @@ separately on port 443 via xray. | Protocol | Endpoint | Used by | |---|---|---| | **SOCKS5** | `:1080` | Native SOCKS5 clients, on hosts that permit raw TCP | +| **SOCKS5 UDP** | `:1080` | `UDP ASSOCIATE` for Telegram, QUIC and UDP DNS | | **SOCKS5 over WebSocket** | `/api/v1/tunnel` | SOCKS5 clients where raw TCP is blocked, via the bundled client | | **HTTP proxy** — `CONNECT` and absolute-form | single port | Browsers and any HTTP client with proxy support | | **HTTPS** | single port | TLS-wrapped access to any of the above | @@ -153,6 +155,26 @@ to the origin, so HTTP proxying requires a directly reachable host. The WebSocket tunnel is unaffected and is the intended path on Render, Koyeb, Heroku and Northflank. +## UDP + +The SOCKS5 port speaks `UDP ASSOCIATE`, so Telegram, QUIC and DNS-over-UDP work +without anything special on the client. It needs no configuration; the relay +picks an ephemeral port, tells the client about it, and opens one socket per +destination as datagrams need it. The TCP control connection is the lifetime of +the association: close it and the relay tears down. + +UDP flows through REALITY too, so the generated `reality-client.json` offers it. + +```bash +# a DNS query over UDP, through the proxy on 127.0.0.1:1080 +dig @8.8.8.8 example.com +tcp=no +proxy +``` + +Two limits worth knowing: the WebSocket tunnel is TCP-only, so a client on the +tunnel gets TCP only. And a client that asks to be told an address of `0.0.0.0` +must send to the proxy host it is already connected to, which every mainstream +SOCKS5 client does. + ## Why the tunnel exists Render forwards inbound traffic to **one HTTP port** and terminates TLS at its load balancer. Koyeb, Heroku and Northflank behave the same way. A SOCKS5 client opening a raw socket against those hosts never reaches the container, and an in-process reverse proxy cannot help: the edge rejects the bytes before any process sees them. @@ -328,7 +350,9 @@ What is still true after all of the above: fingerprinted behind it. - **The camouflage site's certificate is only as good as its uptime.** If the target site is down or slow, handshakes suffer visibly. -- **No SOCKS5 UDP.** Sessions are TCP only, so REALITY carries TCP too. +- **UDP is not available through the WebSocket tunnel.** UDP works on the + SOCKS5 port and through REALITY, but the tunnel is a TCP-only stream, so a + client on the tunnel gets TCP only. ## Configuration @@ -344,6 +368,7 @@ Edit `config.json` or use environment variables (env vars override config file): | `PROXY_USER` | changeme | SOCKS5 username, also the HTTP proxy user | | `PROXY_PASS` | changeme | SOCKS5 password, also the HTTP proxy password | | `AUTH_ENABLED` | true | Enable SOCKS5 and HTTP proxy authentication | +| `UDP_ENABLED` | true | SOCKS5 `UDP ASSOCIATE`. Set false for TCP only | | `MAX_CONNECTIONS` | 1000 | Max simultaneous connections | | `ADMIN_USER` | admin | Admin dashboard username | | `ADMIN_PASS` | changeme | Admin dashboard password | diff --git a/config.json b/config.json index 0080f1f..13507d6 100644 --- a/config.json +++ b/config.json @@ -4,6 +4,7 @@ "metrics_port": 9090, "max_connections": 1000, "auth_enabled": true, + "udp_enabled": true, "username": "changeme", "password": "changeme", "whitelist": [], diff --git a/main.go b/main.go index a80bfb5..08b4d25 100644 --- a/main.go +++ b/main.go @@ -77,6 +77,11 @@ type Config struct { TLSCertFile string `json:"tls_cert_file"` TLSKeyFile string `json:"tls_key_file"` + // SOCKS5 UDP ASSOCIATE. TCP-only was the original behaviour, and a proxy + // that cannot carry UDP breaks DNS lookups and QUIC unless the client falls + // back. The WebSocket tunnel is TCP-only by nature and cannot offer it. + UDPEnabled bool `json:"udp_enabled"` + // REALITY front door: Xray terminates VLESS+REALITY and forwards sessions to // the SOCKS5 port, so users and tiers keep applying. Needs a dedicated IP // with raw TCP; a CDN edge would terminate TLS before reaching us. @@ -119,6 +124,7 @@ func DefaultConfig() Config { TunnelPath: "/api/v1/tunnel", TunnelPadding: 256, TunnelRateRPS: 5, + UDPEnabled: true, RealityBind: defaultRealityBind, RealityDest: defaultRealityDest, RealityXrayBin: "xray", @@ -271,6 +277,10 @@ func LoadConfig(filename string) (Config, error) { cfg.TLSKeyFile = v } + if v := os.Getenv("UDP_ENABLED"); v != "" { + cfg.UDPEnabled = v == "true" || v == "1" + } + // REALITY. Comma-separated lists accept more than one SNI, short id or // VLESS id so a rotation does not need a restart. if v := os.Getenv("REALITY_ENABLED"); v != "" { @@ -420,7 +430,8 @@ const ( methodUserPassword = 0x02 methodNoAcceptable = 0xFF - cmdConnect = 0x01 + cmdConnect = 0x01 + cmdUDPAssociate = 0x03 addrTypeIPv4 = 0x01 addrTypeFQDN = 0x03 @@ -696,13 +707,34 @@ func (s *ProxyServer) handleClient(conn net.Conn, clientIPOverride string) { // Step 3: Read CONNECT request conn.SetReadDeadline(time.Now().Add(time.Duration(cfgSnap.ReadTimeout) * time.Second)) - target, err := s.readRequest(conn, &cfgSnap) + target, command, err := s.readRequest(conn, &cfgSnap) if err != nil { log.Error("request read failed", "error", err) metricConnErrors.WithLabelValues("request_read").Inc() return } + if command == cmdUDPAssociate { + // readRequest already consumed the address the client suggested. This + // relay always picks its own ephemeral port and reports that back, which + // is both simpler and more correct: the suggestion is advisory and is + // frequently wrong on a host with several interfaces. + if !cfgSnap.UDPEnabled { + log.Warn("udp associate refused: udp_enabled is false") + s.sendReply(conn, replyCmdNotSupported, &cfgSnap) + return + } + // Tier limits apply here too: an association is a session, and a + // Free-tier account should not be able to open unlimited UDP targets. + if !s.userAllowedUDP(authenticatedUser, log) { + s.sendReply(conn, replyConnNotAllowed, &cfgSnap) + return + } + log.Info("udp association requested", "suggested_addr", target) + s.relayUDP(conn, log, &cfgSnap, authenticatedUser) + return + } + // Check per-user limits if authenticatedUser != nil && s.store != nil { // Check expiry @@ -888,19 +920,20 @@ func (s *ProxyServer) authenticateUser(conn net.Conn, cfg *Config) (*User, error return nil, errors.New("invalid credentials") } -func (s *ProxyServer) readRequest(conn net.Conn, cfg *Config) (string, error) { +func (s *ProxyServer) readRequest(conn net.Conn, cfg *Config) (string, byte, error) { header := make([]byte, 4) if _, err := io.ReadFull(conn, header); err != nil { - return "", fmt.Errorf("read request header: %w", err) + return "", 0, fmt.Errorf("read request header: %w", err) } if header[0] != socksVersion { - return "", fmt.Errorf("unsupported SOCKS version: %d", header[0]) + return "", 0, fmt.Errorf("unsupported SOCKS version: %d", header[0]) } - if header[1] != cmdConnect { + if header[1] != cmdConnect && header[1] != cmdUDPAssociate { s.sendReply(conn, replyCmdNotSupported, cfg) - return "", fmt.Errorf("unsupported command: %d", header[1]) + return "", 0, fmt.Errorf("unsupported command: %d", header[1]) } + command := header[1] var host string var port uint16 @@ -909,7 +942,7 @@ func (s *ProxyServer) readRequest(conn net.Conn, cfg *Config) (string, error) { case addrTypeIPv4: addr := make([]byte, 6) if _, err := io.ReadFull(conn, addr); err != nil { - return "", fmt.Errorf("read IPv4 addr: %w", err) + return "", command, fmt.Errorf("read IPv4 addr: %w", err) } host = net.IPv4(addr[0], addr[1], addr[2], addr[3]).String() port = binary.BigEndian.Uint16(addr[4:6]) @@ -917,34 +950,34 @@ func (s *ProxyServer) readRequest(conn net.Conn, cfg *Config) (string, error) { case addrTypeFQDN: lenBuf := make([]byte, 1) if _, err := io.ReadFull(conn, lenBuf); err != nil { - return "", fmt.Errorf("read FQDN length: %w", err) + return "", command, fmt.Errorf("read FQDN length: %w", err) } domainLen := int(lenBuf[0]) domain := make([]byte, domainLen) if _, err := io.ReadFull(conn, domain); err != nil { - return "", fmt.Errorf("read FQDN: %w", err) + return "", command, fmt.Errorf("read FQDN: %w", err) } host = string(domain) portBuf := make([]byte, 2) if _, err := io.ReadFull(conn, portBuf); err != nil { - return "", fmt.Errorf("read FQDN port: %w", err) + return "", command, fmt.Errorf("read FQDN port: %w", err) } port = binary.BigEndian.Uint16(portBuf) case addrTypeIPv6: addr := make([]byte, 18) if _, err := io.ReadFull(conn, addr); err != nil { - return "", fmt.Errorf("read IPv6 addr: %w", err) + return "", command, fmt.Errorf("read IPv6 addr: %w", err) } host = net.IP(addr[:16]).String() port = binary.BigEndian.Uint16(addr[16:18]) default: s.sendReply(conn, replyAddrNotSupported, cfg) - return "", fmt.Errorf("unsupported address type: %d", header[3]) + return "", command, fmt.Errorf("unsupported address type: %d", header[3]) } - return fmt.Sprintf("%s:%d", host, port), nil + return fmt.Sprintf("%s:%d", host, port), command, nil } func (s *ProxyServer) sendReply(conn net.Conn, reply byte, cfg *Config) error { diff --git a/reality.go b/reality.go index 8a9929c..7ef496d 100644 --- a/reality.go +++ b/reality.go @@ -306,7 +306,7 @@ func renderRealityClientConfig(address string, port int, listen string, listenPo Listen: listen, Port: listenPort, Protocol: "socks", - Settings: realitySocksInboundConfig{Auth: "noauth", UDP: false}, + Settings: realitySocksInboundConfig{Auth: "noauth", UDP: true}, }} out.Outbounds = []realityVLESSPtr{{ Protocol: "vless", diff --git a/reality_test.go b/reality_test.go index df09f87..506a50d 100644 --- a/reality_test.go +++ b/reality_test.go @@ -211,6 +211,11 @@ func TestRenderRealityClientConfig(t *testing.T) { if out.Inbounds[0].Listen != "127.0.0.1" || out.Inbounds[0].Port != 1081 { t.Errorf("socks inbound = %s:%d, want 127.0.0.1:1081", out.Inbounds[0].Listen, out.Inbounds[0].Port) } + // UDP is the whole point for Telegram and QUIC. A generated config that + // leaves it off silently degrades the client to TCP-only. + if !out.Inbounds[0].Settings.UDP { + t.Error("generated socks inbound must accept UDP") + } if len(out.Outbounds) != 1 || out.Outbounds[0].Protocol != "vless" { t.Fatalf("client config needs a vless outbound, got %+v", out.Outbounds) diff --git a/udp.go b/udp.go new file mode 100644 index 0000000..d4c260c --- /dev/null +++ b/udp.go @@ -0,0 +1,424 @@ +package main + +import ( + "encoding/binary" + "fmt" + "log/slog" + "net" + "sync" + "sync/atomic" + "time" +) + +// ─── SOCKS5 UDP ASSOCIATE (RFC 1928) ──────────────────────────────────────── +// +// UDP is the reason a proxy cannot hide in a browser. DNS lookups and QUIC are +// the two flows that a TCP-only proxy either breaks or leaks, and Telegram +// apps are full of them. +// +// The shape of it is fixed by the RFC: the client opens a TCP control +// connection and sends UDP ASSOCIATE, the server replies with the address of a +// UDP socket it has just opened, and every datagram afterwards is wrapped in a +// small header naming its destination. The TCP connection stays open for the +// life of the association and closing it ends everything -- which is why +// teardown here hangs off the control connection rather than a timer. +// +// Two honest limitations, both from the RFC itself: +// - Fragmentation (FRAG != 0) is not implemented and the datagram is dropped. +// Almost no client emits it; supporting it means reassembling by +// datagram id, and SOCKS5 gives no way to bound the memory that needs. +// - There is no credential exchange over UDP. Authentication happens once on +// the TCP control connection, which is what makes the association +// un-guessable: without a valid TCP handshake there is no reply address. + +const ( + // udpFragFirst is the only fragment marker this relay accepts. + udpFragFirst = 0x00 + + udpMaxDatagram = 65535 + // udpDialTimeout bounds the per-destination socket, so a client pointing + // at an unroutable address cannot pin a goroutine forever. + udpDialTimeout = 5 * time.Second + // udpMaxTargets bounds one association's destinations. Each destination is a + // socket, a goroutine and two 64KB read buffers, and the TCP connection + // limit does not see any of them -- without this, one control connection + // could ask for an unbounded number. + // + // ponytail: 64 destinations per association. Raise it, or make it per-tier, + // if a real workload (a QUIC-heavy app, a DNS resolver pool) ever hits it. + udpMaxTargets = 64 +) + +// udpTarget is one destination socket belonging to an association. +type udpTarget struct { + conn *net.UDPConn + dest string + close sync.Once +} + +func (t *udpTarget) Close() { + t.close.Do(func() { t.conn.Close() }) +} + +// relayUDP runs one UDP association until the control connection dies. +func (s *ProxyServer) relayUDP(control net.Conn, log *slog.Logger, cfg *Config, user *User) { + idle := time.Duration(cfg.IdleTimeout) * time.Second + if idle <= 0 { + idle = 300 * time.Second + } + + // Bind the relay socket in the family the client arrived on, and say so in + // the reply. + // + // "udp4"/"udp6" rather than "udp": asked for a wildcard IPv4 address, + // net.ListenUDP hands back a dual-stack IPv6 socket whose LocalAddr reads + // back as [::], so the associate reply advertised an IPv6 address to a + // client that only understands IPv4. Pinning the network is the fix, and it + // also makes the advertised address match the socket that exists. + family, relayIP := udpFamilyFor(control) + relayConn, err := net.ListenUDP(family, &net.UDPAddr{IP: relayIP}) + if err != nil { + log.Error("could not open a udp relay socket", "error", err) + s.sendReply(control, replyGeneralFailure, cfg) + return + } + defer relayConn.Close() + + if err := s.sendUDPAssociateReply(control, relayConn.LocalAddr(), cfg); err != nil { + log.Debug("udp associate reply failed", "error", err) + return + } + // The client now sends datagrams to this address. Every read deadline below + // is refreshed by traffic in either direction, so an idle session stays open + // as long as it is actually used. + refresh := func() { + deadline := time.Now().Add(idle) + relayConn.SetReadDeadline(deadline) + control.SetReadDeadline(deadline) + } + refresh() + + s.totalConns.Add(1) + metricTotalConns.Inc() + s.recordDestination("udp-associate") + + var upPacer, downPacer *pacer + if user != nil { + upPacer = newPacer(user.BandwidthMbps) + downPacer = newPacer(user.BandwidthMbps) + } + var bytesUp, bytesDown atomic.Int64 + + var ( + targetsMu sync.Mutex + targets = map[string]*udpTarget{} + wg sync.WaitGroup + ) + + // closeTargets is idempotent and safe from any goroutine. + closeTargets := func() { + targetsMu.Lock() + live := make([]*udpTarget, 0, len(targets)) + for _, t := range targets { + live = append(live, t) + } + targets = map[string]*udpTarget{} + targetsMu.Unlock() + for _, t := range live { + t.Close() + } + } + + closeTargetsExcept := func(except *udpTarget) { + targetsMu.Lock() + if t, ok := targets[except.dest]; ok && t == except { + delete(targets, except.dest) + } + targetsMu.Unlock() + except.Close() + } + + // getTarget returns the socket for a destination, creating it on first use. + // One socket per destination keeps replies on the right source port and + // avoids relaying every datagram through a single peer address. + getTarget := func(dest string, client *net.UDPAddr) (*udpTarget, bool) { + targetsMu.Lock() + t, ok := targets[dest] + targetsMu.Unlock() + if ok { + return t, true + } + // Resolution and the dial happen outside the lock: a slow resolver + // would otherwise stall every other destination in this association. + addr := resolveUDPAddr(dest) + if addr == nil { + return nil, false + } + tconn, err := net.DialUDP(udpNetwork(addr), nil, addr) + if err != nil { + return nil, false + } + targetsMu.Lock() + defer targetsMu.Unlock() + if existing, raced := targets[dest]; raced { + // Another datagram for the same destination arrived first; keep the + // socket it made rather than racing two of them. + tconn.Close() + return existing, true + } + if len(targets) >= udpMaxTargets { + tconn.Close() + log.Warn("udp destination cap reached", "limit", udpMaxTargets) + return nil, false + } + fresh := &udpTarget{conn: tconn, dest: dest} + targets[dest] = fresh + + wg.Add(1) + go func() { + defer wg.Done() + s.relayUDPReplies(fresh, relayConn, client, log, &bytesDown, downPacer, refresh) + closeTargetsExcept(fresh) + }() + return fresh, true + } + + // outbound: relay socket -> destination + wg.Add(1) + go func() { + defer wg.Done() + buf := make([]byte, udpMaxDatagram) + for { + n, from, rerr := relayConn.ReadFromUDP(buf) + if rerr != nil { + return + } + refresh() + dest, payload, perr := parseUDPDatagram(buf[:n]) + if perr != nil { + // A malformed or fragmented datagram is dropped rather than + // guessed at. + continue + } + bytesUp.Add(int64(len(payload))) + upPacer.reserve(len(payload)) + + target, ok := getTarget(dest, from) + if !ok { + continue + } + if _, werr := target.conn.Write(payload); werr != nil { + closeTargetsExcept(target) + } + } + }() + + // The control connection is what keeps the association alive and what ends + // it. Some clients close it as soon as the associate reply arrives, which + // RFC 1928 does not sanction; a client that does so gets its association + // torn down, and the honest fix is on the client side. + wg.Add(1) + go func() { + defer wg.Done() + defer closeTargets() + defer relayConn.Close() + one := make([]byte, 1) + for { + if _, rerr := control.Read(one); rerr != nil { + return + } + refresh() + } + }() + + wg.Wait() + log.Info("udp association closed", + "bytes_up", bytesUp.Load(), + "bytes_down", bytesDown.Load(), + ) +} + +// udpFamilyFor picks the UDP network for a client's family, defaulting to IPv4 +// when the address cannot be read at all: a v4 relay is the one every client +// understands. +func udpFamilyFor(control net.Conn) (string, net.IP) { + remote, ok := control.RemoteAddr().(*net.TCPAddr) + if ok && remote.IP != nil && remote.IP.To4() == nil { + return "udp6", net.IPv6zero + } + return "udp4", net.IPv4zero +} + +// relayUDPReplies copies datagrams coming back from one destination, wrapping +// each in a SOCKS5 UDP header addressed to the client. +func (s *ProxyServer) relayUDPReplies(target *udpTarget, relayConn *net.UDPConn, client *net.UDPAddr, log *slog.Logger, bytesDown *atomic.Int64, p *pacer, refresh func()) { + buf := make([]byte, udpMaxDatagram) + for { + n, rerr := target.conn.Read(buf) + if rerr != nil { + return + } + refresh() + bytesDown.Add(int64(n)) + p.reserve(n) + + datagram, err := buildUDPDatagram(target.dest, buf[:n]) + if err != nil { + continue + } + if _, werr := relayConn.WriteToUDP(datagram, client); werr != nil { + return + } + } +} + +// parseUDPDatagram reads RSV/FRAG/ATYP/ADDR/PORT and returns the destination and +// the payload. +func parseUDPDatagram(b []byte) (string, []byte, error) { + if len(b) < 5 { + return "", nil, fmt.Errorf("datagram too short: %d bytes", len(b)) + } + if b[0] != 0 || b[1] != 0 { + return "", nil, fmt.Errorf("reserved bytes are not zero: % x", b[:2]) + } + if b[2] != udpFragFirst { + return "", nil, fmt.Errorf("fragmented datagram dropped (frag=%d)", b[2]) + } + + var host string + var pos int + switch b[3] { + case addrTypeIPv4: + if len(b) < 4+4+2 { + return "", nil, fmt.Errorf("truncated ipv4 address") + } + host = net.IP(b[4:8]).String() + pos = 8 + case addrTypeFQDN: + nameLen := int(b[4]) + if len(b) < 5+nameLen+2 { + return "", nil, fmt.Errorf("truncated domain") + } + host = string(b[5 : 5+nameLen]) + pos = 5 + nameLen + case addrTypeIPv6: + if len(b) < 4+16+2 { + return "", nil, fmt.Errorf("truncated ipv6 address") + } + host = net.IP(b[4:20]).String() + pos = 20 + default: + return "", nil, fmt.Errorf("unsupported address type %d", b[3]) + } + + port := binary.BigEndian.Uint16(b[pos : pos+2]) + return net.JoinHostPort(host, fmt.Sprint(port)), b[pos+2:], nil +} + +// buildUDPDatagram wraps a payload with the header naming its destination. +func buildUDPDatagram(dest string, payload []byte) ([]byte, error) { + host, portStr, err := net.SplitHostPort(dest) + if err != nil { + return nil, err + } + port, err := net.LookupPort("udp", portStr) + if err != nil { + return nil, err + } + + // Prefer a numeric form; only fall back to the name when there is no + // address literal, which is how a client names a domain it wants us to + // resolve. + var hostBytes []byte + var atyp byte + if ip := net.ParseIP(host); ip != nil { + if v4 := ip.To4(); v4 != nil { + atyp, hostBytes = addrTypeIPv4, v4 + } else { + atyp, hostBytes = addrTypeIPv6, ip.To16() + } + } else { + if len(host) > 255 { + return nil, fmt.Errorf("destination host is %d bytes, too long for a SOCKS5 header", len(host)) + } + atyp = addrTypeFQDN + hostBytes = append([]byte{byte(len(host))}, host...) + } + + out := make([]byte, 0, 4+len(hostBytes)+2+len(payload)) + out = append(out, 0, 0, udpFragFirst, atyp) + out = append(out, hostBytes...) + out = binary.BigEndian.AppendUint16(out, uint16(port)) + return append(out, payload...), nil +} + +// resolveUDPAddr turns "host:port" into something DialUDP accepts, resolving a +// name when necessary. It returns nil when the name does not resolve, rather +// than handing back an empty address and letting the dial report it. +func resolveUDPAddr(dest string) *net.UDPAddr { + addr, err := net.ResolveUDPAddr("udp", dest) + if err != nil { + return nil + } + return addr +} + +// udpNetwork keeps the destination socket in the relay's own family, so an IPv4 +// association never opens an IPv6 destination it cannot answer on. +func udpNetwork(addr *net.UDPAddr) string { + if addr.IP.To4() != nil { + return "udp4" + } + return "udp6" +} + +// sendUDPAssociateReply tells the client which UDP socket to send to. The reply +// is the only place that address is published, which is why an attacker who has +// not completed the TCP handshake cannot find the relay socket. +func (s *ProxyServer) sendUDPAssociateReply(conn net.Conn, addr net.Addr, cfg *Config) error { + udpAddr, ok := addr.(*net.UDPAddr) + if !ok { + return fmt.Errorf("relay socket is %T, not a UDP address", addr) + } + conn.SetWriteDeadline(time.Now().Add(time.Duration(cfg.WriteTimeout) * time.Second)) + + resp := []byte{socksVersion, replySucceeded, 0x00} + if v4 := udpAddr.IP.To4(); v4 != nil { + resp = append(resp, addrTypeIPv4) + resp = append(resp, v4...) + } else { + resp = append(resp, addrTypeIPv6) + resp = append(resp, udpAddr.IP.To16()...) + } + resp = binary.BigEndian.AppendUint16(resp, uint16(udpAddr.Port)) + + _, err := conn.Write(resp) + return err +} + +// userAllowedUDP applies the same tier rules to an association as to a TCP +// session. Expiry and data use are checked with exactly the same logic the TCP +// path uses; an association that would not be allowed to open a TCP connection +// has no business opening UDP targets. +func (s *ProxyServer) userAllowedUDP(user *User, log *slog.Logger) bool { + if user == nil || s.store == nil { + return true + } + if user.Expiry != nil { + if expiry, err := time.Parse("2006-01-02 15:04:05", *user.Expiry); err == nil && time.Now().After(expiry) { + log.Warn("user account expired") + return false + } + } + if user.DataLimitBytes > 0 && user.DataUsedBytes >= user.DataLimitBytes { + log.Warn("user data limit reached", "used", user.DataUsedBytes, "limit", user.DataLimitBytes) + return false + } + if user.MaxConnections > 0 { + if active, err := s.store.GetActiveConnCount(user.ID); err == nil && active >= int64(user.MaxConnections) { + log.Warn("user connection limit reached", "active", active, "limit", user.MaxConnections) + return false + } + } + return true +} diff --git a/udp_test.go b/udp_test.go new file mode 100644 index 0000000..e3b2638 --- /dev/null +++ b/udp_test.go @@ -0,0 +1,478 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "io" + "net" + "strings" + "testing" + "time" +) + +// ─── A minimal SOCKS5 UDP client ──────────────────────────────────────────── +// +// There is no SOCKS5 UDP client in the standard library and adding one as a +// dependency for a test would be silly: the wire format is five fields, and +// writing them out here is also the clearest statement of what the relay is +// expected to understand. + +type udpClient struct { + t *testing.T + control net.Conn + socket *net.UDPConn +} + +// associate performs the TCP handshake and UDP ASSOCIATE, returning the relay +// address the server chose. +func newUDPClient(t *testing.T, proxyAddr string) *udpClient { + t.Helper() + + control, err := net.Dial("tcp", proxyAddr) + if err != nil { + t.Fatalf("dial proxy: %v", err) + } + t.Cleanup(func() { control.Close() }) + + // Greeting: no-auth, for the tests that do not care about credentials. + if _, err := control.Write([]byte{0x05, 0x01, 0x00}); err != nil { + t.Fatalf("greeting: %v", err) + } + sel := make([]byte, 2) + if _, err := io.ReadFull(control, sel); err != nil { + t.Fatalf("greeting reply: %v", err) + } + if sel[1] != 0x00 { + t.Fatalf("server selected method 0x%02x, want no-auth", sel[1]) + } + + // UDP ASSOCIATE, with 0.0.0.0:0 as the suggestion. + req := []byte{0x05, 0x03, 0x00, 0x01, 0, 0, 0, 0, 0, 0} + if _, err := control.Write(req); err != nil { + t.Fatalf("associate: %v", err) + } + head := make([]byte, 4) + if _, err := io.ReadFull(control, head); err != nil { + t.Fatalf("associate reply: %v", err) + } + if head[1] != replySucceeded { + t.Fatalf("associate reply = 0x%02x, want success", head[1]) + } + + var host net.IP + var port uint16 + switch head[3] { + case addrTypeIPv4: + buf := make([]byte, 6) + io.ReadFull(control, buf) + host, port = net.IP(buf[:4]), binary.BigEndian.Uint16(buf[4:]) + case addrTypeIPv6: + buf := make([]byte, 18) + io.ReadFull(control, buf) + host, port = net.IP(buf[:16]), binary.BigEndian.Uint16(buf[16:]) + default: + t.Fatalf("associate reply used address type %d", head[3]) + } + if host.IsUnspecified() { + host = net.IPv4(127, 0, 0, 1) + } + + raddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(host.String(), fmt.Sprint(port))) + if err != nil { + t.Fatalf("resolve relay socket: %v", err) + } + socket, err := net.DialUDP("udp", nil, raddr) + if err != nil { + t.Fatalf("dial relay socket: %v", err) + } + t.Cleanup(func() { socket.Close() }) + + return &udpClient{t: t, control: control, socket: socket} +} + +// send wraps a payload and sends it to the destination through the relay. +func (c *udpClient) send(dest string, payload []byte) error { + datagram, err := buildUDPDatagram(dest, payload) + if err != nil { + return err + } + _, err = c.socket.Write(datagram) + return err +} + +// receive reads one relayed datagram and returns its payload. +func (c *udpClient) receive(timeout time.Duration) ([]byte, error) { + c.socket.SetReadDeadline(time.Now().Add(timeout)) + buf := make([]byte, 65535) + n, err := c.socket.Read(buf) + if err != nil { + return nil, err + } + _, payload, err := parseUDPDatagram(buf[:n]) + return payload, err +} + +// echoServer answers every datagram with an uppercased copy. +func echoServer(t *testing.T) string { + t.Helper() + conn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatalf("echo listen: %v", err) + } + t.Cleanup(func() { conn.Close() }) + go func() { + buf := make([]byte, 65535) + for { + n, from, rerr := conn.ReadFromUDP(buf) + if rerr != nil { + return + } + conn.WriteToUDP(bytes.ToUpper(buf[:n]), from) + } + }() + return conn.LocalAddr().String() +} + +// startUDPProxy runs a proxy with a fixed proxy port and returns its address. +func startUDPProxy(t *testing.T, mutate func(*Config)) string { + t.Helper() + cfg := DefaultConfig() + cfg.AuthEnabled = false + cfg.AdminEnabled = false + cfg.SecurityHeadersEnabled = false + cfg.RateLimitEnabled = false + if mutate != nil { + mutate(&cfg) + } + cfg.ProxyPort = freePort(t) + + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", cfg.ProxyPort)) + if err != nil { + t.Fatalf("listen: %v", err) + } + t.Cleanup(func() { ln.Close() }) + + server := NewProxyServer(cfg) + go func() { + for { + conn, aerr := ln.Accept() + if aerr != nil { + return + } + go server.handleClient(conn, "") + } + }() + return ln.Addr().String() +} + +// ─── Tests ────────────────────────────────────────────────────────────────── + +func TestUDPAssociateRoundTrip(t *testing.T) { + proxy := startUDPProxy(t, nil) + echo := echoServer(t) + + client := newUDPClient(t, proxy) + if err := client.send(echo, []byte("hello dns")); err != nil { + t.Fatalf("send: %v", err) + } + got, err := client.receive(5 * time.Second) + if err != nil { + t.Fatalf("receive: %v", err) + } + if string(got) != "HELLO DNS" { + t.Errorf("relayed %q, want %q", got, "HELLO DNS") + } +} + +// Several destinations in one association, each on its own socket, replies +// routed back to the right one. +func TestUDPAssociationHandlesManyDestinations(t *testing.T) { + proxy := startUDPProxy(t, nil) + echo1 := echoServer(t) + echo2 := echoServer(t) + + client := newUDPClient(t, proxy) + for i, dest := range []string{echo1, echo2, echo1, echo2} { + payload := []byte(fmt.Sprintf("packet-%d", i)) + if err := client.send(dest, payload); err != nil { + t.Fatalf("send %d: %v", i, err) + } + got, err := client.receive(5 * time.Second) + if err != nil { + t.Fatalf("receive %d: %v", i, err) + } + want := strings.ToUpper(string(payload)) + if string(got) != want { + t.Errorf("destination %s: got %q, want %q", dest, got, want) + } + } +} + +// UDP accounting must reach the same counters TCP does, or the dashboard shows +// a proxy that is carrying traffic nobody can see. +func TestUDPAssociationIsAccounted(t *testing.T) { + echo := echoServer(t) + cfg := DefaultConfig() + cfg.AuthEnabled = false + cfg.AdminEnabled = false + cfg.SecurityHeadersEnabled = false + cfg.RateLimitEnabled = false + cfg.ProxyPort = freePort(t) + + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", cfg.ProxyPort)) + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() + + server := NewProxyServer(cfg) + before := server.totalConns.Load() + go func() { + for { + conn, aerr := ln.Accept() + if aerr != nil { + return + } + go server.handleClient(conn, "") + } + }() + + client := newUDPClient(t, ln.Addr().String()) + if err := client.send(echo, []byte("counted")); err != nil { + t.Fatalf("send: %v", err) + } + if _, err := client.receive(5 * time.Second); err != nil { + t.Fatalf("receive: %v", err) + } + if got := server.totalConns.Load(); got <= before { + t.Errorf("total connections = %d, want more than %d: the UDP session was not accounted", got, before) + } +} + +// Fragmented datagrams are dropped rather than reassembled; the RFC allows a +// client to send them and says nothing about what a server should do, and +// guessing would mean unbounded buffering. +func TestUDPFragmentedDatagramIsDropped(t *testing.T) { + proxy := startUDPProxy(t, nil) + echo := echoServer(t) + client := newUDPClient(t, proxy) + + datagram, err := buildUDPDatagram(echo, []byte("fragment")) + if err != nil { + t.Fatal(err) + } + datagram[2] = 1 // FRAG = 1: more fragments follow + + if _, err := client.socket.Write(datagram); err != nil { + t.Fatal(err) + } + if _, err := client.receive(700 * time.Millisecond); err == nil { + t.Error("a fragmented datagram was relayed; it must be dropped") + } + + // The association must still work afterwards. + if err := client.send(echo, []byte("after")); err != nil { + t.Fatalf("send after fragment: %v", err) + } + if _, err := client.receive(5 * time.Second); err != nil { + t.Fatalf("association unusable after a dropped fragment: %v", err) + } +} + +func TestUDPMalformedDatagramIsDropped(t *testing.T) { + proxy := startUDPProxy(t, nil) + echo := echoServer(t) + client := newUDPClient(t, proxy) + + for _, bad := range [][]byte{ + {0x05}, + {0x00, 0x00, 0x00, 0x01, 1, 2, 3}, // truncated + {0x01, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0}, // RSV not zero + } { + if _, err := client.socket.Write(bad); err != nil { + t.Fatalf("write malformed datagram: %v", err) + } + } + if _, err := client.receive(700 * time.Millisecond); err == nil { + t.Error("a malformed datagram was relayed") + } + if err := client.send(echo, []byte("still-alive")); err != nil { + t.Fatalf("send after malformed datagrams: %v", err) + } + if got, err := client.receive(5 * time.Second); err != nil || string(got) != "STILL-ALIVE" { + t.Errorf("after malformed datagrams: got %q, err %v", got, err) + } +} + +// The operator can turn UDP off, and then the client is told so rather than +// being left waiting for an address that never comes. +func TestUDPAssociateRefusedWhenDisabled(t *testing.T) { + proxy := startUDPProxy(t, func(c *Config) { c.UDPEnabled = false }) + + control, err := net.Dial("tcp", proxy) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer control.Close() + control.Write([]byte{0x05, 0x01, 0x00}) + sel := make([]byte, 2) + io.ReadFull(control, sel) + control.Write([]byte{0x05, 0x03, 0x00, 0x01, 0, 0, 0, 0, 0, 0}) + + head := make([]byte, 4) + if _, err := io.ReadFull(control, head); err != nil { + t.Fatalf("reply: %v", err) + } + if head[1] == replySucceeded { + t.Error("UDP ASSOCIATE succeeded with udp_enabled=false") + } + if head[1] != replyCmdNotSupported { + t.Errorf("reply = 0x%02x, want 0x%02x (command not supported)", head[1], replyCmdNotSupported) + } +} + +// Closing the control connection ends the association, which is how a client +// tells the server it is finished. +func TestUDPAssociationEndsWithControlConnection(t *testing.T) { + proxy := startUDPProxy(t, nil) + echo := echoServer(t) + + client := newUDPClient(t, proxy) + if err := client.send(echo, []byte("alive")); err != nil { + t.Fatalf("send: %v", err) + } + if _, err := client.receive(5 * time.Second); err != nil { + t.Fatalf("receive: %v", err) + } + + client.control.Close() + + // After the control connection dies the relay socket stops answering. Give + // the teardown a moment, then send into the void. + time.Sleep(300 * time.Millisecond) + if err := client.send(echo, []byte("after-close")); err == nil { + if _, err := client.receive(time.Second); err == nil { + t.Error("the relay socket still answers after the control connection closed") + } + } +} + +// TCP is unaffected: an ordinary CONNECT still works on a proxy that also +// offers UDP. +func TestTCPConnectStillWorksAlongsideUDP(t *testing.T) { + proxy := startUDPProxy(t, nil) + + origin, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("origin listen: %v", err) + } + defer origin.Close() + go func() { + conn, aerr := origin.Accept() + if aerr != nil { + return + } + defer conn.Close() + io.WriteString(conn, "tcp-still-works") + }() + + conn := socks5Connect(t, proxy, "127.0.0.1", origin.Addr().(*net.TCPAddr).Port) + defer conn.Close() + body := make([]byte, len("tcp-still-works")) + if _, err := io.ReadFull(conn, body); err != nil { + t.Fatalf("read: %v", err) + } + if string(body) != "tcp-still-works" { + t.Errorf("got %q", body) + } +} + +// ─── Header encoding ──────────────────────────────────────────────────────── + +func TestUDPDatagramRoundTrip(t *testing.T) { + for _, dest := range []string{ + "1.2.3.4:53", + "[2001:db8::1]:5353", + "dns.example.com:853", + } { + payload := []byte("payload for " + dest) + datagram, err := buildUDPDatagram(dest, payload) + if err != nil { + t.Fatalf("build %s: %v", dest, err) + } + gotDest, gotPayload, err := parseUDPDatagram(datagram) + if err != nil { + t.Fatalf("parse %s: %v", dest, err) + } + if gotDest != dest { + t.Errorf("destination %q round-tripped to %q", dest, gotDest) + } + if !bytes.Equal(gotPayload, payload) { + t.Errorf("payload %q round-tripped to %q", payload, gotPayload) + } + } +} + +func TestUDPDatagramRejectsGarbage(t *testing.T) { + cases := map[string][]byte{ + "empty": {}, + "short header": {0, 0, 0, 1}, + "fragmented": {0, 0, 1, 1, 127, 0, 0, 1, 0, 53, 1}, + "bad address type": {0, 0, 0, 9, 1, 2, 3, 4, 0, 53, 1}, + "truncated v4": {0, 0, 0, 1, 127, 0}, + "reserved set": {0, 9, 0, 1, 127, 0, 0, 1, 0, 53, 1}, + } + for name, b := range cases { + if _, _, err := parseUDPDatagram(b); err == nil { + t.Errorf("%s: parseUDPDatagram accepted % x", name, b) + } + } +} + +// A single control connection must not be able to ask for an unbounded number of +// destination sockets, because the TCP connection limit cannot see them. +func TestUDPDestinationCap(t *testing.T) { + proxy := startUDPProxy(t, nil) + client := newUDPClient(t, proxy) + + // Every destination answers, so each one stays open and the cap is the only + // thing that can stop the association from opening more. + answering := func(i int) string { + conn, lerr := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if lerr != nil { + t.Fatalf("echo listen %d: %v", i, lerr) + } + t.Cleanup(func() { conn.Close() }) + go func() { + buf := make([]byte, 2048) + for { + n, from, rerr := conn.ReadFromUDP(buf) + if rerr != nil { + return + } + conn.WriteToUDP(buf[:n], from) + } + }() + return conn.LocalAddr().String() + } + + for i := 0; i < udpMaxTargets; i++ { + if err := client.send(answering(i), []byte("fill")); err != nil { + t.Fatalf("send %d: %v", i, err) + } + if _, err := client.receive(5 * time.Second); err != nil { + t.Fatalf("first udpMaxTargets destinations must all work, %d failed: %v", i, err) + } + } + + // The one past the cap is dropped. Nothing to wait for: silence is the + // contract. + if err := client.send(answering(udpMaxTargets), []byte("over")); err != nil { + t.Fatalf("send past cap: %v", err) + } + client.socket.SetReadDeadline(time.Now().Add(750 * time.Millisecond)) + if _, err := client.socket.Read(make([]byte, 65535)); err == nil { + t.Error("datagram past the destination cap was relayed") + } +}