Port Knocking from Scratch
Hiding a service behind a secret knock with Linux network namespaces and nftables.
In this post I’ll build port knocking from scratch with two Linux building blocks: a network namespace to act as a second machine, and an nftables firewall that only lets SSH through after the right knock.
Background
Port Knocking
A service like SSH listens on a well-known port, 22, that anyone can probe. Port knocking hides it. Instead of connecting directly, a client first has to “knock” on a secret sequence of ports, in order. Only then does the real port open, and only for that client. For example, we can require a client to hit 7000 → 8000 → 9000 before port 22 accepts its connection, like a secret knock on a door.
Namespaces
Namespaces are a kernel feature that gives a group of processes their own private copy of one part of the system. Processes inside see only their copy, and everything outside it is invisible to them. Linux has eight kinds: network, mount, PID, UTS, IPC, user, cgroup, and time.
A network namespace is a complete, isolated networking stack with its own interfaces, routes, and firewall rules. Docker uses them to give every container its own network. We will use one as a stand-in for a second machine, so we can lock down its firewall without touching the host’s.
nftables
nftables is the modern Linux firewall and the successor to iptables. It is built on netfilter, a set of hooks in the kernel: checkpoints along the path every packet takes, where nftables can run your rules. There are five:
| Hook | When it runs |
|---|---|
prerouting | Every incoming packet, as soon as it arrives, before the kernel decides where it is going |
input | Packets addressed to this machine, just before they are handed to a local program |
forward | Packets passing through on their way somewhere else, when the machine acts as a router |
output | Packets created by local programs, as they are sent |
postrouting | Every outgoing packet, just before it leaves, whether forwarded or created locally |
Every packet takes one of three paths:
- To this machine:
prerouting → input →local program - From this machine: local program
→ output → postrouting - Through this machine:
prerouting → forward → postrouting
Rules live in chains, and each chain attaches to a hook. A packet walks through a chain’s rules in order until one of them gives a verdict:
drop: the packet is thrown away. This is final.accept: the packet passes this chain, but still has to get through any other chains on the same hook and every hook after it.
If no rule gives a verdict, the chain’s policy decides. For port knocking, everything happens at input, since both the knocks and the SSH connection are addressed to the machine itself.
Creating the Namespace
First, the machine we will hide SSH in. Create a network namespace called port:
sudo ip netns add port
ip netns list
# port
The new namespace is bare: its only interface is a loopback, and that is down. Nothing can reach it, and it cannot reach anything.
You can run any command inside the namespace from the host with ip netns exec port <command>. To avoid that prefix every time, open a shell inside it instead:
sudo ip netns exec port bash
From here on, each command block is labeled with where it runs, host or port, and when both sides matter they sit side by side. First, confirm the two shells are in different network namespaces:
$ readlink /proc/$$/ns/net
net:[4026531833]# readlink /proc/$$/ns/net
net:[4026532990]The IDs differ, so the shells are in separate network namespaces. Every other entry in /proc/$$/ns matches the host except mnt, since ip netns exec also gives the shell its own mount namespace so it can remount /sys for the new network.
Connecting the Two
The namespace has no way to reach the outside world yet. We connect it with a veth (virtual ethernet) pair: two interfaces joined by a virtual cable, where anything sent into one end comes out the other. One end stays on the host and the other goes into the namespace. Once it is wired up and addressed, the setup looks like this:
sudo ip link add veth-host type veth peer name veth-port netns port
This creates veth-host on the host, names its other end veth-port, and moves that end into netns port. Both ends exist, but they are down:
$ ip -br addr show veth-host
veth-host@if2 DOWN# ip -br addr
lo DOWN
veth-port@if32101 DOWNThe @ifN suffix is the index of the interface on the other end. veth-host points to interface 2 inside port (loopback is 1), and veth-port points to interface 32101 on the host.
Addressing
We have a link, but neither end has an address. There is no DHCP here, so assign them by hand from any unused private subnet, then bring both ends up:
$ sudo ip addr add 10.99.0.1/24 dev veth-host
$ sudo ip link set veth-host up
$ ip -br addr show veth-host
veth-host@if2 UP 10.99.0.1/24 fe80::b4a9:9cff:fe6e:6fb9/64# ip addr add 10.99.0.2/24 dev veth-port
# ip link set veth-port up
# ip -br addr show veth-port
veth-port@if32101 UP 10.99.0.2/24 fe80::2c61:92ff:fe01:b571/64Test the link from the host:
$ ping -c 3 10.99.0.2
PING 10.99.0.2 (10.99.0.2) 56(84) bytes of data.
64 bytes from 10.99.0.2: icmp_seq=1 ttl=64 time=0.052 ms
64 bytes from 10.99.0.2: icmp_seq=2 ttl=64 time=0.043 ms
64 bytes from 10.99.0.2: icmp_seq=3 ttl=64 time=0.043 ms
--- 10.99.0.2 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2084ms
rtt min/avg/max/mdev = 0.043/0.046/0.052/0.004 msThe host and namespace can talk to each other, so we are ready to build the firewall.
Building the Firewall
Right now nothing stands between the host and the namespace. To see that, start a listener on port 22 inside port and connect to it from the host:
$ nc -vz 10.99.0.2 22
Connection to 10.99.0.2 22 port [tcp/ssh] succeeded!# nc -lk 22 &nc stands in for an SSH server. Port 22 is free inside the namespace even if the host runs SSH, since every network namespace has its own ports.
The namespace also has its own firewall. It is empty, so nft list ruleset prints nothing and everything gets through:
# nft list rulesetThat is what makes the namespace a safe place to experiment: nothing we add here touches the host’s firewall, so a bad rule cannot lock you out.
A Table and a Chain
Everything in nftables lives in a table, a top-level container for chains, sets, and rules. Create one called knock:
# nft add table inet knockThe inet family covers both IPv4 and IPv6. Next, give the table a chain:
# nft add chain inet knock input '{ type filter hook input priority filter; policy drop; }'The chain’s name, input, is just a label. The part in braces is what matters:
type filter: the chain decides whether packets are accepted or droppedhook input: it runs for every packet addressed to the namespacepriority filter: priority0. When several chains share a hook, lower priorities run firstpolicy drop: any packet that no rule accepts is dropped
Nothing is accepted yet, so the namespace goes dark and the same connection now times out:
$ nc -vz -w 2 10.99.0.2 22
nc: connect to 10.99.0.2 port 22 (tcp) timed out: Operation now in progressLetting Connections Through
The kernel’s connection tracking (ct) labels every packet with a state:
new: the first packet of a connection it has not seen beforeestablished: part of a connection that has seen traffic in both directionsrelated: a new connection spawned by an existing one, such as an ICMP error
The knock should only guard the first packet of a connection. Once SSH is let in, the rest of that connection has to flow freely:
# nft add rule inet knock input ct state established,related acceptRules run in the order they are added, so this is checked before any knock rule. It also means an open SSH session survives after the knock expires.
Remembering Knocks
Each knock has to remember the ones before it. nftables does this with sets: in-memory collections that rules can read from and write to. We need three:
# nft add set inet knock stage1 '{ type ipv4_addr; flags dynamic; timeout 10s; }'
# nft add set inet knock stage2 '{ type ipv4_addr; flags dynamic; timeout 10s; }'
# nft add set inet knock allowed '{ type ipv4_addr; flags dynamic; timeout 30s; }'flags dynamic lets rules add entries from the packet path, and timeout expires them. A client gets 10 seconds between knocks, then 30 seconds to connect.
The Knock Rules
Now add one rule per knock, plus one for SSH:
# nft add rule inet knock input tcp dport 7000 add @stage1 '{ ip saddr }' drop
# nft add rule inet knock input tcp dport 8000 ip saddr @stage1 add @stage2 '{ ip saddr }' drop
# nft add rule inet knock input tcp dport 9000 ip saddr @stage2 add @allowed '{ ip saddr }' drop
# nft add rule inet knock input tcp dport 22 ip saddr @allowed acceptip saddr @stage1 matches only if the source address is already in stage1, and add @stage2 '{ ip saddr }' writes it into stage2. Put together, the chain works like this:
| Packet to | Source must be in | Then |
|---|---|---|
7000 | any source | add to stage1, drop |
8000 | stage1 | add to stage2, drop |
9000 | stage2 | add to allowed, drop |
22 | allowed | accept |
| anything else | any source | dropped by the policy |
The knocks themselves are dropped too, so from the outside, ports 7000, 8000, and 9000 look like every other port: no response at all. A knock out of order matches nothing and falls through to the policy.
Knocking
From the host, knock on the three ports in order, then connect. Inside the namespace, the host’s address is now in allowed:
$ for p in 7000 8000 9000; do nc -z -w 1 10.99.0.2 $p; done
$ nc -vz 10.99.0.2 22
Connection to 10.99.0.2 22 port [tcp/ssh] succeeded!# nft list set inet knock allowed
table inet knock {
set allowed {
type ipv4_addr
size 65535
flags dynamic,timeout
timeout 30s
elements = { 10.99.0.1 expires 28s994ms }
}
}Each knock waits one second for a reply that never comes, then moves on. Port 22 is now open to the host alone, until its entry in allowed expires.
Wrapping Up
Port knocking hides a service. It does not secure it. Anyone watching the network can see the sequence and replay it, and a scan that happens to hit 7000, 8000, and 9000 in order unlocks it too. Keep real authentication, like SSH keys, behind the knock.
When you are done, sudo ip netns del port removes the namespace, and the veth pair and firewall go with it.
Happy port knocking.