How to Port Knocking in Linux

Fri 19 June 2015 by Godson

To allow clients to ssh using port knocking

@server : 192.168.1.181

# download knockd rpm from web and install
# rpm -ivh knockd-5.xx.rpm
# rpm -qip knockd-5.xx.rpm - know about the packge
# rpm -ql knockd - to list what are files have installed for knockd

First need to reject ssh port for all on server side

# iptables -A INPUT -p tcp --dport 22 -j REJECT 
# whereis iptables
/sbin/iptables

Then configure knockd

# vim /etc/knockd.conf
[openSSH]
sequence    = 1200,1201,1202 - this is for clients to knock on these ports to connect ssh.
seq_timeout = 5 - with in 5 seconds client should connect, you can change this value based on your requirement.
start_command = /sbin/iptbales rest of the itapbles command - check whereis iptables on your machine, this may vary based on your OS.

[closeSHH]
sequence    = 1202,1201,1200 - these are the ports for client to unlock.
seq_timeout = 5
start_command = /sbin/iptables -D rest of the command


# knockd --help - to know various command options

# knockd -D - to run on debug mode
# knockd - d - run as a daemon which run in backgroud.

@client : 192.168.1.29

# ssh 192.168.1.181 -lroot
 this will not allow to connect because of 192.168.1.181 iptables are rejected for all.

 As per knockd you need to first knock to 1200, 1201, 1202 then the server will allow to connect.

@client

# telnet 192.168.1.181 1200
it will give error agian you need to try telnet on 1201
# telnet 192.168.1.181 1201 
this will also give error, again try with 1202 as mentioned in knockd configuration file
# telnet 192.168.1.181 1202
it will also give same error,

Now try to connetct to ssh

# ssh 192.168.1.181 -lroot - Now it will allow you to connect server.

HOW TO DISCONNECT

As per knockd configuratin you need to knock the server in reverse manner First exit from the server

@client:

# telnet 192.168.1.181 1202
# telnet 192.168.1.181 1201
# telnet 192.168.1.181 1200

Now this will diconnect form knockd

If you again try to connect to server with ssh again it will give error as connection refused.

# ssh 192.168.1.181 -lroot - it will givve connection refused error.

If you want to connect again you need to knock the server again @client

:::    
# telnet 192.168.1.181 1200.
# telnet 192.168.1.181 1201
# telnet 192.168.1.181 1202

Now try to connect

# ssh 192.168.1.181 -lroot - this will connect to the server