Debian / Ubuntu: Set Port Knocking With Knockd and Iptables

Port knocking is a simple method to grant remote access without leaving a port constantly open. This preserves your server from port scanning and script kiddie attacks.

Knockd installation

Open a terminal or login to the remote server using the ssh client. Type the following command:

$ sudo apt-get install knockd

Sample outputs:
[sudo] password for user:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  knockd
0 upgraded, 1 newly installed, 0 to remove and 4 not upgraded.
Need to get 27.6 kB of archives.
After this operation, 168 kB of additional disk space will be used.
Get:1 http://mirrors.kernel.org/debian/ stable/main knockd amd64 0.5-3 [27.6 kB]
Fetched 27.6 kB in 1s (19.5 kB/s)
Selecting previously deselected package knockd.
(Reading database ... 352407 files and directories currently installed.)
Unpacking knockd (from .../knockd_0.5-3_amd64.deb) ...
Processing triggers for man-db ...
Setting up knockd (0.5-3) ...
knockd disabled: not starting. To enable it edit /etc/default/knockd ... (warning).

Configurations

Edit the file /etc/knockd.conf, enter:
$ sudo vi /etc/knockd.conf
Update the config file as follows. Feel free to set the sequence port number as per your setup 2022, 3022, 4022:
 
[options]
#        UseSyslog
         logfile = /var/log/knockd.log 
[openSSH]
        sequence    = 2022,3022,4022
        seq_timeout = 5
        command     = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
        tcpflags    = syn
 
[closeSSH]
        sequence    = 4022,3022,2022
        seq_timeout = 5
        command     = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
        tcpflags    = syn
 
Save and close the file. Edit the file /etc/default/knockd, enter:
$ sudo vi /etc/default/knockd
Find:
START_KNOCKD=0
Replace with:
START_KNOCKD=1
Optional: set an interface name such as eth0 or wlan0 or ppp0 as per your setup:
KNOCKD_OPTS="-i eth0"
Save and close the file.

How do I start / stop / restart kknockd?

Type the following commands:
 
sudo /etc/init.d/knockd start #<-- start server
sudo /etc/init.d/knockd stop #<-- stop server
sudo /etc/init.d/knockd restart #<-- restart server
sudo /etc/init.d/knockd status #<-- see status server
 

How do I knock port?

You need to use the knock command. It is a port-knock client. To open tcp port #22 for sshd at 203.1.2.3 ip address, enter:
$ knock -v 203.1.2.3 2022 3022 3022
Sample outputs:
hitting tcp 203.1.2.3:2022
hitting tcp 203.1.2.3:3022
hitting tcp 203.1.2.3:4022

How do I close down the port?

The syntax is:
$ knock -v 203.1.2.3 4022 3022 2022

How do I verify that port was opened or closed on the server?

Use the ssh client as follows:
$ ssh user@203.1.2.3OR
# iptables -L INPUT -v -n
# iptables -L INPUT -v -n | grep :22