Sunday, April 25, 2010

Port knocking using iptables

The following let you in basic firewall through sequential port knocking to open SSH access for 5 seconds:
# ----------- BEGIN OF CUSTOM RULES -----------
# Note: Knock ports 100,200,300,400 to open SSH port for 5 seconds.
-A INTO-PHASE2 -m recent --name PHASE1 --remove
-A INTO-PHASE2 -m recent --name PHASE2 --set
-A INTO-PHASE2 -j LOG --log-prefix "INTO PHASE2: "
-A INTO-PHASE3 -m recent --name PHASE2 --remove
-A INTO-PHASE3 -m recent --name PHASE3 --set
-A INTO-PHASE3 -j LOG --log-prefix "INTO PHASE3: "
-A INTO-PHASE4 -m recent --name PHASE3 --remove
-A INTO-PHASE4 -m recent --name PHASE4 --set
-A INTO-PHASE4 -j LOG --log-prefix "INTO PHASE4: "

-A INPUT -m recent --name PHASE1 --update

-A INPUT -p tcp --dport 100 -i eth0 -m recent --set --name PHASE1
-A INPUT -p tcp --dport 200 -m recent --rcheck --name PHASE1 -j INTO-PHASE2
-A INPUT -p tcp --dport 300 -m recent --rcheck --name PHASE2 -j INTO-PHASE3
-A INPUT -p tcp --dport 400 -m recent --rcheck --name PHASE3 -j INTO-PHASE4

-A INPUT -p tcp --dport 22 -i eth0 -m recent --rcheck --seconds 5 --name PHASE4 -j ACCEPT

# ------------ END OF CUSTOM RULES ------------
If you are knocking from windows client you can use nmap tool. Download command-line zipfile Add to knockin.cmd:
@echo off
echo Knock in... %1
nmap -PN --host_timeout 1501 --max-retries 0 -p %2 %1 1>&0 2>&0
nmap -PN --host_timeout 1501 --max-retries 0 -p %3 %1 1>&0 2>&0
nmap -PN --host_timeout 1501 --max-retries 0 -p %4 %1 1>&0 2>&0
nmap -PN --host_timeout 1501 --max-retries 0 -p %5 %1 1>&0 2>&0
Run as the following (suppose you are knocking to
C:\Program Files\nmap-5.00>knockin.cmd 100 200 300 400
Right after you issued above command the SSH port remains open for 5 seconds. Use your favorite SSH client to login. Just in case have a look here.

1 comment :

  1. Hi ,
    One thing to Complain :( the Order of the knock sequence
    doesn't matter in this setup .
    if i use first the port 400 and than the other i can get acces to my Server
    and even if i mix the ports i can get access to my Server
    (Works even with ip6tables)

    Maybe a control chain or something like that could check if the knocksequence is in the right order

    But your Knock Idea with iptables is Awesome and could replace a extra program like knockd etc. with some modification perhaps..

    Thank you to bring me on this way of knocking on my Havens door

    greetings from Germany