Port knocking sample client-server

Last updated: 18-jan-2005

This update contains the following improvements:

* configuration of the server is now located in a separate file

Example configuration file for the server:

#$Id: knockd.cfg,v 2.0 2005/01/18 11:57:19 len Exp $
 #knockd configuration file
 [main]
 #the file to monitor
 file=/var/log/all.log
#the pattern to watch for, note that you must have the
 #"ts", "from" and "port" groups (see python "re" module for more documentation)
 pattern=(?P<ts>...............) \w+ IN=eth0 OUT= MAC=[\w:]* SRC=(?P<from>[0-9\.]+) DST=[\d+\.]+.*?PROTO=TCP SPT=\d* DPT=(?P<port>\d+)
#must start with %Y
 date_format=%Y %b %d %H:%M:%S
open_seq=[4002, 7654, 6033]
#not used yet
 close_seq=[4003, 7432, 6021]
#max delay in seconds between knocks
 delay=3
#call this to open up the port, replace with your favorite command
 open_cmd=/bin/echo opening %from 4000
#call this to close up the port, not used yet
 close_cmd=echo opening %from %port
#internal
 #when the internal entry map is larger start cleaning old entries
 mapsize = 20
 #configuration end

the server can be started with: ./knockd.py knockd.cfg
* the scripts are no longer FreeBSD dependant, any log file can be configured using regular expressions and the command to execute can be configured (I tested on FreeBSD and Linux)
* the client has now command line parameters
-d: the ip of the target server (long parameter: –ipdest)
-q: the port sequence in format: “[port1, port2, port3]” (long parameter: –seq)

Port knocking

This is a simple implementation of the port knocking principle in python on a FreeBSD simple. It can be used as a starting point for a more complex system or just as a simple example of the principle.

There are 2 parts:

  • The server which monitor firewall deny logs and, if a sequence of denied requests is present in an interval, opens a port for the machine originating the sequence (for example the port 22 for a ssh connection).
  • The client which tries to make connections on ports on the target machine in a specific order in an interval (the secret knock).

Requirements

I tested the samples on:

  • server: FreeBSD with ipfw and python 2.2, no port open (for another configuration you need to change the parsing rules and firewall manipulation commands).
  • client: FreeBSD with python 2.2 (should work on almost all machine with python installed, even windows).