Commit Graph

30 Commits

Author SHA1 Message Date
Alexandr Stelnykovych 809ad61c42 feat(spn/navigator): add port and protocol to route simulation
Without a port or protocol, rules with a port never matched, so hubs
whose exit policy allows only some ports were always disregarded.

- Add "port" and "protocol" query parameters; parse "encrypted"
  (default: derived from the port, as the firewall does).
- Move the encrypted port list to netutils.IsEncryptedPort.
- Show the simulation inputs and what is not simulated.
- Note that routes do not apply with the "home" routing algorithm.
- Fix the disclaimer and the Connection.Encrypted comment.

Example:
  http://127.0.0.1:817/api/v1/spn/map/main/route/to/example.com?profile=global&port=443&protocol=tcp&encrypted=true
2026-11-20 14:23:16 +02:00
Alexandr Stelnykovych 42366c0d59 fix(linux): cache socket owners, scan /proc once per socket at a time
Issue:
Finding the process of a socket walks /proc/<pid>/fd of every process of the
user. The result was stored on the socket-table entry, which is replaced on
every table refresh (up to 100 per second), so every new connection of a
long-lived socket - a torrent's DHT socket, a listening socket, a resolver -
triggered a full scan. Under a burst, thousands of scans ran at once and
slowed each other down until packets timed out while their lookup was still
running; the connections with a lookup in flight were the memory growth
reported in #2233.

Change:
- Cache the found owner by socket inode for 1-2 s (two generations, lazy
  rotation, bounded size). A cache hit is only used if the PID is still in
  the user's PID list, so an exited owner is scanned for again.
- Run at most one scan per socket at a time (singleflight). Lookups that
  arrive while a scan runs wait for its result instead of scanning too.
  Without this the first scan under a burst never finished.
2026-10-14 17:51:18 +03:00
Alexandr Stelnykovych df06892918 firewall (Linux): skip packets that already have a verdict, drop packets that cannot be queued
Packets that received a verdict while waiting in a queue (the default-drop
after the 20 s verdict timeout) cannot be influenced anymore. Handling them
only created connections, handler workers and "verdict already set" noise,
which made a backlog grow instead of drain.

- packet.Packet gains VerdictSet(). nfqueue and both Windows kext packet
  types report their verdict flag; the base type reports false.
- The dispatcher and the per-connection handler skip packets whose verdict
  is already set.
- nfqueue: a packet that could not be handed to the handler queue within
  1 s will never get a verdict. Drop it right away instead of starting a
  watchdog and keeping it in the kernel queue for 20 s.

This reduces wasted work and log noise under load.

Refs #2233
2026-10-14 15:25:07 +03:00
Alexandr Stelnykovych b61887ba77 Merge pull request #2272 from safing/fix/2066-dns-local-bind
fix(resolver): bind local port before pre-authenticating it (#2066)
2026-10-02 15:11:29 +03:00
Alexandr Stelnykovych 702ef660fa Merge pull request #2279 from safing/fix/2233-1870-LINUX-high-mem-usage-on-conns-burst
fix(network; Linux): fix high memory usage on connection bursts
2026-10-02 15:10:03 +03:00
Alexandr Stelnykovych 6a167b33d5 fix(network; Linux): drop both hint generations when taking a pid hint
SavePIDHint() always writes into the current generation and never checks
the previous one. When the same connection reports an info-only packet
before and after a rotation, both generations hold an entry for its ID.

takePIDHint() removed only the entry it returned. A later take for the
same connection ID then found the older entry in the previous generation
and returned a stale pid instead of a miss.

Delete the connection ID from the previous generation as well when the
current one is consumed. Add a regression test that saves a hint, rotates,
saves a newer hint for the same connection and checks that the second take
is a miss.
2026-10-02 15:07:43 +03:00
Alexandr Stelnykovych b46db6e793 fix(profile): handle failed profile lookups without leaving connections unverdicted
Related ticket: #2275 (and potentially #2253)

A failed profile lookup (e.g. a database query timeout) could leave a
process without a usable profile. Depending on the path, this either
crashed the connection handler with a nil pointer dereference or left
the connection waiting for a profile that was never looked up again.
In both cases the connection never received a verdict. On Windows the
kext then holds the pended connection and the process cannot exit.

- profile: on a failed layer update, keep the previous local profile
  instead of setting it to nil. The layer stays outdated and the update
  is retried on the next connection.
- profile: wrap the iterator error instead of the stale outer variable,
  so the real cause is logged instead of "%!w(<nil>)".
- database/iterator: store the error before closing the channels, so a
  consumer calling Err() right after the range loop always sees it.
  Otherwise a failed profile query could be mistaken for "no match" and
  create a duplicate profile.
- network: do not wait for a profile when gathering connection info.
  The lookup runs once per connection and is not retried, so a
  connection without profile is now denied ("unknown process or
  profile"), same as DNS requests already were.
- network: guard the local profile dereference in the domain lookup.
- process: return the profile lookup error from GetProcessWithProfile
  alongside the process, so API handlers fail with an error instead of
  panicking on a nil profile.
- network: skip connections without profile in the debug data export.
2026-09-29 18:19:33 +03:00
Alexandr Stelnykovych 0761ba7b1e fix(resolver): bind local port before pre-authenticating it (#2066)
Portmaster pre-authenticated a randomly chosen local port for its own DNS
queries before binding it. When the port could not be bound, for example
because it lies in a Hyper-V excluded port range on Windows or is held by
another process, the query failed and counted against the resolver.

Plain DNS now binds a socket first, with a port chosen by the OS, and
pre-authenticates that port before sending. DNS over TCP and TLS retry
with another port when binding fails, and the failed port is skipped by
port selection for an hour. A bind failure no longer counts against the
resolver or the network state, as nothing left the host.
Pre-authentication entries that were never consumed are removed again.

Co-authored-by: DannyA <11684554+dannyagostinelli@users.noreply.github.com>
2026-09-25 17:20:36 +03:00
Alexandr Stelnykovych a496665d1b fix(network; Linux): keep packet order when pulling forward info-only packets
When the first packet of a new outbound connection arrives before its
info-only packet, packetHandlerWorker() briefly waits for that info-only
packet so the process is known before the real packet is evaluated.

The pulled packet was handed to packetHandlerHandleConn() unconditionally,
without checking what it actually was. When the info-only packet did not
arrive in time and a second real packet was queued instead, that packet was
handled - and its verdict issued - before the packet that started the wait.
nfqueue applies verdicts per packet ID, so the kernel then reinjected the two
packets in the wrong order.

Only handle the pulled packet immediately if it is info-only. Info-only
packets never receive a verdict, so applying one early affects nothing on the
wire. A real packet is instead held and handled after the packet that started
the wait, preserving the order in which the interception delivered them.
2026-09-09 18:18:48 +03:00
Alexandr Stelnykovych 090d3bfdfd fix(network;Linux): fix high memory usage on connection bursts
On Linux, memory usage grows without bound during bursts of new connections and
does not recover for a long time afterwards, up to and including exhausting all
available memory on the machine.

Cause: the eBPF connection listener emits an info-only packet for every observed
connect(). handlePacket() treated these like real packets and called
NewIncompleteConnection() + SetFirewallHandler(), which allocates a Connection,
a 100-slot packet queue and a goroutine per event, and registers the connection
in the store.

An info-only packet can never complete a connection: GatherConnectionInfo()
returns early, dataComplete is never set, no verdict is issued and Save() is a
no-op. Its only durable contribution is the PID, which lets the first real
packet skip process.GetPidOfConnection() and its socket table scan. When no real
packet follows - a connect() that fails, a UDP socket that never sends, or a SYN
dropped under load - the connection is only reclaimed by the cleaner after
DeleteIncompleteConnsAfterStartedThreshold. Under a burst, each such event
therefore holds a goroutine and its allocations for that entire timeout, which
is what drives the memory growth and the slow recovery.

Keep only the reported PID instead, in a small cache keyed by connection ID and
expired by a two-generation swap, so entries cost a fraction of a connection
object and are bounded by the arrival rate over a couple of seconds, with no
timers and no scanning. NewIncompleteConnection() adopts the hint when the
packet carries no PID of its own, so the real-packet path and process
attribution are unchanged.

Also guard the info-only pull-forward in packetHandlerWorker() with !pidKnown.
Info-only packets no longer start workers, so the first queued packet is now
always a real packet and the branch would otherwise be entered for every new
outbound connection, adding a wait for an info packet that was already consumed
as a hint.

Note: Windows kext v1 (old version) also reports info-only packets (WFP socket auth), so this
path is active there too; kext v2 and other platforms are unaffected.

https://github.com/safing/portmaster/issues/2233
https://github.com/safing/portmaster/issues/1870
2026-09-09 18:01:28 +03:00
Alexandr Stelnykovych ee8cde31f6 feat: Add Split Tunnel feature (Windows PoC)
Implement initial proof-of-concept for split tunnel functionality on Windows,
allowing applications to route traffic through a designated network interface
while bypassing default system routing.

Features:
- Split tunnel module with TCP/UDP proxy infrastructure
- Firewall integration with split tunnel verdict handling
- SplitTunneling context attached to connections
- Configuration options: enable toggle, interface selection, and policy rules
- UI display of split tunnel connection details in connection info panel
- Subsystem configuration for user-level access

Windows-specific implementation:
- Uses proxy-based interface routing on Windows
- Automatic or manual interface detection and binding
- Support for IPv4 and IPv6 traffic

Note: Linux implementation is under development. SPN takes precedence over
split tunnel when both are enabled, ensuring SPN connections bypass this feature.
2026-04-24 18:04:01 +03:00
Alexandr Stelnykovych 933323d5f9 feat: add VerdictRerouteToSplitTun verdict type
Add a new verdict (value 8) for routing connections through the split
tunnel. This prepares the infrastructure for the upcoming split-tunneling
feature without implementing the full feature yet.

Changes:
- Define VerdictRerouteToSplitTun in network/status.go with String() and Verb()
- Add RerouteToSplitTun() to the Packet interface and InfoPacket stub
- Implement RerouteToSplitTun() for windowskext (v1) and windowskext2 (v2) packets
- Map VerdictRerouteToSplitTun to KextVerdict 11 in kextinterface and kext2
- Handle the verdict in packet_handler.go dispatch, connection.go, api.go,
  metrics.go and nameserver.go
- Add VerdictRerouteToSplitTun = 8 to Angular Verdict enum and update
  stats counting, filter queries and verdict CSS class

(WIP) Note: Linux (nfq) implementation not updated yet. Therefore Linux build will fail.
2026-04-17 20:48:48 +03:00
Daniel 38d84b57b4 Use CallLimiter2 2025-04-07 14:23:58 +02:00
Vladimir Stoilov 59a106b9f2 Merge branch 'develop' into feature/new-installer 2025-01-27 17:26:00 +02:00
Vladimir Stoilov 0f28af66cd Add PID in ETW DNS event in the integration dll (#1768)
* [service] Add reading of PID in ETW DNS event

* [service] Use PID of the ETW DNS events

* [service] Fix use of nil pointer

* [service] Fix compiler error
2025-01-27 17:21:54 +02:00
Vladimir Stoilov 5039e9efca Merge branch 'develop' into feature/new-installer 2025-01-14 16:59:21 +02:00
Vladimir Stoilov 0997f1ce26 Fix broadcast notifications 2024-12-11 16:13:06 +02:00
Vladimir Stoilov ed2338fdb9 [service] Fix error on unitilized dns monitor 2024-12-02 15:25:58 +02:00
Vladimir Stoilov 374c1c2748 Merge branch 'develop' into feature/new-installer 2024-11-28 13:23:13 +02:00
Vladimir Stoilov 1a1bc14804 Feature/systemd query events (#1728)
* [service] Subscribe to systemd-resolver events

* [service] Add disabled state to the resolver

* [service] Add ETW DNS event listener

* [service] DNS listener refactoring

* [service] Add windows core dll project

* [service] DNSListener refactoring, small bugfixes

* [service] Change dns bypass rule

* [service] Update gitignore

* [service] Remove shim from integration module

* [service] Add DNS packet analyzer

* [service] Add self-check in dns monitor

* [service] Fix go linter errors

* [CI] Add github workflow for the windows core dll

* [service] Minor fixes to the dns monitor
2024-11-27 17:10:47 +02:00
Vladimir Stoilov 9bae1afd73 [WIP] New updater first working prototype 2024-09-05 10:25:57 +03:00
Daniel Hååvi 80664d1a27 Restructure modules (#1572)
* Move portbase into monorepo

* Add new simple module mgr

* [WIP] Switch to new simple module mgr

* Add StateMgr and more worker variants

* [WIP] Switch more modules

* [WIP] Switch more modules

* [WIP] swtich more modules

* [WIP] switch all SPN modules

* [WIP] switch all service modules

* [WIP] Convert all workers to the new module system

* [WIP] add new task system to module manager

* [WIP] Add second take for scheduling workers

* [WIP] Add FIXME for bugs in new scheduler

* [WIP] Add minor improvements to scheduler

* [WIP] Add new worker scheduler

* [WIP] Fix more bug related to new module system

* [WIP] Fix start handing of the new module system

* [WIP] Improve startup process

* [WIP] Fix minor issues

* [WIP] Fix missing subsystem in settings

* [WIP] Initialize managers in constructor

* [WIP] Move module event initialization to constrictors

* [WIP] Fix setting for enabling and disabling the SPN module

* [WIP] Move API registeration into module construction

* [WIP] Update states mgr for all modules

* [WIP] Add CmdLine operation support

* Add state helper methods to module group and instance

* Add notification and module status handling to status package

* Fix starting issues

* Remove pilot widget and update security lock to new status data

* Remove debug logs

* Improve http server shutdown

* Add workaround for cleanly shutting down firewall+netquery

* Improve logging

* Add syncing states with notifications for new module system

* Improve starting, stopping, shutdown; resolve FIXMEs/TODOs

* [WIP] Fix most unit tests

* Review new module system and fix minor issues

* Push shutdown and restart events again via API

* Set sleep mode via interface

* Update example/template module

* [WIP] Fix spn/cabin unit test

* Remove deprecated UI elements

* Make log output more similar for the logging transition phase

* Switch spn hub and observer cmds to new module system

* Fix log sources

* Make worker mgr less error prone

* Fix tests and minor issues

* Fix observation hub

* Improve shutdown and restart handling

* Split up big connection.go source file

* Move varint and dsd packages to structures repo

* Improve expansion test

* Fix linter warnings

* Fix interception module on windows

* Fix linter errors

---------

Co-authored-by: Vladimir Stoilov <vladimir@safing.io>
2024-08-09 18:15:48 +03:00
Daniel Hååvi 21addd47b3 Merge pull request #1513 from safing/feature/new-kext
Support for new windows kext
2024-05-28 14:45:23 +02:00
Daniel 5371350b3d Add new ICMP filter handler, fix cleaning of ICMP connections 2024-05-13 15:37:10 +02:00
Daniel b07e09c94f Add helpful comment about lookup tries 2024-05-08 14:19:10 +02:00
Vladimir Stoilov 24f6678ad0 Merge branch 'develop' into feature/new-kext 2024-04-18 10:14:49 +03:00
Alexandr Stelnykovych 6251111cdf [fix] (Windows;performance) Ineffective break statement. Did you mean to break out of the outer loop? 2024-04-12 16:38:49 +03:00
Daniel 0cff5a33f2 Never allow permanent verdicts for ICMP connections 2024-04-10 14:10:34 +02:00
Patrick Pacher 61176af14e Fix linting errors 2024-03-27 16:17:58 +01:00
Patrick Pacher 8579430db9 wip: migrate to mono-repo. SPN has already been moved to spn/ 2024-03-20 09:45:32 +01:00