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

@ -60,7 +60,17 @@ func apiAuthenticator(s *http.Server, r *http.Request) (grantAccess bool, err er
var procsChecked []string
// get process
proc, err := process.GetProcessByEndpoints(r.Context(), remoteIP, remotePort, localIP, localPort, packet.TCP) // switch reverse/local to get remote process
proc, _, err := process.GetProcessByEndpoints(
r.Context(),
packet.IPv4,
packet.TCP,
// switch reverse/local to get remote process
remoteIP,
remotePort,
localIP,
localPort,
false,
)
if err != nil {
return false, fmt.Errorf("failed to get process: %s", err)
}

View file

@ -10,6 +10,7 @@ import (
"github.com/safing/portmaster/network"
"github.com/safing/portmaster/network/netutils"
"github.com/safing/portmaster/network/packet"
"github.com/safing/portmaster/network/state"
"github.com/safing/portmaster/process"
"github.com/safing/portmaster/profile"
"github.com/safing/portmaster/profile/endpoints"
@ -90,12 +91,14 @@ func checkSelfCommunication(conn *network.Connection, pkt packet.Packet) bool {
pktInfo := pkt.Info()
if conn.Process().Pid >= 0 && pktInfo.Src.Equal(pktInfo.Dst) {
// get PID
otherPid, _, err := process.GetPidByEndpoints(
otherPid, _, err := state.Lookup(
pktInfo.Version,
pktInfo.Protocol,
pktInfo.RemoteIP(),
pktInfo.RemotePort(),
pktInfo.LocalIP(),
pktInfo.LocalPort(),
pktInfo.Protocol,
pktInfo.Direction,
)
if err != nil {
log.Warningf("filter: failed to find local peer process PID: %s", err)

View file

@ -6,6 +6,8 @@ import (
"net"
"strings"
"github.com/safing/portmaster/network/packet"
"github.com/safing/portbase/modules/subsystems"
"github.com/safing/portbase/log"
@ -167,13 +169,14 @@ func handleRequest(ctx context.Context, w dns.ResponseWriter, query *dns.Msg) er
}
// start tracer
ctx, tracer := log.AddTracer(ctx)
tracer.Tracef("nameserver: handling new request for %s%s from %s:%d", q.FQDN, q.QType, remoteAddr.IP, remoteAddr.Port)
ctx, tracer := log.AddTracer(context.Background())
defer tracer.Submit()
tracer.Tracef("nameserver: handling new request for %s%s from %s:%d, getting connection", q.FQDN, q.QType, remoteAddr.IP, remoteAddr.Port)
// TODO: if there are 3 request for the same domain/type in a row, delete all caches of that domain
// get connection
conn := network.NewConnectionFromDNSRequest(ctx, q.FQDN, nil, remoteAddr.IP, uint16(remoteAddr.Port))
conn := network.NewConnectionFromDNSRequest(ctx, q.FQDN, nil, packet.IPv4, remoteAddr.IP, uint16(remoteAddr.Port))
// once we decided on the connection we might need to save it to the database
// so we defer that check right now.
@ -191,7 +194,7 @@ func handleRequest(ctx context.Context, w dns.ResponseWriter, query *dns.Msg) er
return
default:
log.Warningf("nameserver: unexpected verdict %s for connection %s, not saving", conn.Verdict, conn)
tracer.Warningf("nameserver: unexpected verdict %s for connection %s, not saving", conn.Verdict, conn)
}
}()
@ -242,7 +245,7 @@ func handleRequest(ctx context.Context, w dns.ResponseWriter, query *dns.Msg) er
tracer.Infof("nameserver: %s handing over to reason-responder: %s", q.FQDN, conn.Reason)
reply := responder.ReplyWithDNS(query, conn.Reason, conn.ReasonContext)
if err := w.WriteMsg(reply); err != nil {
log.Warningf("nameserver: failed to return response %s%s to %s: %s", q.FQDN, q.QType, conn.Process(), err)
tracer.Warningf("nameserver: failed to return response %s%s to %s: %s", q.FQDN, q.QType, conn.Process(), err)
} else {
tracer.Debugf("nameserver: returning response %s%s to %s", q.FQDN, q.QType, conn.Process())
}
@ -269,6 +272,7 @@ func handleRequest(ctx context.Context, w dns.ResponseWriter, query *dns.Msg) er
return nil
}
tracer.Trace("nameserver: deciding on resolved dns")
rrCache = firewall.DecideOnResolvedDNS(conn, q, rrCache)
if rrCache == nil {
sendResponse(w, query, conn.Verdict, conn.Reason, conn.ReasonContext)
@ -283,7 +287,7 @@ func handleRequest(ctx context.Context, w dns.ResponseWriter, query *dns.Msg) er
m.Extra = rrCache.Extra
if err := w.WriteMsg(m); err != nil {
log.Warningf("nameserver: failed to return response %s%s to %s: %s", q.FQDN, q.QType, conn.Process(), err)
tracer.Warningf("nameserver: failed to return response %s%s to %s: %s", q.FQDN, q.QType, conn.Process(), err)
} else {
tracer.Debugf("nameserver: returning response %s%s to %s", q.FQDN, q.QType, conn.Process())
}

View file

@ -10,7 +10,7 @@ import (
"github.com/safing/portbase/modules"
"github.com/safing/portbase/notifications"
"github.com/safing/portmaster/network/packet"
"github.com/safing/portmaster/process"
"github.com/safing/portmaster/network/state"
)
var (
@ -58,7 +58,7 @@ func checkForConflictingService() error {
}
func takeover(resolverIP net.IP) (int, error) {
pid, _, err := process.GetPidByEndpoints(resolverIP, 53, resolverIP, 65535, packet.UDP)
pid, _, err := state.Lookup(0, packet.UDP, resolverIP, 53, nil, 0, false)
if err != nil {
// there may be nothing listening on :53
return 0, nil

View file

@ -4,6 +4,8 @@ import (
"context"
"time"
"github.com/safing/portmaster/network/state"
"github.com/safing/portbase/log"
"github.com/safing/portmaster/process"
)
@ -22,8 +24,12 @@ func connectionCleaner(ctx context.Context) error {
ticker.Stop()
return nil
case <-ticker.C:
// clean connections and processes
activePIDs := cleanConnections()
process.CleanProcessStorage(activePIDs)
// clean udp connection states
state.CleanUDPStates(ctx)
}
}
}
@ -33,12 +39,9 @@ func cleanConnections() (activePIDs map[int]struct{}) {
name := "clean connections" // TODO: change to new fn
_ = module.RunMediumPriorityMicroTask(&name, func(ctx context.Context) error {
activeIDs := make(map[string]struct{})
for _, cID := range process.GetActiveConnectionIDs() {
activeIDs[cID] = struct{}{}
}
now := time.Now().Unix()
now := time.Now().UTC()
nowUnix := now.Unix()
deleteOlderThan := time.Now().Add(-deleteConnsAfterEndedThreshold).Unix()
// lock both together because we cannot fully guarantee in which map a connection lands
@ -49,20 +52,20 @@ func cleanConnections() (activePIDs map[int]struct{}) {
defer dnsConnsLock.Unlock()
// network connections
for key, conn := range conns {
for _, conn := range conns {
conn.Lock()
// delete inactive connections
switch {
case conn.Ended == 0:
// Step 1: check if still active
_, ok := activeIDs[key]
if ok {
exists := state.Exists(conn.IPVersion, conn.IPProtocol, conn.LocalIP, conn.LocalPort, conn.Entity.IP, conn.Entity.Port, now)
if exists {
activePIDs[conn.process.Pid] = struct{}{}
} else {
// Step 2: mark end
activePIDs[conn.process.Pid] = struct{}{}
conn.Ended = now
conn.Ended = nowUnix
conn.Save()
}
case conn.Ended < deleteOlderThan:

View file

@ -25,11 +25,19 @@ type Connection struct { //nolint:maligned // TODO: fix alignment
record.Base
sync.Mutex
ID string
Scope string
Inbound bool
Entity *intel.Entity // needs locking, instance is never shared
process *process.Process
ID string
Scope string
IPVersion packet.IPVersion
Inbound bool
// local endpoint
IPProtocol packet.IPProtocol
LocalIP net.IP
LocalPort uint16
process *process.Process
// remote endpoint
Entity *intel.Entity // needs locking, instance is never shared
Verdict Verdict
Reason string
@ -55,9 +63,18 @@ type Connection struct { //nolint:maligned // TODO: fix alignment
}
// NewConnectionFromDNSRequest returns a new connection based on the given dns request.
func NewConnectionFromDNSRequest(ctx context.Context, fqdn string, cnames []string, localIP net.IP, localPort uint16) *Connection {
func NewConnectionFromDNSRequest(ctx context.Context, fqdn string, cnames []string, ipVersion packet.IPVersion, localIP net.IP, localPort uint16) *Connection {
// get Process
proc, err := process.GetProcessByEndpoints(ctx, localIP, localPort, dnsAddress, dnsPort, packet.UDP)
proc, _, err := process.GetProcessByEndpoints(
ctx,
ipVersion,
packet.UDP,
localIP,
localPort,
dnsAddress, // this might not be correct, but it does not matter, as matching only occurs on the local address
dnsPort,
false, // inbound, irrevelant
)
if err != nil {
log.Warningf("network: failed to find process of dns request for %s: %s", fqdn, err)
proc = process.GetUnidentifiedProcess(ctx)
@ -147,11 +164,18 @@ func NewConnectionFromFirstPacket(pkt packet.Packet) *Connection {
}
return &Connection{
ID: pkt.GetConnectionID(),
Scope: scope,
Inbound: inbound,
Entity: entity,
process: proc,
ID: pkt.GetConnectionID(),
Scope: scope,
IPVersion: pkt.Info().Version,
Inbound: inbound,
// local endpoint
IPProtocol: pkt.Info().Protocol,
LocalIP: pkt.Info().LocalIP(),
LocalPort: pkt.Info().LocalPort(),
process: proc,
// remote endpoint
Entity: entity,
// meta
Started: time.Now().Unix(),
}
}

View file

@ -57,6 +57,13 @@ func (s *StorageInterface) Get(key string) (record.Record, error) {
return conn, nil
}
}
// case "system":
// if len(splitted) >= 2 {
// switch splitted[1] {
// case "":
// process.Get
// }
// }
}
return nil, storage.ErrNotFound

72
network/iphelper/get.go Normal file
View file

@ -0,0 +1,72 @@
// +build windows
package iphelper
import (
"sync"
"github.com/safing/portmaster/network/socket"
)
const (
unidentifiedProcessID = -1
)
var (
ipHelper *IPHelper
lock sync.RWMutex
)
// GetTCP4Table returns the system table for IPv4 TCP activity.
func GetTCP4Table() (connections []*socket.ConnectionInfo, listeners []*socket.BindInfo, err error) {
lock.Lock()
defer lock.Unlock()
err = checkIPHelper()
if err != nil {
return nil, nil, err
}
return ipHelper.getTable(IPv4, TCP)
}
// GetTCP6Table returns the system table for IPv6 TCP activity.
func GetTCP6Table() (connections []*socket.ConnectionInfo, listeners []*socket.BindInfo, err error) {
lock.Lock()
defer lock.Unlock()
err = checkIPHelper()
if err != nil {
return nil, nil, err
}
return ipHelper.getTable(IPv6, TCP)
}
// GetUDP4Table returns the system table for IPv4 UDP activity.
func GetUDP4Table() (binds []*socket.BindInfo, err error) {
lock.Lock()
defer lock.Unlock()
err = checkIPHelper()
if err != nil {
return nil, err
}
_, binds, err = ipHelper.getTable(IPv4, UDP)
return
}
// GetUDP6Table returns the system table for IPv6 UDP activity.
func GetUDP6Table() (binds []*socket.BindInfo, err error) {
lock.Lock()
defer lock.Unlock()
err = checkIPHelper()
if err != nil {
return nil, err
}
_, binds, err = ipHelper.getTable(IPv6, UDP)
return
}

View file

@ -0,0 +1,63 @@
// +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
valid *abool.AtomicBool
}
func checkIPHelper() (err error) {
if ipHelper == nil {
ipHelper, err = New()
return err
}
return nil
}
// 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.valid.Set()
return new, nil
}

View file

@ -3,12 +3,15 @@
package iphelper
import (
"encoding/binary"
"errors"
"fmt"
"net"
"sync"
"unsafe"
"github.com/safing/portmaster/network/socket"
"golang.org/x/sys/windows"
)
@ -22,19 +25,6 @@ const (
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
@ -148,9 +138,9 @@ func increaseBufSize() int {
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
// getTable returns the current connection state table of Windows of the given protocol and IP version.
func (ipHelper *IPHelper) getTable(ipVersion, protocol uint8) (connections []*socket.ConnectionInfo, binds []*socket.BindInfo, err error) { //nolint:gocognit,gocycle // TODO
// docs: https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getextendedtcptable
if !ipHelper.valid.IsSet() {
return nil, nil, errInvalid
@ -220,26 +210,27 @@ func (ipHelper *IPHelper) GetTables(protocol uint8, ipVersion uint8) (connection
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)
binds = append(binds, &socket.BindInfo{
Local: socket.Address{
IP: convertIPv4(row.localAddr),
Port: uint16(row.localPort>>8 | row.localPort<<8),
},
PID: int(row.owningPid),
})
} else {
new.remoteIP = convertIPv4(row.remoteAddr)
new.remotePort = uint16(row.remotePort>>8 | row.remotePort<<8)
connections = append(connections, new)
connections = append(connections, &socket.ConnectionInfo{
Local: socket.Address{
IP: convertIPv4(row.localAddr),
Port: uint16(row.localPort>>8 | row.localPort<<8),
},
Remote: socket.Address{
IP: convertIPv4(row.remoteAddr),
Port: uint16(row.remotePort>>8 | row.remotePort<<8),
},
PID: int(row.owningPid),
})
}
}
case protocol == TCP && ipVersion == IPv6:
@ -248,27 +239,27 @@ func (ipHelper *IPHelper) GetTables(protocol uint8, ipVersion uint8) (connection
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)
binds = append(binds, &socket.BindInfo{
Local: socket.Address{
IP: net.IP(row.localAddr[:]),
Port: uint16(row.localPort>>8 | row.localPort<<8),
},
PID: int(row.owningPid),
})
} else {
new.remoteIP = net.IP(row.remoteAddr[:])
new.remotePort = uint16(row.remotePort>>8 | row.remotePort<<8)
connections = append(connections, new)
connections = append(connections, &socket.ConnectionInfo{
Local: socket.Address{
IP: net.IP(row.localAddr[:]),
Port: uint16(row.localPort>>8 | row.localPort<<8),
},
Remote: socket.Address{
IP: net.IP(row.remoteAddr[:]),
Port: uint16(row.remotePort>>8 | row.remotePort<<8),
},
PID: int(row.owningPid),
})
}
}
case protocol == UDP && ipVersion == IPv4:
@ -277,19 +268,13 @@ func (ipHelper *IPHelper) GetTables(protocol uint8, ipVersion uint8) (connection
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)
}
binds = append(binds, &socket.BindInfo{
Local: socket.Address{
IP: convertIPv4(row.localAddr),
Port: uint16(row.localPort>>8 | row.localPort<<8),
},
PID: int(row.owningPid),
})
}
case protocol == UDP && ipVersion == IPv6:
@ -298,32 +283,22 @@ func (ipHelper *IPHelper) GetTables(protocol uint8, ipVersion uint8) (connection
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)
}
binds = append(binds, &socket.BindInfo{
Local: socket.Address{
IP: net.IP(row.localAddr[:]),
Port: uint16(row.localPort>>8 | row.localPort<<8),
},
PID: int(row.owningPid),
})
}
}
return connections, listeners, nil
return connections, binds, 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),
)
addressBuf := make([]byte, 4)
binary.BigEndian.PutUint32(addressBuf, input)
return net.IP(addressBuf)
}

View file

@ -0,0 +1,54 @@
// +build windows
package iphelper
import (
"fmt"
"testing"
)
func TestSockets(t *testing.T) {
connections, listeners, err := GetTCP4Table()
if err != nil {
t.Fatal(err)
}
fmt.Println("\nTCP 4 connections:")
for _, connection := range connections {
fmt.Printf("%+v\n", connection)
}
fmt.Println("\nTCP 4 listeners:")
for _, listener := range listeners {
fmt.Printf("%+v\n", listener)
}
connections, listeners, err = GetTCP6Table()
if err != nil {
t.Fatal(err)
}
fmt.Println("\nTCP 6 connections:")
for _, connection := range connections {
fmt.Printf("%+v\n", connection)
}
fmt.Println("\nTCP 6 listeners:")
for _, listener := range listeners {
fmt.Printf("%+v\n", listener)
}
binds, err := GetUDP4Table()
if err != nil {
t.Fatal(err)
}
fmt.Println("\nUDP 4 binds:")
for _, bind := range binds {
fmt.Printf("%+v\n", bind)
}
binds, err = GetUDP6Table()
if err != nil {
t.Fatal(err)
}
fmt.Println("\nUDP 6 binds:")
for _, bind := range binds {
fmt.Printf("%+v\n", bind)
}
}

View file

@ -13,13 +13,17 @@ import (
"github.com/safing/portbase/log"
)
const (
unidentifiedProcessID = -1
)
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
// FindPID returns the pid of the given uid and socket inode.
func FindPID(uid, inode int) (pid int, ok bool) { //nolint:gocognit // TODO
pidsByUserLock.Lock()
defer pidsByUserLock.Unlock()

218
network/proc/tables.go Normal file
View file

@ -0,0 +1,218 @@
// +build linux
package proc
import (
"bufio"
"encoding/hex"
"net"
"os"
"strconv"
"strings"
"unicode"
"github.com/safing/portmaster/network/socket"
"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"
UnfetchedProcessID = -2
tcpListenStateHex = "0A"
)
// GetTCP4Table returns the system table for IPv4 TCP activity.
func GetTCP4Table() (connections []*socket.ConnectionInfo, listeners []*socket.BindInfo, err error) {
return getTableFromSource(TCP4, TCP4Data, convertIPv4)
}
// GetTCP6Table returns the system table for IPv6 TCP activity.
func GetTCP6Table() (connections []*socket.ConnectionInfo, listeners []*socket.BindInfo, err error) {
return getTableFromSource(TCP6, TCP6Data, convertIPv6)
}
// GetUDP4Table returns the system table for IPv4 UDP activity.
func GetUDP4Table() (binds []*socket.BindInfo, err error) {
_, binds, err = getTableFromSource(UDP4, UDP4Data, convertIPv4)
return
}
// GetUDP6Table returns the system table for IPv6 UDP activity.
func GetUDP6Table() (binds []*socket.BindInfo, err error) {
_, binds, err = getTableFromSource(UDP6, UDP6Data, convertIPv6)
return
}
func getTableFromSource(stack uint8, procFile string, ipConverter func(string) net.IP) (connections []*socket.ConnectionInfo, binds []*socket.BindInfo, err error) {
// open file
socketData, err := os.Open(procFile)
if err != nil {
return nil, nil, err
}
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
}
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
}
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
}
switch stack {
case UDP4, UDP6:
binds = append(binds, &socket.BindInfo{
Local: socket.Address{
IP: localIP,
Port: uint16(localPort),
},
PID: UnfetchedProcessID,
UID: int(uid),
Inode: int(inode),
})
case TCP4, TCP6:
if line[5] == tcpListenStateHex {
// listener
binds = append(binds, &socket.BindInfo{
Local: socket.Address{
IP: localIP,
Port: uint16(localPort),
},
PID: UnfetchedProcessID,
UID: int(uid),
Inode: int(inode),
})
} else {
// connection
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, &socket.ConnectionInfo{
Local: socket.Address{
IP: localIP,
Port: uint16(localPort),
},
Remote: socket.Address{
IP: remoteIP,
Port: uint16(remotePort),
},
PID: UnfetchedProcessID,
UID: int(uid),
Inode: int(inode),
})
}
}
}
return connections, binds, nil
}
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
}

View file

@ -0,0 +1,60 @@
// +build linux
package proc
import (
"fmt"
"testing"
)
func TestSockets(t *testing.T) {
connections, listeners, err := GetTCP4Table()
if err != nil {
t.Fatal(err)
}
fmt.Println("\nTCP 4 connections:")
for _, connection := range connections {
pid, _ := FindPID(connection.UID, connection.Inode)
fmt.Printf("%d: %+v\n", pid, connection)
}
fmt.Println("\nTCP 4 listeners:")
for _, listener := range listeners {
pid, _ := FindPID(listener.UID, listener.Inode)
fmt.Printf("%d: %+v\n", pid, listener)
}
connections, listeners, err = GetTCP6Table()
if err != nil {
t.Fatal(err)
}
fmt.Println("\nTCP 6 connections:")
for _, connection := range connections {
pid, _ := FindPID(connection.UID, connection.Inode)
fmt.Printf("%d: %+v\n", pid, connection)
}
fmt.Println("\nTCP 6 listeners:")
for _, listener := range listeners {
pid, _ := FindPID(listener.UID, listener.Inode)
fmt.Printf("%d: %+v\n", pid, listener)
}
binds, err := GetUDP4Table()
if err != nil {
t.Fatal(err)
}
fmt.Println("\nUDP 4 binds:")
for _, bind := range binds {
pid, _ := FindPID(bind.UID, bind.Inode)
fmt.Printf("%d: %+v\n", pid, bind)
}
binds, err = GetUDP6Table()
if err != nil {
t.Fatal(err)
}
fmt.Println("\nUDP 6 binds:")
for _, bind := range binds {
pid, _ := FindPID(bind.UID, bind.Inode)
fmt.Printf("%d: %+v\n", pid, bind)
}
}

26
network/socket/socket.go Normal file
View file

@ -0,0 +1,26 @@
package socket
import "net"
// ConnectionInfo holds socket information returned by the system.
type ConnectionInfo struct {
Local Address
Remote Address
PID int
UID int
Inode int
}
// BindInfo holds socket information returned by the system.
type BindInfo struct {
Local Address
PID int
UID int
Inode int
}
// Address is an IP + Port pair.
type Address struct {
IP net.IP
Port uint16
}

103
network/state/exists.go Normal file
View file

@ -0,0 +1,103 @@
package state
import (
"net"
"time"
"github.com/safing/portmaster/network/packet"
"github.com/safing/portmaster/network/socket"
)
const (
UDPConnectionTTL = 10 * time.Minute
)
func Exists(
ipVersion packet.IPVersion,
protocol packet.IPProtocol,
localIP net.IP,
localPort uint16,
remoteIP net.IP,
remotePort uint16,
now time.Time,
) (exists bool) {
switch {
case ipVersion == packet.IPv4 && protocol == packet.TCP:
tcp4Lock.Lock()
defer tcp4Lock.Unlock()
return existsTCP(tcp4Connections, localIP, localPort, remoteIP, remotePort)
case ipVersion == packet.IPv6 && protocol == packet.TCP:
tcp6Lock.Lock()
defer tcp6Lock.Unlock()
return existsTCP(tcp6Connections, localIP, localPort, remoteIP, remotePort)
case ipVersion == packet.IPv4 && protocol == packet.UDP:
udp4Lock.Lock()
defer udp4Lock.Unlock()
return existsUDP(udp4Binds, udp4States, localIP, localPort, remoteIP, remotePort, now)
case ipVersion == packet.IPv6 && protocol == packet.UDP:
udp6Lock.Lock()
defer udp6Lock.Unlock()
return existsUDP(udp6Binds, udp6States, localIP, localPort, remoteIP, remotePort, now)
default:
return false
}
}
func existsTCP(
connections []*socket.ConnectionInfo,
localIP net.IP,
localPort uint16,
remoteIP net.IP,
remotePort uint16,
) (exists bool) {
// search connections
for _, socketInfo := range connections {
if localPort == socketInfo.Local.Port &&
remotePort == socketInfo.Remote.Port &&
remoteIP.Equal(socketInfo.Remote.IP) &&
localIP.Equal(socketInfo.Local.IP) {
return true
}
}
return false
}
func existsUDP(
binds []*socket.BindInfo,
udpStates map[string]map[string]*udpState,
localIP net.IP,
localPort uint16,
remoteIP net.IP,
remotePort uint16,
now time.Time,
) (exists bool) {
connThreshhold := now.Add(-UDPConnectionTTL)
// search binds
for _, socketInfo := range binds {
if localPort == socketInfo.Local.Port &&
(socketInfo.Local.IP[0] == 0 || localIP.Equal(socketInfo.Local.IP)) {
udpConnState, ok := getUDPConnState(socketInfo, udpStates, remoteIP, remotePort)
switch {
case !ok:
return false
case udpConnState.lastSeen.After(connThreshhold):
return true
default:
return false
}
}
}
return false
}

189
network/state/lookup.go Normal file
View file

@ -0,0 +1,189 @@
package state
import (
"errors"
"net"
"sync"
"time"
"github.com/safing/portmaster/network/packet"
"github.com/safing/portmaster/network/socket"
)
// - TCP
// - Outbound: Match listeners (in!), then connections (out!)
// - Inbound: Match listeners (in!), then connections (out!)
// - Clean via connections
// - UDP
// - Any connection: match specific local address or zero IP
// - In or out: save direction of first packet:
// - map[<local udp bind ip+port>]map[<remote ip+port>]{direction, lastSeen}
// - only clean if <local udp bind ip+port> is removed by OS
// - limit <remote ip+port> to 256 entries?
// - clean <remote ip+port> after 72hrs?
// - switch direction to outbound if outbound packet is seen?
// - IP: Unidentified Process
const (
UnidentifiedProcessID = -1
)
// Errors
var (
ErrConnectionNotFound = errors.New("could not find connection in system state tables")
ErrPIDNotFound = errors.New("could not find pid for socket inode")
)
var (
tcp4Lock sync.Mutex
tcp6Lock sync.Mutex
udp4Lock sync.Mutex
udp6Lock sync.Mutex
waitTime = 3 * time.Millisecond
)
func LookupWithPacket(pkt packet.Packet) (pid int, inbound bool, err error) {
meta := pkt.Info()
return Lookup(
meta.Version,
meta.Protocol,
meta.LocalIP(),
meta.LocalPort(),
meta.RemoteIP(),
meta.RemotePort(),
meta.Direction,
)
}
func Lookup(
ipVersion packet.IPVersion,
protocol packet.IPProtocol,
localIP net.IP,
localPort uint16,
remoteIP net.IP,
remotePort uint16,
pktInbound bool,
) (
pid int,
inbound bool,
err error,
) {
// auto-detect version
if ipVersion == 0 {
if ip := localIP.To4(); ip != nil {
ipVersion = packet.IPv4
} else {
ipVersion = packet.IPv6
}
}
switch {
case ipVersion == packet.IPv4 && protocol == packet.TCP:
tcp4Lock.Lock()
defer tcp4Lock.Unlock()
return searchTCP(tcp4Connections, tcp4Listeners, updateTCP4Tables, localIP, localPort)
case ipVersion == packet.IPv6 && protocol == packet.TCP:
tcp6Lock.Lock()
defer tcp6Lock.Unlock()
return searchTCP(tcp6Connections, tcp6Listeners, updateTCP6Tables, localIP, localPort)
case ipVersion == packet.IPv4 && protocol == packet.UDP:
udp4Lock.Lock()
defer udp4Lock.Unlock()
return searchUDP(udp4Binds, udp4States, updateUDP4Table, localIP, localPort, remoteIP, remotePort, pktInbound)
case ipVersion == packet.IPv6 && protocol == packet.UDP:
udp6Lock.Lock()
defer udp6Lock.Unlock()
return searchUDP(udp6Binds, udp6States, updateUDP6Table, localIP, localPort, remoteIP, remotePort, pktInbound)
default:
return UnidentifiedProcessID, false, errors.New("unsupported protocol for finding process")
}
}
func searchTCP(
connections []*socket.ConnectionInfo,
listeners []*socket.BindInfo,
updateTables func() ([]*socket.ConnectionInfo, []*socket.BindInfo),
localIP net.IP,
localPort uint16,
) (
pid int,
inbound bool,
err error,
) {
// search until we find something
for i := 0; i < 5; i++ {
// always search listeners first
for _, socketInfo := range listeners {
if localPort == socketInfo.Local.Port &&
(socketInfo.Local.IP[0] == 0 || localIP.Equal(socketInfo.Local.IP)) {
return checkBindPID(socketInfo, true)
}
}
// search connections
for _, socketInfo := range connections {
if localPort == socketInfo.Local.Port &&
localIP.Equal(socketInfo.Local.IP) {
return checkConnectionPID(socketInfo, false)
}
}
// we found nothing, we could have been too fast, give the kernel some time to think
time.Sleep(waitTime)
// refetch lists
connections, listeners = updateTables()
}
return UnidentifiedProcessID, false, ErrConnectionNotFound
}
func searchUDP(
binds []*socket.BindInfo,
udpStates map[string]map[string]*udpState,
updateTable func() []*socket.BindInfo,
localIP net.IP,
localPort uint16,
remoteIP net.IP,
remotePort uint16,
pktInbound bool,
) (
pid int,
inbound bool,
err error,
) {
// search until we find something
for i := 0; i < 5; i++ {
// search binds
for _, socketInfo := range binds {
if localPort == socketInfo.Local.Port &&
(socketInfo.Local.IP[0] == 0 || localIP.Equal(socketInfo.Local.IP)) {
// do not check direction if remoteIP/Port is not given
if remotePort == 0 {
return checkBindPID(socketInfo, pktInbound)
}
// get direction and return
connInbound := getUDPDirection(socketInfo, udpStates, remoteIP, remotePort, pktInbound)
return checkBindPID(socketInfo, connInbound)
}
}
// we found nothing, we could have been too fast, give the kernel some time to think
time.Sleep(waitTime)
// refetch lists
binds = updateTable()
}
return UnidentifiedProcessID, pktInbound, ErrConnectionNotFound
}

View file

@ -0,0 +1,37 @@
package state
import (
"github.com/safing/portmaster/network/proc"
"github.com/safing/portmaster/network/socket"
)
var (
getTCP4Table = proc.GetTCP4Table
getTCP6Table = proc.GetTCP6Table
getUDP4Table = proc.GetUDP4Table
getUDP6Table = proc.GetUDP6Table
)
func checkConnectionPID(socketInfo *socket.ConnectionInfo, connInbound bool) (pid int, inbound bool, err error) {
if socketInfo.PID == proc.UnfetchedProcessID {
pid, ok := proc.FindPID(socketInfo.UID, socketInfo.Inode)
if ok {
socketInfo.PID = pid
} else {
socketInfo.PID = UnidentifiedProcessID
}
}
return socketInfo.PID, connInbound, nil
}
func checkBindPID(socketInfo *socket.BindInfo, connInbound bool) (pid int, inbound bool, err error) {
if socketInfo.PID == proc.UnfetchedProcessID {
pid, ok := proc.FindPID(socketInfo.UID, socketInfo.Inode)
if ok {
socketInfo.PID = pid
} else {
socketInfo.PID = UnidentifiedProcessID
}
}
return socketInfo.PID, connInbound, nil
}

View file

@ -0,0 +1,21 @@
package state
import (
"github.com/safing/portmaster/network/iphelper"
"github.com/safing/portmaster/network/socket"
)
var (
getTCP4Table = iphelper.GetTCP4Table
getTCP6Table = iphelper.GetTCP6Table
getUDP4Table = iphelper.GetUDP4Table
getUDP6Table = iphelper.GetUDP6Table
)
func checkConnectionPID(socketInfo *socket.ConnectionInfo, connInbound bool) (pid int, inbound bool, err error) {
return socketInfo.PID, connInbound, nil
}
func checkBindPID(socketInfo *socket.BindInfo, connInbound bool) (pid int, inbound bool, err error) {
return socketInfo.PID, connInbound, nil
}

66
network/state/tables.go Normal file
View file

@ -0,0 +1,66 @@
package state
import (
"github.com/safing/portbase/log"
"github.com/safing/portmaster/network/socket"
)
var (
tcp4Connections []*socket.ConnectionInfo
tcp4Listeners []*socket.BindInfo
tcp6Connections []*socket.ConnectionInfo
tcp6Listeners []*socket.BindInfo
udp4Binds []*socket.BindInfo
udp6Binds []*socket.BindInfo
)
func updateTCP4Tables() (connections []*socket.ConnectionInfo, listeners []*socket.BindInfo) {
// FIXME: repeatable once
connections, listeners, err := getTCP4Table()
if err != nil {
log.Warningf("state: failed to get TCP4 socket table: %s", err)
return
}
tcp4Connections = connections
tcp4Listeners = listeners
return tcp4Connections, tcp4Listeners
}
func updateTCP6Tables() (connections []*socket.ConnectionInfo, listeners []*socket.BindInfo) {
connections, listeners, err := getTCP6Table()
if err != nil {
log.Warningf("state: failed to get TCP6 socket table: %s", err)
return
}
tcp6Connections = connections
tcp6Listeners = listeners
return tcp6Connections, tcp6Listeners
}
func updateUDP4Table() (binds []*socket.BindInfo) {
binds, err := getUDP4Table()
if err != nil {
log.Warningf("state: failed to get UDP4 socket table: %s", err)
return
}
udp4Binds = binds
return udp4Binds
}
func updateUDP6Table() (binds []*socket.BindInfo) {
binds, err := getUDP6Table()
if err != nil {
log.Warningf("state: failed to get UDP6 socket table: %s", err)
return
}
udp6Binds = binds
return udp6Binds
}

118
network/state/udp.go Normal file
View file

@ -0,0 +1,118 @@
package state
import (
"context"
"net"
"time"
"github.com/safing/portmaster/network/socket"
)
type udpState struct {
inbound bool
lastSeen time.Time
}
const (
UpdConnStateTTL = 72 * time.Hour
UdpConnStateShortenedTTL = 3 * time.Hour
AggressiveCleaningThreshold = 256
)
var (
udp4States = make(map[string]map[string]*udpState) // locked with udp4Lock
udp6States = make(map[string]map[string]*udpState) // locked with udp6Lock
)
func getUDPConnState(socketInfo *socket.BindInfo, udpStates map[string]map[string]*udpState, remoteIP net.IP, remotePort uint16) (udpConnState *udpState, ok bool) {
bindMap, ok := udpStates[makeUDPStateKey(socketInfo.Local.IP, socketInfo.Local.Port)]
if ok {
udpConnState, ok = bindMap[makeUDPStateKey(remoteIP, remotePort)]
return
}
return nil, false
}
func getUDPDirection(socketInfo *socket.BindInfo, udpStates map[string]map[string]*udpState, remoteIP net.IP, remotePort uint16, pktInbound bool) (connDirection bool) {
localKey := makeUDPStateKey(socketInfo.Local.IP, socketInfo.Local.Port)
bindMap, ok := udpStates[localKey]
if !ok {
bindMap = make(map[string]*udpState)
udpStates[localKey] = bindMap
}
remoteKey := makeUDPStateKey(remoteIP, remotePort)
udpConnState, ok := bindMap[remoteKey]
if !ok {
bindMap[remoteKey] = &udpState{
inbound: pktInbound,
lastSeen: time.Now().UTC(),
}
return pktInbound
}
udpConnState.lastSeen = time.Now().UTC()
return udpConnState.inbound
}
func CleanUDPStates(ctx context.Context) {
now := time.Now().UTC()
udp4Lock.Lock()
updateUDP4Table()
cleanStates(ctx, udp4Binds, udp4States, now)
udp4Lock.Unlock()
udp6Lock.Lock()
updateUDP6Table()
cleanStates(ctx, udp6Binds, udp6States, now)
udp6Lock.Unlock()
}
func cleanStates(
ctx context.Context,
binds []*socket.BindInfo,
udpStates map[string]map[string]*udpState,
now time.Time,
) {
// compute thresholds
threshold := now.Add(-UpdConnStateTTL)
shortThreshhold := now.Add(-UdpConnStateShortenedTTL)
// make list of all active keys
bindKeys := make(map[string]struct{})
for _, socketInfo := range binds {
bindKeys[makeUDPStateKey(socketInfo.Local.IP, socketInfo.Local.Port)] = struct{}{}
}
// clean the udp state storage
for localKey, bindMap := range udpStates {
_, active := bindKeys[localKey]
if active {
// clean old entries
for remoteKey, udpConnState := range bindMap {
if udpConnState.lastSeen.Before(threshold) {
delete(bindMap, remoteKey)
}
}
// if there are too many clean more aggressively
if len(bindMap) > AggressiveCleaningThreshold {
for remoteKey, udpConnState := range bindMap {
if udpConnState.lastSeen.Before(shortThreshhold) {
delete(bindMap, remoteKey)
}
}
}
} else {
// delete the whole thing
delete(udpStates, localKey)
}
}
}
func makeUDPStateKey(ip net.IP, port uint16) string {
// This could potentially go wrong, but as all IPs are created by the same source, everything should be fine.
return string(ip) + string(port)
}

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,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,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)
}
}

View file

@ -152,7 +152,7 @@ func start() error {
err = registry.LoadIndexes()
if err != nil {
return err
log.Warningf("updates: failed to load indexes: %s", err)
}
err = registry.ScanStorage("")
@ -235,8 +235,7 @@ func checkForUpdates(ctx context.Context) (err error) {
}()
if err = registry.UpdateIndexes(); err != nil {
err = fmt.Errorf("failed to update indexes: %w", err)
return
log.Warningf("updates: failed to update indexes: %s", err)
}
err = registry.DownloadUpdates(ctx)

View file

@ -113,15 +113,9 @@ func upgradePortmasterControl() error {
return nil
}
// check if registry tmp dir is ok
err := registry.TmpDir().Ensure()
if err != nil {
return fmt.Errorf("failed to prep updates tmp dir: %s", err)
}
// update portmaster-control in data root
rootControlPath := filepath.Join(filepath.Dir(registry.StorageDir().Path), filename)
err = upgradeFile(rootControlPath, pmCtrlUpdate)
err := upgradeFile(rootControlPath, pmCtrlUpdate)
if err != nil {
return err
}
@ -130,11 +124,11 @@ func upgradePortmasterControl() error {
// upgrade parent process, if it's portmaster-control
parent, err := processInfo.NewProcess(int32(os.Getppid()))
if err != nil {
return fmt.Errorf("could not get parent process for upgrade checks: %s", err)
return fmt.Errorf("could not get parent process for upgrade checks: %w", err)
}
parentName, err := parent.Name()
if err != nil {
return fmt.Errorf("could not get parent process name for upgrade checks: %s", err)
return fmt.Errorf("could not get parent process name for upgrade checks: %w", err)
}
if parentName != filename {
log.Tracef("updates: parent process does not seem to be portmaster-control, name is %s", parentName)
@ -142,7 +136,7 @@ func upgradePortmasterControl() error {
}
parentPath, err := parent.Exe()
if err != nil {
return fmt.Errorf("could not get parent process path for upgrade: %s", err)
return fmt.Errorf("could not get parent process path for upgrade: %w", err)
}
err = upgradeFile(parentPath, pmCtrlUpdate)
if err != nil {
@ -190,7 +184,7 @@ func upgradeFile(fileToUpgrade string, file *updater.File) error {
// ensure tmp dir is here
err = registry.TmpDir().Ensure()
if err != nil {
return fmt.Errorf("unable to check updates tmp dir for moving file that needs upgrade: %s", err)
return fmt.Errorf("could not prepare tmp directory for moving file that needs upgrade: %w", err)
}
// maybe we're on windows and it's in use, try moving
@ -204,17 +198,17 @@ func upgradeFile(fileToUpgrade string, file *updater.File) error {
),
))
if err != nil {
return fmt.Errorf("unable to move file that needs upgrade: %s", err)
return fmt.Errorf("unable to move file that needs upgrade: %w", err)
}
}
}
// copy upgrade
err = copyFile(file.Path(), fileToUpgrade)
err = CopyFile(file.Path(), fileToUpgrade)
if err != nil {
// try again
time.Sleep(1 * time.Second)
err = copyFile(file.Path(), fileToUpgrade)
err = CopyFile(file.Path(), fileToUpgrade)
if err != nil {
return err
}
@ -224,23 +218,30 @@ func upgradeFile(fileToUpgrade string, file *updater.File) error {
if !onWindows {
info, err := os.Stat(fileToUpgrade)
if err != nil {
return fmt.Errorf("failed to get file info on %s: %s", fileToUpgrade, err)
return fmt.Errorf("failed to get file info on %s: %w", fileToUpgrade, err)
}
if info.Mode() != 0755 {
err := os.Chmod(fileToUpgrade, 0755)
if err != nil {
return fmt.Errorf("failed to set permissions on %s: %s", fileToUpgrade, err)
return fmt.Errorf("failed to set permissions on %s: %w", fileToUpgrade, err)
}
}
}
return nil
}
func copyFile(srcPath, dstPath string) (err error) {
func CopyFile(srcPath, dstPath string) (err error) {
// check tmp dir
err = registry.TmpDir().Ensure()
if err != nil {
return fmt.Errorf("could not prepare tmp directory for copying file: %w", err)
}
// open file for writing
atomicDstFile, err := renameio.TempFile(registry.TmpDir().Path, dstPath)
if err != nil {
return fmt.Errorf("could not create temp file for atomic copy: %s", err)
return fmt.Errorf("could not create temp file for atomic copy: %w", err)
}
defer atomicDstFile.Cleanup() //nolint:errcheck // ignore error for now, tmp dir will be cleaned later again anyway
@ -260,7 +261,7 @@ func copyFile(srcPath, dstPath string) (err error) {
// finalize file
err = atomicDstFile.CloseAtomicallyReplace()
if err != nil {
return fmt.Errorf("updates: failed to finalize copy to file %s: %s", dstPath, err)
return fmt.Errorf("updates: failed to finalize copy to file %s: %w", dstPath, err)
}
return nil