return unreachable for ipv6 addresses to force ipv4 (#159)

This commit is contained in:
kulikov0 authored and GitHub committed 2026-07-24 14:38:57 +02:00
1 parent a0229885ca
commit f4714f93d6
7 files changed
+232 -29

No files matched your search

+4 -18
View File
@@ -26,7 +26,6 @@ const (
const readBufSize = 65536
var framePool = sync.Pool{
New: func() any {
buf := make([]byte, 5+readBufSize)
@@ -72,7 +71,6 @@ func logMsg(format string, args ...any) {
}
}
type wsWriter struct {
ws *websocket.Conn
ch chan []byte
@@ -113,7 +111,6 @@ func (w *wsWriter) close() {
<-w.done
}
var activeJoiner struct {
sync.Mutex
j *joinerRelay
@@ -289,13 +286,7 @@ func (j *joinerRelay) handleUDPAssociate(tcpConn net.Conn) {
binary.BigEndian.Uint16(buf[5+dlen:7+dlen]))
headerLen = 5 + dlen + 2
case common.AtypIPv6:
if n < 22 {
continue
}
ip := net.IP(buf[4:20])
dstAddr = fmt.Sprintf("[%s]:%d", ip.String(),
binary.BigEndian.Uint16(buf[20:22]))
headerLen = 22
continue
default:
continue
}
@@ -430,13 +421,9 @@ func (j *joinerRelay) handleSOCKS(conn net.Conn) {
host = fmt.Sprintf("%s:%d", string(buf[5:5+dlen]),
binary.BigEndian.Uint16(buf[5+dlen:7+dlen]))
case common.AtypIPv6:
if n < 22 {
conn.Close()
return
}
ip := net.IP(buf[4:20])
host = fmt.Sprintf("[%s]:%d", ip.String(),
binary.BigEndian.Uint16(buf[20:22]))
conn.Write(common.NetUnreach)
conn.Close()
return
default:
conn.Write(common.AddrErr)
conn.Close()
@@ -471,4 +458,3 @@ func (j *joinerRelay) handleSOCKS(conn net.Conn) {
}
}()
}
+18 -2
View File
@@ -27,7 +27,8 @@ import (
)
var (
tunReady sync.WaitGroup
tunReady sync.WaitGroup
activeFilter *v6Filter
)
func StartTun2Socks(fd, mtu, socksPort int, socksUser, socksPass string) error {
@@ -41,9 +42,20 @@ func StartTun2Socks(fd, mtu, socksPort int, socksUser, socksPass string) error {
os.Setenv("TUN2SOCKS_LOG_LEVEL", "info")
tunReady.Add(1)
defer tunReady.Done()
deviceFd := fd
filter, stackFd, err := startV6Filter(fd, mtu)
if err != nil {
logMsg("tun2socks: v6 filter setup failed: %v, capturing IPv4 only", err)
} else {
activeFilter = filter
deviceFd = stackFd
logMsg("tun2socks: v6 reject filter active")
}
key := &engine.Key{
Proxy: proxy,
Device: fmt.Sprintf("fd://%d", fd),
Device: fmt.Sprintf("fd://%d", deviceFd),
MTU: mtu,
}
engine.Insert(key)
@@ -56,5 +68,9 @@ func StopTun2Socks() {
tunReady.Wait()
C.disable_fdsan()
engine.Stop()
if activeFilter != nil {
activeFilter.stop()
activeFilter = nil
}
logMsg("tun2socks: stopped")
}
+182
View File
@@ -0,0 +1,182 @@
//go:build android
package androidbind
import (
"encoding/binary"
"os"
"sync"
"syscall"
)
const (
ipv6HeaderLen = 40
tcpHeaderLen = 20
icmpv6HeaderLen = 8
nextHeaderTCP = 6
nextHeaderUDP = 17
nextHeaderICMPv6 = 58
tcpFlagSYN = 0x02
tcpFlagRST = 0x04
tcpFlagACK = 0x10
minIPv6MTU = 1280
)
type v6Filter struct {
tunFile *os.File
stackOur *os.File
writeMu sync.Mutex
once sync.Once
}
func startV6Filter(tunFd, mtu int) (*v6Filter, int, error) {
pair, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
if err != nil {
return nil, 0, err
}
f := &v6Filter{
tunFile: os.NewFile(uintptr(tunFd), "vpntun"),
stackOur: os.NewFile(uintptr(pair[0]), "v6filter"),
}
go f.tunToStack(mtu)
go f.stackToTun(mtu)
return f, pair[1], nil
}
func (f *v6Filter) writeTun(pkt []byte) {
f.writeMu.Lock()
f.tunFile.Write(pkt)
f.writeMu.Unlock()
}
func (f *v6Filter) tunToStack(mtu int) {
buf := make([]byte, mtu+128)
for {
n, err := f.tunFile.Read(buf)
if err != nil {
return
}
if n < 1 {
continue
}
switch buf[0] >> 4 {
case 4:
f.stackOur.Write(buf[:n])
case 6:
if reject := buildV6Reject(buf[:n]); reject != nil {
f.writeTun(reject)
}
}
}
}
func (f *v6Filter) stackToTun(mtu int) {
buf := make([]byte, mtu+128)
for {
n, err := f.stackOur.Read(buf)
if err != nil {
return
}
if n > 0 {
f.writeTun(buf[:n])
}
}
}
func (f *v6Filter) stop() {
f.once.Do(func() {
f.stackOur.Close()
f.tunFile.Close()
})
}
// buildV6Reject turns a captured IPv6 packet into an on-device refusal so the
// app falls back to IPv4 immediately: a TCP RST for a connection-initiating
// SYN, an ICMPv6 "no route to destination" for UDP. Anything else, including
// packets carrying extension headers, returns nil and is dropped.
func buildV6Reject(pkt []byte) []byte {
if len(pkt) < ipv6HeaderLen {
return nil
}
switch pkt[6] {
case nextHeaderTCP:
return buildV6TCPReset(pkt)
case nextHeaderUDP:
return buildV6ICMPUnreachable(pkt)
default:
return nil
}
}
func buildV6TCPReset(pkt []byte) []byte {
if len(pkt) < ipv6HeaderLen+tcpHeaderLen {
return nil
}
tcp := pkt[ipv6HeaderLen:]
flags := tcp[13]
if flags&tcpFlagSYN == 0 || flags&tcpFlagACK != 0 {
return nil
}
seq := binary.BigEndian.Uint32(tcp[4:8])
out := make([]byte, ipv6HeaderLen+tcpHeaderLen)
out[0] = 0x60
binary.BigEndian.PutUint16(out[4:6], tcpHeaderLen)
out[6] = nextHeaderTCP
out[7] = 64
copy(out[8:24], pkt[24:40])
copy(out[24:40], pkt[8:24])
reset := out[ipv6HeaderLen:]
copy(reset[0:2], tcp[2:4])
copy(reset[2:4], tcp[0:2])
binary.BigEndian.PutUint32(reset[8:12], seq+1)
reset[12] = 5 << 4
reset[13] = tcpFlagRST | tcpFlagACK
binary.BigEndian.PutUint16(reset[16:18], transportChecksum(out[8:24], out[24:40], nextHeaderTCP, reset))
return out
}
func buildV6ICMPUnreachable(pkt []byte) []byte {
embed := pkt
if max := minIPv6MTU - ipv6HeaderLen - icmpv6HeaderLen; len(embed) > max {
embed = embed[:max]
}
msgLen := icmpv6HeaderLen + len(embed)
out := make([]byte, ipv6HeaderLen+msgLen)
out[0] = 0x60
binary.BigEndian.PutUint16(out[4:6], uint16(msgLen))
out[6] = nextHeaderICMPv6
out[7] = 64
copy(out[8:24], pkt[24:40])
copy(out[24:40], pkt[8:24])
icmp := out[ipv6HeaderLen:]
icmp[0] = 1 // Destination Unreachable
icmp[1] = 0 // no route to destination
copy(icmp[icmpv6HeaderLen:], embed)
binary.BigEndian.PutUint16(icmp[2:4], transportChecksum(out[8:24], out[24:40], nextHeaderICMPv6, icmp))
return out
}
func transportChecksum(srcIP, dstIP []byte, nextHeader uint32, payload []byte) uint16 {
var sum uint32
add := func(b []byte) {
for i := 0; i+1 < len(b); i += 2 {
sum += uint32(b[i])<<8 | uint32(b[i+1])
}
if len(b)&1 == 1 {
sum += uint32(b[len(b)-1]) << 8
}
}
add(srcIP)
add(dstIP)
sum += uint32(len(payload))
sum += nextHeader
add(payload)
for sum>>16 != 0 {
sum = (sum & 0xffff) + (sum >> 16)
}
return ^uint16(sum)
}
+9 -8
View File
@@ -25,17 +25,18 @@ const (
RTPBufSize = 65536
// VP8BufSize fits one RTP packet: 1200 MTU - 1 VP8 descriptor - 64 tunnel wrapper - 9 protocol frame
// (tunnel wrapper = 20 vp8 keepalive header + 4 epoch + 24 XChaCha20 nonce + 16 Poly1305 tag)
VP8BufSize = 1126
DCBufSize = 32768
VP8BufSize = 1126
DCBufSize = 32768
)
var (
NoAuth = []byte{Ver, AuthNone}
OK = []byte{Ver, 0x00, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
ConnFail = []byte{Ver, 0x05, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
CmdErr = []byte{Ver, 0x07, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
AddrErr = []byte{Ver, 0x08, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
GenFail = []byte{Ver, 0x01, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
NoAuth = []byte{Ver, AuthNone}
OK = []byte{Ver, 0x00, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
ConnFail = []byte{Ver, 0x05, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
NetUnreach = []byte{Ver, 0x03, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
CmdErr = []byte{Ver, 0x07, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
AddrErr = []byte{Ver, 0x08, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
GenFail = []byte{Ver, 0x01, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
)
func NegotiateAuth(conn net.Conn, buf []byte, n int, wantUser, wantPass string) bool {
+9 -1
View File
@@ -583,6 +583,11 @@ func (rb *RelayBridge) handleSOCKS(conn net.Conn) {
conn.Close()
return
}
if buf[3] == common.AtypIPv6 {
conn.Write(common.NetUnreach)
conn.Close()
return
}
host, _, err := common.ParseAddress(buf, n)
if err != nil {
conn.Write(common.AddrErr)
@@ -598,7 +603,7 @@ func (rb *RelayBridge) handleSOCKS(conn net.Conn) {
}
// Dial local/private addresses directly instead of tunneling to the creator,
// which cannot reach the joiner's local network. Disabled for now until
// there is a real use case for local network access through the proxy. So idk if
// there is a real use case for local network access through the proxy. So idk if
// this is a bug or a feature
// if ip := net.ParseIP(hostOnly); ip != nil && !ip.IsGlobalUnicast() {
// rb.logFn("relay: SOCKS local dial %s", common.MaskAddr(host))
@@ -737,6 +742,9 @@ func (rb *RelayBridge) handleUDPAssociate(tcpConn net.Conn) {
if frag != 0 {
continue
}
if buf[3] == common.AtypIPv6 {
continue
}
dstAddr, headerLen, addrErr := common.ParseAddress(buf, n)
if addrErr != nil {
continue