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
Portmaster, the SPN hub and the observation hub now verify the intel
index the way they verify the binary index: VerifyIntelUpdates is set
to a new trust store with two dedicated intel signing keys. An intel
index that is unsigned, signed with another key or changed after
signing is refused, and the intel files in use stay as they are.
The intel keys are kept apart from the code signing keys, so that an
intel key can only ever forge intel data, not binaries. A test makes
sure that no code signing key is in the intel trust store, and another
one that ParseIndex accepts exactly an index signed with a trusted key.
main.bandwidth declares ON DELETE CASCADE on conn_id, but foreign keys
are never enabled on the connection, so the cascade never runs. Cleanup
deleted the connections and left their bandwidth rows behind: one row
per connection per second of traffic, kept in memory for the whole
uptime of the process.
Delete the bandwidth rows of the connections that Cleanup is about to
remove, before removing them, and index conn_id, which the bandwidth
chart joins on and the cleanup deletes through. The delete is limited
to the connections being removed, so its cost does not grow with the
rows of live connections, and a bandwidth update that arrives before
its connection is saved is left alone.
Add a test for the cleanup and the index.
The history database is attached to the in-memory connection database
without any configuration. The OpenWAL flag of the write connection only
applies to the main (in-memory) database, so the attached file ran with
the SQLite defaults: rollback journal and synchronous=FULL, which waits
for an fsync on every commit. Bandwidth updates write to it once per
second for every connection with history enabled, all on one goroutine
and under the connection lock.
Set journal_mode=WAL and synchronous=NORMAL on the history database of
the write connection, the same settings the base sqlite storage already
uses. Set synchronous=NORMAL on every pooled read connection as well:
all connections share the pager of the history database (shared cache),
and attaching it from a reader applies the default FULL to that pager
again, silently undoing the setting of the writer.
Measured per history write (Windows, SSD): 5.3 ms before, 0.02 ms after;
the bandwidth update path 6.3 ms before, 0.03 ms after.
Add a test that checks the settings on the write and the pooled read
connections, and two benchmarks to compare the write cost.
When the shutdown did not complete within three minutes, the process
exited without stopping the interception. The kext then kept holding
every new connection for a verdict that never came, and the network
stayed dead until a reboot.
Add a shutdown-timeout hook to cmdbase and let portmaster-core use it
to stop the interception, bounded by ten seconds, before the exit.
IsMyIP and GetLocalNetwork held myNetworksLock while refreshMyNetworks
called the OS, and that call sometimes takes seconds. Every waiting
caller then made its own slow call once it got the lock, so the queue
of goroutines only grew and DNS stayed blocked.
The networks are now an atomic snapshot, read without a lock, and the
refresh runs through singleflight: callers that arrive during a refresh
share its result. The throttle counts from the end of the call, so slow
calls do not run back to back, and the changed flag is reset before the
call, so a change during it is not lost. Callers that arrive during a
refresh after a network change wait for the new networks.
Failing servers were skipped whenever another server in scope was not
marked, even if that server did not answer either. A wrongly marked
server, e.g. after a short stall under load, then stayed unused until the
recovery check.
Ask failing servers after all others, only if none of them answered. An
answer clears the failing state right away. In scopes that continue after
"not found" (.lan, .local, ...), failing servers are skipped once any
server answered, so their timeout does not turn "not found" into a
failure.
https://github.com/safing/portmaster/issues/1891
The IPv4 filter was sized for 100 entries while the current base list
contains about 18k IPv4 addresses. The filter was fully saturated, so every
lookup of a global IPv4 address fell through to the cache database. The
domain filter was sized for 1M entries with about 843k domains in use, which
left little head room for additional intel sources.
Raise the capacities with head room for growth:
domain 1M -> 2M, ipv4 100 -> 200k, ipv6 100 -> 20k, asn 1k -> 10k,
country 100 -> 300. This adds about 2 MB of memory for the domain filter
and doubles the size of its record in the cache database.
Count the values added per entity type and log them next to the capacity
after a base list has been processed, so a list outgrowing its filter can be
spotted in the logs.
Filters restored from the cache database keep their stored size. Existing
installations pick up the new capacities with the next base list update.
Pass the cache database version into resolveUpdateOrder so the ordering
logic can be tested without a database, and cover the base/diff
combinations, including a newer base skipping older diffs.
The cleanup after a base update deleted entries older than "now - 1h".
If the import took longer than an hour of wall-clock time (system sleep,
slow disk), entries written by the import itself were deleted too, and
stayed unblocked until the next base update. Use the update start time,
minus a small margin for clock corrections, as the cutoff instead.
The base/intermediate/urgent file variables used to detect the base file
and to compare versions were never assigned after the v2 updater
rewrite. As a result the "is this the base file" check never matched:
processing a new base.dsdl neither rebuilt the bloom filter from scratch
nor triggered the removal of obsolete entries. Entries that were removed
from the lists upstream stayed in the cache database and in the bloom
filter and kept blocking indefinitely, and both grew over time.
Detect the base file by filename, as the updater returns a new Artifact
instance on every GetFile call, so pointer identity could never match.
Drop the unused variables and the IsNewerThan checks: which files need
processing is already decided by comparing against the persisted cache
database version in resolveUpdateOrder.
A server is marked as failing when it does not answer: timeouts and
connection errors. The recovery check, however, only cleared the mark
when the online check domain resolved to exactly the expected IP. A
server that answers but filters or rewrites that name, for example a
blocklist, DNS rebind protection or a corporate resolver, stayed marked
until Portmaster restarted. With a working fallback configured, that
meant the LAN server and its filter were bypassed for good.
Clear the mark on any answer, whatever the answer is, which is the same
criterion normal queries already use. Timeouts and connection errors
keep the mark.
Issue: https://github.com/safing/portmaster/issues/1891
A DNS server is marked as failing after a few timeouts and then skipped.
When every server in scope is marked, no server is asked at all and the
query is answered with NXDOMAIN, which clients cache. A server that was
wrongly marked, for example after a short stall, therefore breaks name
resolution until the next recovery check or until Portmaster restarts.
Skip failing servers only while another server can still be asked, that
is, one that is neither failing nor an unavailable link-local server.
Otherwise ask the failing servers in their configured order. A successful
answer clears the failing state right away, as it does for normal queries.
Behaviour is unchanged whenever a healthy server is available. When every
server is marked and really down, the query now fails with SERVFAIL after
the timeout instead of an instant, wrong NXDOMAIN.
Issue: https://github.com/safing/portmaster/issues/1891
Issue:
The updates/from-url endpoint was registered with PermitAnyone, so any
local process could call it without authentication. Its handler passed the
request body as an index URL to UpdateFromURL, which ran the update with
the version checks and the auto-download/auto-apply settings bypassed.
Signatures were still verified, but a caller could point Portmaster at a
copy of any older signed index and have it installed without asking the
user, e.g. to bring back a version with an already fixed vulnerability.
Change:
- Remove the endpoint. It was left over from an unfinished feature and
nothing (UI, tray app, scripts) calls it.
- Remove Updater.UpdateFromURL, which had no other callers.
ForceUpdate is unchanged: it is only used by the command line tools and
always uses the configured index URLs.
Fixes#2292
The unit file set LOGLEVEL=info and sourced /etc/default/portmaster, but
never passed the value to portmaster-core. Pass it as --log=${LOGLEVEL}.
An invalid level used to make ServiceConfig.Init fail, which would now turn
a mistyped LOGLEVEL into a service that does not start. Warn and fall back
to the default level instead, as the logger already does on its own.
PORTMASTER_ARGS was appended after "--", where cobra stops parsing flags and
the core ignores the rest, so it has had no effect since the v1 wrapper was
removed. Drop it, and replace the UI README instruction that relied on it
with the equivalent setting (Development Mode).
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.
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
The geoip reader memory-maps geoipv4/v6.mmdb once and only reopened
them on a new artifact version. The intel updater moves every file in
the intel directory on every update, even when unchanged, and the next
update renames the new copy over the moved one.
On Windows a mapped file without open handles cannot be deleted but can
be replaced by such a rename, after which the mapping has no backing
data: evicted pages come back zero-filled, maxminddb fails with
"invalid node in search tree", and geo rules block with "data not
available". Since the switch to Go 1.26 in v2.2.2 os.RemoveAll no
longer unlinks the mapped file on the first update, which is what kept
earlier releases safe.
- Detect a replaced file by its identity (file ID or inode, size and
mtime), taken from an open handle since os.Stat resolves the Windows
file ID lazily, and reload.
- Do not close the previous reader on reload; a lookup may still use
it. The finalizer set by maxminddb.Open unmaps it later.
- Buffer the worker trigger so an update event during a load is not
dropped, and do not hold the broadcaster lock during file access.
https://github.com/safing/portmaster/issues/2265
Related ticket: #2104
On shutdown the NameServer module stopped its listeners with
dns.Server.Shutdown, which waits without limit for all in-flight request
handlers to return. A handler can be stuck in an upstream connect that the
kernel never completes: a connection pended by a firewall driver cannot be
cancelled. In #2104 the pending driver was our own kext, because the
Interception module stops before Resolver and NameServer, so DoT dials
issued in that window had nobody left to answer their verdict. The module
Stop() has no time bound, so the whole shutdown stalled and the Windows
service stayed in "Stopping" until reboot.
- nameserver: stop listeners with ShutdownContext and a 10 second
timeout. Reading from the listener socket stops immediately; only the
wait for running handlers is bounded. Handlers still running
afterwards are cancelled and waited for by the module manager as
before.
- resolver: do not dial a new upstream connection once the instance
has started shutting down. The instance context is cancelled before
any module stops, so this closes the window in which a dial could be
pended after interception is gone. Existing pooled connections are
still used. The resolver instance interface gains ShuttingDown() for
this.
The kext-side part (do not pend new connections after the Shutdown
command) is a separate change that needs a signed driver release.
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.
Related ticket: #1834
The Tauri integration never implemented the action: the install dir
lookup rejected with "not yet supported", the rejection was unhandled,
and the shell plugin would not open local paths from JS anyway. The app
also cannot know the data directory from its arguments, as --data is not
passed on Windows and points to the v1 location on Linux.
Add a read-only core/paths endpoint to the core API (bin, data and log
directories) and an open_dir command in the Tauri app that takes a
directory kind (bin, data, logs), queries the endpoint and opens the
directory natively: ShellExecuteW with the default verb on Windows,
which honors a third-party file manager registered for folders, and
the open crate elsewhere. No path is accepted from the webview, and
further "open directory" actions only need UI changes.
When the geoip lookup for an IP fails, ASN, country and continent rules
returned MatchError, which the firewall treats as a deny. This blocked
connections even for allow rules and for rules whose protocol or port
did not apply to the connection, for example a global
"+ AS32590 UDP/27015-27250" rule blocking TCP/443 connections of an app
with default action "allow". The reported reason
"allowed by rule: ASN data not available to match" was contradictory.
Rules that cannot be evaluated because of missing data now behave as
follows:
- if the rule's protocol or port do not match the connection, the rule
is skipped, as it could never apply
- an allow rule is skipped, so the following rules and the default
action decide
- a deny rule still returns MatchError and fails safe
Related ticket: #2138
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.
The online status check dials its HTTP request from a pre-authenticated
local port. When the request failed before a packet was sent, the
pre-authentication stayed in place and would permit the next outbound
connection from that port, whichever process made it.
Release the port when the request fails, and mark it unusable for port
selection when it could not be bound.
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>
reinsertDisplacedRules() called ListById(table, chain, 1), which panics with
"index out of range [0] with length 0" when the chain holds no rule at that
position - e.g. after another component flushed filter OUTPUT. Use List()
instead and read index 1, as List() prepends the chain policy/definition line
that ListById() omits. A missing jump rule is now treated as "must be
(re-)added" rather than skipped, since skipping would leave the firewall
permanently bypassed, and the delete step uses DeleteIfExists() because the
rule may be gone entirely.
Re-adding rules widened the contract of the maintenance worker, which
previously only reordered existing rules. It ran with no synchronization
against activation/deactivation, so a check firing during a pause/resume could
reinsert a jump rule between the rule-delete loop and DeleteChain, making the
teardown fail with "chain busy" and leaving a dangling chain behind.
Guard all multi-step iptables sequences with iptablesLock:
- activateNfqueueFirewall() and DeactivateNfqueueFirewall() hold it for their
full sequence.
- ensureJumpRulesAtTop() uses TryLock() and skips the round on contention, so
the worker never queues behind an iptables call blocked on the xtables lock,
and returns early when isRunning is false.
- reinsertDisplacedRules() re-checks isRunning between rules - never inside a
move sequence - so a concurrent stop is delayed by at most one sequence and
no TEMPORARY_RULE can be stranded.
The lock is never acquired recursively and no other lock is taken while it is
held, so no lock-ordering cycle is possible.
Reported panic:
github.com/coreos/go-iptables/iptables.(*IPTables).ListById iptables.go:283
interception.reinsertDisplacedRules nfqueue_linux.go:284
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.
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/2233https://github.com/safing/portmaster/issues/1870
Artifact filenames from the index were passed directly to filepath.Join
with no validation, allowing traversal outside the update directory via
names like "../../../../etc/cron.d/evil".
Add validateArtifactFilename() in index.go, called from Index.init()
after platform filtering.
Add tests in index_test.go covering all valid and invalid cases.
Root cause: the conntrack socket is shared between shutdown's bulk-delete and
event-driven per-connection deletes. Concurrent access deadlocks on the socket's
internal RWMutex. Fixed by serialising all conntrack operations with a mutex.
Secondary fix: flush conntrack before destroying nfqueues to avoid kernel-side
conntrack lock contention during queue teardown.
fix(windows): fix logging regression by preserving service ImagePath expansion
- fix Windows logging regression where %PROGRAMDATA% in service args stopped resolving
Enable ForceAttemptHTTP2 on the DoH HTTP transport. Go disables HTTP/2
negotiation by default when a custom TLSClientConfig is set; this flag
restores ALPN h2 negotiation, allowing compatibility with DoH servers
that require HTTP/2. Falls back to HTTP/1.1 transparently when the
server does not support it.
GenerateMockFolder was creating all files empty, so they all shared the
same SHA256 hash. gatherExistingFiles keys files by hash, so only the last
file seen during the walk was retained in the lookup map. This caused
downloadArtifacts to skip or misplace multiple artifacts.
mDNS was tried first for all multicast domains (.local, etc.), causing
a mandatory 1-second timeout before unicast DNS got a turn. For domains
served by a DHCP-assigned DNS server (common in corporate and home
networks), mDNS has no authority and always times out. RFC 6762 §3
requires that .local queries are sent to mDNS multicast, which still
happens; this change only affects the order in which resolvers are
tried sequentially.
https://github.com/safing/portmaster/issues/1959
Passive mDNS records were cached using v.Header().Class instead of
v.Header().Rrtype as the Question type. ClassINET (1) equals TypeA (1)
by coincidence, so A records worked. AAAA (type 28) and PTR (type 12)
records were silently stored as type A and could never be retrieved.
Both SetWriteDeadline and WriteToUDP failures are now soft errors: the
failed protocol is logged as a warning and the other protocol is still
attempted. The query fails only if no protocol could send at all. This
prevents an IPv6 socket error from aborting a query after IPv4 already
sent successfully, which affected PTR, SRV, TXT and other record types
that are sent on both protocols.
When a unicast mDNS response has no Question section, validate that at
least one Answer record name matches the pending query's domain before
associating the response with that query.
Non-compliant devices may echo a multicast query's 16-bit ID in their own unrelated announcements;
without this check their records were stored under the wrong cache key.
https://github.com/safing/portmaster/issues/1959