TExcelTAD

ss, ip and nftables

On a Linux host under investigation, three commands answer the first questions. ss shows the sockets: what listens, what is connected to where, in which state. ip shows the network configuration: interfaces, addresses, routes, neighbours. nft shows (and sets) the firewall rules that decide which packets the host accepts. They replace the older netstat, ifconfig, route, arp and iptables, which you will still meet on old systems and in old guides. The sandbox has only a loopback interface and no root, so ss and ip run for real while nftables appears as a syntax check, a lab transcript and a lab.

ss: sockets

Command Shows
ss -tulnp listening TCP and UDP sockets with the owning process (-p needs root for other users' processes)
ss -tn state established established TCP connections, numeric
ss -tan '( dport = :443 or sport = :443 )' filter by port (the filter language also takes dst, src, states)
ss -Htan | awk '{print $1}' | sort | uniq -c count sockets per state
ss -tnp state syn-recv half-open connections (SYN flood check)
ss -x Unix-domain sockets

The session starts a web server, opens one connection to it from a fixed port, and asks the questions an investigator would.

bash · try it yourself
python3 -m http.server 8000 --bind 127.0.0.1 >http.log 2>&1 &
for i in $(seq 50); do ss -Htln 'sport = :8000' | grep -q . && break; sleep 0.1; done
python3 -c "import socket, time
s = socket.create_connection(('127.0.0.1', 8000), source_address=('127.0.0.1', 45002))
time.sleep(2)" &
sleep 0.4
echo "== listeners:"; ss -tln
echo "== established connections involving port 8000:"
ss -tn state established '( dport = :8000 or sport = :8000 )' | { read -r head; echo "$head"; sort; }   # sorted: the order varies
echo "== sockets per state:"; ss -Htan | awk '{print $1}' | sort | uniq -c
kill %1; wait 2>/dev/null
== listeners:
State  Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0      5          127.0.0.1:8000      0.0.0.0:*
== established connections involving port 8000:
Recv-Q Send-Q Local Address:Port  Peer Address:Port Process
0      0          127.0.0.1:45002    127.0.0.1:8000
0      0          127.0.0.1:8000     127.0.0.1:45002
== sockets per state:
      2 ESTAB
      1 LISTEN

In an incident, the interesting lines are connections to addresses you don't recognise, listeners that aren't in the baseline, and processes that shouldn't have sockets at all (a text editor with a connection to the Internet).

ip: interfaces, addresses, routes, neighbours

bash · try it yourself
echo "== interfaces:"; ip -br link
echo "== addresses:";  ip -br addr
echo "== routes (main table, then IPv6):"; ip route; ip -6 route
echo "== neighbours (ARP/NDP cache):"; ip neigh
echo "(empty: a sandbox with only loopback has no neighbours and no default route)"
== interfaces:
lo               UNKNOWN        00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
== addresses:
lo               UNKNOWN        127.0.0.1/8 ::1/128
== routes (main table, then IPv6):
== neighbours (ARP/NDP cache):
(empty: a sandbox with only loopback has no neighbours and no default route)

On a real server the same commands show the Ethernet interfaces and their MACs, every address including secondary ones (ip addr reveals an extra address an attacker added for a tunnel), the default gateway, and the neighbour cache, where an ARP-spoofed gateway shows up as an unexpected MAC (ARP Spoofing). Useful extras: ip -s link (packet and error counters), ip route get <address> (which route a packet would take), ip -d link (VLAN, bridge and tunnel details).

nftables: the firewall

nftables organises rules into tables (per address family: ip, ip6, inet for both, arp, bridge), chains attached to hooks (input, forward, output, prerouting, postrouting) with a priority and a default policy, and rules evaluated top to bottom until one gives a terminal verdict (accept, drop, reject). Before you load a ruleset, check it. The sandbox can't load rules (no CAP_NET_ADMIN), but nft -c still parses the file, so syntax errors are found before the permission check:

bash · try it yourself
cat > lab.nft <<'RULES'
table inet lab_filter {
    chain input {
        type filter hook input priority filter; policy drop;
        ct state established,related accept
        ct state invalid drop
        iif "lo" accept
        tcp dport 22 ip saddr 10.10.0.0/24 accept
        tcp dport { 80, 443 } accept
        counter log prefix "lab-drop: " drop
    }
}
RULES
sed 's/{ 80, 443 } accept/{ 80, 443 accept/' lab.nft > broken.nft
echo "== a typo:"; nft -c -f broken.nft 2>&1
echo "== the correct file (parses; loading needs root):"; nft -c -f lab.nft 2>&1
== a typo:
broken.nft:8:29-34: Error: syntax error, unexpected accept, expecting comma or '}'
        tcp dport { 80, 443 accept
                            ^^^^^^
netlink: Error: cache initialization failed: Operation not permitted
== the correct file (parses; loading needs root):
netlink: Error: cache initialization failed: Operation not permitted

The ruleset reads like a policy: accept replies to connections the host started (ct state established,related), drop packets that fit no connection (invalid), allow loopback, SSH only from the lab network, web from anywhere, and log and drop the rest, with policy drop as the safety net. On a lab machine with root, loading it and looking at the counters goes like this (lab session):

console
lab-host# nft -f lab.nft
lab-host# nft list chain inet lab_filter input
table inet lab_filter {
	chain input {
		type filter hook input priority filter; policy drop;
		ct state established,related accept
		ct state invalid drop
		iif "lo" accept
		tcp dport 22 ip saddr 10.10.0.0/24 accept
		tcp dport { 80, 443 } accept
		counter packets 12 bytes 640 log prefix "lab-drop: " drop
	}
}
lab-host# journalctl -k -g lab-drop -n 1
Jan 15 10:02:11 lab-host kernel: lab-drop: IN=eth0 OUT= MAC=02:00:00:0a:0a:0a:02:00:00:0a:0a:01:08:00 SRC=192.0.2.66 DST=10.10.0.10 LEN=60 TOS=0x00 PREC=0x00 TTL=52 ID=40321 DF PROTO=TCP SPT=51515 DPT=3389 WINDOW=64240 RES=0x00 SYN URGP=0

The lab below walks packets through rule lists like this one: first match wins, and the default policy catches the rest. Try the "shadowed rules" set to see a rule that can never match, and the "stateful" set with replies and odd packets.

chain input { type filter hook input priority 0; policy drop; } on 10.10.0.101ct state established,related accept4 pkts2ct state invalid drop1 pkt3tcp dport 443 ct state new accept0 pkts4ip saddr 10.10.0.0/24 tcp dport 22 ct state new accept1 pkt—policy drop (no rule matched)2 pktspackets (source → protocol/destination port, conntrack state)#1203.0.113.7 → tcp/443 establishedHTTPS session✓ accept (rule 1)#2192.0.2.80 → tcp/50514 establishedreply to our download✓ accept (rule 1)#3192.0.2.53 → udp/40123 establishedreply to our DNS query✓ accept (rule 1)#4192.0.2.1 → icmp relatedICMP error for us✓ accept (rule 1)#5198.51.100.9 → tcp/443 invalidstray ACK✕ drop (rule 2)#6198.51.100.9 → tcp/23 newtelnet scan✕ drop (policy)#7198.51.100.9 → tcp/445 newSMB scan✕ drop (policy)#810.10.0.21 → tcp/22 newadmin SSH✓ accept (rule 4)

Firewall design, segmentation and rule review are the subject of Network Security.

How these commands support detection and response

  • Triage: ss -tnp and ip addr on a suspicious host within the first minutes, saved to a file with timestamps (volatile evidence disappears on reboot).
  • Baselines: listener lists and rulesets in version control; differences are findings.
  • Firewall evidence: rule counters (counter), log rules and the kernel log show what was dropped; nft monitor shows rule changes live.

How they are used safely

  • Prefer read-only commands during an investigation; changing routes or rules on a compromised host can destroy evidence or alert the intruder.
  • Load firewall changes atomically (nft -f file replaces the whole set in one transaction) and keep a console or out-of-band path, or a timed rollback, so a mistake doesn't lock you out.
  • ss -p and nft need root on real systems; use sudo with an audit trail, not a root shell.

Pitfalls

  • Reading a 0.0.0.0:22 line as the whole story: that socket is IPv4 only, but a separate [::]:22 line accepts IPv6 connections, so check both address families.
  • An inet table rule with ip saddr matches only IPv4; IPv6 SSH would fall to later rules (here: the policy drop, which is safe, but other orders aren't).
  • Mixing iptables and nftables on one host: both act on packets, and the effective policy is hard to read.

Practice

1. Which ss command lists only connections to remote port 443?

ss -tn '( dport = :443 )' (add state established to skip other states).

2. In the ruleset, an HTTPS request from 203.0.113.5 arrives. Which rule matches?

It is a new connection (not established, not invalid), not on loopback, not port 22, so tcp dport { 80, 443 } accept matches and accepts it.

3. Why is ct state established,related accept the first rule?

Most packets belong to existing connections; matching them first is efficient and lets replies to the host's own outbound connections in without opening ports for them. New connections are then judged by the specific rules below.

Test yourself

Which command shows listening TCP and UDP sockets with numeric ports?

  1. ip route
  2. ss -tuln
  3. nft list ruleset
  4. ip neigh

Where would an ARP-spoofed gateway show up on a Linux host?

  1. ss -tln
  2. ip neigh (an unexpected MAC for the gateway address)
  3. nft list ruleset
  4. ip -br link

What does policy drop on an nftables input chain mean?

  1. All packets are dropped
  2. Packets that no rule accepted are dropped
  3. Only logged packets are dropped
  4. The chain is disabled

What did nft -c -f broken.nft report in the sandbox?

  1. The ruleset was loaded
  2. A syntax error with the line and position
  3. Nothing
  4. A kernel panic