DEV Community

stackpulse-lab
stackpulse-lab

Posted on Originally published at github.com

Stop memorizing ss flags: zero-dependency port inventory, conflict detection, and baseline drift

"Which process owns this port?" usually turns into a pile of ss -tulpn,
lsof -i, and ps output read by eye. The harder half is: "It was fine
yesterday — why is there an extra listener today?" That kind of change never
raises an error. It quietly widens the attack surface or prevents the next
service from starting.

This article uses PortPulse to
turn both questions into reproducible commands that fit in CI: inventory
and baseline reconciliation. Every terminal output and exit code below was
produced on a real Linux host.

1. A one-off lookup cannot answer "did it change?"

ss is good at answering now:

ss -tulpn | grep -E ':(80|443|5432|6379)\b'
Enter fullscreen mode Exit fullscreen mode

You have to remember the flags, the format changes across versions, and every
check ends with a human diff. Real incidents are rarely "I cannot find who owns
8080." They look like this:

  • after a migration the old service was never stopped, so 0.0.0.0:8080 and 127.0.0.1:8080 both listen and traffic lands on either one;
  • a debug port was left open and moved from loopback to a public interface;
  • a container restarted, the port stayed, but the owner changed from nginx to a temporary script;
  • a service on the backup host was stopped by mistake, the port disappeared, and nobody noticed until the next reconciliation.

These are all drift: the current state no longer matches "what it should be."
To detect drift you need a reviewable baseline and an exit code that expresses
the conclusion.

Question ss / netstat PortPulse
Who owns this port ✅ faster ✅ table + stable JSON
Did the listener set drift ❌ diff it yourself ✅ baseline + check, exit code 4
Duplicate bind / wildcard overlap ❌ eyeball it ✅ automatic conflict
CI / scheduled inspection parse text that changes ✅ stable JSON, zero dependencies
Read permissions some fields need root ✅ degrades: counts unattributed explicitly

PortPulse only reads /proc. It does not open connections, send signals, kill
processes, or modify configuration.

2. Install and take the first inventory

pip install portpulse-cli
portpulse --version
Enter fullscreen mode Exit fullscreen mode
$ portpulse --version
portpulse 0.1.0
Enter fullscreen mode Exit fullscreen mode

Linux (procfs) and Python 3.9+ are required; there are no third-party
dependencies. Start a demo service and look at the inventory:

# Demo: give a temporary HTTP server a stable name
ln -sf "$(command -v python3)" /tmp/legacy_web
/tmp/legacy_web -m http.server 18731 --bind 127.0.0.1 &
portpulse list --proto tcp --port 18731
Enter fullscreen mode Exit fullscreen mode
$ portpulse list --proto tcp --port 18731
PROTO  ADDRESS    PORT   STATE   PID      PROCESS     USER        CMD
-----  ---------  -----  ------  -------  ----------  ----------  -----------------------------------------------
tcp    127.0.0.1  18731  LISTEN  3055293  legacy_web  stackpulse  /tmp/opencode/pp-demo/legacy_web -m http.server
1 socket (tcp=1)
Enter fullscreen mode Exit fullscreen mode

Useful filters:

portpulse list --json                  # stable fields for scripts
portpulse list --proto udp             # UDP only
portpulse list --port 443 --port 8443  # repeatable
portpulse list --process nginx         # process name or command line
portpulse list --all                   # include ESTABLISHED and friends
Enter fullscreen mode Exit fullscreen mode

A port is the resource identity; the process is only its current owner. That is
why the baseline key is proto + address + port, and a process/user change is
reported as changed instead of "missing + unexpected". This matters during
restarts, upgrades, and canary switches.

3. Write the baseline: "what should be listening"

portpulse baseline --write ports-baseline.json
portpulse check --baseline ports-baseline.json
Enter fullscreen mode Exit fullscreen mode
$ portpulse baseline --write ports-baseline.json
baseline written: 13 socket(s) -> ports-baseline.json (host: VM-0-14-rockylinux)
exit=0

$ portpulse check --baseline ports-baseline.json
baseline matches: 13 expected / 13 current socket(s)
exit=0
Enter fullscreen mode Exit fullscreen mode

This host has 12 system listeners plus the demo service. The baseline is JSON
with one record per proto/address/port/process/user. It contains no traffic
payload.

check has exactly four result types:

Result Meaning Typical cause
missing In the baseline, absent now service down, stopped by mistake, incomplete migration
unexpected Not in the baseline, present now debug port, backdoor, container mapping, stray process
changed Port still there, owner or user changed taken over by another program, restarted from a different binary
conflict Duplicate bind or wildcard/loopback overlap bind order decides who wins — a classic incident source

Exit codes are fixed: 0 matches, 4 drift or conflict, 2 invalid input or
unreadable procfs.

4. Real output for all four kinds of drift

4.1 changed: same port, different owner

Stop legacy_web and start a plain python3 on the same port:

$ portpulse check --baseline ports-baseline.json
drift detected: 13 expected / 13 current socket(s)
changed:    tcp 127.0.0.1:18731 fields=process before=legacy_web/stackpulse after=python3/stackpulse
exit=4
Enter fullscreen mode Exit fullscreen mode

The socket count is identical; only the process changed. A check that compares
"is the port open?" would miss this entirely — yet "who is listening" is exactly
what a security review cares about.

4.2 unexpected + conflict: one port bound twice

This demo uses SO_REUSEPORT to bind 0.0.0.0:18733 and
127.0.0.1:18733 at the same time:

import socket, time
socks = []
for addr in ("0.0.0.0", "127.0.0.1"):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    s.bind((addr, 18733))
    s.listen(1)
    socks.append(s)
time.sleep(600)
Enter fullscreen mode Exit fullscreen mode
$ portpulse list --proto tcp --port 18733
PROTO  ADDRESS    PORT   STATE   PID      PROCESS  USER        CMD
-----  ---------  -----  ------  -------  -------  ----------  ----------------------------------------
tcp    0.0.0.0    18733  LISTEN  3055313  python3  stackpulse  python3 /tmp/opencode/pp-demo/dupbind.py
tcp    127.0.0.1  18733  LISTEN  3055313  python3  stackpulse  python3 /tmp/opencode/pp-demo/dupbind.py
2 sockets (tcp=2); conflicts=1
conflict: tcp/18733 overlap: 0.0.0.0 pid=3055313, 127.0.0.1 pid=3055313
exit=0
Enter fullscreen mode Exit fullscreen mode

list shows the scene as it is, so it still exits 0. Whether a conflict is a
failure is check's decision:

$ portpulse check --baseline ports-baseline.json
drift detected: 13 expected / 15 current socket(s)
unexpected: tcp 0.0.0.0:18733 process=python3 user=stackpulse
unexpected: tcp 127.0.0.1:18733 process=python3 user=stackpulse
changed:    tcp 127.0.0.1:18731 fields=process before=legacy_web/stackpulse after=python3/stackpulse
conflict:   tcp/18733 overlap: 0.0.0.0 pid=3055313, 127.0.0.1 pid=3055313
exit=4
Enter fullscreen mode Exit fullscreen mode

Why is 0.0.0.0 plus 127.0.0.1 on the same port dangerous? The kernel
delivers connections to the most specific binding, but both sockets are in
LISTEN; which process receives a connection depends on bind order and kernel
version. A debug service you thought was loopback-only may also be reachable on
a public interface. PortPulse does not guess who "wins" — it reports the overlap
explicitly.

4.3 missing: the service disappeared

Stop the demo service:

$ portpulse check --baseline ports-baseline.json
drift detected: 13 expected / 12 current socket(s)
missing:    tcp 127.0.0.1:18731 process=legacy_web user=stackpulse
exit=4
Enter fullscreen mode Exit fullscreen mode

Restart it and the result returns to baseline matches, exit 0. That is the
loop you can schedule: change → reconcile → exit code → alert.

5. JSON and CI: let the exit code speak

--json comes from the same comparison as the text output, with stable fields:

$ portpulse check --baseline ports-baseline.json --json; echo "exit=$?"
ok: False
counts: {'expected': 13, 'current': 15, 'missing': 0, 'unexpected': 2, 'changed': 1, 'conflicts': 1}
conflict: overlap 18733
exit=4
Enter fullscreen mode Exit fullscreen mode

A small inspection script without jq:

#!/usr/bin/env bash
set -uo pipefail

portpulse check --baseline /etc/portpulse/ports-baseline.json \
  --json > /var/tmp/port-drift.json
status=$?

if [ "$status" -eq 4 ]; then
  python3 - <<'PY'
import json
report = json.load(open("/var/tmp/port-drift.json"))
print("drift:", report["counts"])
for item in report["unexpected"]:
    print("new listener:", item["proto"], item["address"], item["port"], item["process"])
for item in report["conflicts"]:
    print("conflict:", item["proto"], item["port"], item["kind"])
PY
  exit 4
fi
exit "$status"
Enter fullscreen mode Exit fullscreen mode

Two traps:

  1. Do not let a pipeline swallow the exit code. In portpulse check ... | tee log, $? is tee's status. Use ${PIPESTATUS[0]} or redirect first and check afterwards.
  2. Version the baseline, but do not put it in a public repo. It contains no secrets, but it does expose internal topology (database ports, admin ports, service names). Keep it in a private config repo or a configuration manager and review changes.

For scheduled checks, reuse the same baseline. On hosts with many dynamic or
container ports, narrow the scope with --port so ephemeral listeners are not
reported as drift:

portpulse check --baseline ports-baseline.json --port 80 --port 443 --port 5432
Enter fullscreen mode Exit fullscreen mode

6. Attribution boundaries: say "unknown" when it is unknown

When PortPulse runs as a normal user, the kernel hides other users'
/proc/<pid>/fd, so some sockets cannot be attributed. The tool does not guess a
PID. It shows -, counts the socket as unattributed, and says so in the
summary:

$ portpulse list
...
7 sockets (tcp=5 udp=2); unattributed=6 (run as root for full attribution)
Enter fullscreen mode Exit fullscreen mode

That is more trustworthy than pretending every port has an owner. "Six
unattributed sockets" is a fact you can put in an audit report; an invented PID
is an incident. Use sudo or an account with CAP_SYS_PTRACE when you need full
attribution. For inventory and drift checks, an unprivileged account is enough.

7. Six rules for production use

  1. The baseline means "known and approved", not "whatever is running now." Review the first snapshot by hand.
  2. Update and commit the baseline with every intentional change, so the diff becomes part of the change record.
  3. Port identity does not include the process; owner/user changes are changed, which avoids double noise on every restart.
  4. Treat conflict separately. It means two sockets are fighting over one port, not just "multiple listeners".
  5. Put the permission boundary in the report. When unattributed > 0, state the coverage limit.
  6. Read-only is the boundary. PortPulse will not kill a process or edit systemd for you; remediation still belongs to a human or config management.

8. How it fits with schedules and heartbeats

Port drift often arrives together with "the job did not run": the service did not
start → the port disappeared → the backup script cannot connect → cron still
exits 0. Three layers, three questions:

Layer Tool Question
Expression CronPulse Will this schedule ever fire? Any DST traps?
Heartbeat PulseWatch Did it actually run today?
Port PortPulse Is the service still there? Extra or stolen listeners?

If you would rather not assemble three reports by hand, the delivery kit's
quickcheck.py
combines secret scanning and crontab/timer drift into one redacted Markdown
report; PortPulse supplies the port-layer evidence. The online heartbeat and DST
checker is free for three monitors at https://hook.kogasa.xyz.

9. Reproduction checklist

# 1. Install
pip install portpulse-cli
portpulse --version

# 2. Create a baseline (review the inventory first)
portpulse baseline --write ports-baseline.json
portpulse check --baseline ports-baseline.json

# 3. Create drift: same port, different process; then a duplicate bind
#    (see the legacy_web / dupbind.py examples above)
portpulse check --baseline ports-baseline.json
echo $?   # 4

# 4. Restore the host
portpulse check --baseline ports-baseline.json
echo $?   # 0

# 5. Run the source tests
git clone https://github.com/stackpulse-lab/portpulse
cd portpulse && python3 run_tests.py
Enter fullscreen mode Exit fullscreen mode

On this machine python3 run_tests.py printed:

Ran 55 tests in 0.062s

OK
Enter fullscreen mode Exit fullscreen mode

One sentence: port troubleshooting should not depend on memorized ss flags
and a human diff. Write the baseline once, then let
missing / unexpected / changed / conflict and the exit code decide. Read-only
/proc, zero dependencies, CI-friendly.

Top comments (0)