Initial commit after restructure

This commit is contained in:
Daniel
2018-08-13 14:14:27 +02:00
commit bdeddc41f9
177 changed files with 26108 additions and 0 deletions

220
process/iphelper/get.go Normal file
View File

@@ -0,0 +1,220 @@
// +build windows
package iphelper
import (
"fmt"
"net"
"sync"
)
var (
tcp4Connections []*connectionEntry
tcp4Listeners []*connectionEntry
tcp6Connections []*connectionEntry
tcp6Listeners []*connectionEntry
udp4Connections []*connectionEntry
udp4Listeners []*connectionEntry
udp6Connections []*connectionEntry
udp6Listeners []*connectionEntry
ipHelper *IPHelper
lock sync.RWMutex
)
func checkIPHelper() (err error) {
if ipHelper == nil {
ipHelper, err = New()
return err
}
return nil
}
func GetTCP4PacketInfo(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, pktDirection bool) (pid int, direction bool, err error) {
// search
pid, direction = search(tcp4Connections, tcp4Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return
}
// 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 -1, direction, err
}
// search
pid, direction = search(tcp4Connections, tcp4Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return
}
return -1, direction, nil
}
func GetTCP6PacketInfo(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, pktDirection bool) (pid int, direction bool, err error) {
// search
pid, direction = search(tcp6Connections, tcp6Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return
}
// 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 -1, direction, err
}
// search
pid, direction = search(tcp6Connections, tcp6Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return
}
return -1, direction, nil
}
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
}
// 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 -1, pktDirection, err
}
// search
pid, _ = search(udp4Connections, udp4Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return pid, pktDirection, nil
}
return -1, pktDirection, nil
}
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
}
// 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 -1, pktDirection, err
}
// search
pid, _ = search(udp6Connections, udp6Listeners, localIP, remoteIP, localPort, remotePort, pktDirection)
if pid >= 0 {
return pid, pktDirection, nil
}
return -1, pktDirection, nil
}
func search(connections, listeners []*connectionEntry, localIP, remoteIP net.IP, localPort, remotePort uint16, pktDirection bool) (pid int, direction bool) {
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 -1, 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 -1
}
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 -1
}
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

@@ -0,0 +1,77 @@
// +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")
)
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
}
func New() (*IPHelper, error) {
new := &IPHelper{}
new.valid = abool.NewBool(false)
var err error
// load dll
new.dll = windows.NewLazySystemDLL("iphlpapi.dll")
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
}

263
process/iphelper/tables.go Normal file
View File

@@ -0,0 +1,263 @@
// +build windows
package iphelper
import (
"encoding/binary"
"errors"
"fmt"
"net"
"unsafe"
"golang.org/x/sys/windows"
)
const (
iphelper_TCP_TABLE_OWNER_PID_ALL uintptr = 5
iphelper_UDP_TABLE_OWNER_PID uintptr = 1
iphelper_TCP_STATE_LISTEN uint32 = 2
)
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
localScopeId uint32
localPort uint32
remoteAddr [16]byte
remoteScopeId uint32
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
localScopeId uint32
localPort uint32
owningPid uint32
}
const (
IPv4 uint8 = 4
IPv6 uint8 = 6
TCP uint8 = 6
UDP uint8 = 17
)
func (ipHelper *IPHelper) GetTables(protocol uint8, ipVersion uint8) (connections []*connectionEntry, listeners []*connectionEntry, err error) {
// 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")
}
bufSize := 4096
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
iphelper_TCP_TABLE_OWNER_PID_ALL, // _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,
iphelper_UDP_TABLE_OWNER_PID, // _In_ UDP_TABLE_CLASS TableClass,
0, // _In_ ULONG Reserved
)
}
switch r1 {
// case windows.ERROR_INSUFFICIENT_BUFFER:
// return nil, fmt.Errorf("insufficient buffer error: %s", err)
// case windows.ERROR_INVALID_PARAMETER:
// return nil, fmt.Errorf("invalid parameter: %s", err)
case windows.NO_ERROR:
default:
return nil, nil, fmt.Errorf("unexpected error: %s", 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
new.localIP = make([]byte, 4)
binary.LittleEndian.PutUint32(new.localIP, row.localAddr)
new.localPort = uint16(row.localPort>>8 | row.localPort<<8)
// remote
if row.state == iphelper_TCP_STATE_LISTEN {
if new.localIP.Equal(net.IPv4zero) {
new.localIP = nil
}
listeners = append(listeners, new)
} else {
new.remoteIP = make([]byte, 4)
binary.LittleEndian.PutUint32(new.remoteIP, 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 == iphelper_TCP_STATE_LISTEN {
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 = make([]byte, 4)
binary.LittleEndian.PutUint32(new.localIP, 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
}

View File

@@ -0,0 +1,62 @@
// +build windows
package main
import (
"fmt"
"github.com/Safing/safing-core/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)
}
}

Binary file not shown.