port knocking with knockd, hiding ssh from the internet

I have small vps that i use for everything, and the auth log on that thing is just bots trying ssh password all day long. fail2ban help, but it still feel stupid to expose port 22 to whole internet. So one day i found knockd, and now ssh on that vps is basically invisible.

The idea of port knocking is simple. You send packet to some closed ports, in the right order, and a daemon watch for that sequence and then run a command, usually open firewall port 22 just for your ip. Wrong sequence, nothing happen, the port stay closed. To everyone else your vps look like it is not running ssh at all.

Setup on server

Install it, on debian/ubuntu:

$ sudo apt install knockd

The config live in /etc/knockd.conf, this is mine:

[options]
    UseSyslog
    Interface = eth0

[openSSH]
    sequence      = 7000,8000,9000
    seq_timeout   = 10
    tcpflags      = syn
    command       = /usr/sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
    cmd_timeout   = 30
    stop_command  = /usr/sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT

[closeSSH]
    sequence      = 9000,8000,7000
    seq_timeout   = 10
    tcpflags      = syn
    command       = /usr/sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT

What the important part:

Then enable it:

$ sudo systemctl enable knockd --now

One thing that bite me first time, on debian you also need to set START_KNOCKD=1 in /etc/default/knockd, and if your interface not eth0, put the right one in KNOCKD_OPTS="-i ens3" or whatever. Otherwise service start fine but it listen nothing.

Also make sure your firewall drop 22 for everyone first, else the whole exercise is pointless.

Client side

knockd package come with knock command:

$ knock your-vps 7000 8000 9000
$ ssh user@your-vps

That’s it. No knock command on your laptop? Use nc in loop:

$ for p in 7000 8000 9000; do nc -w1 your-vps $p; done

You can even knock from phone, there is app for it, i use it once when my laptop die in middle of session.

Gotchas, most of them learned hard way

What i actually do

Is it overkill for personal vps? Maybe. But my auth log now is almost empty and i sleep better, and it is 15 minute setup, so why not.

- [ ] Ref: https://github.com/jvinet/knockd
- [ ] Ref: https://manpages.debian.org/testing/knockd/knockd.1.en.html
- [ ] Ref: https://wiki.archlinux.org/title/Port_knocking