Revamp process attribution of network connections

This commit is contained in:
Daniel
2020-05-15 17:15:22 +02:00
parent 7a03eed1ff
commit 55b0ae8944
34 changed files with 1234 additions and 1196 deletions

View File

@@ -5,137 +5,65 @@ import (
"errors"
"net"
"github.com/safing/portmaster/network/state"
"github.com/safing/portbase/log"
"github.com/safing/portmaster/network/packet"
)
// Errors
var (
ErrConnectionNotFound = errors.New("could not find connection in system state tables")
ErrProcessNotFound = errors.New("could not find process in system state tables")
ErrProcessNotFound = errors.New("could not find process in system state tables")
)
// GetPidByPacket returns the pid of the owner of the packet.
func GetPidByPacket(pkt packet.Packet) (pid int, direction bool, err error) {
var localIP net.IP
var localPort uint16
var remoteIP net.IP
var remotePort uint16
if pkt.IsInbound() {
localIP = pkt.Info().Dst
remoteIP = pkt.Info().Src
} else {
localIP = pkt.Info().Src
remoteIP = pkt.Info().Dst
}
if pkt.HasPorts() {
if pkt.IsInbound() {
localPort = pkt.Info().DstPort
remotePort = pkt.Info().SrcPort
} else {
localPort = pkt.Info().SrcPort
remotePort = pkt.Info().DstPort
}
}
switch {
case pkt.Info().Protocol == packet.TCP && pkt.Info().Version == packet.IPv4:
return getTCP4PacketInfo(localIP, localPort, remoteIP, remotePort, pkt.IsInbound())
case pkt.Info().Protocol == packet.UDP && pkt.Info().Version == packet.IPv4:
return getUDP4PacketInfo(localIP, localPort, remoteIP, remotePort, pkt.IsInbound())
case pkt.Info().Protocol == packet.TCP && pkt.Info().Version == packet.IPv6:
return getTCP6PacketInfo(localIP, localPort, remoteIP, remotePort, pkt.IsInbound())
case pkt.Info().Protocol == packet.UDP && pkt.Info().Version == packet.IPv6:
return getUDP6PacketInfo(localIP, localPort, remoteIP, remotePort, pkt.IsInbound())
default:
return UnidentifiedProcessID, false, errors.New("unsupported protocol for finding process")
}
}
// GetProcessByPacket returns the process that owns the given packet.
func GetProcessByPacket(pkt packet.Packet) (process *Process, direction bool, err error) {
if !enableProcessDetection() {
log.Tracer(pkt.Ctx()).Tracef("process: process detection disabled")
return GetUnidentifiedProcess(pkt.Ctx()), pkt.Info().Direction, nil
}
log.Tracer(pkt.Ctx()).Tracef("process: getting process and profile by packet")
var pid int
pid, direction, err = GetPidByPacket(pkt)
if err != nil {
log.Tracer(pkt.Ctx()).Errorf("process: failed to find PID of connection: %s", err)
return nil, direction, err
}
if pid < 0 {
log.Tracer(pkt.Ctx()).Errorf("process: %s", ErrConnectionNotFound.Error())
return nil, direction, ErrConnectionNotFound
}
process, err = GetOrFindPrimaryProcess(pkt.Ctx(), pid)
if err != nil {
log.Tracer(pkt.Ctx()).Errorf("process: failed to find (primary) process with PID: %s", err)
return nil, direction, err
}
err = process.GetProfile(pkt.Ctx())
if err != nil {
log.Tracer(pkt.Ctx()).Errorf("process: failed to get profile for process %s: %s", process, err)
}
return process, direction, nil
}
// GetPidByEndpoints returns the pid of the owner of the described link.
func GetPidByEndpoints(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, protocol packet.IPProtocol) (pid int, direction bool, err error) {
ipVersion := packet.IPv4
if v4 := localIP.To4(); v4 == nil {
ipVersion = packet.IPv6
}
switch {
case protocol == packet.TCP && ipVersion == packet.IPv4:
return getTCP4PacketInfo(localIP, localPort, remoteIP, remotePort, false)
case protocol == packet.UDP && ipVersion == packet.IPv4:
return getUDP4PacketInfo(localIP, localPort, remoteIP, remotePort, false)
case protocol == packet.TCP && ipVersion == packet.IPv6:
return getTCP6PacketInfo(localIP, localPort, remoteIP, remotePort, false)
case protocol == packet.UDP && ipVersion == packet.IPv6:
return getUDP6PacketInfo(localIP, localPort, remoteIP, remotePort, false)
default:
return UnidentifiedProcessID, false, errors.New("unsupported protocol for finding process")
}
func GetProcessByPacket(pkt packet.Packet) (process *Process, inbound bool, err error) {
meta := pkt.Info()
return GetProcessByEndpoints(
pkt.Ctx(),
meta.Version,
meta.Protocol,
meta.LocalIP(),
meta.LocalPort(),
meta.RemoteIP(),
meta.RemotePort(),
meta.Direction,
)
}
// GetProcessByEndpoints returns the process that owns the described link.
func GetProcessByEndpoints(ctx context.Context, localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, protocol packet.IPProtocol) (process *Process, err error) {
func GetProcessByEndpoints(
ctx context.Context,
ipVersion packet.IPVersion,
protocol packet.IPProtocol,
localIP net.IP,
localPort uint16,
remoteIP net.IP,
remotePort uint16,
pktInbound bool,
) (
process *Process,
connInbound bool,
err error,
) {
if !enableProcessDetection() {
log.Tracer(ctx).Tracef("process: process detection disabled")
return GetUnidentifiedProcess(ctx), nil
return GetUnidentifiedProcess(ctx), pktInbound, nil
}
log.Tracer(ctx).Tracef("process: getting process and profile by endpoints")
log.Tracer(ctx).Tracef("process: getting pid from system network state")
var pid int
pid, _, err = GetPidByEndpoints(localIP, localPort, remoteIP, remotePort, protocol)
pid, connInbound, err = state.Lookup(ipVersion, protocol, localIP, localPort, remoteIP, remotePort, pktInbound)
if err != nil {
log.Tracer(ctx).Errorf("process: failed to find PID of connection: %s", err)
return nil, err
}
if pid < 0 {
log.Tracer(ctx).Errorf("process: %s", ErrConnectionNotFound.Error())
return nil, ErrConnectionNotFound
return nil, connInbound, err
}
process, err = GetOrFindPrimaryProcess(ctx, pid)
if err != nil {
log.Tracer(ctx).Errorf("process: failed to find (primary) process with PID: %s", err)
return nil, err
return nil, connInbound, err
}
err = process.GetProfile(ctx)
@@ -143,10 +71,5 @@ func GetProcessByEndpoints(ctx context.Context, localIP net.IP, localPort uint16
log.Tracer(ctx).Errorf("process: failed to get profile for process %s: %s", process, err)
}
return process, nil
}
// GetActiveConnectionIDs returns a list of all active connection IDs.
func GetActiveConnectionIDs() []string {
return getActiveConnectionIDs()
return process, connInbound, nil
}

View File

@@ -1,13 +0,0 @@
package process
import (
"github.com/safing/portmaster/process/proc"
)
var (
getTCP4PacketInfo = proc.GetTCP4PacketInfo
getTCP6PacketInfo = proc.GetTCP6PacketInfo
getUDP4PacketInfo = proc.GetUDP4PacketInfo
getUDP6PacketInfo = proc.GetUDP6PacketInfo
getActiveConnectionIDs = proc.GetActiveConnectionIDs
)

View File

@@ -1,13 +0,0 @@
package process
import (
"github.com/safing/portmaster/process/iphelper"
)
var (
getTCP4PacketInfo = iphelper.GetTCP4PacketInfo
getTCP6PacketInfo = iphelper.GetTCP6PacketInfo
getUDP4PacketInfo = iphelper.GetUDP4PacketInfo
getUDP6PacketInfo = iphelper.GetUDP6PacketInfo
getActiveConnectionIDs = iphelper.GetActiveConnectionIDs
)

View File

@@ -1,260 +0,0 @@
// +build windows
package iphelper
import (
"fmt"
"net"
"sync"
"time"
)
const (
unidentifiedProcessID = -1
)
var (
tcp4Connections []*ConnectionEntry
tcp4Listeners []*ConnectionEntry
tcp6Connections []*ConnectionEntry
tcp6Listeners []*ConnectionEntry
udp4Connections []*ConnectionEntry
udp4Listeners []*ConnectionEntry
udp6Connections []*ConnectionEntry
udp6Listeners []*ConnectionEntry
ipHelper *IPHelper
lock sync.RWMutex
waitTime = 15 * time.Millisecond
)
func checkIPHelper() (err error) {
if ipHelper == nil {
ipHelper, err = New()
return err
}
return nil
}
// GetTCP4PacketInfo returns the pid of the given IPv4/TCP connection.
func GetTCP4PacketInfo(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, pktDirection bool) (pid int, direction bool, err error) {
// search
pid, _ = search(tcp4Connections, tcp4Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return pid, pktDirection, nil
}
for i := 0; i < 3; i++ {
// give kernel some time, then try again
// log.Tracef("process: giving kernel some time to think")
// if unable to find, refresh
lock.Lock()
err = checkIPHelper()
if err == nil {
tcp4Connections, tcp4Listeners, err = ipHelper.GetTables(TCP, IPv4)
}
lock.Unlock()
if err != nil {
return unidentifiedProcessID, pktDirection, err
}
// search
pid, _ = search(tcp4Connections, tcp4Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return pid, pktDirection, nil
}
time.Sleep(waitTime)
}
return unidentifiedProcessID, pktDirection, nil
}
// GetTCP6PacketInfo returns the pid of the given IPv6/TCP connection.
func GetTCP6PacketInfo(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, pktDirection bool) (pid int, direction bool, err error) {
// search
pid, _ = search(tcp6Connections, tcp6Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return pid, pktDirection, nil
}
for i := 0; i < 3; i++ {
// give kernel some time, then try again
// log.Tracef("process: giving kernel some time to think")
// if unable to find, refresh
lock.Lock()
err = checkIPHelper()
if err == nil {
tcp6Connections, tcp6Listeners, err = ipHelper.GetTables(TCP, IPv6)
}
lock.Unlock()
if err != nil {
return unidentifiedProcessID, pktDirection, err
}
// search
pid, _ = search(tcp6Connections, tcp6Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return pid, pktDirection, nil
}
time.Sleep(waitTime)
}
return unidentifiedProcessID, pktDirection, nil
}
// GetUDP4PacketInfo returns the pid of the given IPv4/UDP connection.
func GetUDP4PacketInfo(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, pktDirection bool) (pid int, direction bool, err error) {
// search
pid, _ = search(udp4Connections, udp4Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return pid, pktDirection, nil
}
for i := 0; i < 3; i++ {
// give kernel some time, then try again
// log.Tracef("process: giving kernel some time to think")
// if unable to find, refresh
lock.Lock()
err = checkIPHelper()
if err == nil {
udp4Connections, udp4Listeners, err = ipHelper.GetTables(UDP, IPv4)
}
lock.Unlock()
if err != nil {
return unidentifiedProcessID, pktDirection, err
}
// search
pid, _ = search(udp4Connections, udp4Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return pid, pktDirection, nil
}
time.Sleep(waitTime)
}
return unidentifiedProcessID, pktDirection, nil
}
// GetUDP6PacketInfo returns the pid of the given IPv6/UDP connection.
func GetUDP6PacketInfo(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, pktDirection bool) (pid int, direction bool, err error) {
// search
pid, _ = search(udp6Connections, udp6Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return pid, pktDirection, nil
}
for i := 0; i < 3; i++ {
// give kernel some time, then try again
// log.Tracef("process: giving kernel some time to think")
// if unable to find, refresh
lock.Lock()
err = checkIPHelper()
if err == nil {
udp6Connections, udp6Listeners, err = ipHelper.GetTables(UDP, IPv6)
}
lock.Unlock()
if err != nil {
return unidentifiedProcessID, pktDirection, err
}
// search
pid, _ = search(udp6Connections, udp6Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return pid, pktDirection, nil
}
time.Sleep(waitTime)
}
return unidentifiedProcessID, pktDirection, nil
}
func search(connections, listeners []*ConnectionEntry, localIP, remoteIP net.IP, localPort, remotePort uint16, pktDirection bool) (pid int, direction bool) { //nolint:unparam // TODO: use direction, it may not be used because results caused problems, investigate.
lock.RLock()
defer lock.RUnlock()
if pktDirection {
// inbound
pid = searchListeners(listeners, localIP, localPort)
if pid >= 0 {
return pid, true
}
pid = searchConnections(connections, localIP, remoteIP, localPort, remotePort)
if pid >= 0 {
return pid, false
}
} else {
// outbound
pid = searchConnections(connections, localIP, remoteIP, localPort, remotePort)
if pid >= 0 {
return pid, false
}
pid = searchListeners(listeners, localIP, localPort)
if pid >= 0 {
return pid, true
}
}
return unidentifiedProcessID, pktDirection
}
func searchConnections(list []*ConnectionEntry, localIP, remoteIP net.IP, localPort, remotePort uint16) (pid int) {
for _, entry := range list {
if localPort == entry.localPort &&
remotePort == entry.remotePort &&
remoteIP.Equal(entry.remoteIP) &&
localIP.Equal(entry.localIP) {
return entry.pid
}
}
return unidentifiedProcessID
}
func searchListeners(list []*ConnectionEntry, localIP net.IP, localPort uint16) (pid int) {
for _, entry := range list {
if localPort == entry.localPort &&
(entry.localIP == nil || // nil IP means zero IP, see tables.go
localIP.Equal(entry.localIP)) {
return entry.pid
}
}
return unidentifiedProcessID
}
// GetActiveConnectionIDs returns all currently active connection IDs.
func GetActiveConnectionIDs() (connections []string) {
lock.Lock()
defer lock.Unlock()
for _, entry := range tcp4Connections {
connections = append(connections, fmt.Sprintf("%d-%s-%d-%s-%d", TCP, entry.localIP, entry.localPort, entry.remoteIP, entry.remotePort))
}
for _, entry := range tcp6Connections {
connections = append(connections, fmt.Sprintf("%d-%s-%d-%s-%d", TCP, entry.localIP, entry.localPort, entry.remoteIP, entry.remotePort))
}
for _, entry := range udp4Connections {
connections = append(connections, fmt.Sprintf("%d-%s-%d-%s-%d", UDP, entry.localIP, entry.localPort, entry.remoteIP, entry.remotePort))
}
for _, entry := range udp6Connections {
connections = append(connections, fmt.Sprintf("%d-%s-%d-%s-%d", UDP, entry.localIP, entry.localPort, entry.remoteIP, entry.remotePort))
}
return
}

View File

@@ -1,79 +0,0 @@
// +build windows
package iphelper
import (
"errors"
"fmt"
"github.com/tevino/abool"
"golang.org/x/sys/windows"
)
var (
errInvalid = errors.New("IPHelper not initialzed or broken")
)
// IPHelper represents a subset of the Windows iphlpapi.dll.
type IPHelper struct {
dll *windows.LazyDLL
getExtendedTCPTable *windows.LazyProc
getExtendedUDPTable *windows.LazyProc
// getOwnerModuleFromTcpEntry *windows.LazyProc
// getOwnerModuleFromTcp6Entry *windows.LazyProc
// getOwnerModuleFromUdpEntry *windows.LazyProc
// getOwnerModuleFromUdp6Entry *windows.LazyProc
valid *abool.AtomicBool
}
// New returns a new IPHelper API (with an instance of iphlpapi.dll loaded).
func New() (*IPHelper, error) {
new := &IPHelper{}
new.valid = abool.NewBool(false)
var err error
// load dll
new.dll = windows.NewLazySystemDLL("iphlpapi.dll")
err = new.dll.Load()
if err != nil {
return nil, err
}
// load functions
new.getExtendedTCPTable = new.dll.NewProc("GetExtendedTcpTable")
err = new.getExtendedTCPTable.Find()
if err != nil {
return nil, fmt.Errorf("could find proc GetExtendedTcpTable: %s", err)
}
new.getExtendedUDPTable = new.dll.NewProc("GetExtendedUdpTable")
err = new.getExtendedUDPTable.Find()
if err != nil {
return nil, fmt.Errorf("could find proc GetExtendedUdpTable: %s", err)
}
// new.getOwnerModuleFromTcpEntry = new.dll.NewProc("GetOwnerModuleFromTcpEntry")
// err = new.getOwnerModuleFromTcpEntry.Find()
// if err != nil {
// return nil, fmt.Errorf("could find proc GetOwnerModuleFromTcpEntry: %s", err)
// }
// new.getOwnerModuleFromTcp6Entry = new.dll.NewProc("GetOwnerModuleFromTcp6Entry")
// err = new.getOwnerModuleFromTcp6Entry.Find()
// if err != nil {
// return nil, fmt.Errorf("could find proc GetOwnerModuleFromTcp6Entry: %s", err)
// }
// new.getOwnerModuleFromUdpEntry = new.dll.NewProc("GetOwnerModuleFromUdpEntry")
// err = new.getOwnerModuleFromUdpEntry.Find()
// if err != nil {
// return nil, fmt.Errorf("could find proc GetOwnerModuleFromUdpEntry: %s", err)
// }
// new.getOwnerModuleFromUdp6Entry = new.dll.NewProc("GetOwnerModuleFromUdp6Entry")
// err = new.getOwnerModuleFromUdp6Entry.Find()
// if err != nil {
// return nil, fmt.Errorf("could find proc GetOwnerModuleFromUdp6Entry: %s", err)
// }
new.valid.Set()
return new, nil
}

View File

@@ -1,329 +0,0 @@
// +build windows
package iphelper
import (
"errors"
"fmt"
"net"
"sync"
"unsafe"
"golang.org/x/sys/windows"
)
// Windows API constants
const (
iphelperTCPTableOwnerPIDAll uintptr = 5
iphelperUDPTableOwnerPID uintptr = 1
iphelperTCPStateListen uint32 = 2
winErrInsufficientBuffer = uintptr(windows.ERROR_INSUFFICIENT_BUFFER)
winErrInvalidParameter = uintptr(windows.ERROR_INVALID_PARAMETER)
)
// ConnectionEntry describes a connection state table entry.
type ConnectionEntry struct {
localIP net.IP
remoteIP net.IP
localPort uint16
remotePort uint16
pid int
}
func (entry *ConnectionEntry) String() string {
return fmt.Sprintf("PID=%d %s:%d <> %s:%d", entry.pid, entry.localIP, entry.localPort, entry.remoteIP, entry.remotePort)
}
type iphelperTCPTable struct {
// docs: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366921(v=vs.85).aspx
numEntries uint32
table [4096]iphelperTCPRow
}
type iphelperTCPRow struct {
// docs: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366913(v=vs.85).aspx
state uint32
localAddr uint32
localPort uint32
remoteAddr uint32
remotePort uint32
owningPid uint32
}
type iphelperTCP6Table struct {
// docs: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366905(v=vs.85).aspx
numEntries uint32
table [4096]iphelperTCP6Row
}
type iphelperTCP6Row struct {
// docs: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366896(v=vs.85).aspx
localAddr [16]byte
_ uint32 // localScopeID
localPort uint32
remoteAddr [16]byte
_ uint32 // remoteScopeID
remotePort uint32
state uint32
owningPid uint32
}
type iphelperUDPTable struct {
// docs: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366932(v=vs.85).aspx
numEntries uint32
table [4096]iphelperUDPRow
}
type iphelperUDPRow struct {
// docs: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366928(v=vs.85).aspx
localAddr uint32
localPort uint32
owningPid uint32
}
type iphelperUDP6Table struct {
// docs: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366925(v=vs.85).aspx
numEntries uint32
table [4096]iphelperUDP6Row
}
type iphelperUDP6Row struct {
// docs: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366923(v=vs.85).aspx
localAddr [16]byte
_ uint32 // localScopeID
localPort uint32
owningPid uint32
}
// IP and Protocol constants
const (
IPv4 uint8 = 4
IPv6 uint8 = 6
TCP uint8 = 6
UDP uint8 = 17
)
const (
startBufSize = 4096
bufSizeUses = 100
)
var (
bufSize = startBufSize
bufSizeUsageLeft = bufSizeUses
bufSizeLock sync.Mutex
)
func getBufSize() int {
bufSizeLock.Lock()
defer bufSizeLock.Unlock()
// using bufSize
bufSizeUsageLeft--
// check if we want to reset
if bufSizeUsageLeft <= 0 {
// reset
bufSize = startBufSize
bufSizeUsageLeft = bufSizeUses
}
return bufSize
}
func increaseBufSize() int {
bufSizeLock.Lock()
defer bufSizeLock.Unlock()
// increase
bufSize *= 2
// not too much
if bufSize > 65536 {
bufSize = 65536
}
// reset
bufSizeUsageLeft = bufSizeUses
// return new bufSize
return bufSize
}
// GetTables returns the current connection state table of Windows of the given protocol and IP version.
func (ipHelper *IPHelper) GetTables(protocol uint8, ipVersion uint8) (connections []*ConnectionEntry, listeners []*ConnectionEntry, err error) { //nolint:gocognit,gocycle // TODO
// docs: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365928(v=vs.85).aspx
if !ipHelper.valid.IsSet() {
return nil, nil, errInvalid
}
var afClass int
switch ipVersion {
case IPv4:
afClass = windows.AF_INET
case IPv6:
afClass = windows.AF_INET6
default:
return nil, nil, errors.New("invalid protocol")
}
// try max 3 times
maxTries := 3
bufSize := getBufSize()
var buf []byte
for i := 1; i <= maxTries; i++ {
buf = make([]byte, bufSize)
var r1 uintptr
switch protocol {
case TCP:
r1, _, err = ipHelper.getExtendedTCPTable.Call(
uintptr(unsafe.Pointer(&buf[0])), // _Out_ PVOID pTcpTable
uintptr(unsafe.Pointer(&bufSize)), // _Inout_ PDWORD pdwSize
0, // _In_ BOOL bOrder
uintptr(afClass), // _In_ ULONG ulAf
iphelperTCPTableOwnerPIDAll, // _In_ TCP_TABLE_CLASS TableClass
0, // _In_ ULONG Reserved
)
case UDP:
r1, _, err = ipHelper.getExtendedUDPTable.Call(
uintptr(unsafe.Pointer(&buf[0])), // _Out_ PVOID pUdpTable,
uintptr(unsafe.Pointer(&bufSize)), // _Inout_ PDWORD pdwSize,
0, // _In_ BOOL bOrder,
uintptr(afClass), // _In_ ULONG ulAf,
iphelperUDPTableOwnerPID, // _In_ UDP_TABLE_CLASS TableClass,
0, // _In_ ULONG Reserved
)
}
switch r1 {
case winErrInsufficientBuffer:
if i >= maxTries {
return nil, nil, fmt.Errorf("insufficient buffer error (tried %d times): [NT 0x%X] %s", i, r1, err)
}
bufSize = increaseBufSize()
case winErrInvalidParameter:
return nil, nil, fmt.Errorf("invalid parameter: [NT 0x%X] %s", r1, err)
case windows.NO_ERROR:
// success
break
default:
return nil, nil, fmt.Errorf("unexpected error: [NT 0x%X] %s", r1, err)
}
}
// parse output
switch {
case protocol == TCP && ipVersion == IPv4:
tcpTable := (*iphelperTCPTable)(unsafe.Pointer(&buf[0]))
table := tcpTable.table[:tcpTable.numEntries]
for _, row := range table {
new := &ConnectionEntry{}
// PID
new.pid = int(row.owningPid)
// local
if row.localAddr != 0 {
new.localIP = convertIPv4(row.localAddr)
}
new.localPort = uint16(row.localPort>>8 | row.localPort<<8)
// remote
if row.state == iphelperTCPStateListen {
listeners = append(listeners, new)
} else {
new.remoteIP = convertIPv4(row.remoteAddr)
new.remotePort = uint16(row.remotePort>>8 | row.remotePort<<8)
connections = append(connections, new)
}
}
case protocol == TCP && ipVersion == IPv6:
tcpTable := (*iphelperTCP6Table)(unsafe.Pointer(&buf[0]))
table := tcpTable.table[:tcpTable.numEntries]
for _, row := range table {
new := &ConnectionEntry{}
// PID
new.pid = int(row.owningPid)
// local
new.localIP = net.IP(row.localAddr[:])
new.localPort = uint16(row.localPort>>8 | row.localPort<<8)
// remote
if row.state == iphelperTCPStateListen {
if new.localIP.Equal(net.IPv6zero) {
new.localIP = nil
}
listeners = append(listeners, new)
} else {
new.remoteIP = net.IP(row.remoteAddr[:])
new.remotePort = uint16(row.remotePort>>8 | row.remotePort<<8)
connections = append(connections, new)
}
}
case protocol == UDP && ipVersion == IPv4:
udpTable := (*iphelperUDPTable)(unsafe.Pointer(&buf[0]))
table := udpTable.table[:udpTable.numEntries]
for _, row := range table {
new := &ConnectionEntry{}
// PID
new.pid = int(row.owningPid)
// local
new.localPort = uint16(row.localPort>>8 | row.localPort<<8)
if row.localAddr == 0 {
listeners = append(listeners, new)
} else {
new.localIP = convertIPv4(row.localAddr)
connections = append(connections, new)
}
}
case protocol == UDP && ipVersion == IPv6:
udpTable := (*iphelperUDP6Table)(unsafe.Pointer(&buf[0]))
table := udpTable.table[:udpTable.numEntries]
for _, row := range table {
new := &ConnectionEntry{}
// PID
new.pid = int(row.owningPid)
// local
new.localIP = net.IP(row.localAddr[:])
new.localPort = uint16(row.localPort>>8 | row.localPort<<8)
if new.localIP.Equal(net.IPv6zero) {
new.localIP = nil
listeners = append(listeners, new)
} else {
connections = append(connections, new)
}
}
}
return connections, listeners, nil
}
func convertIPv4(input uint32) net.IP {
return net.IPv4(
uint8(input&0xFF),
uint8(input>>8&0xFF),
uint8(input>>16&0xFF),
uint8(input>>24&0xFF),
)
}

View File

@@ -1,62 +0,0 @@
// +build windows
package main
import (
"fmt"
"github.com/safing/portmaster/process/iphelper"
)
func main() {
iph, err := iphelper.New()
if err != nil {
panic(err)
}
fmt.Printf("TCP4\n")
conns, lConns, err := iph.GetTables(iphelper.TCP, iphelper.IPv4)
if err != nil {
panic(err)
}
fmt.Printf("Connections:\n")
for _, conn := range conns {
fmt.Printf("%s\n", conn)
}
fmt.Printf("Listeners:\n")
for _, conn := range lConns {
fmt.Printf("%s\n", conn)
}
fmt.Printf("\nTCP6\n")
conns, lConns, err = iph.GetTables(iphelper.TCP, iphelper.IPv6)
if err != nil {
panic(err)
}
fmt.Printf("Connections:\n")
for _, conn := range conns {
fmt.Printf("%s\n", conn)
}
fmt.Printf("Listeners:\n")
for _, conn := range lConns {
fmt.Printf("%s\n", conn)
}
fmt.Printf("\nUDP4\n")
_, lConns, err = iph.GetTables(iphelper.UDP, iphelper.IPv4)
if err != nil {
panic(err)
}
for _, conn := range lConns {
fmt.Printf("%s\n", conn)
}
fmt.Printf("\nUDP6\n")
_, lConns, err = iph.GetTables(iphelper.UDP, iphelper.IPv6)
if err != nil {
panic(err)
}
for _, conn := range lConns {
fmt.Printf("%s\n", conn)
}
}

View File

@@ -1,83 +0,0 @@
// +build linux
package proc
import (
"net"
"time"
)
// PID querying return codes
const (
Success uint8 = iota
NoSocket
NoProcess
)
var (
waitTime = 15 * time.Millisecond
)
// GetPidOfConnection returns the PID of the given connection.
func GetPidOfConnection(localIP net.IP, localPort uint16, protocol uint8) (pid int, status uint8) {
uid, inode, ok := getConnectionSocket(localIP, localPort, protocol)
if !ok {
uid, inode, ok = getListeningSocket(localIP, localPort, protocol)
for i := 0; i < 3 && !ok; i++ {
// give kernel some time, then try again
// log.Tracef("process: giving kernel some time to think")
time.Sleep(waitTime)
uid, inode, ok = getConnectionSocket(localIP, localPort, protocol)
if !ok {
uid, inode, ok = getListeningSocket(localIP, localPort, protocol)
}
}
if !ok {
return unidentifiedProcessID, NoSocket
}
}
pid, ok = GetPidOfInode(uid, inode)
for i := 0; i < 3 && !ok; i++ {
// give kernel some time, then try again
// log.Tracef("process: giving kernel some time to think")
time.Sleep(waitTime)
pid, ok = GetPidOfInode(uid, inode)
}
if !ok {
return unidentifiedProcessID, NoProcess
}
return
}
// GetPidOfIncomingConnection returns the PID of the given incoming connection.
func GetPidOfIncomingConnection(localIP net.IP, localPort uint16, protocol uint8) (pid int, status uint8) {
uid, inode, ok := getListeningSocket(localIP, localPort, protocol)
if !ok {
// for TCP4 and UDP4, also try TCP6 and UDP6, as linux sometimes treats them as a single dual socket, and shows the IPv6 version.
switch protocol {
case TCP4:
uid, inode, ok = getListeningSocket(localIP, localPort, TCP6)
case UDP4:
uid, inode, ok = getListeningSocket(localIP, localPort, UDP6)
}
if !ok {
return unidentifiedProcessID, NoSocket
}
}
pid, ok = GetPidOfInode(uid, inode)
for i := 0; i < 3 && !ok; i++ {
// give kernel some time, then try again
// log.Tracef("process: giving kernel some time to think")
time.Sleep(waitTime)
pid, ok = GetPidOfInode(uid, inode)
}
if !ok {
return unidentifiedProcessID, NoProcess
}
return
}

View File

@@ -1,66 +0,0 @@
// +build linux
package proc
import (
"errors"
"net"
)
const (
unidentifiedProcessID = -1
)
// GetTCP4PacketInfo searches the network state tables for a TCP4 connection
func GetTCP4PacketInfo(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, pktDirection bool) (pid int, direction bool, err error) {
return search(TCP4, localIP, localPort, pktDirection)
}
// GetTCP6PacketInfo searches the network state tables for a TCP6 connection
func GetTCP6PacketInfo(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, pktDirection bool) (pid int, direction bool, err error) {
return search(TCP6, localIP, localPort, pktDirection)
}
// GetUDP4PacketInfo searches the network state tables for a UDP4 connection
func GetUDP4PacketInfo(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, pktDirection bool) (pid int, direction bool, err error) {
return search(UDP4, localIP, localPort, pktDirection)
}
// GetUDP6PacketInfo searches the network state tables for a UDP6 connection
func GetUDP6PacketInfo(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, pktDirection bool) (pid int, direction bool, err error) {
return search(UDP6, localIP, localPort, pktDirection)
}
func search(protocol uint8, localIP net.IP, localPort uint16, pktDirection bool) (pid int, direction bool, err error) {
var status uint8
if pktDirection {
pid, status = GetPidOfIncomingConnection(localIP, localPort, protocol)
if pid >= 0 {
return pid, true, nil
}
// pid, status = GetPidOfConnection(localIP, localPort, protocol)
// if pid >= 0 {
// return pid, false, nil
// }
} else {
pid, status = GetPidOfConnection(localIP, localPort, protocol)
if pid >= 0 {
return pid, false, nil
}
// pid, status = GetPidOfIncomingConnection(localIP, localPort, protocol)
// if pid >= 0 {
// return pid, true, nil
// }
}
switch status {
case NoSocket:
return unidentifiedProcessID, direction, errors.New("could not find socket")
case NoProcess:
return unidentifiedProcessID, direction, errors.New("could not find PID")
default:
return unidentifiedProcessID, direction, nil
}
}

View File

@@ -1,164 +0,0 @@
// +build linux
package proc
import (
"fmt"
"os"
"sort"
"strconv"
"sync"
"syscall"
"github.com/safing/portbase/log"
)
var (
pidsByUserLock sync.Mutex
pidsByUser = make(map[int][]int)
)
// GetPidOfInode returns the pid of the given uid and socket inode.
func GetPidOfInode(uid, inode int) (int, bool) { //nolint:gocognit // TODO
pidsByUserLock.Lock()
defer pidsByUserLock.Unlock()
pidsUpdated := false
// get pids of user, update if missing
pids, ok := pidsByUser[uid]
if !ok {
// log.Trace("process: no processes of user, updating table")
updatePids()
pidsUpdated = true
pids, ok = pidsByUser[uid]
}
if ok {
// if user has pids, start checking them first
var checkedUserPids []int
for _, possiblePID := range pids {
if findSocketFromPid(possiblePID, inode) {
return possiblePID, true
}
checkedUserPids = append(checkedUserPids, possiblePID)
}
// if we fail on the first run and have not updated, update and check the ones we haven't tried so far.
if !pidsUpdated {
// log.Trace("process: socket not found in any process of user, updating table")
// update
updatePids()
// sort for faster search
for i, j := 0, len(checkedUserPids)-1; i < j; i, j = i+1, j-1 {
checkedUserPids[i], checkedUserPids[j] = checkedUserPids[j], checkedUserPids[i]
}
len := len(checkedUserPids)
// check unchecked pids
for _, possiblePID := range pids {
// only check if not already checked
if sort.SearchInts(checkedUserPids, possiblePID) == len {
if findSocketFromPid(possiblePID, inode) {
return possiblePID, true
}
}
}
}
}
// check all other pids
// log.Trace("process: socket not found in any process of user, checking all pids")
// TODO: find best order for pidsByUser for best performance
for possibleUID, pids := range pidsByUser {
if possibleUID != uid {
for _, possiblePID := range pids {
if findSocketFromPid(possiblePID, inode) {
return possiblePID, true
}
}
}
}
return unidentifiedProcessID, false
}
func findSocketFromPid(pid, inode int) bool {
socketName := fmt.Sprintf("socket:[%d]", inode)
entries := readDirNames(fmt.Sprintf("/proc/%d/fd", pid))
if len(entries) == 0 {
return false
}
for _, entry := range entries {
link, err := os.Readlink(fmt.Sprintf("/proc/%d/fd/%s", pid, entry))
if err != nil {
if !os.IsNotExist(err) {
log.Warningf("process: failed to read link /proc/%d/fd/%s: %s", pid, entry, err)
}
continue
}
if link == socketName {
return true
}
}
return false
}
func updatePids() {
pidsByUser = make(map[int][]int)
entries := readDirNames("/proc")
if len(entries) == 0 {
return
}
entryLoop:
for _, entry := range entries {
pid, err := strconv.ParseInt(entry, 10, 32)
if err != nil {
continue entryLoop
}
statData, err := os.Stat(fmt.Sprintf("/proc/%d", pid))
if err != nil {
log.Warningf("process: could not stat /proc/%d: %s", pid, err)
continue entryLoop
}
sys, ok := statData.Sys().(*syscall.Stat_t)
if !ok {
log.Warningf("process: unable to parse /proc/%d: wrong type", pid)
continue entryLoop
}
pids, ok := pidsByUser[int(sys.Uid)]
if ok {
pidsByUser[int(sys.Uid)] = append(pids, int(pid))
} else {
pidsByUser[int(sys.Uid)] = []int{int(pid)}
}
}
for _, slice := range pidsByUser {
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
slice[i], slice[j] = slice[j], slice[i]
}
}
}
func readDirNames(dir string) (names []string) {
file, err := os.Open(dir)
if err != nil {
if !os.IsNotExist(err) {
log.Warningf("process: could not open directory %s: %s", dir, err)
}
return
}
defer file.Close()
names, err = file.Readdirnames(0)
if err != nil {
log.Warningf("process: could not get entries from directory %s: %s", dir, err)
return []string{}
}
return
}

View File

@@ -1,18 +0,0 @@
// +build linux
package proc
import (
"log"
"testing"
)
func TestProcessFinder(t *testing.T) {
updatePids()
log.Printf("pidsByUser: %v", pidsByUser)
pid, _ := GetPidOfInode(1000, 112588)
log.Printf("pid: %d", pid)
}

View File

@@ -1,370 +0,0 @@
// +build linux
package proc
import (
"bufio"
"encoding/hex"
"fmt"
"net"
"os"
"strconv"
"strings"
"sync"
"unicode"
"github.com/safing/portbase/log"
)
/*
1. find socket inode
- by incoming (listenting sockets) or outgoing (local port + external IP + port) - also local IP?
- /proc/net/{tcp|udp}[6]
2. get list of processes of uid
3. find socket inode in process fds
- if not found, refresh map of uid->pids
- if not found, check ALL pids: maybe euid != uid
4. gather process info
Cache every step!
*/
// Network Related Constants
const (
TCP4 uint8 = iota
UDP4
TCP6
UDP6
ICMP4
ICMP6
TCP4Data = "/proc/net/tcp"
UDP4Data = "/proc/net/udp"
TCP6Data = "/proc/net/tcp6"
UDP6Data = "/proc/net/udp6"
ICMP4Data = "/proc/net/icmp"
ICMP6Data = "/proc/net/icmp6"
)
var (
// connectionSocketsLock sync.Mutex
// connectionTCP4 = make(map[string][]int)
// connectionUDP4 = make(map[string][]int)
// connectionTCP6 = make(map[string][]int)
// connectionUDP6 = make(map[string][]int)
listeningSocketsLock sync.Mutex
addressListeningTCP4 = make(map[string][]int)
addressListeningUDP4 = make(map[string][]int)
addressListeningTCP6 = make(map[string][]int)
addressListeningUDP6 = make(map[string][]int)
globalListeningTCP4 = make(map[uint16][]int)
globalListeningUDP4 = make(map[uint16][]int)
globalListeningTCP6 = make(map[uint16][]int)
globalListeningUDP6 = make(map[uint16][]int)
)
func getConnectionSocket(localIP net.IP, localPort uint16, protocol uint8) (int, int, bool) {
// listeningSocketsLock.Lock()
// defer listeningSocketsLock.Unlock()
var procFile string
var localIPHex string
switch protocol {
case TCP4:
procFile = TCP4Data
localIPBytes := []byte(localIP.To4())
localIPHex = strings.ToUpper(hex.EncodeToString([]byte{localIPBytes[3], localIPBytes[2], localIPBytes[1], localIPBytes[0]}))
case UDP4:
procFile = UDP4Data
localIPBytes := []byte(localIP.To4())
localIPHex = strings.ToUpper(hex.EncodeToString([]byte{localIPBytes[3], localIPBytes[2], localIPBytes[1], localIPBytes[0]}))
case TCP6:
procFile = TCP6Data
localIPHex = hex.EncodeToString([]byte(localIP))
case UDP6:
procFile = UDP6Data
localIPHex = hex.EncodeToString([]byte(localIP))
}
localPortHex := fmt.Sprintf("%04X", localPort)
// log.Tracef("process/proc: searching for PID of: %s:%d (%s:%s)", localIP, localPort, localIPHex, localPortHex)
// open file
socketData, err := os.Open(procFile)
if err != nil {
log.Warningf("process/proc: could not read %s: %s", procFile, err)
return unidentifiedProcessID, unidentifiedProcessID, false
}
defer socketData.Close()
// file scanner
scanner := bufio.NewScanner(socketData)
scanner.Split(bufio.ScanLines)
// parse
scanner.Scan() // skip first line
for scanner.Scan() {
line := strings.FieldsFunc(scanner.Text(), procDelimiter)
// log.Tracef("line: %s", line)
if len(line) < 14 {
// log.Tracef("process: too short: %s", line)
continue
}
if line[1] != localIPHex {
continue
}
if line[2] != localPortHex {
continue
}
ok := true
uid, err := strconv.ParseInt(line[11], 10, 32)
if err != nil {
log.Warningf("process: could not parse uid %s: %s", line[11], err)
uid = -1
ok = false
}
inode, err := strconv.ParseInt(line[13], 10, 32)
if err != nil {
log.Warningf("process: could not parse inode %s: %s", line[13], err)
inode = -1
ok = false
}
// log.Tracef("process/proc: identified process of %s:%d: socket=%d uid=%d", localIP, localPort, int(inode), int(uid))
return int(uid), int(inode), ok
}
return unidentifiedProcessID, unidentifiedProcessID, false
}
func getListeningSocket(localIP net.IP, localPort uint16, protocol uint8) (uid, inode int, ok bool) {
listeningSocketsLock.Lock()
defer listeningSocketsLock.Unlock()
var addressListening map[string][]int
var globalListening map[uint16][]int
switch protocol {
case TCP4:
addressListening = addressListeningTCP4
globalListening = globalListeningTCP4
case UDP4:
addressListening = addressListeningUDP4
globalListening = globalListeningUDP4
case TCP6:
addressListening = addressListeningTCP6
globalListening = globalListeningTCP6
case UDP6:
addressListening = addressListeningUDP6
globalListening = globalListeningUDP6
}
data, ok := addressListening[fmt.Sprintf("%s:%d", localIP, localPort)]
if !ok {
data, ok = globalListening[localPort]
}
if ok {
return data[0], data[1], true
}
updateListeners(protocol)
data, ok = addressListening[fmt.Sprintf("%s:%d", localIP, localPort)]
if !ok {
data, ok = globalListening[localPort]
}
if ok {
return data[0], data[1], true
}
return unidentifiedProcessID, unidentifiedProcessID, false
}
func procDelimiter(c rune) bool {
return unicode.IsSpace(c) || c == ':'
}
func convertIPv4(data string) net.IP {
decoded, err := hex.DecodeString(data)
if err != nil {
log.Warningf("process: could not parse IPv4 %s: %s", data, err)
return nil
}
if len(decoded) != 4 {
log.Warningf("process: decoded IPv4 %s has wrong length", decoded)
return nil
}
ip := net.IPv4(decoded[3], decoded[2], decoded[1], decoded[0])
return ip
}
func convertIPv6(data string) net.IP {
decoded, err := hex.DecodeString(data)
if err != nil {
log.Warningf("process: could not parse IPv6 %s: %s", data, err)
return nil
}
if len(decoded) != 16 {
log.Warningf("process: decoded IPv6 %s has wrong length", decoded)
return nil
}
ip := net.IP(decoded)
return ip
}
func updateListeners(protocol uint8) {
switch protocol {
case TCP4:
addressListeningTCP4, globalListeningTCP4 = getListenerMaps(TCP4Data, "00000000", "0A", convertIPv4)
case UDP4:
addressListeningUDP4, globalListeningUDP4 = getListenerMaps(UDP4Data, "00000000", "07", convertIPv4)
case TCP6:
addressListeningTCP6, globalListeningTCP6 = getListenerMaps(TCP6Data, "00000000000000000000000000000000", "0A", convertIPv6)
case UDP6:
addressListeningUDP6, globalListeningUDP6 = getListenerMaps(UDP6Data, "00000000000000000000000000000000", "07", convertIPv6)
}
}
func getListenerMaps(procFile, zeroIP, socketStatusListening string, ipConverter func(string) net.IP) (map[string][]int, map[uint16][]int) {
addressListening := make(map[string][]int)
globalListening := make(map[uint16][]int)
// open file
socketData, err := os.Open(procFile)
if err != nil {
log.Warningf("process: could not read %s: %s", procFile, err)
return addressListening, globalListening
}
defer socketData.Close()
// file scanner
scanner := bufio.NewScanner(socketData)
scanner.Split(bufio.ScanLines)
// parse
scanner.Scan() // skip first line
for scanner.Scan() {
line := strings.FieldsFunc(scanner.Text(), procDelimiter)
if len(line) < 14 {
// log.Tracef("process: too short: %s", line)
continue
}
if line[5] != socketStatusListening {
// skip if not listening
// log.Tracef("process: not listening %s: %s", line, line[5])
continue
}
port, err := strconv.ParseUint(line[2], 16, 16)
// log.Tracef("port: %s", line[2])
if err != nil {
log.Warningf("process: could not parse port %s: %s", line[2], err)
continue
}
uid, err := strconv.ParseInt(line[11], 10, 32)
// log.Tracef("uid: %s", line[11])
if err != nil {
log.Warningf("process: could not parse uid %s: %s", line[11], err)
continue
}
inode, err := strconv.ParseInt(line[13], 10, 32)
// log.Tracef("inode: %s", line[13])
if err != nil {
log.Warningf("process: could not parse inode %s: %s", line[13], err)
continue
}
if line[1] == zeroIP {
globalListening[uint16(port)] = []int{int(uid), int(inode)}
} else {
address := ipConverter(line[1])
if address != nil {
addressListening[fmt.Sprintf("%s:%d", address, port)] = []int{int(uid), int(inode)}
}
}
}
return addressListening, globalListening
}
// GetActiveConnectionIDs returns all connection IDs that are still marked as active by the OS.
func GetActiveConnectionIDs() []string {
var connections []string
connections = append(connections, getConnectionIDsFromSource(TCP4Data, 6, convertIPv4)...)
connections = append(connections, getConnectionIDsFromSource(UDP4Data, 17, convertIPv4)...)
connections = append(connections, getConnectionIDsFromSource(TCP6Data, 6, convertIPv6)...)
connections = append(connections, getConnectionIDsFromSource(UDP6Data, 17, convertIPv6)...)
return connections
}
func getConnectionIDsFromSource(source string, protocol uint16, ipConverter func(string) net.IP) []string {
var connections []string
// open file
socketData, err := os.Open(source)
if err != nil {
log.Warningf("process: could not read %s: %s", source, err)
return connections
}
defer socketData.Close()
// file scanner
scanner := bufio.NewScanner(socketData)
scanner.Split(bufio.ScanLines)
// parse
scanner.Scan() // skip first line
for scanner.Scan() {
line := strings.FieldsFunc(scanner.Text(), procDelimiter)
if len(line) < 14 {
// log.Tracef("process: too short: %s", line)
continue
}
// skip listeners and closed connections
if line[5] == "0A" || line[5] == "07" {
continue
}
localIP := ipConverter(line[1])
if localIP == nil {
continue
}
localPort, err := strconv.ParseUint(line[2], 16, 16)
if err != nil {
log.Warningf("process: could not parse port: %s", err)
continue
}
remoteIP := ipConverter(line[3])
if remoteIP == nil {
continue
}
remotePort, err := strconv.ParseUint(line[4], 16, 16)
if err != nil {
log.Warningf("process: could not parse port: %s", err)
continue
}
connections = append(connections, fmt.Sprintf("%d-%s-%d-%s-%d", protocol, localIP, localPort, remoteIP, remotePort))
}
return connections
}

View File

@@ -1,40 +0,0 @@
// +build linux
package proc
import (
"net"
"testing"
)
func TestSockets(t *testing.T) {
updateListeners(TCP4)
updateListeners(UDP4)
updateListeners(TCP6)
updateListeners(UDP6)
t.Logf("addressListeningTCP4: %v", addressListeningTCP4)
t.Logf("globalListeningTCP4: %v", globalListeningTCP4)
t.Logf("addressListeningUDP4: %v", addressListeningUDP4)
t.Logf("globalListeningUDP4: %v", globalListeningUDP4)
t.Logf("addressListeningTCP6: %v", addressListeningTCP6)
t.Logf("globalListeningTCP6: %v", globalListeningTCP6)
t.Logf("addressListeningUDP6: %v", addressListeningUDP6)
t.Logf("globalListeningUDP6: %v", globalListeningUDP6)
getListeningSocket(net.IPv4zero, 53, TCP4)
getListeningSocket(net.IPv4zero, 53, UDP4)
getListeningSocket(net.IPv6zero, 53, TCP6)
getListeningSocket(net.IPv6zero, 53, UDP6)
// spotify: 192.168.0.102:5353 192.121.140.65:80
localIP := net.IPv4(192, 168, 127, 10)
uid, inode, ok := getConnectionSocket(localIP, 46634, TCP4)
t.Logf("getConnectionSocket: %d %d %v", uid, inode, ok)
activeConnectionIDs := GetActiveConnectionIDs()
for _, connID := range activeConnectionIDs {
t.Logf("active: %s", connID)
}
}