From f858ef492f77186080edac84a7e37dccaef6dcd3 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Mon, 17 Oct 2022 00:06:32 -0700 Subject: [PATCH 01/19] PoC replace kext start with go code --- firewall/interception/windowskext/kext.go | 128 ++++++++++++++++++++-- 1 file changed, 119 insertions(+), 9 deletions(-) diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index d438538e..73ce5d4f 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -29,6 +29,8 @@ var ( kextLock sync.RWMutex ready = abool.NewBool(false) urgentRequests *int32 + + kextHandle windows.Handle ) func init() { @@ -50,6 +52,7 @@ type WinKext struct { setVerdict *windows.Proc getPayload *windows.Proc clearCache *windows.Proc + setHandle *windows.Proc } // Init initializes the DLL and the Kext (Kernel Driver). @@ -98,6 +101,11 @@ func Init(dllPath, driverPath string) error { log.Errorf("could not find proc PortmasterClearCache (v1.0.12+) in dll: %s", err) } + new.setHandle, err = new.dll.FindProc("PortmasterSetDeviceHandle") + if err != nil { + log.Errorf("could not find proc PortmasterSetDeviceHandle in dll: %s", err) + } + // initialize dll/kext rc, _, lastErr := new.init.Call() if rc != windows.NO_ERROR { @@ -117,22 +125,124 @@ func Start() error { kextLock.Lock() defer kextLock.Unlock() - // convert to C string - charArray := make([]byte, len(kext.driverPath)+1) - copy(charArray, []byte(kext.driverPath)) - charArray[len(charArray)-1] = 0 // force NULL byte at the end + filename := `\\.\PortmasterKext` - rc, _, lastErr := kext.start.Call( - uintptr(unsafe.Pointer(&charArray[0])), - ) - if rc != windows.NO_ERROR { - return formatErr(lastErr, rc) + u16fname, err := syscall.UTF16FromString(filename) + if err != nil { + return fmt.Errorf("Bad filename: %s", err) } + u16DriverPath, err := syscall.UTF16FromString(kext.driverPath) + if err != nil { + return fmt.Errorf("Bad driver path: %s", err) + } + kextHandle, err = windows.CreateFile(&u16fname[0], windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.OPEN_EXISTING, 0, 0) + if err == nil { + return nil // All good + } + + service, err := portmasterDriverInstall(&u16DriverPath[0]) + if err != nil { + return fmt.Errorf("Faield to start service: %s", err) + } + + kextHandle, err = windows.CreateFile(&u16fname[0], + windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, + windows.OPEN_EXISTING, 0, 0) + + windows.DeleteService(service) + windows.CloseServiceHandle(service) + + if err != nil { + return fmt.Errorf("Faield to kext service: %s %q", err, filename) + } + + // rc, _, lastErr := kext.start.Call( + // uintptr(unsafe.Pointer(&charArray[0])), + // ) + // if rc != windows.NO_ERROR { + // return formatErr(lastErr, rc) + // } + + kext.setHandle.Call(uintptr(kextHandle)) + ready.Set() + testRead() return nil } +func testRead() { + + buf := [5]byte{1, 2, 3, 4, 5} + var read uint32 = 0 + err := windows.ReadFile(kextHandle, buf[:], &read, nil) + + if err != nil { + log.Criticalf("Erro reading test data: %s", err) + } + + log.Criticalf("Read restul: %v", buf) +} + +func createService(manager windows.Handle, portmasterKextPath *uint16) (windows.Handle, error) { + u16fname, err := syscall.UTF16FromString("PortmasterKext") + if err != nil { + return 0, fmt.Errorf("Bad service: %s", err) + } + service, err := windows.OpenService(manager, &u16fname[0], windows.SERVICE_ALL_ACCESS) + if err == nil { + return service, nil + } + service, err = windows.CreateService(manager, &u16fname[0], &u16fname[0], windows.SERVICE_ALL_ACCESS, windows.SERVICE_KERNEL_DRIVER, windows.SERVICE_DEMAND_START, windows.SERVICE_ERROR_NORMAL, portmasterKextPath, nil, nil, nil, nil, nil) + if err != nil { + return 0, err + } + + return service, nil +} + +func portmasterDriverInstall(portmasterKextPath *uint16) (windows.Handle, error) { + // Open the service manager: + manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ALL_ACCESS) + if err != nil { + return 0, fmt.Errorf("Failed to open service manager: %d", err) + } + defer windows.CloseServiceHandle(manager) + + var service windows.Handle +retryLoop: + for i := 0; i < 3; i++ { + service, err = createService(manager, portmasterKextPath) + if err == nil { + break retryLoop + } + } + + if err != nil { + return 0, fmt.Errorf("Failed to create service: %s", err) + } + + err = windows.StartService(service, 0, nil) + // Start the service: + if err != nil { + err = windows.GetLastError() + if err == windows.ERROR_SERVICE_ALREADY_RUNNING { + // windows.SetLastError(0) + // windows.SetLast + } else { + // Failed to start service; clean-up: + var status windows.SERVICE_STATUS + _ = windows.ControlService(service, windows.SERVICE_CONTROL_STOP, &status) + _ = windows.DeleteService(service) + _ = windows.CloseServiceHandle(service) + service = 0 + //windows.SetLastError(err) + } + } + + return service, nil +} + // Stop intercepting. func Stop() error { kextLock.Lock() From 3b341496af557a79bf382c0c0ff40ae3d8ce495c Mon Sep 17 00:00:00 2001 From: Vladimir Date: Mon, 17 Oct 2022 23:45:49 -0700 Subject: [PATCH 02/19] remove the need for the glue library --- firewall/interception/interception_windows.go | 6 +- firewall/interception/windowskext/kext.go | 191 +++++------------- .../interception/windowskext/kext_request.go | 50 +++++ 3 files changed, 96 insertions(+), 151 deletions(-) create mode 100644 firewall/interception/windowskext/kext_request.go diff --git a/firewall/interception/interception_windows.go b/firewall/interception/interception_windows.go index 382869be..151dc070 100644 --- a/firewall/interception/interception_windows.go +++ b/firewall/interception/interception_windows.go @@ -10,16 +10,12 @@ import ( // start starts the interception. func start(ch chan packet.Packet) error { - dllFile, err := updates.GetPlatformFile("kext/portmaster-kext.dll") - if err != nil { - return fmt.Errorf("interception: could not get kext dll: %s", err) - } kextFile, err := updates.GetPlatformFile("kext/portmaster-kext.sys") if err != nil { return fmt.Errorf("interception: could not get kext sys: %s", err) } - err = windowskext.Init(dllFile.Path(), kextFile.Path()) + err = windowskext.Init("", kextFile.Path()) if err != nil { return fmt.Errorf("interception: could not init windows kext: %s", err) } diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index 73ce5d4f..42159227 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -6,6 +6,7 @@ package windowskext import ( "errors" "fmt" + "os/exec" "sync" "sync/atomic" "syscall" @@ -25,10 +26,10 @@ var ( winErrInvalidData = uintptr(windows.ERROR_INVALID_DATA) - kext *WinKext kextLock sync.RWMutex ready = abool.NewBool(false) urgentRequests *int32 + driverPath string kextHandle windows.Handle ) @@ -38,85 +39,9 @@ func init() { urgentRequests = &urgentRequestsValue } -// WinKext holds the DLL handle. -type WinKext struct { - sync.RWMutex - - dll *windows.DLL - driverPath string - - init *windows.Proc - start *windows.Proc - stop *windows.Proc - recvVerdictRequest *windows.Proc - setVerdict *windows.Proc - getPayload *windows.Proc - clearCache *windows.Proc - setHandle *windows.Proc -} - // Init initializes the DLL and the Kext (Kernel Driver). -func Init(dllPath, driverPath string) error { - - new := &WinKext{ - driverPath: driverPath, - } - - var err error - - // load dll - new.dll, err = windows.LoadDLL(dllPath) - if err != nil { - return err - } - - // load functions - new.init, err = new.dll.FindProc("PortmasterInit") - if err != nil { - return fmt.Errorf("could not find proc PortmasterStart in dll: %s", err) - } - new.start, err = new.dll.FindProc("PortmasterStart") - if err != nil { - return fmt.Errorf("could not find proc PortmasterStart in dll: %s", err) - } - new.stop, err = new.dll.FindProc("PortmasterStop") - if err != nil { - return fmt.Errorf("could not find proc PortmasterStop in dll: %s", err) - } - new.recvVerdictRequest, err = new.dll.FindProc("PortmasterRecvVerdictRequest") - if err != nil { - return fmt.Errorf("could not find proc PortmasterRecvVerdictRequest in dll: %s", err) - } - new.setVerdict, err = new.dll.FindProc("PortmasterSetVerdict") - if err != nil { - return fmt.Errorf("could not find proc PortmasterSetVerdict in dll: %s", err) - } - new.getPayload, err = new.dll.FindProc("PortmasterGetPayload") - if err != nil { - return fmt.Errorf("could not find proc PortmasterGetPayload in dll: %s", err) - } - new.clearCache, err = new.dll.FindProc("PortmasterClearCache") - if err != nil { - // the loaded dll is an old version - log.Errorf("could not find proc PortmasterClearCache (v1.0.12+) in dll: %s", err) - } - - new.setHandle, err = new.dll.FindProc("PortmasterSetDeviceHandle") - if err != nil { - log.Errorf("could not find proc PortmasterSetDeviceHandle in dll: %s", err) - } - - // initialize dll/kext - rc, _, lastErr := new.init.Call() - if rc != windows.NO_ERROR { - return formatErr(lastErr, rc) - } - - // set kext - kextLock.Lock() - defer kextLock.Unlock() - kext = new - +func Init(dllPath, path string) error { + driverPath = path return nil } @@ -132,7 +57,7 @@ func Start() error { return fmt.Errorf("Bad filename: %s", err) } - u16DriverPath, err := syscall.UTF16FromString(kext.driverPath) + u16DriverPath, err := syscall.UTF16FromString(driverPath) if err != nil { return fmt.Errorf("Bad driver path: %s", err) } @@ -157,26 +82,14 @@ func Start() error { return fmt.Errorf("Faield to kext service: %s %q", err, filename) } - // rc, _, lastErr := kext.start.Call( - // uintptr(unsafe.Pointer(&charArray[0])), - // ) - // if rc != windows.NO_ERROR { - // return formatErr(lastErr, rc) - // } - - kext.setHandle.Call(uintptr(kextHandle)) - ready.Set() testRead() return nil } func testRead() { - buf := [5]byte{1, 2, 3, 4, 5} - var read uint32 = 0 - err := windows.ReadFile(kextHandle, buf[:], &read, nil) - + _, err := deviceIoControl(IOCTL_TEST, &buf[0], uintptr(len(buf))) if err != nil { log.Criticalf("Erro reading test data: %s", err) } @@ -252,10 +165,11 @@ func Stop() error { } ready.UnSet() - rc, _, lastErr := kext.stop.Call() - if rc != windows.NO_ERROR { - return formatErr(lastErr, rc) + err := windows.CloseHandle(kextHandle) + if err != nil { + log.Errorf("kext: faield to close handle: %s", err) } + _, _ = exec.Command("sc", "stop", "PortmasterKext").Output() return nil } @@ -266,9 +180,6 @@ func RecvVerdictRequest() (*VerdictRequest, error) { if !ready.IsSet() { return nil, ErrKextNotReady } - - new := &VerdictRequest{} - // wait for urgent requests to complete for i := 1; i <= 100; i++ { if atomic.LoadInt32(urgentRequests) <= 0 { @@ -280,19 +191,18 @@ func RecvVerdictRequest() (*VerdictRequest, error) { time.Sleep(100 * time.Microsecond) } - // timestamp := time.Now() - rc, _, lastErr := kext.recvVerdictRequest.Call( - uintptr(unsafe.Pointer(new)), - ) - // log.Tracef("winkext: getting verdict request took %s", time.Now().Sub(timestamp)) + timestamp := time.Now() + var new VerdictRequest - if rc != windows.NO_ERROR { - if rc == winErrInvalidData { - return nil, nil - } - return nil, formatErr(lastErr, rc) + data := (*byte)(unsafe.Pointer(&new)) + _, err := deviceIoControl(IOCTL_RECV_VERDICT_REQ, data, unsafe.Sizeof(new)) + if err != nil { + return nil, err } - return new, nil + log.Tracef("winkext: getting verdict request took %s", time.Now().Sub(timestamp)) + + log.Criticalf("%v", new) + return &new, nil } // SetVerdict sets the verdict for a packet and/or connection. @@ -309,17 +219,18 @@ func SetVerdict(pkt *Packet, verdict network.Verdict) error { return ErrKextNotReady } + verdictInfo := struct { + id uint32 + verdict network.Verdict + }{pkt.verdictRequest.id, verdict} + atomic.AddInt32(urgentRequests, 1) - // timestamp := time.Now() - rc, _, lastErr := kext.setVerdict.Call( - uintptr(pkt.verdictRequest.id), - uintptr(verdict), - ) - // log.Tracef("winkext: settings verdict for packetID %d took %s", packetID, time.Now().Sub(timestamp)) + _, err := deviceIoControlBufferd(IOCTL_SET_VERDICT, + (*byte)(unsafe.Pointer(&verdictInfo)), unsafe.Sizeof(verdictInfo), nil, 0) atomic.AddInt32(urgentRequests, -1) - if rc != windows.NO_ERROR { + if err != nil { log.Tracer(pkt.Ctx()).Errorf("kext: failed to set verdict %s on packet %d", verdict, pkt.verdictRequest.id) - return formatErr(lastErr, rc) + return err } return nil } @@ -338,26 +249,31 @@ func GetPayload(packetID uint32, packetSize uint32) ([]byte, error) { buf := make([]byte, packetSize) + payload := struct { + id uint32 + length uint32 + }{packetID, packetSize} + atomic.AddInt32(urgentRequests, 1) + + writenSize, err := deviceIoControlBufferd(IOCTL_GET_PAYLOAD, + (*byte)(unsafe.Pointer(&payload)), unsafe.Sizeof(payload), + &buf[0], uintptr(packetSize)) + // timestamp := time.Now() - rc, _, lastErr := kext.getPayload.Call( - uintptr(packetID), - uintptr(unsafe.Pointer(&buf[0])), - uintptr(unsafe.Pointer(&packetSize)), - ) // log.Tracef("winkext: getting payload for packetID %d took %s", packetID, time.Now().Sub(timestamp)) atomic.AddInt32(urgentRequests, -1) - if rc != windows.NO_ERROR { - return nil, formatErr(lastErr, rc) + if err != nil { + return nil, err } - if packetSize == 0 { + if writenSize == 0 { return nil, errors.New("windows kext did not return any data") } - if packetSize < uint32(len(buf)) { - return buf[:packetSize], nil + if writenSize < uint32(len(buf)) { + return buf[:writenSize], nil } return buf, nil @@ -371,23 +287,6 @@ func ClearCache() error { return ErrKextNotReady } - if kext.clearCache == nil { - log.Error("kext: cannot clear cache: clearCache function missing") - } - - rc, _, lastErr := kext.clearCache.Call() - - if rc != windows.NO_ERROR { - return formatErr(lastErr, rc) - } - - return nil -} - -func formatErr(err error, rc uintptr) error { - sysErr, ok := err.(syscall.Errno) - if ok { - return fmt.Errorf("%s [LE 0x%X] [RC 0x%X]", err, uintptr(sysErr), rc) - } + _, err := deviceIoControl(IOCTL_CLEAR_CACHE, nil, 0) return err } diff --git a/firewall/interception/windowskext/kext_request.go b/firewall/interception/windowskext/kext_request.go new file mode 100644 index 00000000..828b2561 --- /dev/null +++ b/firewall/interception/windowskext/kext_request.go @@ -0,0 +1,50 @@ +//go:build windows +// +build windows + +package windowskext + +import "golang.org/x/sys/windows" + +const ( + METHOD_BUFFERED = 0 + METHOD_IN_DIRECT = 1 + METHOD_OUT_DIRECT = 2 + METHOD_NEITHER = 3 + SIOCTL_TYPE = 40000 +) + +var ( + IOCTL_HELLO = ctl_code(SIOCTL_TYPE, 0x800, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_RECV_VERDICT_REQ_POLL = ctl_code(SIOCTL_TYPE, 0x801, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_RECV_VERDICT_REQ = ctl_code(SIOCTL_TYPE, 0x802, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_SET_VERDICT = ctl_code(SIOCTL_TYPE, 0x803, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_GET_PAYLOAD = ctl_code(SIOCTL_TYPE, 0x804, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_CLEAR_CACHE = ctl_code(SIOCTL_TYPE, 0x805, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_TEST = ctl_code(SIOCTL_TYPE, 0x806, METHOD_NEITHER, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) +) + +func ctl_code(device_type, function, method, access uint32) uint32 { + return (device_type << 16) | (access << 14) | (function << 2) | method +} + +func deviceIoControl(code uint32, data *byte, size uintptr) (uint32, error) { + var bytesReturned uint32 + err := windows.DeviceIoControl(kextHandle, + code, + nil, 0, + data, uint32(size), + &bytesReturned, nil) + + return bytesReturned, err +} + +func deviceIoControlBufferd(code uint32, inData *byte, inSize uintptr, outData *byte, outSize uintptr) (uint32, error) { + var bytesReturned uint32 + err := windows.DeviceIoControl(kextHandle, + code, + inData, uint32(inSize), + outData, uint32(outSize), + &bytesReturned, nil) + + return bytesReturned, err +} From 1f677cb93f5d02c57311675990ba309896037439 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Wed, 19 Oct 2022 13:25:11 -0700 Subject: [PATCH 03/19] Refactoring --- firewall/interception/windowskext/kext.go | 144 +++++------------- .../interception/windowskext/kext_request.go | 50 ------ firewall/interception/windowskext/service.go | 85 +++++++++++ firewall/interception/windowskext/syscall.go | 91 +++++++++++ 4 files changed, 212 insertions(+), 158 deletions(-) delete mode 100644 firewall/interception/windowskext/kext_request.go create mode 100644 firewall/interception/windowskext/service.go create mode 100644 firewall/interception/windowskext/syscall.go diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index 42159227..7906d1b2 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -9,7 +9,6 @@ import ( "os/exec" "sync" "sync/atomic" - "syscall" "time" "unsafe" @@ -34,6 +33,8 @@ var ( kextHandle windows.Handle ) +const driverName = "PortmasterKext" + func init() { var urgentRequestsValue int32 urgentRequests = &urgentRequestsValue @@ -50,112 +51,37 @@ func Start() error { kextLock.Lock() defer kextLock.Unlock() - filename := `\\.\PortmasterKext` + filename := `\\.\` + driverName - u16fname, err := syscall.UTF16FromString(filename) - if err != nil { - return fmt.Errorf("Bad filename: %s", err) - } - - u16DriverPath, err := syscall.UTF16FromString(driverPath) - if err != nil { - return fmt.Errorf("Bad driver path: %s", err) - } - kextHandle, err = windows.CreateFile(&u16fname[0], windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.OPEN_EXISTING, 0, 0) + // check if driver is already installed + var err error + kextHandle, err = openDriver(filename) if err == nil { - return nil // All good + return nil // device was already initialized } - service, err := portmasterDriverInstall(&u16DriverPath[0]) + // initialize and start driver service + service, err := driverInstall(driverPath) if err != nil { - return fmt.Errorf("Faield to start service: %s", err) + return fmt.Errorf("Failed to start service: %s", err) } - kextHandle, err = windows.CreateFile(&u16fname[0], - windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, - windows.OPEN_EXISTING, 0, 0) + // open the driver + kextHandle, err = openDriver(filename) + // close the service handles windows.DeleteService(service) windows.CloseServiceHandle(service) + // driver was not installed if err != nil { - return fmt.Errorf("Faield to kext service: %s %q", err, filename) + return fmt.Errorf("Failed to start the kext service: %s %q", err, filename) } ready.Set() - testRead() return nil } -func testRead() { - buf := [5]byte{1, 2, 3, 4, 5} - _, err := deviceIoControl(IOCTL_TEST, &buf[0], uintptr(len(buf))) - if err != nil { - log.Criticalf("Erro reading test data: %s", err) - } - - log.Criticalf("Read restul: %v", buf) -} - -func createService(manager windows.Handle, portmasterKextPath *uint16) (windows.Handle, error) { - u16fname, err := syscall.UTF16FromString("PortmasterKext") - if err != nil { - return 0, fmt.Errorf("Bad service: %s", err) - } - service, err := windows.OpenService(manager, &u16fname[0], windows.SERVICE_ALL_ACCESS) - if err == nil { - return service, nil - } - service, err = windows.CreateService(manager, &u16fname[0], &u16fname[0], windows.SERVICE_ALL_ACCESS, windows.SERVICE_KERNEL_DRIVER, windows.SERVICE_DEMAND_START, windows.SERVICE_ERROR_NORMAL, portmasterKextPath, nil, nil, nil, nil, nil) - if err != nil { - return 0, err - } - - return service, nil -} - -func portmasterDriverInstall(portmasterKextPath *uint16) (windows.Handle, error) { - // Open the service manager: - manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ALL_ACCESS) - if err != nil { - return 0, fmt.Errorf("Failed to open service manager: %d", err) - } - defer windows.CloseServiceHandle(manager) - - var service windows.Handle -retryLoop: - for i := 0; i < 3; i++ { - service, err = createService(manager, portmasterKextPath) - if err == nil { - break retryLoop - } - } - - if err != nil { - return 0, fmt.Errorf("Failed to create service: %s", err) - } - - err = windows.StartService(service, 0, nil) - // Start the service: - if err != nil { - err = windows.GetLastError() - if err == windows.ERROR_SERVICE_ALREADY_RUNNING { - // windows.SetLastError(0) - // windows.SetLast - } else { - // Failed to start service; clean-up: - var status windows.SERVICE_STATUS - _ = windows.ControlService(service, windows.SERVICE_CONTROL_STOP, &status) - _ = windows.DeleteService(service) - _ = windows.CloseServiceHandle(service) - service = 0 - //windows.SetLastError(err) - } - } - - return service, nil -} - // Stop intercepting. func Stop() error { kextLock.Lock() @@ -165,11 +91,11 @@ func Stop() error { } ready.UnSet() - err := windows.CloseHandle(kextHandle) + err := closeDriver(kextHandle) if err != nil { - log.Errorf("kext: faield to close handle: %s", err) + log.Errorf("winkext: failed to close the handle: %s", err) } - _, _ = exec.Command("sc", "stop", "PortmasterKext").Output() + _, _ = exec.Command("sc", "stop", driverName).Output() return nil } @@ -194,14 +120,16 @@ func RecvVerdictRequest() (*VerdictRequest, error) { timestamp := time.Now() var new VerdictRequest - data := (*byte)(unsafe.Pointer(&new)) - _, err := deviceIoControl(IOCTL_RECV_VERDICT_REQ, data, unsafe.Sizeof(new)) + data := asByteArray(&new) + bytesRead, err := deviceIoControlRead(kextHandle, IOCTL_RECV_VERDICT_REQ, data) if err != nil { return nil, err } - log.Tracef("winkext: getting verdict request took %s", time.Now().Sub(timestamp)) + if bytesRead == 0 { + return nil, nil // no error, no new verdict request + } - log.Criticalf("%v", new) + log.Tracef("winkext: getting verdict request took %s", time.Now().Sub(timestamp)) return &new, nil } @@ -225,8 +153,8 @@ func SetVerdict(pkt *Packet, verdict network.Verdict) error { }{pkt.verdictRequest.id, verdict} atomic.AddInt32(urgentRequests, 1) - _, err := deviceIoControlBufferd(IOCTL_SET_VERDICT, - (*byte)(unsafe.Pointer(&verdictInfo)), unsafe.Sizeof(verdictInfo), nil, 0) + data := asByteArray(&verdictInfo) + _, err := deviceIoControlWrite(kextHandle, IOCTL_SET_VERDICT, data) atomic.AddInt32(urgentRequests, -1) if err != nil { log.Tracer(pkt.Ctx()).Errorf("kext: failed to set verdict %s on packet %d", verdict, pkt.verdictRequest.id) @@ -255,25 +183,21 @@ func GetPayload(packetID uint32, packetSize uint32) ([]byte, error) { }{packetID, packetSize} atomic.AddInt32(urgentRequests, 1) + data := asByteArray(&payload) + bytesRead, err := deviceIoControlReadWrite(kextHandle, IOCTL_GET_PAYLOAD, data, unsafe.Slice(&buf[0], packetSize)) - writenSize, err := deviceIoControlBufferd(IOCTL_GET_PAYLOAD, - (*byte)(unsafe.Pointer(&payload)), unsafe.Sizeof(payload), - &buf[0], uintptr(packetSize)) - - // timestamp := time.Now() - // log.Tracef("winkext: getting payload for packetID %d took %s", packetID, time.Now().Sub(timestamp)) atomic.AddInt32(urgentRequests, -1) if err != nil { return nil, err } - if writenSize == 0 { + if bytesRead == 0 { return nil, errors.New("windows kext did not return any data") } - if writenSize < uint32(len(buf)) { - return buf[:writenSize], nil + if bytesRead < uint32(len(buf)) { + return buf[:bytesRead], nil } return buf, nil @@ -287,6 +211,10 @@ func ClearCache() error { return ErrKextNotReady } - _, err := deviceIoControl(IOCTL_CLEAR_CACHE, nil, 0) + _, err := deviceIoControlRead(kextHandle, IOCTL_CLEAR_CACHE, nil) return err } + +func asByteArray[T any](obj *T) []byte { + return unsafe.Slice((*byte)(unsafe.Pointer(obj)), unsafe.Sizeof(*obj)) +} diff --git a/firewall/interception/windowskext/kext_request.go b/firewall/interception/windowskext/kext_request.go deleted file mode 100644 index 828b2561..00000000 --- a/firewall/interception/windowskext/kext_request.go +++ /dev/null @@ -1,50 +0,0 @@ -//go:build windows -// +build windows - -package windowskext - -import "golang.org/x/sys/windows" - -const ( - METHOD_BUFFERED = 0 - METHOD_IN_DIRECT = 1 - METHOD_OUT_DIRECT = 2 - METHOD_NEITHER = 3 - SIOCTL_TYPE = 40000 -) - -var ( - IOCTL_HELLO = ctl_code(SIOCTL_TYPE, 0x800, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) - IOCTL_RECV_VERDICT_REQ_POLL = ctl_code(SIOCTL_TYPE, 0x801, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) - IOCTL_RECV_VERDICT_REQ = ctl_code(SIOCTL_TYPE, 0x802, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) - IOCTL_SET_VERDICT = ctl_code(SIOCTL_TYPE, 0x803, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) - IOCTL_GET_PAYLOAD = ctl_code(SIOCTL_TYPE, 0x804, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) - IOCTL_CLEAR_CACHE = ctl_code(SIOCTL_TYPE, 0x805, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) - IOCTL_TEST = ctl_code(SIOCTL_TYPE, 0x806, METHOD_NEITHER, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) -) - -func ctl_code(device_type, function, method, access uint32) uint32 { - return (device_type << 16) | (access << 14) | (function << 2) | method -} - -func deviceIoControl(code uint32, data *byte, size uintptr) (uint32, error) { - var bytesReturned uint32 - err := windows.DeviceIoControl(kextHandle, - code, - nil, 0, - data, uint32(size), - &bytesReturned, nil) - - return bytesReturned, err -} - -func deviceIoControlBufferd(code uint32, inData *byte, inSize uintptr, outData *byte, outSize uintptr) (uint32, error) { - var bytesReturned uint32 - err := windows.DeviceIoControl(kextHandle, - code, - inData, uint32(inSize), - outData, uint32(outSize), - &bytesReturned, nil) - - return bytesReturned, err -} diff --git a/firewall/interception/windowskext/service.go b/firewall/interception/windowskext/service.go new file mode 100644 index 00000000..c1e2b52f --- /dev/null +++ b/firewall/interception/windowskext/service.go @@ -0,0 +1,85 @@ +//go:build windows +// +build windows + +package windowskext + +import ( + "fmt" + "syscall" + + "golang.org/x/sys/windows" +) + +func createService(manager windows.Handle, portmasterKextPath *uint16) (windows.Handle, error) { + u16filename, err := syscall.UTF16FromString(driverName) + if err != nil { + return 0, fmt.Errorf("Bad service: %s", err) + } + service, err := windows.OpenService(manager, &u16filename[0], windows.SERVICE_ALL_ACCESS) + if err == nil { + return service, nil + } + service, err = windows.CreateService(manager, &u16filename[0], &u16filename[0], windows.SERVICE_ALL_ACCESS, windows.SERVICE_KERNEL_DRIVER, windows.SERVICE_DEMAND_START, windows.SERVICE_ERROR_NORMAL, portmasterKextPath, nil, nil, nil, nil, nil) + if err != nil { + return 0, err + } + + return service, nil +} + +func driverInstall(portmasterKextPath string) (windows.Handle, error) { + u16kextPath, _ := syscall.UTF16FromString(portmasterKextPath) + // Open the service manager: + manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ALL_ACCESS) + if err != nil { + return 0, fmt.Errorf("Failed to open service manager: %d", err) + } + defer windows.CloseServiceHandle(manager) + + var service windows.Handle +retryLoop: + for i := 0; i < 3; i++ { + service, err = createService(manager, &u16kextPath[0]) + if err == nil { + break retryLoop + } + } + + if err != nil { + return 0, fmt.Errorf("Failed to create service: %s", err) + } + + err = windows.StartService(service, 0, nil) + // Start the service: + if err != nil { + err = windows.GetLastError() + if err == windows.ERROR_SERVICE_ALREADY_RUNNING { + // windows.SetLastError(0) + } else { + // Failed to start service; clean-up: + var status windows.SERVICE_STATUS + _ = windows.ControlService(service, windows.SERVICE_CONTROL_STOP, &status) + _ = windows.DeleteService(service) + _ = windows.CloseServiceHandle(service) + service = 0 + //windows.SetLastError(err) + } + } + + return service, nil +} + +func openDriver(filename string) (windows.Handle, error) { + u16filename, _ := syscall.UTF16FromString(filename) + + handle, err := windows.CreateFile(&u16filename[0], windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.OPEN_EXISTING, 0, 0) + if err != nil { + return 0, err + } + + return handle, nil +} + +func closeDriver(handle windows.Handle) error { + return windows.CloseHandle(handle) +} diff --git a/firewall/interception/windowskext/syscall.go b/firewall/interception/windowskext/syscall.go new file mode 100644 index 00000000..6ec11348 --- /dev/null +++ b/firewall/interception/windowskext/syscall.go @@ -0,0 +1,91 @@ +//go:build windows +// +build windows + +package windowskext + +import "golang.org/x/sys/windows" + +const ( + METHOD_BUFFERED = 0 + METHOD_IN_DIRECT = 1 + METHOD_OUT_DIRECT = 2 + METHOD_NEITHER = 3 + + SIOCTL_TYPE = 40000 +) + +var ( + IOCTL_HELLO = ctlCode(SIOCTL_TYPE, 0x800, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_RECV_VERDICT_REQ_POLL = ctlCode(SIOCTL_TYPE, 0x801, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_RECV_VERDICT_REQ = ctlCode(SIOCTL_TYPE, 0x802, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_SET_VERDICT = ctlCode(SIOCTL_TYPE, 0x803, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_GET_PAYLOAD = ctlCode(SIOCTL_TYPE, 0x804, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_CLEAR_CACHE = ctlCode(SIOCTL_TYPE, 0x805, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) +) + +func ctlCode(device_type, function, method, access uint32) uint32 { + return (device_type << 16) | (access << 14) | (function << 2) | method +} + +func deviceIoControlRead(handle windows.Handle, code uint32, data []byte) (uint32, error) { + var bytesReturned uint32 + + var dataPtr *byte = nil + var dataSize uint32 = 0 + if data != nil { + dataPtr = &data[0] + dataSize = uint32(len(data)) + } + + err := windows.DeviceIoControl(handle, + code, + nil, 0, + dataPtr, dataSize, + &bytesReturned, nil) + + return bytesReturned, err +} + +func deviceIoControlWrite(handle windows.Handle, code uint32, data []byte) (uint32, error) { + var bytesReturned uint32 + + var dataPtr *byte = nil + var dataSize uint32 = 0 + if data != nil { + dataPtr = &data[0] + dataSize = uint32(len(data)) + } + + err := windows.DeviceIoControl(handle, + code, + dataPtr, dataSize, + nil, 0, + &bytesReturned, nil) + + return bytesReturned, err +} + +func deviceIoControlReadWrite(handle windows.Handle, code uint32, inData []byte, outData []byte) (uint32, error) { + var bytesReturned uint32 + + var inDataPtr *byte = nil + var inDataSize uint32 = 0 + if inData != nil { + inDataPtr = &inData[0] + inDataSize = uint32(len(inData)) + } + + var outDataPtr *byte = nil + var outDataSize uint32 = 0 + if outData != nil { + outDataPtr = &outData[0] + outDataSize = uint32(len(outData)) + } + err := windows.DeviceIoControl(handle, + code, + inDataPtr, inDataSize, + outDataPtr, outDataSize, + &bytesReturned, nil) + + return bytesReturned, err +} From 1ff27784c31515e7e6e174ce5d29136f3b7cbc9e Mon Sep 17 00:00:00 2001 From: Vladimir Date: Wed, 2 Nov 2022 15:03:26 -0700 Subject: [PATCH 04/19] Refactoring and more comments --- firewall/interception/windowskext/handler.go | 7 ++++++ firewall/interception/windowskext/kext.go | 25 ++++++++++++++------ firewall/interception/windowskext/service.go | 12 ++++++---- 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/firewall/interception/windowskext/handler.go b/firewall/interception/windowskext/handler.go index 623c49a3..a19cbfdc 100644 --- a/firewall/interception/windowskext/handler.go +++ b/firewall/interception/windowskext/handler.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package windowskext @@ -10,6 +11,7 @@ import ( "github.com/tevino/abool" "github.com/safing/portbase/log" + "github.com/safing/portmaster/network" "github.com/safing/portmaster/network/packet" ) @@ -43,6 +45,11 @@ type VerdictRequest struct { packetSize uint32 } +type VerdictInfo struct { + id uint32 // ID from RegisterPacket + verdict network.Verdict // verdict for the connection +} + // Handler transforms received packets to the Packet interface. func Handler(packets chan packet.Packet) { if !ready.IsSet() { diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index 7906d1b2..084ecded 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -70,8 +70,8 @@ func Start() error { kextHandle, err = openDriver(filename) // close the service handles - windows.DeleteService(service) - windows.CloseServiceHandle(service) + _ = windows.DeleteService(service) + _ = windows.CloseServiceHandle(service) // driver was not installed if err != nil { @@ -95,7 +95,11 @@ func Stop() error { if err != nil { log.Errorf("winkext: failed to close the handle: %s", err) } - _, _ = exec.Command("sc", "stop", driverName).Output() + + _, err = exec.Command("sc", "stop", driverName).Output() // This is a question of taste, but it is a robust and solid solution + if err != nil { + log.Errorf("winkext: failed to stop the service: %q", err) + } return nil } @@ -118,8 +122,10 @@ func RecvVerdictRequest() (*VerdictRequest, error) { } timestamp := time.Now() + // Initialize struct for the output data var new VerdictRequest + // Make driver request data := asByteArray(&new) bytesRead, err := deviceIoControlRead(kextHandle, IOCTL_RECV_VERDICT_REQ, data) if err != nil { @@ -147,11 +153,9 @@ func SetVerdict(pkt *Packet, verdict network.Verdict) error { return ErrKextNotReady } - verdictInfo := struct { - id uint32 - verdict network.Verdict - }{pkt.verdictRequest.id, verdict} + verdictInfo := VerdictInfo{pkt.verdictRequest.id, verdict} + // Make driver request atomic.AddInt32(urgentRequests, 1) data := asByteArray(&verdictInfo) _, err := deviceIoControlWrite(kextHandle, IOCTL_SET_VERDICT, data) @@ -169,6 +173,7 @@ func GetPayload(packetID uint32, packetSize uint32) ([]byte, error) { return nil, ErrNoPacketID } + // Check if driver is initialized kextLock.RLock() defer kextLock.RUnlock() if !ready.IsSet() { @@ -177,11 +182,13 @@ func GetPayload(packetID uint32, packetSize uint32) ([]byte, error) { buf := make([]byte, packetSize) + // Combine id and length payload := struct { id uint32 length uint32 }{packetID, packetSize} + // Make driver request atomic.AddInt32(urgentRequests, 1) data := asByteArray(&payload) bytesRead, err := deviceIoControlReadWrite(kextHandle, IOCTL_GET_PAYLOAD, data, unsafe.Slice(&buf[0], packetSize)) @@ -192,6 +199,7 @@ func GetPayload(packetID uint32, packetSize uint32) ([]byte, error) { return nil, err } + // check the result and return if bytesRead == 0 { return nil, errors.New("windows kext did not return any data") } @@ -206,11 +214,14 @@ func GetPayload(packetID uint32, packetSize uint32) ([]byte, error) { func ClearCache() error { kextLock.RLock() defer kextLock.RUnlock() + + // Check if driver is initialized if !ready.IsSet() { log.Error("kext: failed to clear the cache: kext not ready") return ErrKextNotReady } + // Make driver request _, err := deviceIoControlRead(kextHandle, IOCTL_CLEAR_CACHE, nil) return err } diff --git a/firewall/interception/windowskext/service.go b/firewall/interception/windowskext/service.go index c1e2b52f..a2807a59 100644 --- a/firewall/interception/windowskext/service.go +++ b/firewall/interception/windowskext/service.go @@ -15,10 +15,13 @@ func createService(manager windows.Handle, portmasterKextPath *uint16) (windows. if err != nil { return 0, fmt.Errorf("Bad service: %s", err) } + // Check if it's already created service, err := windows.OpenService(manager, &u16filename[0], windows.SERVICE_ALL_ACCESS) if err == nil { return service, nil } + + // Create the service service, err = windows.CreateService(manager, &u16filename[0], &u16filename[0], windows.SERVICE_ALL_ACCESS, windows.SERVICE_KERNEL_DRIVER, windows.SERVICE_DEMAND_START, windows.SERVICE_ERROR_NORMAL, portmasterKextPath, nil, nil, nil, nil, nil) if err != nil { return 0, err @@ -36,6 +39,7 @@ func driverInstall(portmasterKextPath string) (windows.Handle, error) { } defer windows.CloseServiceHandle(manager) + // Try to create the service. Retry if it fails. var service windows.Handle retryLoop: for i := 0; i < 3; i++ { @@ -49,20 +53,18 @@ retryLoop: return 0, fmt.Errorf("Failed to create service: %s", err) } - err = windows.StartService(service, 0, nil) // Start the service: + err = windows.StartService(service, 0, nil) + if err != nil { err = windows.GetLastError() - if err == windows.ERROR_SERVICE_ALREADY_RUNNING { - // windows.SetLastError(0) - } else { + if err != windows.ERROR_SERVICE_ALREADY_RUNNING { // Failed to start service; clean-up: var status windows.SERVICE_STATUS _ = windows.ControlService(service, windows.SERVICE_CONTROL_STOP, &status) _ = windows.DeleteService(service) _ = windows.CloseServiceHandle(service) service = 0 - //windows.SetLastError(err) } } From 5d2715ca171d3167f9581fa0b4a8bb053cd88ecb Mon Sep 17 00:00:00 2001 From: Vladimir Date: Thu, 3 Nov 2022 10:58:00 +0100 Subject: [PATCH 05/19] remove kext glue dll from dependencies --- firewall/interception/interception_windows.go | 2 +- firewall/interception/windowskext/kext.go | 2 +- updates/helper/updates.go | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/firewall/interception/interception_windows.go b/firewall/interception/interception_windows.go index 151dc070..0441d3a6 100644 --- a/firewall/interception/interception_windows.go +++ b/firewall/interception/interception_windows.go @@ -15,7 +15,7 @@ func start(ch chan packet.Packet) error { return fmt.Errorf("interception: could not get kext sys: %s", err) } - err = windowskext.Init("", kextFile.Path()) + err = windowskext.Init(kextFile.Path()) if err != nil { return fmt.Errorf("interception: could not init windows kext: %s", err) } diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index 084ecded..ca8315e6 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -41,7 +41,7 @@ func init() { } // Init initializes the DLL and the Kext (Kernel Driver). -func Init(dllPath, path string) error { +func Init(path string) error { driverPath = path return nil } diff --git a/updates/helper/updates.go b/updates/helper/updates.go index 17fe6116..80193ee8 100644 --- a/updates/helper/updates.go +++ b/updates/helper/updates.go @@ -52,7 +52,6 @@ func MandatoryUpdates() (identifiers []string) { identifiers = append( identifiers, PlatformIdentifier("core/portmaster-core.exe"), - PlatformIdentifier("kext/portmaster-kext.dll"), PlatformIdentifier("kext/portmaster-kext.sys"), PlatformIdentifier("kext/portmaster-kext.pdb"), PlatformIdentifier("start/portmaster-start.exe"), From f226473d9a5777a0ace384b7425fd1a96207794e Mon Sep 17 00:00:00 2001 From: vladimir Date: Thu, 3 Nov 2022 19:08:16 +0200 Subject: [PATCH 06/19] Linux reset verdict of individual connections --- firewall/interception.go | 9 ++-- firewall/interception/interception_linux.go | 5 ++ firewall/interception/nfq/conntrack.go | 57 +++++++++++++++++++-- firewall/interception/nfqueue_linux.go | 8 +++ 4 files changed, 70 insertions(+), 9 deletions(-) diff --git a/firewall/interception.go b/firewall/interception.go index bc4395a7..e5be02dc 100644 --- a/firewall/interception.go +++ b/firewall/interception.go @@ -149,6 +149,10 @@ func resetAllConnectionVerdicts() { // Save if verdict changed. if conn.Verdict.Firewall != previousVerdict { + err := interception.UpdateVerdictOfConnection(conn) + if err != nil { + log.Debugf("filter: failed to delete connection verdict: %s", err) + } conn.Save() tracer.Infof("filter: verdict of connection %s changed from %s to %s", conn, previousVerdict.Verb(), conn.VerdictVerb()) changedVerdicts++ @@ -159,11 +163,6 @@ func resetAllConnectionVerdicts() { } tracer.Infof("filter: changed verdict on %d connections", changedVerdicts) tracer.Submit() - - err := interception.ResetVerdictOfAllConnections() - if err != nil { - log.Errorf("interception: failed to remove persistent verdicts: %s", err) - } } func interceptionStart() error { diff --git a/firewall/interception/interception_linux.go b/firewall/interception/interception_linux.go index 6fe38edf..f0f1d99f 100644 --- a/firewall/interception/interception_linux.go +++ b/firewall/interception/interception_linux.go @@ -2,6 +2,7 @@ package interception import ( "github.com/safing/portmaster/firewall/interception/nfq" + "github.com/safing/portmaster/network" "github.com/safing/portmaster/network/packet" ) @@ -19,3 +20,7 @@ func stop() error { func ResetVerdictOfAllConnections() error { return nfq.DeleteAllMarkedConnection() } + +func UpdateVerdictOfConnection(conn *network.Connection) error { + return nfq.DeleteMarkedConnection(conn) +} diff --git a/firewall/interception/nfq/conntrack.go b/firewall/interception/nfq/conntrack.go index ac25728d..ce494792 100644 --- a/firewall/interception/nfq/conntrack.go +++ b/firewall/interception/nfq/conntrack.go @@ -4,20 +4,37 @@ package nfq import ( "encoding/binary" + "fmt" ct "github.com/florianl/go-conntrack" "github.com/safing/portbase/log" "github.com/safing/portmaster/netenv" + "github.com/safing/portmaster/network" ) -// DeleteAllMarkedConnection deletes all marked entries from the conntrack table. -func DeleteAllMarkedConnection() error { - nfct, err := ct.Open(&ct.Config{}) +var ( + nfct *ct.Nfct // Conntrack handler. NFCT: Network Filter Connection Tracking +) + +func InitNFCT() error { + var err error + nfct, err = ct.Open(&ct.Config{}) if err != nil { return err } - defer func() { _ = nfct.Close() }() + return nil +} + +func DeinitNFCT() { + _ = nfct.Close() +} + +// DeleteAllMarkedConnection deletes all marked entries from the conntrack table. +func DeleteAllMarkedConnection() error { + if nfct == nil { + return fmt.Errorf("nfq: nfct not initialized") + } // Delete all ipv4 marked connections deleted := deleteMarkedConnections(nfct, ct.IPv4) @@ -64,3 +81,35 @@ func deleteMarkedConnections(nfct *ct.Nfct, f ct.Family) (deleted int) { } return deleted } + +func DeleteMarkedConnection(conn *network.Connection) error { + if nfct == nil { + return fmt.Errorf("nfq: nfct not initialized") + } + + con := ct.Con{ + Origin: &ct.IPTuple{ + Src: &conn.LocalIP, + Dst: &conn.Entity.IP, + Proto: &ct.ProtoTuple{ + Number: &conn.Entity.Protocol, + SrcPort: &conn.LocalPort, + DstPort: &conn.Entity.Port, + }, + }, + } + connections, err := nfct.Get(ct.Conntrack, ct.IPv4, con) + if err != nil { + return fmt.Errorf("nfq: failed to find entry for connection %s: %s", conn.String(), err) + } + + if len(connections) > 1 { + log.Warningf("nfq: multiple entries found for single connection: %s -> %d", conn.String(), len(connections)) + } + + for _, connection := range connections { + nfct.Delete(ct.Conntrack, ct.IPv4, connection) + } + + return nil +} diff --git a/firewall/interception/nfqueue_linux.go b/firewall/interception/nfqueue_linux.go index 488cc7a4..54d7f91a 100644 --- a/firewall/interception/nfqueue_linux.go +++ b/firewall/interception/nfqueue_linux.go @@ -147,6 +147,11 @@ func activateNfqueueFirewall() error { } } + if err := nfq.InitNFCT(); err != nil { + return err + } + nfq.DeleteAllMarkedConnection() + return nil } @@ -166,6 +171,9 @@ func DeactivateNfqueueFirewall() error { } } + nfq.DeleteAllMarkedConnection() + nfq.DeinitNFCT() + return result.ErrorOrNil() } From ad8bb2059d311f6c298d3a3e38e5143eb3ed7866 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Fri, 4 Nov 2022 11:21:53 +0100 Subject: [PATCH 07/19] Version and update verdict kernel functions --- firewall/interception.go | 4 +- firewall/interception/interception_windows.go | 14 +++++ firewall/interception/windowskext/handler.go | 22 ++++++++ firewall/interception/windowskext/kext.go | 55 +++++++++++++++++++ firewall/interception/windowskext/syscall.go | 23 +++++++- 5 files changed, 115 insertions(+), 3 deletions(-) diff --git a/firewall/interception.go b/firewall/interception.go index e5be02dc..706111b4 100644 --- a/firewall/interception.go +++ b/firewall/interception.go @@ -177,7 +177,9 @@ func interceptionStart() error { interceptionModule.StartWorker("stat logger", statLogger) interceptionModule.StartWorker("packet handler", packetHandler) - return interception.Start() + err := interception.Start() + + return err } func interceptionStop() error { diff --git a/firewall/interception/interception_windows.go b/firewall/interception/interception_windows.go index 0441d3a6..d1931fb8 100644 --- a/firewall/interception/interception_windows.go +++ b/firewall/interception/interception_windows.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/safing/portmaster/firewall/interception/windowskext" + "github.com/safing/portmaster/network" "github.com/safing/portmaster/network/packet" "github.com/safing/portmaster/updates" ) @@ -39,3 +40,16 @@ func stop() error { func ResetVerdictOfAllConnections() error { return windowskext.ClearCache() } + +func UpdateVerdictOfConnection(conn *network.Connection) error { + return windowskext.UpdateVerdict(conn) +} + +func GetVersion() (string, error) { + version, err := windowskext.GetVersion() + if err != nil { + return "", err + } + + return version.String(), nil +} diff --git a/firewall/interception/windowskext/handler.go b/firewall/interception/windowskext/handler.go index a19cbfdc..2b0e6e5c 100644 --- a/firewall/interception/windowskext/handler.go +++ b/firewall/interception/windowskext/handler.go @@ -6,6 +6,7 @@ package windowskext import ( "encoding/binary" "errors" + "fmt" "net" "github.com/tevino/abool" @@ -50,6 +51,23 @@ type VerdictInfo struct { verdict network.Verdict // verdict for the connection } +type VerdictUpdateInfo struct { + ipV6 uint8 //True: IPv6, False: IPv4 + protocol uint8 //Protocol (UDP, TCP, ...) + localIP [4]uint32 //Source Address, only srcIP[0] if IPv4 + remoteIP [4]uint32 //Destination Address + localPort uint16 //Source Port + remotePort uint16 //Destination port + verdict uint8 //New verdict +} + +type VersionInfo struct { + major uint8 + minor uint8 + revision uint8 + build uint8 +} + // Handler transforms received packets to the Packet interface. func Handler(packets chan packet.Packet) { if !ready.IsSet() { @@ -152,3 +170,7 @@ func convertIPv6(input [4]uint32) net.IP { } return net.IP(addressBuf) } + +func (v *VersionInfo) String() string { + return fmt.Sprintf("%d.%d.%d.%d", v.major, v.minor, v.revision, v.build) +} diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index ca8315e6..5f7642df 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -226,6 +226,61 @@ func ClearCache() error { return err } +func UpdateVerdict(conn *network.Connection) error { + kextLock.RLock() + defer kextLock.RUnlock() + + // Check if driver is initialized + if !ready.IsSet() { + log.Error("kext: failed to clear the cache: kext not ready") + return ErrKextNotReady + } + + // initialize variables + info := &VerdictUpdateInfo{ + ipV6: uint8(conn.IPVersion), + protocol: uint8(conn.IPProtocol), + localPort: conn.LocalPort, + remotePort: conn.Entity.Port, + verdict: uint8(conn.Verdict.Active), + } + + // copy ip addresses + copy(asByteArray(&info.localIP[0]), conn.LocalIP) + copy(asByteArray(&info.remoteIP[0]), conn.Entity.IP) + + // Make driver request + data := asByteArray(&info) + err := deviceIoControlDirect(kextHandle, IOCTL_UPDATE_VERDICT, data) + return err +} + +func GetVersion() (*VersionInfo, error) { + kextLock.RLock() + defer kextLock.RUnlock() + + // Check if driver is initialized + if !ready.IsSet() { + log.Error("kext: failed to clear the cache: kext not ready") + return nil, ErrKextNotReady + } + + data := make([]uint8, 4) + err := deviceIoControlDirect(kextHandle, IOCTL_VERSION, data) + + if err != nil { + return nil, err + } + + version := &VersionInfo{ + major: data[0], + minor: data[1], + revision: data[2], + build: data[3], + } + return version, nil +} + func asByteArray[T any](obj *T) []byte { return unsafe.Slice((*byte)(unsafe.Pointer(obj)), unsafe.Sizeof(*obj)) } diff --git a/firewall/interception/windowskext/syscall.go b/firewall/interception/windowskext/syscall.go index 6ec11348..7a06cd41 100644 --- a/firewall/interception/windowskext/syscall.go +++ b/firewall/interception/windowskext/syscall.go @@ -15,12 +15,13 @@ const ( ) var ( - IOCTL_HELLO = ctlCode(SIOCTL_TYPE, 0x800, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) - IOCTL_RECV_VERDICT_REQ_POLL = ctlCode(SIOCTL_TYPE, 0x801, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_VERSION = ctlCode(SIOCTL_TYPE, 0x800, METHOD_NEITHER, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_RECV_VERDICT_REQ_POLL = ctlCode(SIOCTL_TYPE, 0x801, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) // Not used IOCTL_RECV_VERDICT_REQ = ctlCode(SIOCTL_TYPE, 0x802, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) IOCTL_SET_VERDICT = ctlCode(SIOCTL_TYPE, 0x803, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) IOCTL_GET_PAYLOAD = ctlCode(SIOCTL_TYPE, 0x804, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) IOCTL_CLEAR_CACHE = ctlCode(SIOCTL_TYPE, 0x805, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_UPDATE_VERDICT = ctlCode(SIOCTL_TYPE, 0x806, METHOD_NEITHER, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) ) func ctlCode(device_type, function, method, access uint32) uint32 { @@ -89,3 +90,21 @@ func deviceIoControlReadWrite(handle windows.Handle, code uint32, inData []byte, return bytesReturned, err } + +// Use for METHOD_NEITHER IOCTL, the data buffer is passed directly to the kernel +func deviceIoControlDirect(handle windows.Handle, code uint32, data []byte) error { + var dataPtr *byte = nil + var dataSize uint32 = 0 + if data != nil { + dataPtr = &data[0] + dataSize = uint32(len(data)) + } + + err := windows.DeviceIoControl(handle, + code, + dataPtr, dataSize, + nil, 0, + nil, nil) + + return err +} From 1b480066be2e2510571ebb1e8f16a80efac18d11 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Fri, 4 Nov 2022 14:01:13 +0100 Subject: [PATCH 08/19] fix slow system calls windows kext --- firewall/interception/windowskext/service.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/firewall/interception/windowskext/service.go b/firewall/interception/windowskext/service.go index a2807a59..1e95b294 100644 --- a/firewall/interception/windowskext/service.go +++ b/firewall/interception/windowskext/service.go @@ -74,7 +74,7 @@ retryLoop: func openDriver(filename string) (windows.Handle, error) { u16filename, _ := syscall.UTF16FromString(filename) - handle, err := windows.CreateFile(&u16filename[0], windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.OPEN_EXISTING, 0, 0) + handle, err := windows.CreateFile(&u16filename[0], windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_OVERLAPPED, 0) if err != nil { return 0, err } From 3768db6b32e47ec9c32f2a055338368c7e75c129 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Mon, 7 Nov 2022 11:07:49 +0100 Subject: [PATCH 09/19] Removed legacy code and refactoring --- firewall/interception/windowskext/handler.go | 6 +- firewall/interception/windowskext/kext.go | 116 +++++++++--------- firewall/interception/windowskext/service.go | 117 ++++++++++++------- firewall/interception/windowskext/syscall.go | 63 ++++------ 4 files changed, 157 insertions(+), 145 deletions(-) diff --git a/firewall/interception/windowskext/handler.go b/firewall/interception/windowskext/handler.go index a19cbfdc..6a664d05 100644 --- a/firewall/interception/windowskext/handler.go +++ b/firewall/interception/windowskext/handler.go @@ -52,14 +52,10 @@ type VerdictInfo struct { // Handler transforms received packets to the Packet interface. func Handler(packets chan packet.Packet) { - if !ready.IsSet() { - return - } - defer close(packets) for { - if !ready.IsSet() { + if kextHandle == winInvalidHandleValue { return } diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index ca8315e6..b308e96e 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -6,15 +6,13 @@ package windowskext import ( "errors" "fmt" - "os/exec" "sync" - "sync/atomic" + "syscall" "time" "unsafe" "github.com/safing/portbase/log" "github.com/safing/portmaster/network" - "github.com/tevino/abool" "golang.org/x/sys/windows" ) @@ -23,25 +21,22 @@ var ( ErrKextNotReady = errors.New("the windows kernel extension (driver) is not ready to accept commands") ErrNoPacketID = errors.New("the packet has no ID, possibly because it was fast-tracked by the kernel extension") - winErrInvalidData = uintptr(windows.ERROR_INVALID_DATA) - - kextLock sync.RWMutex - ready = abool.NewBool(false) - urgentRequests *int32 - driverPath string + kextLock sync.RWMutex + driverPath string kextHandle windows.Handle + service *KextService ) -const driverName = "PortmasterKext" - -func init() { - var urgentRequestsValue int32 - urgentRequests = &urgentRequestsValue -} +const ( + winErrInvalidData = uintptr(windows.ERROR_INVALID_DATA) + winInvalidHandleValue = windows.Handle(^uintptr(0)) // Max value + driverName = "PortmasterKext" +) // Init initializes the DLL and the Kext (Kernel Driver). func Init(path string) error { + kextHandle = winInvalidHandleValue driverPath = path return nil } @@ -61,24 +56,25 @@ func Start() error { } // initialize and start driver service - service, err := driverInstall(driverPath) + service, err = createKextService(driverName, driverPath) if err != nil { - return fmt.Errorf("Failed to start service: %s", err) + return fmt.Errorf("failed to create service: %w", err) + } + + err = service.start() + + if err != nil { + return fmt.Errorf("failed to start service: %w", err) } // open the driver kextHandle, err = openDriver(filename) - // close the service handles - _ = windows.DeleteService(service) - _ = windows.CloseServiceHandle(service) - // driver was not installed if err != nil { - return fmt.Errorf("Failed to start the kext service: %s %q", err, filename) + return fmt.Errorf("failed to open driver: %q %w", filename, err) } - ready.Set() return nil } @@ -86,20 +82,27 @@ func Start() error { func Stop() error { kextLock.Lock() defer kextLock.Unlock() - if !ready.IsSet() { - return ErrKextNotReady - } - ready.UnSet() err := closeDriver(kextHandle) if err != nil { - log.Errorf("winkext: failed to close the handle: %s", err) + log.Warningf("winkext: failed to close the handle: %s", err) } - _, err = exec.Command("sc", "stop", driverName).Output() // This is a question of taste, but it is a robust and solid solution + err = service.stop() if err != nil { - log.Errorf("winkext: failed to stop the service: %q", err) + log.Warningf("winkext: failed to stop service: %s", err) } + // Driver file may change on the next start so it's better to delete the service + err = service.delete() + if err != nil { + log.Warningf("winkext: failed to delete service: %s", err) + } + err = service.closeHandle() + if err != nil { + log.Warningf("winkext: failed to close the handle: %s", err) + } + + kextHandle = winInvalidHandleValue return nil } @@ -107,19 +110,9 @@ func Stop() error { func RecvVerdictRequest() (*VerdictRequest, error) { kextLock.RLock() defer kextLock.RUnlock() - if !ready.IsSet() { + if kextHandle == winInvalidHandleValue { return nil, ErrKextNotReady } - // wait for urgent requests to complete - for i := 1; i <= 100; i++ { - if atomic.LoadInt32(urgentRequests) <= 0 { - break - } - if i == 100 { - log.Warningf("winkext: RecvVerdictRequest waited 100 times") - } - time.Sleep(100 * time.Microsecond) - } timestamp := time.Now() // Initialize struct for the output data @@ -127,7 +120,7 @@ func RecvVerdictRequest() (*VerdictRequest, error) { // Make driver request data := asByteArray(&new) - bytesRead, err := deviceIoControlRead(kextHandle, IOCTL_RECV_VERDICT_REQ, data) + bytesRead, err := deviceIOControl(kextHandle, IOCTL_RECV_VERDICT_REQ, nil, data) if err != nil { return nil, err } @@ -148,7 +141,7 @@ func SetVerdict(pkt *Packet, verdict network.Verdict) error { kextLock.RLock() defer kextLock.RUnlock() - if !ready.IsSet() { + if kextHandle == winInvalidHandleValue { log.Tracer(pkt.Ctx()).Errorf("kext: failed to set verdict %s: kext not ready", verdict) return ErrKextNotReady } @@ -156,10 +149,8 @@ func SetVerdict(pkt *Packet, verdict network.Verdict) error { verdictInfo := VerdictInfo{pkt.verdictRequest.id, verdict} // Make driver request - atomic.AddInt32(urgentRequests, 1) data := asByteArray(&verdictInfo) - _, err := deviceIoControlWrite(kextHandle, IOCTL_SET_VERDICT, data) - atomic.AddInt32(urgentRequests, -1) + _, err := deviceIOControl(kextHandle, IOCTL_SET_VERDICT, data, nil) if err != nil { log.Tracer(pkt.Ctx()).Errorf("kext: failed to set verdict %s on packet %d", verdict, pkt.verdictRequest.id) return err @@ -176,7 +167,7 @@ func GetPayload(packetID uint32, packetSize uint32) ([]byte, error) { // Check if driver is initialized kextLock.RLock() defer kextLock.RUnlock() - if !ready.IsSet() { + if kextHandle == winInvalidHandleValue { return nil, ErrKextNotReady } @@ -189,11 +180,8 @@ func GetPayload(packetID uint32, packetSize uint32) ([]byte, error) { }{packetID, packetSize} // Make driver request - atomic.AddInt32(urgentRequests, 1) data := asByteArray(&payload) - bytesRead, err := deviceIoControlReadWrite(kextHandle, IOCTL_GET_PAYLOAD, data, unsafe.Slice(&buf[0], packetSize)) - - atomic.AddInt32(urgentRequests, -1) + bytesRead, err := deviceIOControl(kextHandle, IOCTL_GET_PAYLOAD, data, unsafe.Slice(&buf[0], packetSize)) if err != nil { return nil, err @@ -216,16 +204,38 @@ func ClearCache() error { defer kextLock.RUnlock() // Check if driver is initialized - if !ready.IsSet() { + if kextHandle == winInvalidHandleValue { log.Error("kext: failed to clear the cache: kext not ready") return ErrKextNotReady } // Make driver request - _, err := deviceIoControlRead(kextHandle, IOCTL_CLEAR_CACHE, nil) + _, err := deviceIOControl(kextHandle, IOCTL_CLEAR_CACHE, nil, nil) return err } func asByteArray[T any](obj *T) []byte { return unsafe.Slice((*byte)(unsafe.Pointer(obj)), unsafe.Sizeof(*obj)) } + +func openDriver(filename string) (windows.Handle, error) { + u16filename, err := syscall.UTF16FromString(filename) + if err != nil { + return winInvalidHandleValue, fmt.Errorf("failed to convert driver filename to UTF16 string %w", err) + } + + handle, err := windows.CreateFile(&u16filename[0], windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_OVERLAPPED, 0) + if err != nil { + return winInvalidHandleValue, err + } + + return handle, nil +} + +func closeDriver(handle windows.Handle) error { + if kextHandle == winInvalidHandleValue { + return ErrKextNotReady + } + + return windows.CloseHandle(handle) +} diff --git a/firewall/interception/windowskext/service.go b/firewall/interception/windowskext/service.go index 1e95b294..b8f8ed70 100644 --- a/firewall/interception/windowskext/service.go +++ b/firewall/interception/windowskext/service.go @@ -10,78 +10,105 @@ import ( "golang.org/x/sys/windows" ) -func createService(manager windows.Handle, portmasterKextPath *uint16) (windows.Handle, error) { - u16filename, err := syscall.UTF16FromString(driverName) - if err != nil { - return 0, fmt.Errorf("Bad service: %s", err) - } - // Check if it's already created - service, err := windows.OpenService(manager, &u16filename[0], windows.SERVICE_ALL_ACCESS) - if err == nil { - return service, nil - } - - // Create the service - service, err = windows.CreateService(manager, &u16filename[0], &u16filename[0], windows.SERVICE_ALL_ACCESS, windows.SERVICE_KERNEL_DRIVER, windows.SERVICE_DEMAND_START, windows.SERVICE_ERROR_NORMAL, portmasterKextPath, nil, nil, nil, nil, nil) - if err != nil { - return 0, err - } - - return service, nil +type KextService struct { + handle windows.Handle } -func driverInstall(portmasterKextPath string) (windows.Handle, error) { - u16kextPath, _ := syscall.UTF16FromString(portmasterKextPath) +func createKextService(driverName string, driverPath string) (*KextService, error) { // Open the service manager: manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ALL_ACCESS) if err != nil { - return 0, fmt.Errorf("Failed to open service manager: %d", err) + return nil, fmt.Errorf("failed to open service manager: %d", err) } defer windows.CloseServiceHandle(manager) - // Try to create the service. Retry if it fails. - var service windows.Handle -retryLoop: - for i := 0; i < 3; i++ { - service, err = createService(manager, &u16kextPath[0]) - if err == nil { - break retryLoop - } + driverNameU16, err := syscall.UTF16FromString(driverName) + if err != nil { + return nil, fmt.Errorf("failed to convert driver name to UTF16 string: %w", err) + } + // Check if it's already created + service, err := windows.OpenService(manager, &driverNameU16[0], windows.SERVICE_ALL_ACCESS) + if err == nil { + return &KextService{handle: service}, nil // service was already created } + driverPathU16, err := syscall.UTF16FromString(driverPath) + + // Create the service + service, err = windows.CreateService(manager, &driverNameU16[0], &driverNameU16[0], windows.SERVICE_ALL_ACCESS, windows.SERVICE_KERNEL_DRIVER, windows.SERVICE_DEMAND_START, windows.SERVICE_ERROR_NORMAL, &driverPathU16[0], nil, nil, nil, nil, nil) if err != nil { - return 0, fmt.Errorf("Failed to create service: %s", err) + return nil, err + } + + return &KextService{handle: service}, nil +} + +func (s *KextService) isValid() bool { + return s != nil && s.handle != winInvalidHandleValue && s.handle != 0 +} + +func (s *KextService) start() error { + if !s.isValid() { + return fmt.Errorf("kext service not initialized") } // Start the service: - err = windows.StartService(service, 0, nil) + err := windows.StartService(s.handle, 0, nil) if err != nil { err = windows.GetLastError() if err != windows.ERROR_SERVICE_ALREADY_RUNNING { // Failed to start service; clean-up: var status windows.SERVICE_STATUS - _ = windows.ControlService(service, windows.SERVICE_CONTROL_STOP, &status) - _ = windows.DeleteService(service) - _ = windows.CloseServiceHandle(service) - service = 0 + _ = windows.ControlService(s.handle, windows.SERVICE_CONTROL_STOP, &status) + _ = windows.DeleteService(s.handle) + _ = windows.CloseServiceHandle(s.handle) + s.handle = winInvalidHandleValue + return err } } - return service, nil + return nil } -func openDriver(filename string) (windows.Handle, error) { - u16filename, _ := syscall.UTF16FromString(filename) - - handle, err := windows.CreateFile(&u16filename[0], windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_OVERLAPPED, 0) - if err != nil { - return 0, err +func (s *KextService) stop() error { + if !s.isValid() { + return fmt.Errorf("kext service not initialized") } - return handle, nil + var status windows.SERVICE_STATUS + err := windows.ControlService(s.handle, windows.SERVICE_CONTROL_STOP, &status) + if err != nil { + return fmt.Errorf("service failed to stop: %w", err) + } + + if status.CurrentState != windows.SERVICE_STOP_PENDING && status.CurrentState != windows.SERVICE_STOPPED { + return fmt.Errorf("service unexpected status after stop: %d", status.CurrentState) + } + + return nil } -func closeDriver(handle windows.Handle) error { - return windows.CloseHandle(handle) +func (s *KextService) delete() error { + if !s.isValid() { + return fmt.Errorf("kext service not initialized") + } + + err := windows.DeleteService(s.handle) + if err != nil { + return fmt.Errorf("failed to delete service: %s", err) + } + return nil +} + +func (s *KextService) closeHandle() error { + if !s.isValid() { + return fmt.Errorf("kext service not initialized") + } + + err := windows.CloseServiceHandle(s.handle) + if err != nil { + return fmt.Errorf("failed to close service handle: %s", err) + } + return nil } diff --git a/firewall/interception/windowskext/syscall.go b/firewall/interception/windowskext/syscall.go index 6ec11348..24d308a7 100644 --- a/firewall/interception/windowskext/syscall.go +++ b/firewall/interception/windowskext/syscall.go @@ -27,47 +27,7 @@ func ctlCode(device_type, function, method, access uint32) uint32 { return (device_type << 16) | (access << 14) | (function << 2) | method } -func deviceIoControlRead(handle windows.Handle, code uint32, data []byte) (uint32, error) { - var bytesReturned uint32 - - var dataPtr *byte = nil - var dataSize uint32 = 0 - if data != nil { - dataPtr = &data[0] - dataSize = uint32(len(data)) - } - - err := windows.DeviceIoControl(handle, - code, - nil, 0, - dataPtr, dataSize, - &bytesReturned, nil) - - return bytesReturned, err -} - -func deviceIoControlWrite(handle windows.Handle, code uint32, data []byte) (uint32, error) { - var bytesReturned uint32 - - var dataPtr *byte = nil - var dataSize uint32 = 0 - if data != nil { - dataPtr = &data[0] - dataSize = uint32(len(data)) - } - - err := windows.DeviceIoControl(handle, - code, - dataPtr, dataSize, - nil, 0, - &bytesReturned, nil) - - return bytesReturned, err -} - -func deviceIoControlReadWrite(handle windows.Handle, code uint32, inData []byte, outData []byte) (uint32, error) { - var bytesReturned uint32 - +func deviceIOControlAsync(handle windows.Handle, code uint32, inData []byte, outData []byte) (*windows.Overlapped, error) { var inDataPtr *byte = nil var inDataSize uint32 = 0 if inData != nil { @@ -81,11 +41,30 @@ func deviceIoControlReadWrite(handle windows.Handle, code uint32, inData []byte, outDataPtr = &outData[0] outDataSize = uint32(len(outData)) } + + overlapped := &windows.Overlapped{} err := windows.DeviceIoControl(handle, code, inDataPtr, inDataSize, outDataPtr, outDataSize, - &bytesReturned, nil) + nil, overlapped) + + if err != nil { + return nil, err + } + + return overlapped, nil + +} + +func deviceIOControl(handle windows.Handle, code uint32, inData []byte, outData []byte) (uint32, error) { + overlapped, err := deviceIOControlAsync(handle, code, inData, outData) + if err != nil { + return 0, err + } + + var bytesReturned uint32 + err = windows.GetOverlappedResult(handle, overlapped, &bytesReturned, true) return bytesReturned, err } From 5e8569dfddf2175d0c57ec8a933cd8ae96e0afaa Mon Sep 17 00:00:00 2001 From: Vladimir Date: Mon, 7 Nov 2022 11:18:09 +0100 Subject: [PATCH 10/19] add defer when measuring time --- firewall/interception/windowskext/kext.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index b308e96e..59e4af35 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -115,6 +115,7 @@ func RecvVerdictRequest() (*VerdictRequest, error) { } timestamp := time.Now() + defer log.Tracef("winkext: getting verdict request took %s", time.Now().Sub(timestamp)) // Initialize struct for the output data var new VerdictRequest @@ -128,7 +129,6 @@ func RecvVerdictRequest() (*VerdictRequest, error) { return nil, nil // no error, no new verdict request } - log.Tracef("winkext: getting verdict request took %s", time.Now().Sub(timestamp)) return &new, nil } From 101bf16727517bfe5652f3e1fc4ec83f26942d1b Mon Sep 17 00:00:00 2001 From: Vladimir Date: Mon, 7 Nov 2022 16:09:41 +0100 Subject: [PATCH 11/19] better kext service handling --- firewall/interception/windowskext/kext.go | 29 +++++----- firewall/interception/windowskext/service.go | 61 +++++++++++++++++--- 2 files changed, 68 insertions(+), 22 deletions(-) diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index 59e4af35..949eb0aa 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -46,28 +46,27 @@ func Start() error { kextLock.Lock() defer kextLock.Unlock() - filename := `\\.\` + driverName - - // check if driver is already installed - var err error - kextHandle, err = openDriver(filename) - if err == nil { - return nil // device was already initialized - } - // initialize and start driver service - service, err = createKextService(driverName, driverPath) + service, err := createKextService(driverName, driverPath) if err != nil { + log.Warningf("winkext: failed to create service: %s", err) return fmt.Errorf("failed to create service: %w", err) } - err = service.start() + running, err := service.isRunning() + if err == nil && !running { + err = service.start(true) - if err != nil { - return fmt.Errorf("failed to start service: %w", err) + if err != nil { + log.Warningf("winkext: failed to start service: %s", err) + return fmt.Errorf("failed to start service: %w", err) + } + } else if err != nil { + return fmt.Errorf("service not initialized: %w", err) } - // open the driver + // Open the driver + filename := `\\.\` + driverName kextHandle, err = openDriver(filename) // driver was not installed @@ -88,7 +87,7 @@ func Stop() error { log.Warningf("winkext: failed to close the handle: %s", err) } - err = service.stop() + err = service.stop(true) if err != nil { log.Warningf("winkext: failed to stop service: %s", err) } diff --git a/firewall/interception/windowskext/service.go b/firewall/interception/windowskext/service.go index b8f8ed70..08b37088 100644 --- a/firewall/interception/windowskext/service.go +++ b/firewall/interception/windowskext/service.go @@ -6,6 +6,7 @@ package windowskext import ( "fmt" "syscall" + "time" "golang.org/x/sys/windows" ) @@ -47,7 +48,40 @@ func (s *KextService) isValid() bool { return s != nil && s.handle != winInvalidHandleValue && s.handle != 0 } -func (s *KextService) start() error { +func (s *KextService) isRunning() (bool, error) { + if !s.isValid() { + return false, fmt.Errorf("kext service not initialized") + } + var status windows.SERVICE_STATUS + err := windows.QueryServiceStatus(s.handle, &status) + if err != nil { + return false, err + } + return status.CurrentState == windows.SERVICE_RUNNING, nil +} + +func waitForServiceStatus(handle windows.Handle, neededStatus uint32, timeLimit time.Duration) (bool, error) { + var status windows.SERVICE_STATUS + status.CurrentState = windows.SERVICE_NO_CHANGE + start := time.Now() + for status.CurrentState == neededStatus { + err := windows.QueryServiceStatus(handle, &status) + if err != nil { + return false, fmt.Errorf("failed while waiting for service to start: %w", err) + } + + if time.Now().Sub(start) > timeLimit { + return false, fmt.Errorf("time limit reached") + } + + // Sleep for 1/10 of the wait hint, recommended time from microsoft + time.Sleep(time.Duration((status.WaitHint / 10)) * time.Millisecond) + } + + return true, nil +} + +func (s *KextService) start(wait bool) error { if !s.isValid() { return fmt.Errorf("kext service not initialized") } @@ -68,22 +102,35 @@ func (s *KextService) start() error { } } + // Wait for service to start + if wait { + success, err := waitForServiceStatus(s.handle, windows.SERVICE_RUNNING, time.Duration(10*time.Second)) + if err != nil || !success { + return fmt.Errorf("service did not start: %w", err) + } + } + return nil } -func (s *KextService) stop() error { +func (s *KextService) stop(wait bool) error { if !s.isValid() { - return fmt.Errorf("kext service not initialized") + return fmt.Errorf("kext service not initialized %v", s) } + // Stop the service var status windows.SERVICE_STATUS err := windows.ControlService(s.handle, windows.SERVICE_CONTROL_STOP, &status) if err != nil { return fmt.Errorf("service failed to stop: %w", err) } - if status.CurrentState != windows.SERVICE_STOP_PENDING && status.CurrentState != windows.SERVICE_STOPPED { - return fmt.Errorf("service unexpected status after stop: %d", status.CurrentState) + // Wait for service to stop + if wait { + success, err := waitForServiceStatus(s.handle, windows.SERVICE_STOPPED, time.Duration(10*time.Second)) + if err != nil || !success { + return fmt.Errorf("service did not stop: %w", err) + } } return nil @@ -91,7 +138,7 @@ func (s *KextService) stop() error { func (s *KextService) delete() error { if !s.isValid() { - return fmt.Errorf("kext service not initialized") + return fmt.Errorf("kext service not initialized %v", s) } err := windows.DeleteService(s.handle) @@ -103,7 +150,7 @@ func (s *KextService) delete() error { func (s *KextService) closeHandle() error { if !s.isValid() { - return fmt.Errorf("kext service not initialized") + return fmt.Errorf("kext service not initialized %v", s) } err := windows.CloseServiceHandle(s.handle) From fed7b74f513d2291f8f86087ed78574e301f03b2 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Mon, 7 Nov 2022 16:42:12 +0100 Subject: [PATCH 12/19] fix stopping of the kext service --- firewall/interception/windowskext/kext.go | 5 ++--- firewall/interception/windowskext/service.go | 6 +++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index 949eb0aa..938ade25 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -47,9 +47,9 @@ func Start() error { defer kextLock.Unlock() // initialize and start driver service - service, err := createKextService(driverName, driverPath) + var err error + service, err = createKextService(driverName, driverPath) if err != nil { - log.Warningf("winkext: failed to create service: %s", err) return fmt.Errorf("failed to create service: %w", err) } @@ -58,7 +58,6 @@ func Start() error { err = service.start(true) if err != nil { - log.Warningf("winkext: failed to start service: %s", err) return fmt.Errorf("failed to start service: %w", err) } } else if err != nil { diff --git a/firewall/interception/windowskext/service.go b/firewall/interception/windowskext/service.go index 08b37088..647753c6 100644 --- a/firewall/interception/windowskext/service.go +++ b/firewall/interception/windowskext/service.go @@ -115,7 +115,7 @@ func (s *KextService) start(wait bool) error { func (s *KextService) stop(wait bool) error { if !s.isValid() { - return fmt.Errorf("kext service not initialized %v", s) + return fmt.Errorf("kext service not initialized") } // Stop the service @@ -138,7 +138,7 @@ func (s *KextService) stop(wait bool) error { func (s *KextService) delete() error { if !s.isValid() { - return fmt.Errorf("kext service not initialized %v", s) + return fmt.Errorf("kext service not initialized") } err := windows.DeleteService(s.handle) @@ -150,7 +150,7 @@ func (s *KextService) delete() error { func (s *KextService) closeHandle() error { if !s.isValid() { - return fmt.Errorf("kext service not initialized %v", s) + return fmt.Errorf("kext service not initialized") } err := windows.CloseServiceHandle(s.handle) From 8b8755458efb377e7d0df3206c284325e7027738 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Tue, 8 Nov 2022 16:39:26 +0100 Subject: [PATCH 13/19] fix sending update verdict info --- firewall/interception/windowskext/handler.go | 30 ++++++++++++++++++-- firewall/interception/windowskext/kext.go | 24 ++++++++-------- firewall/interception/windowskext/syscall.go | 4 +-- 3 files changed, 42 insertions(+), 16 deletions(-) diff --git a/firewall/interception/windowskext/handler.go b/firewall/interception/windowskext/handler.go index ddfa21ef..f9f541f6 100644 --- a/firewall/interception/windowskext/handler.go +++ b/firewall/interception/windowskext/handler.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "net" + "unsafe" "github.com/tevino/abool" @@ -68,6 +69,10 @@ type VersionInfo struct { build uint8 } +func (v *VersionInfo) String() string { + return fmt.Sprintf("%d.%d.%d.%d", v.major, v.minor, v.revision, v.build) +} + // Handler transforms received packets to the Packet interface. func Handler(packets chan packet.Packet) { defer close(packets) @@ -167,6 +172,27 @@ func convertIPv6(input [4]uint32) net.IP { return net.IP(addressBuf) } -func (v *VersionInfo) String() string { - return fmt.Sprintf("%d.%d.%d.%d", v.major, v.minor, v.revision, v.build) +func ipAddressToArray(ip net.IP, isIPv6 bool) [4]uint32 { + array := [4]uint32{0} + if isIPv6 { + for i := 0; i < 4; i++ { + binary.BigEndian.PutUint32(asByteArrayWithLength(&array[i], 4), getUInt32Value(&ip[i])) + } + } else { + binary.BigEndian.PutUint32(asByteArrayWithLength(&array[0], 4), getUInt32Value(&ip[0])) + } + + return array +} + +func asByteArray[T any](obj *T) []byte { + return unsafe.Slice((*byte)(unsafe.Pointer(obj)), unsafe.Sizeof(*obj)) +} + +func asByteArrayWithLength[T any](obj *T, size uint32) []byte { + return unsafe.Slice((*byte)(unsafe.Pointer(obj)), size) +} + +func getUInt32Value[T any](obj *T) uint32 { + return *(*uint32)(unsafe.Pointer(obj)) } diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index 1f85083e..33a387e7 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -13,6 +13,7 @@ import ( "github.com/safing/portbase/log" "github.com/safing/portmaster/network" + "github.com/safing/portmaster/network/packet" "golang.org/x/sys/windows" ) @@ -217,24 +218,27 @@ func UpdateVerdict(conn *network.Connection) error { defer kextLock.RUnlock() // Check if driver is initialized - if !ready.IsSet() { + if kextHandle == winInvalidHandleValue { log.Error("kext: failed to clear the cache: kext not ready") return ErrKextNotReady } + var isIpv6 uint8 = 0 + if conn.IPVersion == packet.IPv6 { + isIpv6 = 1 + } + // initialize variables - info := &VerdictUpdateInfo{ - ipV6: uint8(conn.IPVersion), + info := VerdictUpdateInfo{ + ipV6: isIpv6, protocol: uint8(conn.IPProtocol), + localIP: ipAddressToArray(conn.LocalIP, isIpv6 == 1), localPort: conn.LocalPort, + remoteIP: ipAddressToArray(conn.Entity.IP, isIpv6 == 1), remotePort: conn.Entity.Port, verdict: uint8(conn.Verdict.Active), } - // copy ip addresses - copy(asByteArray(&info.localIP[0]), conn.LocalIP) - copy(asByteArray(&info.remoteIP[0]), conn.Entity.IP) - // Make driver request data := asByteArray(&info) err := deviceIoControlDirect(kextHandle, IOCTL_UPDATE_VERDICT, data) @@ -246,7 +250,7 @@ func GetVersion() (*VersionInfo, error) { defer kextLock.RUnlock() // Check if driver is initialized - if !ready.IsSet() { + if kextHandle == winInvalidHandleValue { log.Error("kext: failed to clear the cache: kext not ready") return nil, ErrKextNotReady } @@ -267,10 +271,6 @@ func GetVersion() (*VersionInfo, error) { return version, nil } -func asByteArray[T any](obj *T) []byte { - return unsafe.Slice((*byte)(unsafe.Pointer(obj)), unsafe.Sizeof(*obj)) -} - func openDriver(filename string) (windows.Handle, error) { u16filename, err := syscall.UTF16FromString(filename) if err != nil { diff --git a/firewall/interception/windowskext/syscall.go b/firewall/interception/windowskext/syscall.go index 69c0b6ef..2b85adf5 100644 --- a/firewall/interception/windowskext/syscall.go +++ b/firewall/interception/windowskext/syscall.go @@ -15,13 +15,13 @@ const ( ) var ( - IOCTL_VERSION = ctlCode(SIOCTL_TYPE, 0x800, METHOD_NEITHER, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_VERSION = ctlCode(SIOCTL_TYPE, 0x800, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) IOCTL_RECV_VERDICT_REQ_POLL = ctlCode(SIOCTL_TYPE, 0x801, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) // Not used IOCTL_RECV_VERDICT_REQ = ctlCode(SIOCTL_TYPE, 0x802, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) IOCTL_SET_VERDICT = ctlCode(SIOCTL_TYPE, 0x803, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) IOCTL_GET_PAYLOAD = ctlCode(SIOCTL_TYPE, 0x804, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) IOCTL_CLEAR_CACHE = ctlCode(SIOCTL_TYPE, 0x805, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) - IOCTL_UPDATE_VERDICT = ctlCode(SIOCTL_TYPE, 0x806, METHOD_NEITHER, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) + IOCTL_UPDATE_VERDICT = ctlCode(SIOCTL_TYPE, 0x806, METHOD_BUFFERED, windows.FILE_READ_DATA|windows.FILE_WRITE_DATA) ) func ctlCode(device_type, function, method, access uint32) uint32 { From 075f9151cd6686d5ec310051d8d3199bb6c67514 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Tue, 8 Nov 2022 16:53:54 +0100 Subject: [PATCH 14/19] More efficient verdict update structure --- firewall/interception/windowskext/handler.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/firewall/interception/windowskext/handler.go b/firewall/interception/windowskext/handler.go index f9f541f6..e30e4498 100644 --- a/firewall/interception/windowskext/handler.go +++ b/firewall/interception/windowskext/handler.go @@ -29,6 +29,7 @@ const ( VerdictRequestFlagSocketAuth = 2 ) +// Do not change the order of the members! The structure to communicate with the kernel extension. // VerdictRequest is the request structure from the Kext. type VerdictRequest struct { id uint32 // ID from RegisterPacket @@ -47,18 +48,20 @@ type VerdictRequest struct { packetSize uint32 } +// Do not change the order of the members! The structure to communicate with the kernel extension. type VerdictInfo struct { id uint32 // ID from RegisterPacket verdict network.Verdict // verdict for the connection } +// Do not change the order of the members! The structure to communicate with the kernel extension. type VerdictUpdateInfo struct { - ipV6 uint8 //True: IPv6, False: IPv4 - protocol uint8 //Protocol (UDP, TCP, ...) localIP [4]uint32 //Source Address, only srcIP[0] if IPv4 remoteIP [4]uint32 //Destination Address localPort uint16 //Source Port remotePort uint16 //Destination port + ipV6 uint8 //True: IPv6, False: IPv4 + protocol uint8 //Protocol (UDP, TCP, ...) verdict uint8 //New verdict } From a04b76ff580be0324f702f30a7655c2cb3d2ffbb Mon Sep 17 00:00:00 2001 From: Vladimir Date: Wed, 9 Nov 2022 12:17:23 +0100 Subject: [PATCH 15/19] Fix linter errors --- firewall/interception.go | 4 +--- firewall/interception/interception_linux.go | 1 + firewall/interception/interception_windows.go | 4 +++- firewall/interception/nfq/conntrack.go | 18 +++++++++++++----- firewall/interception/nfqueue_linux.go | 4 ++-- 5 files changed, 20 insertions(+), 11 deletions(-) diff --git a/firewall/interception.go b/firewall/interception.go index 706111b4..e5be02dc 100644 --- a/firewall/interception.go +++ b/firewall/interception.go @@ -177,9 +177,7 @@ func interceptionStart() error { interceptionModule.StartWorker("stat logger", statLogger) interceptionModule.StartWorker("packet handler", packetHandler) - err := interception.Start() - - return err + return interception.Start() } func interceptionStop() error { diff --git a/firewall/interception/interception_linux.go b/firewall/interception/interception_linux.go index f0f1d99f..5ee31eb2 100644 --- a/firewall/interception/interception_linux.go +++ b/firewall/interception/interception_linux.go @@ -21,6 +21,7 @@ func ResetVerdictOfAllConnections() error { return nfq.DeleteAllMarkedConnection() } +// UpdateVerdictOfConnection deletes the verdict of specific connection so in can be initialized again with the next packet func UpdateVerdictOfConnection(conn *network.Connection) error { return nfq.DeleteMarkedConnection(conn) } diff --git a/firewall/interception/interception_windows.go b/firewall/interception/interception_windows.go index d1931fb8..5a21f345 100644 --- a/firewall/interception/interception_windows.go +++ b/firewall/interception/interception_windows.go @@ -41,11 +41,13 @@ func ResetVerdictOfAllConnections() error { return windowskext.ClearCache() } +// UpdateVerdictOfConnection updates the verdict of specific connection in the kernel extension func UpdateVerdictOfConnection(conn *network.Connection) error { return windowskext.UpdateVerdict(conn) } -func GetVersion() (string, error) { +// GetKextVersion returns the version of the kernel extension +func GetKextVersion() (string, error) { version, err := windowskext.GetVersion() if err != nil { return "", err diff --git a/firewall/interception/nfq/conntrack.go b/firewall/interception/nfq/conntrack.go index ce494792..bcb10101 100644 --- a/firewall/interception/nfq/conntrack.go +++ b/firewall/interception/nfq/conntrack.go @@ -13,10 +13,9 @@ import ( "github.com/safing/portmaster/network" ) -var ( - nfct *ct.Nfct // Conntrack handler. NFCT: Network Filter Connection Tracking -) +var nfct *ct.Nfct // Conntrack handler. NFCT: Network Filter Connection Tracking +// InitNFCT initializes the network filter conntrack library func InitNFCT() error { var err error nfct, err = ct.Open(&ct.Config{}) @@ -26,6 +25,7 @@ func InitNFCT() error { return nil } +// DeinitNFCT deinitializes the network filter conntrack library func DeinitNFCT() { _ = nfct.Close() } @@ -82,6 +82,7 @@ func deleteMarkedConnections(nfct *ct.Nfct, f ct.Family) (deleted int) { return deleted } +// DeleteMarkedConnection removes a specific connection from the conntrack table func DeleteMarkedConnection(conn *network.Connection) error { if nfct == nil { return fmt.Errorf("nfq: nfct not initialized") @@ -100,7 +101,7 @@ func DeleteMarkedConnection(conn *network.Connection) error { } connections, err := nfct.Get(ct.Conntrack, ct.IPv4, con) if err != nil { - return fmt.Errorf("nfq: failed to find entry for connection %s: %s", conn.String(), err) + return fmt.Errorf("nfq: failed to find entry for connection %s: %w", conn.String(), err) } if len(connections) > 1 { @@ -108,7 +109,14 @@ func DeleteMarkedConnection(conn *network.Connection) error { } for _, connection := range connections { - nfct.Delete(ct.Conntrack, ct.IPv4, connection) + deleteErr := nfct.Delete(ct.Conntrack, ct.IPv4, connection) + if err == nil { + err = deleteErr + } + } + + if err != nil { + log.Warningf("nfq: error while deleting conntrack entries for connection %s: %s", conn.String(), err) } return nil diff --git a/firewall/interception/nfqueue_linux.go b/firewall/interception/nfqueue_linux.go index 54d7f91a..10de02b3 100644 --- a/firewall/interception/nfqueue_linux.go +++ b/firewall/interception/nfqueue_linux.go @@ -150,7 +150,7 @@ func activateNfqueueFirewall() error { if err := nfq.InitNFCT(); err != nil { return err } - nfq.DeleteAllMarkedConnection() + _ = nfq.DeleteAllMarkedConnection() return nil } @@ -171,7 +171,7 @@ func DeactivateNfqueueFirewall() error { } } - nfq.DeleteAllMarkedConnection() + _ = nfq.DeleteAllMarkedConnection() nfq.DeinitNFCT() return result.ErrorOrNil() From 852fb32bbdea261c1ce85f65d9ae9b4c6d13e76a Mon Sep 17 00:00:00 2001 From: Vladimir Date: Wed, 9 Nov 2022 12:23:53 +0100 Subject: [PATCH 16/19] Fix linter warnings --- firewall/interception/interception_linux.go | 2 +- firewall/interception/interception_windows.go | 4 ++-- firewall/interception/nfq/conntrack.go | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/firewall/interception/interception_linux.go b/firewall/interception/interception_linux.go index 5ee31eb2..be94e5b9 100644 --- a/firewall/interception/interception_linux.go +++ b/firewall/interception/interception_linux.go @@ -21,7 +21,7 @@ func ResetVerdictOfAllConnections() error { return nfq.DeleteAllMarkedConnection() } -// UpdateVerdictOfConnection deletes the verdict of specific connection so in can be initialized again with the next packet +// UpdateVerdictOfConnection deletes the verdict of specific connection so in can be initialized again with the next packet. func UpdateVerdictOfConnection(conn *network.Connection) error { return nfq.DeleteMarkedConnection(conn) } diff --git a/firewall/interception/interception_windows.go b/firewall/interception/interception_windows.go index 5a21f345..7a29affe 100644 --- a/firewall/interception/interception_windows.go +++ b/firewall/interception/interception_windows.go @@ -41,12 +41,12 @@ func ResetVerdictOfAllConnections() error { return windowskext.ClearCache() } -// UpdateVerdictOfConnection updates the verdict of specific connection in the kernel extension +// UpdateVerdictOfConnection updates the verdict of specific connection in the kernel extension. func UpdateVerdictOfConnection(conn *network.Connection) error { return windowskext.UpdateVerdict(conn) } -// GetKextVersion returns the version of the kernel extension +// GetKextVersion returns the version of the kernel extension. func GetKextVersion() (string, error) { version, err := windowskext.GetVersion() if err != nil { diff --git a/firewall/interception/nfq/conntrack.go b/firewall/interception/nfq/conntrack.go index bcb10101..b9a189a4 100644 --- a/firewall/interception/nfq/conntrack.go +++ b/firewall/interception/nfq/conntrack.go @@ -13,7 +13,7 @@ import ( "github.com/safing/portmaster/network" ) -var nfct *ct.Nfct // Conntrack handler. NFCT: Network Filter Connection Tracking +var nfct *ct.Nfct // Conntrack handler. NFCT: Network Filter Connection Tracking. // InitNFCT initializes the network filter conntrack library func InitNFCT() error { @@ -25,7 +25,7 @@ func InitNFCT() error { return nil } -// DeinitNFCT deinitializes the network filter conntrack library +// DeinitNFCT deinitializes the network filter conntrack library. func DeinitNFCT() { _ = nfct.Close() } @@ -82,7 +82,7 @@ func deleteMarkedConnections(nfct *ct.Nfct, f ct.Family) (deleted int) { return deleted } -// DeleteMarkedConnection removes a specific connection from the conntrack table +// DeleteMarkedConnection removes a specific connection from the conntrack table. func DeleteMarkedConnection(conn *network.Connection) error { if nfct == nil { return fmt.Errorf("nfq: nfct not initialized") From f43cf9974da8cb94ee8a66f9378ce77ba56b2bac Mon Sep 17 00:00:00 2001 From: Vladimir Date: Wed, 9 Nov 2022 12:26:53 +0100 Subject: [PATCH 17/19] fix linter dot --- firewall/interception/nfq/conntrack.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/firewall/interception/nfq/conntrack.go b/firewall/interception/nfq/conntrack.go index b9a189a4..d29da0cb 100644 --- a/firewall/interception/nfq/conntrack.go +++ b/firewall/interception/nfq/conntrack.go @@ -15,7 +15,7 @@ import ( var nfct *ct.Nfct // Conntrack handler. NFCT: Network Filter Connection Tracking. -// InitNFCT initializes the network filter conntrack library +// InitNFCT initializes the network filter conntrack library. func InitNFCT() error { var err error nfct, err = ct.Open(&ct.Config{}) From c43f6fe463b1ef00e04eb246874d120b27dbad34 Mon Sep 17 00:00:00 2001 From: vladimir Date: Thu, 10 Nov 2022 17:36:58 +0200 Subject: [PATCH 18/19] minor refactoring --- firewall/interception.go | 2 +- firewall/interception/nfq/conntrack.go | 4 ++-- firewall/interception/nfqueue_linux.go | 2 +- firewall/interception/windowskext/handler.go | 18 +++++++++--------- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/firewall/interception.go b/firewall/interception.go index e5be02dc..4999c5b3 100644 --- a/firewall/interception.go +++ b/firewall/interception.go @@ -151,7 +151,7 @@ func resetAllConnectionVerdicts() { if conn.Verdict.Firewall != previousVerdict { err := interception.UpdateVerdictOfConnection(conn) if err != nil { - log.Debugf("filter: failed to delete connection verdict: %s", err) + log.Debugf("filter: failed to update connection verdict: %s", err) } conn.Save() tracer.Infof("filter: verdict of connection %s changed from %s to %s", conn, previousVerdict.Verb(), conn.VerdictVerb()) diff --git a/firewall/interception/nfq/conntrack.go b/firewall/interception/nfq/conntrack.go index d29da0cb..4de81036 100644 --- a/firewall/interception/nfq/conntrack.go +++ b/firewall/interception/nfq/conntrack.go @@ -25,8 +25,8 @@ func InitNFCT() error { return nil } -// DeinitNFCT deinitializes the network filter conntrack library. -func DeinitNFCT() { +// TeardownNFCT deinitializes the network filter conntrack library. +func TeardownNFCT() { _ = nfct.Close() } diff --git a/firewall/interception/nfqueue_linux.go b/firewall/interception/nfqueue_linux.go index 10de02b3..2ba1ab8f 100644 --- a/firewall/interception/nfqueue_linux.go +++ b/firewall/interception/nfqueue_linux.go @@ -172,7 +172,7 @@ func DeactivateNfqueueFirewall() error { } _ = nfq.DeleteAllMarkedConnection() - nfq.DeinitNFCT() + nfq.TeardownNFCT() return result.ErrorOrNil() } diff --git a/firewall/interception/windowskext/handler.go b/firewall/interception/windowskext/handler.go index e30e4498..2932a31a 100644 --- a/firewall/interception/windowskext/handler.go +++ b/firewall/interception/windowskext/handler.go @@ -29,7 +29,7 @@ const ( VerdictRequestFlagSocketAuth = 2 ) -// Do not change the order of the members! The structure to communicate with the kernel extension. +// Do not change the order of the members! The structure is used to communicate with the kernel extension. // VerdictRequest is the request structure from the Kext. type VerdictRequest struct { id uint32 // ID from RegisterPacket @@ -48,7 +48,7 @@ type VerdictRequest struct { packetSize uint32 } -// Do not change the order of the members! The structure to communicate with the kernel extension. +// Do not change the order of the members! The structure is used to communicate with the kernel extension. type VerdictInfo struct { id uint32 // ID from RegisterPacket verdict network.Verdict // verdict for the connection @@ -56,13 +56,13 @@ type VerdictInfo struct { // Do not change the order of the members! The structure to communicate with the kernel extension. type VerdictUpdateInfo struct { - localIP [4]uint32 //Source Address, only srcIP[0] if IPv4 - remoteIP [4]uint32 //Destination Address - localPort uint16 //Source Port - remotePort uint16 //Destination port - ipV6 uint8 //True: IPv6, False: IPv4 - protocol uint8 //Protocol (UDP, TCP, ...) - verdict uint8 //New verdict + localIP [4]uint32 // Source Address, only srcIP[0] if IPv4 + remoteIP [4]uint32 // Destination Address + localPort uint16 // Source Port + remotePort uint16 // Destination port + ipV6 uint8 // True: IPv6, False: IPv4 + protocol uint8 // Protocol (UDP, TCP, ...) + verdict uint8 // New verdict } type VersionInfo struct { From b1fb9e10b4c3b4033786dcc2f8f20f08d4d68ae2 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Thu, 10 Nov 2022 16:41:56 +0100 Subject: [PATCH 19/19] minor refactoring 2 --- firewall/interception/windowskext/kext.go | 2 +- firewall/interception/windowskext/service.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/firewall/interception/windowskext/kext.go b/firewall/interception/windowskext/kext.go index 33a387e7..e4ae511a 100644 --- a/firewall/interception/windowskext/kext.go +++ b/firewall/interception/windowskext/kext.go @@ -114,7 +114,7 @@ func RecvVerdictRequest() (*VerdictRequest, error) { } timestamp := time.Now() - defer log.Tracef("winkext: getting verdict request took %s", time.Now().Sub(timestamp)) + defer log.Tracef("winkext: getting verdict request took %s", time.Since(timestamp)) // Initialize struct for the output data var new VerdictRequest diff --git a/firewall/interception/windowskext/service.go b/firewall/interception/windowskext/service.go index 647753c6..ed4429e8 100644 --- a/firewall/interception/windowskext/service.go +++ b/firewall/interception/windowskext/service.go @@ -70,7 +70,7 @@ func waitForServiceStatus(handle windows.Handle, neededStatus uint32, timeLimit return false, fmt.Errorf("failed while waiting for service to start: %w", err) } - if time.Now().Sub(start) > timeLimit { + if time.Since(start) > timeLimit { return false, fmt.Errorf("time limit reached") }