diff --git a/adapter/inbound/util.go b/adapter/inbound/util.go index 0cc1e761a..81c3dde62 100644 --- a/adapter/inbound/util.go +++ b/adapter/inbound/util.go @@ -16,9 +16,11 @@ func parseSocksAddr(target socks5.Addr) *C.Metadata { switch target[0] { case socks5.AtypDomainName: + // Convert before arithmetic so long domain lengths cannot overflow a byte. + domainEnd := 2 + int(target[1]) // trim for FQDN - metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".") - metadata.DstPort = uint16((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1])) + metadata.Host = strings.TrimRight(string(target[2:domainEnd]), ".") + metadata.DstPort = uint16(target[domainEnd])<<8 | uint16(target[domainEnd+1]) case socks5.AtypIPv4: metadata.DstIP, _ = netip.AddrFromSlice(target[1 : 1+net.IPv4len]) metadata.DstPort = uint16((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1])) diff --git a/adapter/inbound/util_test.go b/adapter/inbound/util_test.go new file mode 100644 index 000000000..7db637fd0 --- /dev/null +++ b/adapter/inbound/util_test.go @@ -0,0 +1,33 @@ +package inbound + +import ( + "fmt" + "strings" + "testing" + + "github.com/metacubex/mihomo/transport/socks5" +) + +func TestParseSocksAddrDomainLengths(t *testing.T) { + for length := 0; length <= 255; length++ { + t.Run(fmt.Sprint(length), func(t *testing.T) { + host := strings.Repeat("a", length) + addr := append(socks5.Addr{socks5.AtypDomainName, byte(length)}, []byte(host)...) + addr = append(addr, 0x12, 0x34) + got := parseSocksAddr(addr) + if got.Host != host || got.DstPort != 0x1234 { + t.Fatalf("length %d: host=%q port=%d", length, got.Host, got.DstPort) + } + }) + } +} + +func TestParseSocksAddrFQDN(t *testing.T) { + host := "example.com." + addr := append(socks5.Addr{socks5.AtypDomainName, byte(len(host))}, []byte(host)...) + addr = append(addr, 0x01, 0xbb) + got := parseSocksAddr(addr) + if got.Host != "example.com" || got.DstPort != 443 { + t.Fatalf("host=%q port=%d", got.Host, got.DstPort) + } +}