shadowsocks / go-shadowsocks2

Modern Shadowsocks in Go
Apache License 2.0
4.51k stars 1.41k forks source link

Can not get the real ip address and port with Packet Filter TCP redirection in MacOS 12.3.1(Intel) #231

Open BigSully opened 2 years ago

BigSully commented 2 years ago

When I tried to set up transparent proxy in macos, go-shadowsocks could not get the real ip address and port with Packet Filter TCP redirection in MacOS 12.3.1(Intel).
The error returned is invalid argument, which is reported by the following code.

if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), DIOCNATLOOK, uintptr(unsafe.Pointer(&nl))); errno != 0 {
    return nil, errno
}

https://github.com/shadowsocks/go-shadowsocks2/blob/v0.1.5/pfutil/pf_darwin.go#L44

And I noticed that when run as transparent proxy, mitmproxy takes a different way, which is to parse real ip address and port from output of sudo -n /sbin/pfctl -s state, instead of using DIOCNATLOOK on the pf device /dev/pf.

https://github.com/mitmproxy/mitmproxy/blob/v8.1.0/mitmproxy/platform/osx.py#L6

BigSully commented 2 years ago

https://github.com/shadowsocks/go-shadowsocks2/blob/v0.1.5/pfutil/pf_darwin.go#L40

copy(nl.saddr[:], saddr.IP)
copy(nl.daddr[:], daddr.IP)

if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), DIOCNATLOOK, uintptr(unsafe.Pointer(&nl))); errno != 0 {
    return nil, errno
}

In my case, the saddr.IP is a byte array [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 192, 168, 1, 4], which is actually an IPv4-mapped IPv6 address.The same goes for daddr.IP. While ioctl seems to want an ip address of 4 bytes. After I change the above 2 lines to the following, the go-shadowsocks2 works just fine with pfctl redirection.

copy(nl.saddr[:], saddr.IP[12:16])
copy(nl.daddr[:], daddr.IP[12:16])