Fix Linux process search matching the wrong socket

This commit is contained in:
世界
2026-09-06 15:51:35 +08:00
parent 288411b0b9
commit 4ef3432c0d
3 changed files with 234 additions and 28 deletions
+123 -27
View File
@@ -9,6 +9,7 @@ import (
"os"
"sync"
"syscall"
"time"
E "github.com/sagernet/sing/common/exceptions"
N "github.com/sagernet/sing/common/network"
@@ -19,6 +20,7 @@ const (
sizeOfSocketDiagRequest = syscall.SizeofNlMsghdr + sizeOfSocketDiagRequestData
socketDiagResponseMinSize = 72
socketDiagByFamily = 20
socketDiagTimeout = 100 * time.Millisecond
)
type socketDiagConn struct {
@@ -28,6 +30,13 @@ type socketDiagConn struct {
fd int
}
type socketDiagEntry struct {
source netip.AddrPort
destination netip.AddrPort
uid uint32
inode uint32
}
func socketDiagConnIndex(family, protocol uint8) int {
index := 0
if protocol == syscall.IPPROTO_UDP {
@@ -83,15 +92,6 @@ func (c *socketDiagConn) query(source netip.AddrPort, destination netip.AddrPort
return 0, 0, err
}
func querySocketDiagOnce(family, protocol uint8, source netip.AddrPort) (inode, uid uint32, err error) {
fd, err := openSocketDiag()
if err != nil {
return 0, 0, E.Cause(err, "dial netlink")
}
defer syscall.Close(fd)
return querySocketDiag(fd, packSocketDiagRequest(family, protocol, source, netip.AddrPort{}, true))
}
func (c *socketDiagConn) ensureOpenLocked() error {
if c.fd != -1 {
return nil
@@ -109,12 +109,12 @@ func openSocketDiag() (int, error) {
if err != nil {
return -1, err
}
timeout := &syscall.Timeval{Usec: 100}
if err = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, timeout); err != nil {
timeout := syscall.NsecToTimeval(socketDiagTimeout.Nanoseconds())
if err = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &timeout); err != nil {
syscall.Close(fd)
return -1, err
}
if err = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, timeout); err != nil {
if err = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &timeout); err != nil {
syscall.Close(fd)
return -1, err
}
@@ -196,36 +196,132 @@ func querySocketDiag(fd int, request []byte) (inode, uid uint32, err error) {
if err != nil {
return 0, 0, E.Cause(err, "parse netlink message")
}
return unpackSocketDiagMessages(messages)
}
func unpackSocketDiagMessages(messages []syscall.NetlinkMessage) (inode, uid uint32, err error) {
for _, message := range messages {
switch message.Header.Type {
case syscall.NLMSG_DONE:
continue
case syscall.NLMSG_ERROR:
err = unpackSocketDiagError(&message)
if err != nil {
return 0, 0, err
}
case socketDiagByFamily:
inode, uid = unpackSocketDiagResponse(&message)
if inode != 0 || uid != 0 {
return inode, uid, nil
entry, valid := unpackSocketDiagEntry(&message)
if valid && (entry.inode != 0 || entry.uid != 0) {
return entry.inode, entry.uid, nil
}
}
}
return 0, 0, ErrNotFound
}
func unpackSocketDiagResponse(msg *syscall.NetlinkMessage) (inode, uid uint32) {
if len(msg.Data) < socketDiagResponseMinSize {
return 0, 0
// The dump only filters by port (inet_diag_dump_icsk, udp_dump), so every socket
// in the namespace with the requested local port is returned regardless of address.
// A dual-stack socket carrying a v4-mapped address is only listed under AF_INET6.
func dumpSocketDiag(family, protocol uint8, source netip.AddrPort, destination netip.AddrPort) (inode, uid uint32, err error) {
families := []uint8{family}
if family == syscall.AF_INET {
families = append(families, syscall.AF_INET6)
}
uid = binary.NativeEndian.Uint32(msg.Data[64:68])
inode = binary.NativeEndian.Uint32(msg.Data[68:72])
return inode, uid
for _, dumpFamily := range families {
inode, uid, err = dumpSocketDiagFamily(dumpFamily, protocol, source, destination)
if err == nil || !errors.Is(err, ErrNotFound) {
return inode, uid, err
}
}
return 0, 0, ErrNotFound
}
func dumpSocketDiagFamily(family, protocol uint8, source netip.AddrPort, destination netip.AddrPort) (inode, uid uint32, err error) {
fd, err := openSocketDiag()
if err != nil {
return 0, 0, E.Cause(err, "dial netlink")
}
defer syscall.Close(fd)
_, err = syscall.Write(fd, packSocketDiagRequest(family, protocol, source, netip.AddrPort{}, true))
if err != nil {
return 0, 0, E.Cause(err, "write netlink request")
}
var (
localMatch socketDiagEntry
hasLocalMatch bool
wildcardMatch socketDiagEntry
hasWildcardMatch bool
buffer = make([]byte, 64<<10)
n int
messages []syscall.NetlinkMessage
)
for {
n, err = syscall.Read(fd, buffer)
if err != nil {
return 0, 0, E.Cause(err, "read netlink response")
}
messages, err = syscall.ParseNetlinkMessage(buffer[:n])
if err != nil {
return 0, 0, E.Cause(err, "parse netlink message")
}
if len(messages) == 0 {
return 0, 0, E.New("empty netlink response")
}
for _, message := range messages {
switch message.Header.Type {
case syscall.NLMSG_DONE:
if hasLocalMatch {
return localMatch.inode, localMatch.uid, nil
}
if hasWildcardMatch {
return wildcardMatch.inode, wildcardMatch.uid, nil
}
return 0, 0, ErrNotFound
case syscall.NLMSG_ERROR:
err = unpackSocketDiagError(&message)
if err != nil {
return 0, 0, err
}
case socketDiagByFamily:
entry, valid := unpackSocketDiagEntry(&message)
if !valid || (entry.inode == 0 && entry.uid == 0) || entry.source.Port() != source.Port() {
continue
}
if entry.source.Addr() == source.Addr() && (!destination.IsValid() || entry.destination == destination) {
return entry.inode, entry.uid, nil
}
if protocol != syscall.IPPROTO_UDP {
continue
}
if !hasLocalMatch && entry.source.Addr() == source.Addr() {
hasLocalMatch = true
localMatch = entry
}
if !hasWildcardMatch && entry.source.Addr().IsUnspecified() {
hasWildcardMatch = true
wildcardMatch = entry
}
}
}
}
}
func unpackSocketDiagEntry(msg *syscall.NetlinkMessage) (socketDiagEntry, bool) {
if len(msg.Data) < socketDiagResponseMinSize {
return socketDiagEntry{}, false
}
data := msg.Data
var sourceAddr, destinationAddr netip.Addr
switch data[0] {
case syscall.AF_INET:
sourceAddr = netip.AddrFrom4([4]byte(data[8:12]))
destinationAddr = netip.AddrFrom4([4]byte(data[24:28]))
case syscall.AF_INET6:
sourceAddr = netip.AddrFrom16([16]byte(data[8:24])).Unmap()
destinationAddr = netip.AddrFrom16([16]byte(data[24:40])).Unmap()
default:
return socketDiagEntry{}, false
}
return socketDiagEntry{
source: netip.AddrPortFrom(sourceAddr, binary.BigEndian.Uint16(data[4:6])),
destination: netip.AddrPortFrom(destinationAddr, binary.BigEndian.Uint16(data[6:8])),
uid: binary.NativeEndian.Uint32(data[64:68]),
inode: binary.NativeEndian.Uint32(data[68:72]),
}, true
}
func unpackSocketDiagError(msg *syscall.NetlinkMessage) error {