Port Knocking allows one to open/close a remote port in the firewall of a server with the usage of a secret combination of ports (141 trillion possible combinations).
It creates an extra layer of security for sensitive services such as SSH Server.
sudo apt update sudo apt install knockd -y sudo nano /etc/knockd.conf
Edit the configuration accordingly:
[options] UseSyslog [openSSH] sequence = 54321,12345,10101 seq_timeout = 5 command = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT tcpflags = syn [closeSSH] sequence = 12345,10101,54321 seq_timeout = 5 command = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT tcpflags = syn
Note: the port will be open for connections exclusively from the %IP% who is opening the port with the correct sequence, remaining closed for the whole internet. By default, it is set for 5 seconds since the first and last knock of the sequence with no other port being knocked.
sudo nano /etc/default/knockd
Change the following configuration:
Start the service.
sudo systemctl start knockd sudo systemctl enable knockd sudo ufw enable sudo reboot
And make sure port 22 is not enabled on the firewall and is enabled.
sudo apt update sudo apt install knockd -y
Send the knock sequence to open the port:
knock -v myserver.com 54321 12345 10101 --delay 100
Send the knock sequence to close the port:
knock -v myserver.com 12345 10101 54321 --delay 100
Note: the delay of 100 milliseconds is recommended because depending on the route each packet takes they may arrive in a different order.
The combination can be sent using telnet:
timeout 0.1 telnet myserver.com 54321 ; timeout 0.1 telnet myserver.com 12345 ; timeout 0.1 telnet myserver.com 10101 timeout 0.1 telnet myserver.com 12345 ; timeout 0.1 telnet myserver.com 10101 ; timeout 0.1 telnet myserver.com 54321