Protecting Kali (2020.1) with knockd and ufw

2020-02-18 04:00:00 -0600

Important

Knockd is only additional protection, remember to harden your SSH config!


Install

apt install knockd ufw


Not plug and play

Now edit ports in /etc/knockd.conf and you are ready?
Unfortunately no.


Change your /etc/default/knockd

# control if we start knockd at init or not
# 1 = start
# anything else = don't start
# PLEASE EDIT /etc/knockd.conf BEFORE ENABLING
START_KNOCKD=1

# command line options
# you can remove -v if you dont want logging
KNOCKD_OPTS="-i eth0 -v"

Default knockd.conf uses open and close sections, it’s easier to put them into one section. This example opens SSH port for 10 seconds and then closes it.

Change your /etc/knockd.conf

[options]
        UseSyslog

[SSH]
        sequence    = 1234,2341,1342
        seq_timeout = 5
        start_command     = ufw insert 1 allow from %IP% to any port 22
        stop_command     = ufw delete allow from %IP% to any port 22
        tcpflags    = syn
        cmd_timeout = 10



Enable knockd at startup

First we need to change /lib/systemd/system/knockd.service

[Unit]
Description=Port-Knock Daemon
After=network.target
Documentation=man:knockd(1)

[Service]
EnvironmentFile=-/etc/default/knockd
ExecStart=/usr/sbin/knockd $KNOCKD_OPTS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=mixed
SuccessExitStatus=0 2 15
CapabilityBoundingSet=CAP_NET_RAW CAP_NET_ADMIN

[Install]
WantedBy=multi-user.target
Alias=knockd.service

Enable with systemctl

systemctl enable knockd.service

Enable and configure ufw. This disables only SSH, so that your other services are not affected.

ufw default enable
ufw deny from any to any port 22
ufw enable



Magic open ports

You can use nmap --max-retries 0 -p 1234,2341,1342 hostname to open ports, also you can use knock hostname 1234 2341 1342 but this is cumbersome.

Instead you can add following into your ~/.ssh/config and port knock will be done for you automatically.

Host MYSSH
    ProxyCommand bash -c 'knock myhostname 1234 2341 1342; nc %h %p'
    HostName myhostname