Home · Guides / 5 / Secure / 5.3
Guide 5.3
Obscure open ports with knockd
Port knocking keeps a daemon such as SSH closed until the client sends a short sequence of packets to unused ports. It is optional obscurity for a cloud host you still log into over the public internet. It is not a substitute for SSH keys, and it does not apply to the onion HTTP port (that should stay on 127.0.0.1).
Install knockd
-
On Ubuntu or Debian:
sudo apt update sudo apt install knockd iptables-persistentThe client that will open the port also needs the
knockcommand (same package on Debian/Ubuntu). -
Enable the daemon in
/etc/default/knockd:START_KNOCKD=1
Configure a sequence
-
Edit
/etc/knockd.conf. Use your own ports — the numbers below are only an example, in the same style as Wallen’s walkthrough:[options] UseSyslog [openSSH] sequence = 7000,8000,9000 seq_timeout = 10 command = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 22 -j ACCEPT tcpflags = syn [closeSSH] sequence = 9000,8000,7000 seq_timeout = 10 command = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT tcpflags = synIf SSH already listens on a non-default port, change
--dport 22to match.%IP%is replaced with the knocker’s address so you do not open SSH to the whole internet. -
Start knockd, then close the public SSH accept rule so only a successful knock inserts a temporary allow. Example with iptables (UFW users should put equivalent rules in UFW, or stop UFW from fighting iptables):
sudo systemctl enable --now knockd sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT sudo iptables -A INPUT -p tcp --dport 22 -j DROP sudo netfilter-persistent saveDo not run the DROP rule until knockd is running and you still have an established session (the ESTABLISHED rule keeps your current login).
Open and close from the client
-
From another machine that has
knockinstalled:knock -v SERVER_IP 7000 8000 9000 ssh user@SERVER_IP -
When you are done, reverse the sequence so the allow rule is removed:
knock -v SERVER_IP 9000 8000 7000