Skip to content

Commit 867d0bc

Browse files
authored
Merge pull request #1536 from safing/fix/icmp+apiauth+docs+service
Fix ICMP, APIAuth, Dosc, Service
2 parents 0f808f5 + 5371350 commit 867d0bc

File tree

7 files changed

+172
-43
lines changed

7 files changed

+172
-43
lines changed

Diff for: packaging/linux/portmaster.service

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ RestartSec=10
1515
RestartPreventExitStatus=24
1616
LockPersonality=yes
1717
MemoryDenyWriteExecute=yes
18+
MemoryLow=2G
1819
NoNewPrivileges=yes
1920
PrivateTmp=yes
2021
PIDFile=/var/lib/portmaster/core-lock.pid

Diff for: service/firewall/api.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,11 @@ func apiAuthenticator(r *http.Request, s *http.Server) (token *api.AuthToken, er
7575
if err != nil {
7676
return nil, fmt.Errorf("failed to get local IP/Port: %w", err)
7777
}
78+
// Correct 0.0.0.0 to 127.0.0.1 to fix local process-based authentication,
79+
// if 0.0.0.0 is used as the API listen address.
80+
if localIP.Equal(net.IPv4zero) {
81+
localIP = net.IPv4(127, 0, 0, 1)
82+
}
7883

7984
// get remote IP/Port
8085
remoteIP, remotePort, err := netutils.ParseIPPort(r.RemoteAddr)
@@ -110,7 +115,6 @@ func apiAuthenticator(r *http.Request, s *http.Server) (token *api.AuthToken, er
110115
if !retry {
111116
break
112117
}
113-
114118
// wait a little
115119
time.Sleep(500 * time.Millisecond)
116120
}

Diff for: service/firewall/module.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ func init() {
4949
}
5050

5151
func prep() error {
52-
network.SetDefaultFirewallHandler(verdictHandler)
52+
network.SetDefaultFirewallHandler(defaultFirewallHandler)
5353

5454
// Reset connections every time configuration changes
5555
// this will be triggered on spn enable/disable

Diff for: service/firewall/packet_handler.go

+100-17
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ import (
2222
"github.com/safing/portmaster/service/network"
2323
"github.com/safing/portmaster/service/network/netutils"
2424
"github.com/safing/portmaster/service/network/packet"
25-
"github.com/safing/portmaster/service/network/reference"
2625
"github.com/safing/portmaster/service/process"
2726
"github.com/safing/portmaster/spn/access"
2827
)
@@ -227,7 +226,6 @@ func fastTrackedPermit(conn *network.Connection, pkt packet.Packet) (verdict net
227226
meta.Src.Equal(meta.Dst) {
228227
log.Tracer(pkt.Ctx()).Debugf("filter: fast-track network self-check: %s", pkt)
229228
return network.VerdictAccept, true
230-
231229
}
232230

233231
switch meta.Protocol { //nolint:exhaustive // Checking for specific values only.
@@ -374,6 +372,8 @@ func fastTrackedPermit(conn *network.Connection, pkt packet.Packet) (verdict net
374372
}
375373

376374
func fastTrackHandler(conn *network.Connection, pkt packet.Packet) {
375+
conn.SaveWhenFinished()
376+
377377
fastTrackedVerdict, permanent := fastTrackedPermit(conn, pkt)
378378
if fastTrackedVerdict != network.VerdictUndecided {
379379
// Set verdict on connection.
@@ -402,6 +402,8 @@ func fastTrackHandler(conn *network.Connection, pkt packet.Packet) {
402402
}
403403

404404
func gatherDataHandler(conn *network.Connection, pkt packet.Packet) {
405+
conn.SaveWhenFinished()
406+
405407
// Get process info
406408
_ = conn.GatherConnectionInfo(pkt)
407409
// Errors are informational and are logged to the context.
@@ -412,11 +414,20 @@ func gatherDataHandler(conn *network.Connection, pkt packet.Packet) {
412414
}
413415

414416
// Continue to filter handler, when connection data is complete.
415-
conn.UpdateFirewallHandler(filterHandler)
416-
filterHandler(conn, pkt)
417+
switch conn.IPProtocol { //nolint:exhaustive
418+
case packet.ICMP, packet.ICMPv6:
419+
conn.UpdateFirewallHandler(icmpFilterHandler)
420+
icmpFilterHandler(conn, pkt)
421+
422+
default:
423+
conn.UpdateFirewallHandler(filterHandler)
424+
filterHandler(conn, pkt)
425+
}
417426
}
418427

419428
func filterHandler(conn *network.Connection, pkt packet.Packet) {
429+
conn.SaveWhenFinished()
430+
420431
// Skip if data is not complete or packet is info-only.
421432
if !conn.DataIsComplete() || pkt.InfoOnly() {
422433
return
@@ -469,11 +480,12 @@ func filterHandler(conn *network.Connection, pkt packet.Packet) {
469480
switch {
470481
case conn.Inspecting:
471482
log.Tracer(pkt.Ctx()).Trace("filter: start inspecting")
472-
conn.SetFirewallHandler(inspectAndVerdictHandler)
483+
conn.UpdateFirewallHandler(inspectAndVerdictHandler)
473484
inspectAndVerdictHandler(conn, pkt)
485+
474486
default:
475487
conn.StopFirewallHandler()
476-
issueVerdict(conn, pkt, 0, true)
488+
verdictHandler(conn, pkt)
477489
}
478490
}
479491

@@ -529,6 +541,18 @@ func FilterConnection(ctx context.Context, conn *network.Connection, pkt packet.
529541
}
530542
}
531543

544+
// defaultFirewallHandler is used when no other firewall handler is set on a connection.
545+
func defaultFirewallHandler(conn *network.Connection, pkt packet.Packet) {
546+
switch conn.IPProtocol { //nolint:exhaustive
547+
case packet.ICMP, packet.ICMPv6:
548+
// Always use the ICMP handler for ICMP connections.
549+
icmpFilterHandler(conn, pkt)
550+
551+
default:
552+
verdictHandler(conn, pkt)
553+
}
554+
}
555+
532556
func verdictHandler(conn *network.Connection, pkt packet.Packet) {
533557
// Ignore info-only packets in this handler.
534558
if pkt.InfoOnly() {
@@ -556,24 +580,83 @@ func inspectAndVerdictHandler(conn *network.Connection, pkt packet.Packet) {
556580
issueVerdict(conn, pkt, 0, true)
557581
}
558582

583+
func icmpFilterHandler(conn *network.Connection, pkt packet.Packet) {
584+
// Load packet data.
585+
err := pkt.LoadPacketData()
586+
if err != nil {
587+
log.Tracer(pkt.Ctx()).Debugf("filter: failed to load ICMP packet data: %s", err)
588+
issueVerdict(conn, pkt, network.VerdictDrop, false)
589+
return
590+
}
591+
592+
// Submit to ICMP listener.
593+
submitted := netenv.SubmitPacketToICMPListener(pkt)
594+
if submitted {
595+
issueVerdict(conn, pkt, network.VerdictDrop, false)
596+
return
597+
}
598+
599+
// Handle echo request and replies regularly.
600+
// Other ICMP packets are considered system business.
601+
icmpLayers := pkt.Layers().LayerClass(layers.LayerClassIPControl)
602+
switch icmpLayer := icmpLayers.(type) {
603+
case *layers.ICMPv4:
604+
switch icmpLayer.TypeCode.Type() {
605+
case layers.ICMPv4TypeEchoRequest,
606+
layers.ICMPv4TypeEchoReply:
607+
// Continue
608+
default:
609+
issueVerdict(conn, pkt, network.VerdictAccept, false)
610+
return
611+
}
612+
613+
case *layers.ICMPv6:
614+
switch icmpLayer.TypeCode.Type() {
615+
case layers.ICMPv6TypeEchoRequest,
616+
layers.ICMPv6TypeEchoReply:
617+
// Continue
618+
619+
default:
620+
issueVerdict(conn, pkt, network.VerdictAccept, false)
621+
return
622+
}
623+
}
624+
625+
// Check if we already have a verdict.
626+
switch conn.Verdict { //nolint:exhaustive
627+
case network.VerdictUndecided, network.VerdictUndeterminable:
628+
// Apply privacy filter and check tunneling.
629+
FilterConnection(pkt.Ctx(), conn, pkt, true, false)
630+
631+
// Save and propagate changes.
632+
conn.SaveWhenFinished()
633+
}
634+
635+
// Outbound direction has priority.
636+
if conn.Inbound && conn.Ended == 0 && pkt.IsOutbound() {
637+
// Change direction from inbound to outbound on first outbound ICMP packet.
638+
conn.Inbound = false
639+
640+
// Apply privacy filter and check tunneling.
641+
FilterConnection(pkt.Ctx(), conn, pkt, true, false)
642+
643+
// Save and propagate changes.
644+
conn.SaveWhenFinished()
645+
}
646+
647+
issueVerdict(conn, pkt, 0, false)
648+
}
649+
559650
func issueVerdict(conn *network.Connection, pkt packet.Packet, verdict network.Verdict, allowPermanent bool) {
560651
// Check if packed was already fast-tracked by the OS integration.
561652
if pkt.FastTrackedByIntegration() {
562653
return
563654
}
564655

565656
// Enable permanent verdict.
566-
if allowPermanent && !conn.VerdictPermanent {
567-
switch {
568-
case !permanentVerdicts():
569-
// Permanent verdicts are disabled by configuration.
570-
case conn.Entity != nil && reference.IsICMP(conn.Entity.Protocol):
571-
case pkt != nil && reference.IsICMP(uint8(pkt.Info().Protocol)):
572-
// ICMP is handled differently based on payload, so we cannot use persistent verdicts.
573-
default:
574-
conn.VerdictPermanent = true
575-
conn.SaveWhenFinished()
576-
}
657+
if allowPermanent && !conn.VerdictPermanent && permanentVerdicts() {
658+
conn.VerdictPermanent = true
659+
conn.SaveWhenFinished()
577660
}
578661

579662
// do not allow to circumvent decision: e.g. to ACCEPT packets from a DROP-ed connection

Diff for: service/network/clean.go

+39-13
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ import (
1111
)
1212

1313
const (
14+
// EndConnsAfterInactiveFor defines the amount of time after not seen
15+
// connections of unsupported protocols are marked as ended.
16+
EndConnsAfterInactiveFor = 5 * time.Minute
17+
18+
// EndICMPConnsAfterInactiveFor defines the amount of time after not seen
19+
// ICMP "connections" are marked as ended.
20+
EndICMPConnsAfterInactiveFor = 1 * time.Minute
21+
1422
// DeleteConnsAfterEndedThreshold defines the amount of time after which
1523
// ended connections should be removed from the internal connection state.
1624
DeleteConnsAfterEndedThreshold = 10 * time.Minute
@@ -48,7 +56,9 @@ func cleanConnections() (activePIDs map[int]struct{}) {
4856
_ = module.RunMicroTask("clean connections", 0, func(ctx context.Context) error {
4957
now := time.Now().UTC()
5058
nowUnix := now.Unix()
51-
ignoreNewer := nowUnix - 1
59+
ignoreNewer := nowUnix - 2
60+
endNotSeenSince := now.Add(-EndConnsAfterInactiveFor).Unix()
61+
endICMPNotSeenSince := now.Add(-EndICMPConnsAfterInactiveFor).Unix()
5262
deleteOlderThan := now.Add(-DeleteConnsAfterEndedThreshold).Unix()
5363
deleteIncompleteOlderThan := now.Add(-DeleteIncompleteConnsAfterStartedThreshold).Unix()
5464

@@ -68,22 +78,37 @@ func cleanConnections() (activePIDs map[int]struct{}) {
6878
// Remove connection from state.
6979
conn.delete()
7080
}
81+
7182
case conn.Ended == 0:
7283
// Step 1: check if still active
73-
exists := state.Exists(&packet.Info{
74-
Inbound: false, // src == local
75-
Version: conn.IPVersion,
76-
Protocol: conn.IPProtocol,
77-
Src: conn.LocalIP,
78-
SrcPort: conn.LocalPort,
79-
Dst: conn.Entity.IP,
80-
DstPort: conn.Entity.Port,
81-
PID: process.UndefinedProcessID,
82-
SeenAt: time.Unix(conn.Started, 0), // State tables will be updated if older than this.
83-
}, now)
84+
var connActive bool
85+
switch conn.IPProtocol { //nolint:exhaustive
86+
case packet.TCP, packet.UDP:
87+
connActive = state.Exists(&packet.Info{
88+
Inbound: false, // src == local
89+
Version: conn.IPVersion,
90+
Protocol: conn.IPProtocol,
91+
Src: conn.LocalIP,
92+
SrcPort: conn.LocalPort,
93+
Dst: conn.Entity.IP,
94+
DstPort: conn.Entity.Port,
95+
PID: process.UndefinedProcessID,
96+
SeenAt: time.Unix(conn.Started, 0), // State tables will be updated if older than this.
97+
}, now)
98+
// Update last seen value for permanent verdict connections.
99+
if connActive && conn.VerdictPermanent {
100+
conn.lastSeen.Store(nowUnix)
101+
}
102+
103+
case packet.ICMP, packet.ICMPv6:
104+
connActive = conn.lastSeen.Load() > endICMPNotSeenSince
105+
106+
default:
107+
connActive = conn.lastSeen.Load() > endNotSeenSince
108+
}
84109

85110
// Step 2: mark as ended
86-
if !exists {
111+
if !connActive {
87112
conn.Ended = nowUnix
88113

89114
// Stop the firewall handler, in case one is running.
@@ -97,6 +122,7 @@ func cleanConnections() (activePIDs map[int]struct{}) {
97122
if conn.process != nil {
98123
activePIDs[conn.process.Pid] = struct{}{}
99124
}
125+
100126
case conn.Ended < deleteOlderThan:
101127
// Step 3: delete
102128
// DEBUG:

Diff for: service/network/connection.go

+25-10
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"net"
88
"sync"
9+
"sync/atomic"
910
"time"
1011

1112
"github.com/tevino/abool"
@@ -180,6 +181,11 @@ type Connection struct { //nolint:maligned // TODO: fix alignment
180181
// BytesSent holds the observed sent bytes of the connection.
181182
BytesSent uint64
182183

184+
// lastSeen holds the timestamp when the connection was last seen.
185+
// If permanent verdicts are enabled and bandwidth reporting is not active,
186+
// this value will likely not be correct.
187+
lastSeen atomic.Int64
188+
183189
// prompt holds the active prompt for this connection, if there is one.
184190
prompt *notifications.Notification
185191
// promptLock locks the prompt separately from the connection.
@@ -340,6 +346,7 @@ func NewConnectionFromDNSRequest(ctx context.Context, fqdn string, cnames []stri
340346
Ended: timestamp,
341347
dataComplete: abool.NewBool(true),
342348
}
349+
dnsConn.lastSeen.Store(timestamp)
343350

344351
// Inherit internal status of profile.
345352
if localProfile := proc.Profile().LocalProfile(); localProfile != nil {
@@ -383,6 +390,7 @@ func NewConnectionFromExternalDNSRequest(ctx context.Context, fqdn string, cname
383390
Ended: timestamp,
384391
dataComplete: abool.NewBool(true),
385392
}
393+
dnsConn.lastSeen.Store(timestamp)
386394

387395
// Inherit internal status of profile.
388396
if localProfile := remoteHost.Profile().LocalProfile(); localProfile != nil {
@@ -418,6 +426,7 @@ func NewIncompleteConnection(pkt packet.Packet) *Connection {
418426
PID: info.PID,
419427
dataComplete: abool.NewBool(false),
420428
}
429+
conn.lastSeen.Store(conn.Started)
421430

422431
// Bullshit check Started timestamp.
423432
if conn.Started < tooOldTimestamp {
@@ -569,6 +578,7 @@ func (conn *Connection) GatherConnectionInfo(pkt packet.Packet) (err error) {
569578
conn.dataComplete.Set()
570579
}
571580

581+
conn.SaveWhenFinished()
572582
return nil
573583
}
574584

@@ -859,6 +869,9 @@ func (conn *Connection) StopFirewallHandler() {
859869

860870
// HandlePacket queues packet of Link for handling.
861871
func (conn *Connection) HandlePacket(pkt packet.Packet) {
872+
// Update last seen timestamp.
873+
conn.lastSeen.Store(time.Now().Unix())
874+
862875
conn.pktQueueLock.Lock()
863876
defer conn.pktQueueLock.Unlock()
864877

@@ -994,17 +1007,19 @@ func packetHandlerHandleConn(ctx context.Context, conn *Connection, pkt packet.P
9941007
// Record metrics.
9951008
packetHandlingHistogram.UpdateDuration(pkt.Info().SeenAt)
9961009

997-
// Log result and submit trace.
998-
switch {
999-
case conn.DataIsComplete():
1000-
tracer.Infof("filter: connection %s %s: %s", conn, conn.VerdictVerb(), conn.Reason.Msg)
1001-
case conn.Verdict != VerdictUndecided:
1002-
tracer.Debugf("filter: connection %s fast-tracked", pkt)
1003-
default:
1004-
tracer.Debugf("filter: gathered data on connection %s", conn)
1010+
// Log result and submit trace, when there are any changes.
1011+
if conn.saveWhenFinished {
1012+
switch {
1013+
case conn.DataIsComplete():
1014+
tracer.Infof("filter: connection %s %s: %s", conn, conn.VerdictVerb(), conn.Reason.Msg)
1015+
case conn.Verdict != VerdictUndecided:
1016+
tracer.Debugf("filter: connection %s fast-tracked", pkt)
1017+
default:
1018+
tracer.Debugf("filter: gathered data on connection %s", conn)
1019+
}
1020+
// Submit trace logs.
1021+
tracer.Submit()
10051022
}
1006-
// Submit trace logs.
1007-
tracer.Submit()
10081023

10091024
// Push changes, if there are any.
10101025
if conn.saveWhenFinished {

0 commit comments

Comments
 (0)