Linux: Open ssh port access using a combination (knocking technique)

PHOTO EMBED

Mon Aug 29 2022 14:09:43 GMT+0000 (Coordinated Universal Time)

Saved by @marcopinero #bash

#
# first you must stablish iptables rule for keeping port 22 closed
# and ports to use as combination. I used 3030, 55050 and 7070 (is very important
# to use unsorted ports)
#
#  #-- rules to keep open combination ports:
#

sudo iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

#
#  #-- rules to keep ssh port (22) closed:
#

sudo iptables -A INPUT -p tcp -m tcp --dport 22 -j DROP

#
#  #-- then we save iptables
#

sudo iptables-save

#
#  #-- if you want to know how to make this rules "persistent" search info on google about
#      iptables-persistent package or look at this url 
#
#      http://askubuntu.com/questions/119393/how-to-save-rules-of-the-iptables
#
#      it helped me.
#

# debian and derived distros... install knockd:

sudo apt-get install knockd

# we edit /etc/default/knockd: (knockd confif file)

sudo nano /etc/default/knockd

# and set:

    START_KNOCKD=0
    
# to

    START_KNOCKD=1
    
# let's create our ports sequence: let's say 3030,55050,7070 = open, and 7070,55050,3030 = close.
# for this we edit /etc/knockd.conf:

sudo nano /etc/knockd.conf:
    
[options]
  UseSyslog

[openSSH]
  sequence    = 3030,55050,7070
  seq_timeout = 1
# add our input access to iptables  
  command     = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 22 -j DROP
  tcpflags    = syn

[closeSSH]
  sequence    = 7070,55050,3030
  seq_timeout = 1
# delete our input access to iptables
  command     = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j DROP
  tcpflags    = syn
  
# we start service:

sudo /etc/init.d/knockd start

# That's all, we're done.
# .. and now... How can I open my host's ssh port (22) from remote location?
# ... just like this (using telnet):

# OPEN:
telnet 192.168.1.33 3030; telnet 192.168.1.33 55050; telnet 192.168.1.33 7070

# you'll this output at syslog (example with 192.168.1.33):

#  knockd: 192.168.1.33: openSSH: Stage 1
#  knockd: 192.168.1.33: openSSH: Stage 2
#  knockd: 192.168.1.33: openSSH: Stage 3
#  knockd: 192.168.1.33: openSSH: OPEN SESAME
#  knockd: openSSH: running command: /sbin/iptables -I INPUT -s 192.168.1.33...



# and then we CLOSE it:
telnet 192.168.1.33 7070; telnet 192.168.1.33 55050; telnet 192.168.1.33 3030

# you'll this output at syslog (example with 192.168.1.33):

#  knockd: 192.168.1.33: closeSSH: Stage 1
#  knockd: 192.168.1.33: closeSSH: Stage 2
#  knockd: 192.168.1.33: closeSSH: Stage 3
#  knockd: 192.168.1.33: closeSSH: OPEN SESAME
#  knockd: closeSSH: running command: /sbin/iptables -D INPUT -s 192.168.1.33...

content_copyCOPY