How to Secure SSH Service with Port Knocking on Ubuntu/Debian and CentOS
Port knocking is a security technique that keeps the SSH port closed until a predefined sequence of "knocks" (specific port requests) is detected. The SSH port opens for the client only after the correct sequence is sent, which makes it harder for attackers to find the port.
Make sure you have console or out-of-band access to the server before configuring port knocking. Incorrect firewall or knockd rules can block your SSH access. Keep your current SSH session open until you have confirmed that the knock sequence works.
Set Up the Server
Install knockd
On Ubuntu / Debian, install the knockd package from the default repository:
On CentOS, enable the EPEL repository first, then install knockd:
Edit the knockd configuration
Open the knockd.conf configuration file:
Replace the default port sequences with your own custom sequences. The first opens the SSH port and the second (the reverse) closes it:
Modify the line that opens port 22:
Save and close the file.
Enable the knockd service
Edit the file that enables the service, and change the lines shown.
On Ubuntu / Debian, edit /etc/default/knockd:
On CentOS, edit /etc/sysconfig/knockd:
Save and close the file.
Start knockd
Restart and enable the knockd service:
Check the status to make sure it is running:
Install iptables
On Ubuntu / Debian, install iptables and the persistent module:
On CentOS, install iptables and iptables-services:
Block SSH port 22
Block SSH port 22 for all incoming connections, while keeping already established connections open:
Save the iptables rules
On Ubuntu / Debian, save the rules and reload them:
On CentOS, save the rules and restart iptables:
Check the Setup from a Client
Check that port 22 is filtered
From the client machine, use nmap to verify that port 22 is filtered:
You should see:
Test an SSH connection
Try to connect via SSH:
You should receive:
Open and Close the SSH Port with a Knock
Replace your-server-ip with the actual IP address of your server, and use the same knock sequences you configured on the server.
Install the knock client
Install knockd on your local machine, which includes the knock client.
On Ubuntu / Debian:
On CentOS:
Send the knock sequence
Send the configured knock sequence to open the SSH port on the server:
Connect over SSH
Once the correct sequence is received, the SSH port opens and you can connect:
Close the SSH port
After you have finished your task, send the reverse knock sequence to close port 22:
Verify that the reverse sequence closes SSH port 22 before you end your session.

