Add windowskext integration, update related packages
This commit is contained in:
@@ -3,8 +3,12 @@ package interception
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/Safing/portmaster/firewall/interception/windivert"
|
||||
"github.com/Safing/portbase/log"
|
||||
"github.com/Safing/portbase/notifications"
|
||||
"github.com/Safing/portbase/utils/osdetail"
|
||||
"github.com/Safing/portmaster/firewall/interception/windowskext"
|
||||
"github.com/Safing/portmaster/network/packet"
|
||||
"github.com/Safing/portmaster/updates"
|
||||
)
|
||||
|
||||
var Packets chan packet.Packet
|
||||
@@ -17,15 +21,73 @@ func init() {
|
||||
// Start starts the interception.
|
||||
func Start() error {
|
||||
|
||||
wd, err := windivert.New("/WinDivert.dll", "")
|
||||
dllFile, err := updates.GetPlatformFile("kext/portmaster-kext.dll")
|
||||
if err != nil {
|
||||
return fmt.Errorf("firewall/interception: could not init windivert: %s", err)
|
||||
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)
|
||||
}
|
||||
|
||||
return wd.Packets(Packets)
|
||||
err = windowskext.Init(dllFile.Path(), kextFile.Path())
|
||||
if err != nil {
|
||||
return fmt.Errorf("interception: could not init windows kext: %s", err)
|
||||
}
|
||||
|
||||
err = windowskext.Start()
|
||||
if err != nil {
|
||||
return fmt.Errorf("interception: could not start windows kext: %s", err)
|
||||
}
|
||||
|
||||
go windowskext.Handler(Packets)
|
||||
go handleWindowsDNSCache()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop starts the interception.
|
||||
func Stop() error {
|
||||
return nil
|
||||
return windowskext.Stop()
|
||||
}
|
||||
|
||||
func handleWindowsDNSCache() {
|
||||
|
||||
err := osdetail.StopService("dnscache")
|
||||
if err != nil {
|
||||
// cannot stop dnscache, try disabling
|
||||
if err == osdetail.ErrServiceNotStoppable {
|
||||
err := osdetail.DisableDNSCache()
|
||||
if err != nil {
|
||||
log.Warningf("firewall/interception: failed to disable Windows Service \"DNS Client\" (dnscache) for better interception: %s", err)
|
||||
notifyDisableDNSCache()
|
||||
}
|
||||
notifyRebootRequired()
|
||||
return
|
||||
}
|
||||
|
||||
// error while stopping service
|
||||
log.Warningf("firewall/interception: failed to stop Windows Service \"DNS Client\" (dnscache) for better interception: %s", err)
|
||||
notifyDisableDNSCache()
|
||||
}
|
||||
|
||||
// log that service is stopped
|
||||
log.Info("firewall/interception: Windows Service \"DNS Client\" (dnscache) is stopped for better interception")
|
||||
|
||||
}
|
||||
|
||||
func notifyDisableDNSCache() {
|
||||
(¬ifications.Notification{
|
||||
ID: "windows-disable-dns-cache",
|
||||
Message: "The Portmaster needs the Windows Service \"DNS Client\" (dnscache) to be disabled for best effectiveness.",
|
||||
Type: notifications.Warning,
|
||||
}).Init().Save()
|
||||
}
|
||||
|
||||
func notifyRebootRequired() {
|
||||
(¬ifications.Notification{
|
||||
ID: "windows-dnscache-reboot-required",
|
||||
Message: "Please restart your system to complete Portmaster integration.",
|
||||
Type: notifications.Warning,
|
||||
}).Init().Save()
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/Safing/portmaster/firewall/interception/windowskext"
|
||||
)
|
||||
|
||||
func main() {
|
||||
kext, err := windowskext.New("./WinDivert.dll")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
vR, err := kext.RecvVerdictRequest()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Printf("verdictRequest: %+v", vR)
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,42 +1,3 @@
|
||||
Go-NFQueue
|
||||
==========
|
||||
Go Wrapper For Creating IPTables' NFQueue clients in Go
|
||||
|
||||
Usage
|
||||
------
|
||||
Check the `examples/main.go` file
|
||||
|
||||
```bash
|
||||
cd $GOPATH/github.com/OneOfOne/go-nfqueue/examples
|
||||
go build -race && sudo ./examples
|
||||
```
|
||||
* Open another terminal :
|
||||
```bash
|
||||
sudo iptables -I INPUT 1 -m conntrack --ctstate NEW -j NFQUEUE --queue-num 0
|
||||
#or
|
||||
sudo iptables -I INPUT -i eth0 -m conntrack --ctstate NEW -j NFQUEUE --queue-num 0
|
||||
curl --head localhost
|
||||
ping localhost
|
||||
sudo iptables -D INPUT -m conntrack --ctstate NEW -j NFQUEUE --queue-num 0
|
||||
```
|
||||
Then you can `ctrl+c` the program to exit.
|
||||
|
||||
* If you have recent enough iptables/nfqueue you could also use a balanced (multithreaded queue).
|
||||
* check the example in `examples/mq/multiqueue.go`
|
||||
|
||||
```bash
|
||||
iptables -I INPUT 1 -m conntrack --ctstate NEW -j NFQUEUE --queue-balance 0:5 --queue-cpu-fanout
|
||||
```
|
||||
Notes
|
||||
-----
|
||||
|
||||
You must run the executable as root.
|
||||
This is *WIP*, but all patches are welcome.
|
||||
|
||||
License
|
||||
-------
|
||||
go-nfqueue is under the Apache v2 license, check the included license file.
|
||||
Copyright © [Ahmed W.](http://www.limitlessfx.com/)
|
||||
See the included `LICENSE` file.
|
||||
|
||||
> Copyright (c) 2014 Ahmed W.
|
||||
Parts of this package (this directory) are forked from the go-nfqueue repo: https://github.com/OneOfOne/go-nfqueue
|
||||
These portions are copyrighted by Ahmed W.
|
||||
The (high probable) fork commit is: https://github.com/OneOfOne/go-nfqueue/commit/3bdd8bdfd98a1ed51119f9cf7494162484dfbe7c
|
||||
|
||||
@@ -1,154 +1,130 @@
|
||||
package windowskext
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"github.com/tevino/abool"
|
||||
|
||||
"github.com/Safing/portbase/log"
|
||||
"github.com/Safing/portmaster/network/packet"
|
||||
|
||||
"github.com/tevino/abool"
|
||||
)
|
||||
|
||||
func (wd *WinDivert) Packets(packets chan packet.Packet) error {
|
||||
go wd.packetHandler(packets)
|
||||
return nil
|
||||
// VerdictRequest is the request structure from the Kext.
|
||||
type VerdictRequest struct {
|
||||
id uint32 /* ID from RegisterPacket */
|
||||
processID uint64 /* Process ID. Nice to have*/
|
||||
direction uint8
|
||||
ipV6 uint8 /* True: IPv6, False: IPv4 */
|
||||
protocol uint8 /* Protocol */
|
||||
_ uint8
|
||||
localIP [4]uint32 /* Source Address */
|
||||
remoteIP [4]uint32 /* Destination Address */
|
||||
localPort uint16 /* Source Port */
|
||||
remotePort uint16 /* Destination port */
|
||||
compartmentId uint32
|
||||
interfaceIndex uint32
|
||||
subInterfaceIndex uint32
|
||||
packetSize uint32
|
||||
}
|
||||
|
||||
func (wd *WinDivert) packetHandler(packets chan packet.Packet) {
|
||||
// Handler transforms received packets to the Packet interface.
|
||||
func Handler(packets chan packet.Packet) {
|
||||
if !ready.IsSet() {
|
||||
return
|
||||
}
|
||||
|
||||
defer close(packets)
|
||||
|
||||
for {
|
||||
if !wd.valid.IsSet() {
|
||||
if !ready.IsSet() {
|
||||
return
|
||||
}
|
||||
|
||||
packetData, packetAddress, err := wd.Recv()
|
||||
packetInfo, err := RecvVerdictRequest()
|
||||
if err != nil {
|
||||
log.Warningf("failed to get packet from windivert: %s", err)
|
||||
log.Warningf("failed to get packet from windows kext: %s", err)
|
||||
continue
|
||||
}
|
||||
|
||||
ipHeader, tpcUdpHeader, payload, err := parseIpPacket(packetData)
|
||||
if err != nil {
|
||||
log.Warningf("failed to parse packet from windivert: %s", err)
|
||||
log.Warningf("failed packet payload (%d): %s", len(packetData), string(packetData))
|
||||
if packetInfo == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// log.Tracef("packet: %+v", packetInfo)
|
||||
|
||||
// New Packet
|
||||
new := &Packet{
|
||||
windivert: wd,
|
||||
packetData: packetData,
|
||||
packetAddress: packetAddress,
|
||||
verdictSet: abool.NewBool(false),
|
||||
verdictRequest: packetInfo,
|
||||
verdictSet: abool.NewBool(false),
|
||||
}
|
||||
new.IPHeader = ipHeader
|
||||
new.TCPUDPHeader = tpcUdpHeader
|
||||
new.Payload = payload
|
||||
if packetAddress.Direction == directionInbound {
|
||||
new.Direction = packet.InBound
|
||||
|
||||
info := new.Info()
|
||||
info.Direction = packetInfo.direction > 0
|
||||
info.InTunnel = false
|
||||
info.Protocol = packet.IPProtocol(packetInfo.protocol)
|
||||
|
||||
// IP version
|
||||
if packetInfo.ipV6 == 1 {
|
||||
info.Version = packet.IPv6
|
||||
} else {
|
||||
new.Direction = packet.OutBound
|
||||
info.Version = packet.IPv4
|
||||
}
|
||||
|
||||
// IPs
|
||||
if info.Version == packet.IPv4 {
|
||||
// IPv4
|
||||
if info.Direction {
|
||||
// Inbound
|
||||
info.Src = convertIPv4(packetInfo.remoteIP)
|
||||
info.Dst = convertIPv4(packetInfo.localIP)
|
||||
} else {
|
||||
// Outbound
|
||||
info.Src = convertIPv4(packetInfo.localIP)
|
||||
info.Dst = convertIPv4(packetInfo.remoteIP)
|
||||
}
|
||||
} else {
|
||||
// IPv6
|
||||
if info.Direction {
|
||||
// Inbound
|
||||
info.Src = convertIPv6(packetInfo.remoteIP)
|
||||
info.Dst = convertIPv6(packetInfo.localIP)
|
||||
} else {
|
||||
// Outbound
|
||||
info.Src = convertIPv6(packetInfo.localIP)
|
||||
info.Dst = convertIPv6(packetInfo.remoteIP)
|
||||
}
|
||||
}
|
||||
|
||||
// Ports
|
||||
if info.Direction {
|
||||
// Inbound
|
||||
info.SrcPort = packetInfo.remotePort
|
||||
info.DstPort = packetInfo.localPort
|
||||
} else {
|
||||
// Outbound
|
||||
info.SrcPort = packetInfo.localPort
|
||||
info.DstPort = packetInfo.remotePort
|
||||
}
|
||||
|
||||
packets <- new
|
||||
}
|
||||
}
|
||||
|
||||
func parseIpPacket(packetData []byte) (ipHeader *packet.IPHeader, tpcUdpHeader *packet.TCPUDPHeader, payload []byte, err error) {
|
||||
|
||||
var parsedPacket gopacket.Packet
|
||||
|
||||
if len(packetData) == 0 {
|
||||
return nil, nil, nil, errors.New("empty packet")
|
||||
}
|
||||
|
||||
switch packetData[0] >> 4 {
|
||||
case 4:
|
||||
parsedPacket = gopacket.NewPacket(packetData, layers.LayerTypeIPv4, gopacket.DecodeOptions{Lazy: true, NoCopy: true})
|
||||
if ipv4Layer := parsedPacket.Layer(layers.LayerTypeIPv4); ipv4Layer != nil {
|
||||
ipv4, _ := ipv4Layer.(*layers.IPv4)
|
||||
ipHeader = &packet.IPHeader{
|
||||
Version: 4,
|
||||
Protocol: packet.IPProtocol(ipv4.Protocol),
|
||||
Tos: ipv4.TOS,
|
||||
TTL: ipv4.TTL,
|
||||
Src: ipv4.SrcIP,
|
||||
Dst: ipv4.DstIP,
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
if errLayer := parsedPacket.ErrorLayer(); errLayer != nil {
|
||||
err = errLayer.Error()
|
||||
}
|
||||
return nil, nil, nil, fmt.Errorf("failed to parse IPv4 packet: %s", err)
|
||||
}
|
||||
case 6:
|
||||
parsedPacket = gopacket.NewPacket(packetData, layers.LayerTypeIPv6, gopacket.DecodeOptions{Lazy: true, NoCopy: true})
|
||||
if ipv6Layer := parsedPacket.Layer(layers.LayerTypeIPv6); ipv6Layer != nil {
|
||||
ipv6, _ := ipv6Layer.(*layers.IPv6)
|
||||
ipHeader = &packet.IPHeader{
|
||||
Version: 6,
|
||||
Protocol: packet.IPProtocol(ipv6.NextHeader),
|
||||
Tos: ipv6.TrafficClass,
|
||||
TTL: ipv6.HopLimit,
|
||||
Src: ipv6.SrcIP,
|
||||
Dst: ipv6.DstIP,
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
if errLayer := parsedPacket.ErrorLayer(); errLayer != nil {
|
||||
err = errLayer.Error()
|
||||
}
|
||||
return nil, nil, nil, fmt.Errorf("failed to parse IPv6 packet: %s", err)
|
||||
}
|
||||
default:
|
||||
return nil, nil, nil, errors.New("unknown IP version")
|
||||
}
|
||||
|
||||
switch ipHeader.Protocol {
|
||||
case packet.TCP:
|
||||
if tcpLayer := parsedPacket.Layer(layers.LayerTypeTCP); tcpLayer != nil {
|
||||
tcp, _ := tcpLayer.(*layers.TCP)
|
||||
tpcUdpHeader = &packet.TCPUDPHeader{
|
||||
SrcPort: uint16(tcp.SrcPort),
|
||||
DstPort: uint16(tcp.DstPort),
|
||||
Checksum: tcp.Checksum,
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
if errLayer := parsedPacket.ErrorLayer(); errLayer != nil {
|
||||
err = errLayer.Error()
|
||||
}
|
||||
return nil, nil, nil, fmt.Errorf("could not parse TCP layer: %s", err)
|
||||
}
|
||||
case packet.UDP:
|
||||
if udpLayer := parsedPacket.Layer(layers.LayerTypeUDP); udpLayer != nil {
|
||||
udp, _ := udpLayer.(*layers.UDP)
|
||||
tpcUdpHeader = &packet.TCPUDPHeader{
|
||||
SrcPort: uint16(udp.SrcPort),
|
||||
DstPort: uint16(udp.DstPort),
|
||||
Checksum: udp.Checksum,
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
if errLayer := parsedPacket.ErrorLayer(); errLayer != nil {
|
||||
err = errLayer.Error()
|
||||
}
|
||||
return nil, nil, nil, fmt.Errorf("could not parse UDP layer: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
if appLayer := parsedPacket.ApplicationLayer(); appLayer != nil {
|
||||
payload = appLayer.Payload()
|
||||
}
|
||||
|
||||
if errLayer := parsedPacket.ErrorLayer(); errLayer != nil {
|
||||
return nil, nil, nil, errLayer.Error()
|
||||
}
|
||||
|
||||
return
|
||||
func convertIPv4(input [4]uint32) net.IP {
|
||||
return net.IPv4(
|
||||
uint8(input[0]>>24&0xFF),
|
||||
uint8(input[0]>>16&0xFF),
|
||||
uint8(input[0]>>8&0xFF),
|
||||
uint8(input[0]&0xFF),
|
||||
)
|
||||
}
|
||||
|
||||
func convertIPv6(input [4]uint32) net.IP {
|
||||
addressBuf := make([]byte, 16)
|
||||
for i := 0; i < 4; i++ {
|
||||
binary.BigEndian.PutUint32(addressBuf[i:i+3], input[i])
|
||||
}
|
||||
return net.IP(addressBuf)
|
||||
}
|
||||
|
||||
@@ -1,61 +1,206 @@
|
||||
package windowskext
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Safing/portmaster/network"
|
||||
"github.com/tevino/abool"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// Package errors
|
||||
var (
|
||||
ErrKextNotReady = errors.New("the windows kernel extension (driver) is not ready to accept commands")
|
||||
|
||||
kext *WinKext
|
||||
kextLock sync.RWMutex
|
||||
ready = abool.NewBool(false)
|
||||
)
|
||||
|
||||
// WinKext holds the DLL handle.
|
||||
type WinKext struct {
|
||||
dll *windows.DLL
|
||||
sync.RWMutex
|
||||
|
||||
dll *windows.DLL
|
||||
driverPath string
|
||||
|
||||
init *windows.Proc
|
||||
start *windows.Proc
|
||||
stop *windows.Proc
|
||||
recvVerdictRequest *windows.Proc
|
||||
|
||||
valid *abool.AtomicBool
|
||||
setVerdict *windows.Proc
|
||||
getPayload *windows.Proc
|
||||
}
|
||||
|
||||
type VerdictRequest struct {
|
||||
ID uint32
|
||||
ProcessID uint32
|
||||
Direction bool
|
||||
IPv6 bool
|
||||
Protocol uint8
|
||||
SrcIP [4]uint32
|
||||
DstIP [4]uint32
|
||||
SrcPort uint16
|
||||
DstPort uint16
|
||||
}
|
||||
// Init initializes the DLL and the Kext (Kernel Driver).
|
||||
func Init(dllPath, driverPath string) error {
|
||||
|
||||
func New(dllLocation string) (*WinKext, error) {
|
||||
new := &WinKext{
|
||||
driverPath: driverPath,
|
||||
}
|
||||
|
||||
new := &WinKext{}
|
||||
var err error
|
||||
|
||||
// load dll
|
||||
new.dll, err = windows.LoadDLL(dllLocation)
|
||||
new.dll, err = windows.LoadDLL(dllPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
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 nil, fmt.Errorf("could not find proc PortmasterRecvVerdictRequest: %s", err)
|
||||
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)
|
||||
}
|
||||
|
||||
return new, nil
|
||||
// initialize dll/kext
|
||||
rc, _, lastErr := new.init.Call()
|
||||
if rc != windows.NO_ERROR {
|
||||
return formatErr(lastErr)
|
||||
}
|
||||
|
||||
// set kext
|
||||
kextLock.Lock()
|
||||
defer kextLock.Unlock()
|
||||
kext = new
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (kext *WinKext) RecvVerdictRequest() (*VerdictRequest, error) {
|
||||
// Start intercepting.
|
||||
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
|
||||
|
||||
rc, _, lastErr := kext.start.Call(
|
||||
uintptr(unsafe.Pointer(&charArray[0])),
|
||||
)
|
||||
if rc != windows.NO_ERROR {
|
||||
return formatErr(lastErr)
|
||||
}
|
||||
|
||||
ready.Set()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop intercepting.
|
||||
func Stop() error {
|
||||
kextLock.Lock()
|
||||
defer kextLock.Unlock()
|
||||
if !ready.IsSet() {
|
||||
return ErrKextNotReady
|
||||
}
|
||||
ready.UnSet()
|
||||
|
||||
rc, _, lastErr := kext.stop.Call()
|
||||
if rc != windows.NO_ERROR {
|
||||
return formatErr(lastErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecvVerdictRequest waits for the next verdict request from the kext. If a timeout is reached, both *VerdictRequest and error will be nil.
|
||||
func RecvVerdictRequest() (*VerdictRequest, error) {
|
||||
kextLock.RLock()
|
||||
defer kextLock.RUnlock()
|
||||
if !ready.IsSet() {
|
||||
return nil, ErrKextNotReady
|
||||
}
|
||||
|
||||
new := &VerdictRequest{}
|
||||
|
||||
rc, _, lastErr := kext.recvVerdictRequest.Call(
|
||||
uintptr(unsafe.Pointer(new)),
|
||||
)
|
||||
if rc != 0 {
|
||||
return nil, lastErr
|
||||
if rc == 13 /* ERROR_INVALID_DATA */ {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, formatErr(lastErr)
|
||||
}
|
||||
return new, nil
|
||||
}
|
||||
|
||||
// SetVerdict sets the verdict for a packet and/or connection.
|
||||
func SetVerdict(packetID uint32, verdict network.Verdict) error {
|
||||
kextLock.RLock()
|
||||
defer kextLock.RUnlock()
|
||||
if !ready.IsSet() {
|
||||
return ErrKextNotReady
|
||||
}
|
||||
|
||||
rc, _, lastErr := kext.setVerdict.Call(
|
||||
uintptr(packetID),
|
||||
uintptr(verdict),
|
||||
)
|
||||
if rc != windows.NO_ERROR {
|
||||
return formatErr(lastErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetPayload returns the payload of a packet.
|
||||
func GetPayload(packetID uint32, packetSize uint32) ([]byte, error) {
|
||||
kextLock.RLock()
|
||||
defer kextLock.RUnlock()
|
||||
if !ready.IsSet() {
|
||||
return nil, ErrKextNotReady
|
||||
}
|
||||
|
||||
buf := make([]byte, packetSize)
|
||||
|
||||
rc, _, lastErr := kext.getPayload.Call(
|
||||
uintptr(packetID),
|
||||
uintptr(unsafe.Pointer(&buf[0])),
|
||||
uintptr(unsafe.Pointer(&packetSize)),
|
||||
)
|
||||
if rc != windows.NO_ERROR {
|
||||
return nil, formatErr(lastErr)
|
||||
}
|
||||
|
||||
if packetSize == 0 {
|
||||
return nil, errors.New("windows kext did not return any data")
|
||||
}
|
||||
|
||||
if packetSize < uint32(len(buf)) {
|
||||
return buf[:packetSize], nil
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
func formatErr(err error) error {
|
||||
sysErr, ok := err.(syscall.Errno)
|
||||
if ok {
|
||||
return fmt.Errorf("%s [0x%X]", err, uintptr(sysErr))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,55 +1,108 @@
|
||||
package windowskext
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/tevino/abool"
|
||||
|
||||
"github.com/Safing/portbase/log"
|
||||
"github.com/Safing/portmaster/network"
|
||||
"github.com/Safing/portmaster/network/packet"
|
||||
)
|
||||
|
||||
// Packet represents an IP packet.
|
||||
type Packet struct {
|
||||
packet.PacketBase
|
||||
|
||||
kextID uint32
|
||||
packetData []byte
|
||||
verdictRequest *VerdictRequest
|
||||
verdictSet *abool.AtomicBool
|
||||
|
||||
verdictSet *abool.AtomicBool
|
||||
payloadLoaded bool
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
// GetPayload returns the full raw packet.
|
||||
func (pkt *Packet) GetPayload() ([]byte, error) {
|
||||
pkt.lock.Lock()
|
||||
defer pkt.lock.Unlock()
|
||||
|
||||
if !pkt.payloadLoaded {
|
||||
pkt.payloadLoaded = true
|
||||
|
||||
payload, err := GetPayload(pkt.verdictRequest.id, pkt.verdictRequest.packetSize)
|
||||
if err != nil {
|
||||
log.Errorf("windowskext: failed to load payload %s", err)
|
||||
return nil, packet.ErrFailedToLoadPayload
|
||||
}
|
||||
pkt.Payload = payload
|
||||
}
|
||||
|
||||
if len(pkt.Payload) == 0 {
|
||||
return nil, packet.ErrFailedToLoadPayload
|
||||
}
|
||||
return pkt.Payload, nil
|
||||
}
|
||||
|
||||
// Accept accepts the packet.
|
||||
func (pkt *Packet) Accept() error {
|
||||
if pkt.verdictSet.SetToIf(false, true) {
|
||||
return pkt.windivert.Send(pkt.packetData, pkt.packetAddress)
|
||||
return SetVerdict(pkt.verdictRequest.id, -network.VerdictAccept)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Block blocks the packet.
|
||||
func (pkt *Packet) Block() error {
|
||||
if pkt.verdictSet.SetToIf(false, true) {
|
||||
// TODO: implement blocking mechanism
|
||||
return nil
|
||||
return SetVerdict(pkt.verdictRequest.id, -network.VerdictBlock)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Drop drops the packet.
|
||||
func (pkt *Packet) Drop() error {
|
||||
if pkt.verdictSet.SetToIf(false, true) {
|
||||
return SetVerdict(pkt.verdictRequest.id, -network.VerdictDrop)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PermanentAccept permanently accepts connection (and the current packet).
|
||||
func (pkt *Packet) PermanentAccept() error {
|
||||
return pkt.Accept()
|
||||
if pkt.verdictSet.SetToIf(false, true) {
|
||||
return SetVerdict(pkt.verdictRequest.id, network.VerdictAccept)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PermanentBlock permanently blocks connection (and the current packet).
|
||||
func (pkt *Packet) PermanentBlock() error {
|
||||
return pkt.Block()
|
||||
if pkt.verdictSet.SetToIf(false, true) {
|
||||
return SetVerdict(pkt.verdictRequest.id, network.VerdictBlock)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PermanentDrop permanently drops connection (and the current packet).
|
||||
func (pkt *Packet) PermanentDrop() error {
|
||||
return pkt.Drop()
|
||||
if pkt.verdictSet.SetToIf(false, true) {
|
||||
return SetVerdict(pkt.verdictRequest.id, network.VerdictDrop)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RerouteToNameserver permanently reroutes the connection to the local nameserver (and the current packet).
|
||||
func (pkt *Packet) RerouteToNameserver() error {
|
||||
if pkt.verdictSet.SetToIf(false, true) {
|
||||
return SetVerdict(pkt.verdictRequest.id, network.VerdictRerouteToNameserver)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RerouteToTunnel permanently reroutes the connection to the local tunnel entrypoint (and the current packet).
|
||||
func (pkt *Packet) RerouteToTunnel() error {
|
||||
if pkt.verdictSet.SetToIf(false, true) {
|
||||
return SetVerdict(pkt.verdictRequest.id, network.VerdictRerouteToTunnel)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
26
firewall/interception/windowskext/test/endian/main.go
Normal file
26
firewall/interception/windowskext/test/endian/main.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const integerSize int = int(unsafe.Sizeof(0))
|
||||
|
||||
func isBigEndian() bool {
|
||||
var i int = 0x1
|
||||
bs := (*[integerSize]byte)(unsafe.Pointer(&i))
|
||||
if bs[0] == 0 {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
if isBigEndian() {
|
||||
fmt.Println("System is Big Endian (Network Byte Order): uint16 0x1234 is 0x1234 in memory")
|
||||
} else {
|
||||
fmt.Println("System is Little Endian (Host Byte Order): uint16 0x1234 is 0x3412 in memory")
|
||||
}
|
||||
}
|
||||
110
firewall/interception/windowskext/test/main.go
Normal file
110
firewall/interception/windowskext/test/main.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/Safing/portbase/log"
|
||||
"github.com/Safing/portmaster/firewall/interception/windowskext"
|
||||
"github.com/Safing/portmaster/network/packet"
|
||||
)
|
||||
|
||||
var (
|
||||
packets chan packet.Packet
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
// check parameter count
|
||||
if len(os.Args) < 3 {
|
||||
fmt.Printf("usage: %s <dll> <sys>", os.Args[0])
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// check parameters
|
||||
for i := 1; i < 3; i++ {
|
||||
if _, err := os.Stat(os.Args[i]); err != nil {
|
||||
fmt.Printf("could not access %s: %s", os.Args[i], err)
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
// logging
|
||||
log.Start()
|
||||
log.Info("starting Portmaster Windows Kext Test Program")
|
||||
|
||||
// init
|
||||
err := windowskext.Init(os.Args[1], os.Args[2])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// start
|
||||
err = windowskext.Start()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
packets = make(chan packet.Packet, 1000)
|
||||
go windowskext.Handler(packets)
|
||||
go handlePackets()
|
||||
|
||||
// catch interrupt for clean shutdown
|
||||
signalCh := make(chan os.Signal)
|
||||
signal.Notify(
|
||||
signalCh,
|
||||
os.Interrupt,
|
||||
syscall.SIGHUP,
|
||||
syscall.SIGINT,
|
||||
syscall.SIGTERM,
|
||||
syscall.SIGQUIT,
|
||||
)
|
||||
<-signalCh
|
||||
fmt.Println(" <INTERRUPT>")
|
||||
log.Warning("program was interrupted, shutting down")
|
||||
|
||||
// stop
|
||||
err = windowskext.Stop()
|
||||
if err != nil {
|
||||
fmt.Printf("error stopping: %s\n", err)
|
||||
}
|
||||
|
||||
log.Info("shutdown complete")
|
||||
log.Shutdown()
|
||||
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func handlePackets() {
|
||||
for {
|
||||
pkt := <-packets
|
||||
|
||||
if pkt == nil {
|
||||
log.Infof("stopped handling packets")
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("received packet: %s", pkt)
|
||||
|
||||
data, err := pkt.GetPayload()
|
||||
if err != nil {
|
||||
log.Errorf("failed to get payload: %s", err)
|
||||
} else {
|
||||
log.Infof("payload is: %x", data)
|
||||
}
|
||||
|
||||
// reroute dns requests to nameserver
|
||||
if pkt.IsOutbound() && !pkt.Info().Src.Equal(pkt.Info().Dst) && pkt.Info().DstPort == 53 {
|
||||
log.Infof("rerouting %s", pkt)
|
||||
pkt.RerouteToNameserver()
|
||||
continue
|
||||
}
|
||||
|
||||
// accept all
|
||||
log.Infof("accepting %s", pkt)
|
||||
pkt.PermanentAccept()
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user