1- use std:: collections:: HashMap ;
2- use std:: net:: { IpAddr , Ipv4Addr , SocketAddr } ;
1+ use std:: collections:: { HashMap , VecDeque } ;
2+ use std:: net:: SocketAddr ;
33use std:: sync:: Arc ;
44use std:: time:: Duration ;
55
@@ -604,6 +604,22 @@ const UDP_INITIAL_POLL_DELAY: Duration = Duration::from_millis(500);
604604/// so an idle UDP destination costs roughly one batch slot every 35 s.
605605const UDP_MAX_POLL_DELAY : Duration = Duration :: from_secs ( 30 ) ;
606606
607+ /// Cap on simultaneous UDP relay sessions per SOCKS5 ASSOCIATE. STUN
608+ /// candidate gathering and DNS fanout produce dozens of distinct
609+ /// targets; an abusive or runaway client could produce thousands.
610+ /// 256 is generous for legitimate use and bounds tunnel-node UDP
611+ /// sessions a single ASSOCIATE can hold open. On overflow we evict
612+ /// the least-recently-inserted target (rough LRU — good enough for
613+ /// long-tail eviction without tracking access on the hot path).
614+ const MAX_UDP_SESSIONS_PER_ASSOCIATE : usize = 256 ;
615+
616+ /// Drop UDP datagrams larger than this (pre-base64). Standard MTU is
617+ /// 1500B, jumbo frames are ~9000B; anything above that is either a
618+ /// pathologically fragmented IP datagram or abusive traffic. Each
619+ /// datagram carries ~33% base64 + JSON envelope overhead and consumes
620+ /// Apps Script per-account quota, so a permissive ceiling here matters.
621+ const MAX_UDP_PAYLOAD_BYTES : usize = 9 * 1024 ;
622+
607623async fn handle_socks5_udp_associate (
608624 mut control : TcpStream ,
609625 rewrite_ctx : Arc < RewriteCtx > ,
@@ -623,15 +639,18 @@ async fn handle_socks5_udp_associate(
623639 // Per RFC 1928 §6 the UDP relay only accepts datagrams from the
624640 // SOCKS5 client. We pin the source IP to the control TCP peer up
625641 // front so a third party on the bind interface can't hijack the
626- // session by sending the first datagram.
642+ // session by sending the first datagram. THIS — not the bind IP
643+ // below — is what actually keeps unauthenticated traffic out.
627644 let client_peer_ip = control. peer_addr ( ) ?. ip ( ) ;
628645
629- // The local TUN bridge talks to us over loopback. Binding the UDP relay
630- // there avoids exposing an unauthenticated UDP socket on LAN interfaces.
631- let bind_ip = match control. local_addr ( ) ?. ip ( ) {
632- IpAddr :: V4 ( ip) if ip. is_unspecified ( ) => IpAddr :: V4 ( Ipv4Addr :: LOCALHOST ) ,
633- ip => ip,
634- } ;
646+ // Bind the UDP relay to the same local IP the SOCKS5 client used
647+ // to reach the control TCP socket. `TcpStream::local_addr()` on an
648+ // accepted socket returns the concrete terminating address (e.g.
649+ // 127.0.0.1 for a loopback client, 192.168.1.5 for a LAN client),
650+ // not the listener's bind specifier — so this naturally tracks the
651+ // path the client took. Source-IP filtering above is the security
652+ // boundary; the bind choice is just about reachability.
653+ let bind_ip = control. local_addr ( ) ?. ip ( ) ;
635654 let udp = Arc :: new ( UdpSocket :: bind ( SocketAddr :: new ( bind_ip, 0 ) ) . await ?) ;
636655 write_socks5_reply ( & mut control, 0x00 , Some ( udp. local_addr ( ) ?) ) . await ?;
637656 tracing:: info!(
@@ -645,6 +664,12 @@ async fn handle_socks5_udp_associate(
645664 let mut client_addr: Option < SocketAddr > = None ;
646665 let sessions: Arc < Mutex < HashMap < SocksUdpTarget , UdpRelaySession > > > =
647666 Arc :: new ( Mutex :: new ( HashMap :: new ( ) ) ) ;
667+ // Insertion-order log used for LRU-on-overflow eviction. We track
668+ // it alongside (rather than inside) the HashMap so eviction can
669+ // run under the same lock as the cap check.
670+ let mut insertion_order: VecDeque < SocksUdpTarget > = VecDeque :: new ( ) ;
671+ let mut oversized_dropped: u64 = 0 ;
672+ let mut sessions_evicted: u64 = 0 ;
648673
649674 loop {
650675 tokio:: select! {
@@ -674,6 +699,23 @@ async fn handle_socks5_udp_associate(
674699 let Some ( ( target, payload) ) = parse_socks5_udp_packet( & buf[ ..n] ) else {
675700 continue ;
676701 } ;
702+
703+ // Size guard: drop oversize datagrams before they reach
704+ // the mux. Each datagram costs ~payload * 1.33 in the
705+ // batched JSON envelope plus tunnel-node CPU; uncapped,
706+ // a runaway client can exhaust Apps Script quota.
707+ if payload. len( ) > MAX_UDP_PAYLOAD_BYTES {
708+ oversized_dropped += 1 ;
709+ if oversized_dropped == 1 || oversized_dropped. is_multiple_of( 100 ) {
710+ tracing:: debug!(
711+ "udp datagram dropped: {} B > {} B (count={})" ,
712+ payload. len( ) ,
713+ MAX_UDP_PAYLOAD_BYTES ,
714+ oversized_dropped,
715+ ) ;
716+ }
717+ continue ;
718+ }
677719 let payload = payload. to_vec( ) ;
678720
679721 // Fast path: existing session — push payload onto its
@@ -686,6 +728,35 @@ async fn handle_socks5_udp_associate(
686728 }
687729 }
688730
731+ // Cap reached → evict the oldest session before opening
732+ // a new one. The evicted target's `UdpRelaySession` is
733+ // dropped here, which closes its uplink channel; the
734+ // task then exits its select! and tells tunnel-node to
735+ // close. Any in-flight uplink already in the channel is
736+ // delivered before the task exits.
737+ {
738+ let mut sess = sessions. lock( ) . await ;
739+ while sess. len( ) >= MAX_UDP_SESSIONS_PER_ASSOCIATE {
740+ let Some ( victim) = insertion_order. pop_front( ) else {
741+ break ;
742+ } ;
743+ if sess. remove( & victim) . is_some( ) {
744+ sessions_evicted += 1 ;
745+ if sessions_evicted == 1
746+ || sessions_evicted. is_multiple_of( 50 )
747+ {
748+ tracing:: debug!(
749+ "udp session cap {} reached; evicted {}:{} (total evicted={})" ,
750+ MAX_UDP_SESSIONS_PER_ASSOCIATE ,
751+ victim. host,
752+ victim. port,
753+ sessions_evicted,
754+ ) ;
755+ }
756+ }
757+ }
758+ }
759+
689760 // New target: open via tunnel-node and spawn the per-session
690761 // task. The first datagram rides the udp_open op so we
691762 // save one round trip on session establishment.
@@ -734,6 +805,7 @@ async fn handle_socks5_udp_associate(
734805 task_sessions. lock( ) . await . remove( & task_target) ;
735806 } ) ;
736807
808+ insertion_order. push_back( target. clone( ) ) ;
737809 sessions
738810 . lock( )
739811 . await
@@ -832,7 +904,20 @@ async fn send_udp_response_packets(
832904 } ;
833905 for packet in packets {
834906 let framed = build_socks5_udp_packet ( target, & packet) ;
835- let _ = udp. send_to ( & framed, client_addr) . await ;
907+ if let Err ( e) = udp. send_to ( & framed, client_addr) . await {
908+ // Errors here mean the local socket can't reach the SOCKS5
909+ // client (ENETUNREACH, EHOSTDOWN, etc.). Surface at debug
910+ // so a "my UDP traffic isn't coming back" report has
911+ // something to grep for; volume is bounded by what we'd
912+ // have delivered anyway.
913+ tracing:: debug!(
914+ "udp send to client {} failed for {}:{}: {}" ,
915+ client_addr,
916+ target. host,
917+ target. port,
918+ e,
919+ ) ;
920+ }
836921 }
837922}
838923
@@ -890,7 +975,12 @@ fn parse_socks5_udp_packet(buf: &[u8]) -> Option<(SocksUdpTarget, &[u8])> {
890975 }
891976 let addr = buf[ pos..pos + len] . to_vec ( ) ;
892977 pos += len;
893- ( String :: from_utf8_lossy ( & addr) . into_owned ( ) , addr)
978+ // Reject non-UTF-8 hostnames at the parser. Lossy decoding
979+ // would forward U+FFFD into DNS and trigger an opaque
980+ // NXDOMAIN — failing fast here gives us a clean parse-level
981+ // drop that the test suite can assert on.
982+ let host = std:: str:: from_utf8 ( & addr) . ok ( ) ?. to_owned ( ) ;
983+ ( host, addr)
894984 }
895985 0x04 => {
896986 if buf. len ( ) < pos + 16 + 2 {
@@ -2026,6 +2116,15 @@ mod tests {
20262116 assert ! ( parse_socks5_udp_packet( & raw) . is_none( ) ) ;
20272117 }
20282118
2119+ #[ test]
2120+ fn socks5_udp_rejects_non_utf8_domain ( ) {
2121+ // Lone continuation byte (0x80) — not valid UTF-8. Lossy decode
2122+ // would forward U+FFFD into DNS; strict parse should reject so
2123+ // we fail fast instead of issuing a doomed lookup.
2124+ let raw = [ 0 , 0 , 0 , 0x03 , 1 , 0x80 , 0 , 80 ] ;
2125+ assert ! ( parse_socks5_udp_packet( & raw) . is_none( ) ) ;
2126+ }
2127+
20292128 #[ test]
20302129 fn socks5_udp_rejects_truncated_inputs ( ) {
20312130 // Header alone is not enough.
0 commit comments