Merge pull request #186 from safing/feature/ipv6-dual-stack-support

Add IPv6 dual-stack support
This commit is contained in:
Patrick Pacher
2020-11-04 08:45:35 +01:00
committed by GitHub
6 changed files with 149 additions and 70 deletions

View File

@@ -207,6 +207,7 @@ func procDelimiter(c rune) bool {
} }
func convertIPv4(data string) net.IP { func convertIPv4(data string) net.IP {
// Decode and bullshit check the data length.
decoded, err := hex.DecodeString(data) decoded, err := hex.DecodeString(data)
if err != nil { if err != nil {
log.Warningf("proc: could not parse IPv4 %s: %s", data, err) log.Warningf("proc: could not parse IPv4 %s: %s", data, err)
@@ -216,11 +217,14 @@ func convertIPv4(data string) net.IP {
log.Warningf("proc: decoded IPv4 %s has wrong length", decoded) log.Warningf("proc: decoded IPv4 %s has wrong length", decoded)
return nil return nil
} }
// Build the IPv4 address with the reversed byte order.
ip := net.IPv4(decoded[3], decoded[2], decoded[1], decoded[0]) ip := net.IPv4(decoded[3], decoded[2], decoded[1], decoded[0])
return ip return ip
} }
func convertIPv6(data string) net.IP { func convertIPv6(data string) net.IP {
// Decode and bullshit check the data length.
decoded, err := hex.DecodeString(data) decoded, err := hex.DecodeString(data)
if err != nil { if err != nil {
log.Warningf("proc: could not parse IPv6 %s: %s", data, err) log.Warningf("proc: could not parse IPv6 %s: %s", data, err)
@@ -230,6 +234,11 @@ func convertIPv6(data string) net.IP {
log.Warningf("proc: decoded IPv6 %s has wrong length", decoded) log.Warningf("proc: decoded IPv6 %s has wrong length", decoded)
return nil return nil
} }
// Build the IPv6 address with the translated byte order.
for i := 0; i < 16; i += 4 {
decoded[i], decoded[i+1], decoded[i+2], decoded[i+3] = decoded[i+3], decoded[i+2], decoded[i+1], decoded[i]
}
ip := net.IP(decoded) ip := net.IP(decoded)
return ip return ip
} }

View File

@@ -29,6 +29,8 @@ type BindInfo struct {
PID int PID int
UID int UID int
Inode int Inode int
ListensAny bool
} }
// Address is an IP + Port pair. // Address is an IP + Port pair.

View File

@@ -31,7 +31,7 @@ var (
var ( var (
baseWaitTime = 3 * time.Millisecond baseWaitTime = 3 * time.Millisecond
lookupRetries = 7 lookupRetries = 7 * 2 // Every retry takes two full passes.
) )
// Lookup looks for the given connection in the system state tables and returns the PID of the associated process and whether the connection is inbound. // Lookup looks for the given connection in the system state tables and returns the PID of the associated process and whether the connection is inbound.
@@ -68,97 +68,147 @@ func (table *tcpTable) lookup(pktInfo *packet.Info) (
inbound bool, inbound bool,
err error, err error,
) { ) {
// Search pattern: search, wait, search, refresh, search, wait, search, refresh, ...
localIP := pktInfo.LocalIP() // Search for the socket until found.
localPort := pktInfo.LocalPort()
// search until we find something
for i := 0; i <= lookupRetries; i++ { for i := 0; i <= lookupRetries; i++ {
table.lock.RLock() // Check main table for socket.
socketInfo, inbound := table.findSocket(pktInfo)
// always search listeners first if socketInfo == nil && table.dualStack != nil {
for _, socketInfo := range table.listeners { // If there was no match in the main table and we are dual-stack, check
if localPort == socketInfo.Local.Port && // the dual-stack table for the socket.
(socketInfo.Local.IP[0] == 0 || localIP.Equal(socketInfo.Local.IP)) { socketInfo, inbound = table.dualStack.findSocket(pktInfo)
table.lock.RUnlock()
return checkPID(socketInfo, true)
}
} }
// search connections // If there's a match, check we have the PID and return.
for _, socketInfo := range table.connections { if socketInfo != nil {
if localPort == socketInfo.Local.Port && return checkPID(socketInfo, inbound)
localIP.Equal(socketInfo.Local.IP) {
table.lock.RUnlock()
return checkPID(socketInfo, false)
}
} }
table.lock.RUnlock()
// every time, except for the last iteration // every time, except for the last iteration
if i < lookupRetries { if i < lookupRetries {
// we found nothing, we could have been too fast, give the kernel some time to think // Take turns in waiting and refreshing in order to satisfy the search pattern.
// back off timer: with 3ms baseWaitTime: 3, 6, 9, 12, 15, 18, 21ms - 84ms in total if i%2 == 0 {
time.Sleep(time.Duration(i+1) * baseWaitTime) // we found nothing, we could have been too fast, give the kernel some time to think
// back off timer: with 3ms baseWaitTime: 3, 6, 9, 12, 15, 18, 21ms - 84ms in total
// refetch lists time.Sleep(time.Duration(i+1) * baseWaitTime)
table.updateTables() } else {
// refetch lists
table.updateTables()
if table.dualStack != nil {
table.dualStack.updateTables()
}
}
} }
} }
return socket.UnidentifiedProcessID, pktInfo.Inbound, ErrConnectionNotFound return socket.UnidentifiedProcessID, pktInfo.Inbound, ErrConnectionNotFound
} }
func (table *tcpTable) findSocket(pktInfo *packet.Info) (
socketInfo socket.Info,
inbound bool,
) {
localIP := pktInfo.LocalIP()
localPort := pktInfo.LocalPort()
table.lock.RLock()
defer table.lock.RUnlock()
// always search listeners first
for _, socketInfo := range table.listeners {
if localPort == socketInfo.Local.Port &&
(socketInfo.ListensAny || localIP.Equal(socketInfo.Local.IP)) {
return socketInfo, false
}
}
// search connections
for _, socketInfo := range table.connections {
if localPort == socketInfo.Local.Port &&
localIP.Equal(socketInfo.Local.IP) {
return socketInfo, false
}
}
return nil, false
}
func (table *udpTable) lookup(pktInfo *packet.Info) ( func (table *udpTable) lookup(pktInfo *packet.Info) (
pid int, pid int,
inbound bool, inbound bool,
err error, err error,
) { ) {
localIP := pktInfo.LocalIP() // Search pattern: search, wait, search, refresh, search, wait, search, refresh, ...
localPort := pktInfo.LocalPort()
isInboundMulticast := pktInfo.Inbound && netutils.ClassifyIP(localIP) == netutils.LocalMulticast
// TODO: Currently broadcast/multicast scopes are not checked, so we might // TODO: Currently broadcast/multicast scopes are not checked, so we might
// attribute an incoming broadcast/multicast packet to the wrong process if // attribute an incoming broadcast/multicast packet to the wrong process if
// there are multiple processes listening on the same local port, but // there are multiple processes listening on the same local port, but
// binding to different addresses. This highly unusual for clients. // binding to different addresses. This highly unusual for clients.
isInboundMulticast := pktInfo.Inbound && netutils.ClassifyIP(pktInfo.LocalIP()) == netutils.LocalMulticast
// search until we find something // Search for the socket until found.
for i := 0; i <= lookupRetries; i++ { for i := 0; i <= lookupRetries; i++ {
table.lock.RLock() // Check main table for socket.
socketInfo := table.findSocket(pktInfo, isInboundMulticast)
// search binds if socketInfo == nil && table.dualStack != nil {
for _, socketInfo := range table.binds { // If there was no match in the main table and we are dual-stack, check
if localPort == socketInfo.Local.Port && // the dual-stack table for the socket.
(socketInfo.Local.IP[0] == 0 || // zero IP socketInfo = table.dualStack.findSocket(pktInfo, isInboundMulticast)
isInboundMulticast || // inbound broadcast, multicast
localIP.Equal(socketInfo.Local.IP)) {
table.lock.RUnlock()
// do not check direction if remoteIP/Port is not given
if pktInfo.RemotePort() == 0 {
return checkPID(socketInfo, pktInfo.Inbound)
}
// get direction and return
connInbound := table.getDirection(socketInfo, pktInfo)
return checkPID(socketInfo, connInbound)
}
} }
table.lock.RUnlock() // If there's a match, get the direction and check we have the PID, then return.
if socketInfo != nil {
// If there is no remote port, do check for the direction of the
// connection. This will be the case for pure checking functions
// that do not want to change direction state.
if pktInfo.RemotePort() == 0 {
return checkPID(socketInfo, pktInfo.Inbound)
}
// Get (and save) the direction of the connection.
connInbound := table.getDirection(socketInfo, pktInfo)
// Check we have the PID and return.
return checkPID(socketInfo, connInbound)
}
// every time, except for the last iteration // every time, except for the last iteration
if i < lookupRetries { if i < lookupRetries {
// we found nothing, we could have been too fast, give the kernel some time to think // Take turns in waiting and refreshing in order to satisfy the search pattern.
// back off timer: with 3ms baseWaitTime: 3, 6, 9, 12, 15, 18, 21ms - 84ms in total if i%2 == 0 {
time.Sleep(time.Duration(i+1) * baseWaitTime) // we found nothing, we could have been too fast, give the kernel some time to think
// back off timer: with 3ms baseWaitTime: 3, 6, 9, 12, 15, 18, 21ms - 84ms in total
// refetch lists time.Sleep(time.Duration(i+1) * baseWaitTime)
table.updateTable() } else {
// refetch lists
table.updateTable()
if table.dualStack != nil {
table.dualStack.updateTable()
}
}
} }
} }
return socket.UnidentifiedProcessID, pktInfo.Inbound, ErrConnectionNotFound return socket.UnidentifiedProcessID, pktInfo.Inbound, ErrConnectionNotFound
} }
func (table *udpTable) findSocket(pktInfo *packet.Info, isInboundMulticast bool) (socketInfo *socket.BindInfo) {
localIP := pktInfo.LocalIP()
localPort := pktInfo.LocalPort()
table.lock.RLock()
defer table.lock.RUnlock()
// search binds
for _, socketInfo := range table.binds {
if localPort == socketInfo.Local.Port &&
(socketInfo.ListensAny || // zero IP (dual-stack)
isInboundMulticast || // inbound broadcast, multicast
localIP.Equal(socketInfo.Local.IP)) {
return socketInfo
}
}
return nil
}

View File

@@ -1,6 +1,8 @@
package state package state
import ( import (
"net"
"github.com/safing/portbase/log" "github.com/safing/portbase/log"
) )
@@ -15,6 +17,11 @@ func (table *tcpTable) updateTables() {
return return
} }
// Pre-check for any listeners.
for _, bindInfo := range listeners {
bindInfo.ListensAny = bindInfo.Local.IP.Equal(net.IPv4zero) || bindInfo.Local.IP.Equal(net.IPv6zero)
}
table.connections = connections table.connections = connections
table.listeners = listeners table.listeners = listeners
}) })
@@ -31,6 +38,11 @@ func (table *udpTable) updateTable() {
return return
} }
// Pre-check for any listeners.
for _, bindInfo := range binds {
bindInfo.ListensAny = bindInfo.Local.IP.Equal(net.IPv4zero) || bindInfo.Local.IP.Equal(net.IPv6zero)
}
table.binds = binds table.binds = binds
}) })
} }

View File

@@ -16,16 +16,19 @@ type tcpTable struct {
fetchOnceAgain utils.OnceAgain fetchOnceAgain utils.OnceAgain
fetchTable func() (connections []*socket.ConnectionInfo, listeners []*socket.BindInfo, err error) fetchTable func() (connections []*socket.ConnectionInfo, listeners []*socket.BindInfo, err error)
dualStack *tcpTable
} }
var ( var (
tcp4Table = &tcpTable{
version: 4,
fetchTable: getTCP4Table,
}
tcp6Table = &tcpTable{ tcp6Table = &tcpTable{
version: 6, version: 6,
fetchTable: getTCP6Table, fetchTable: getTCP6Table,
} }
tcp4Table = &tcpTable{
version: 4,
fetchTable: getTCP4Table,
dualStack: tcp6Table,
}
) )

View File

@@ -22,6 +22,8 @@ type udpTable struct {
states map[string]map[string]*udpState states map[string]map[string]*udpState
statesLock sync.Mutex statesLock sync.Mutex
dualStack *udpTable
} }
type udpState struct { type udpState struct {
@@ -41,17 +43,18 @@ const (
) )
var ( var (
udp4Table = &udpTable{
version: 4,
fetchTable: getUDP4Table,
states: make(map[string]map[string]*udpState),
}
udp6Table = &udpTable{ udp6Table = &udpTable{
version: 6, version: 6,
fetchTable: getUDP6Table, fetchTable: getUDP6Table,
states: make(map[string]map[string]*udpState), states: make(map[string]map[string]*udpState),
} }
udp4Table = &udpTable{
version: 4,
fetchTable: getUDP4Table,
states: make(map[string]map[string]*udpState),
dualStack: udp6Table,
}
) )
// CleanUDPStates cleans the udp connection states which save connection directions. // CleanUDPStates cleans the udp connection states which save connection directions.