Secure SSH access on your server

We will use knockd to hide SSH from scripting brute-force tools, wandering around the Internet.

Operating system used:

  • Ubuntu 18.04

Preparation

Install knockd

sudo apt install knockd
sudo systemctl enable knockd
sudo service knockd start

Configure knockd

After install, default open knock sequence is 7000,8000,9000. Default manually invited closing sequence is 9000,8000,7000.

We will remove these lines, and add our own setup. Do choose your own sequence.

This is my /etc/knockd.conf :

[options]
    UseSyslog
[SSH]
    sequence      = 23800,9258,29015
    seq_timeout   = 5
    start_command = ufw insert 1 allow from %IP% to any port 22
    tcpflags      = syn
    cmd_timeout   = 10
    stop_command  = ufw delete allow from %IP% to any port 22

This configures knockd to listen for connections on the 4 specified ports, within 5 seconds after each other. Once the sequence is completed, a hole is opened for 10 seconds using the given ufw commands.

Test

nc -w 1 server.example.com 23800
nc -w 1 server.example.com 9258
nc -w 1 server.example.com 29015

ssh server.example.com

Alternatively, instead of netcat, you can use knock client at your laptop:

knock -d 300 server.example.com 23800 9258 29015
ssh server.example.com

This process can be easily followed in /var/log/syslog:

Jan 30 13:40:17 test9 knockd: 80.80.47.198: SSH: Stage 1
Jan 30 13:40:18 test9 knockd: 80.80.47.198: SSH: Stage 2
Jan 30 13:40:19 test9 knockd: 80.80.47.198: SSH: Stage 3
Jan 30 13:40:19 test9 knockd: 80.80.47.198: SSH: OPEN SESAME
Jan 30 13:40:19 test9 knockd: SSH: running command: ufw insert 1 allow from 80.80.47.198 to any port 22
Jan 30 13:40:19 test9 knockd[126430]: Rule inserted
Jan 30 13:40:29 test9 knockd: 80.80.47.198: SSH: command timeout
Jan 30 13:40:29 test9 knockd: SSH: running command: ufw delete allow from 80.80.47.198 to any port 22
Jan 30 13:40:29 test9 knockd[126465]: Rule deleted

Disable existing OpenSSH rule, if any

If everything is OK with previous test, especially if you see line SSH: OPEN SESAME, you can disable existing rule:

sudo ufw delete allow OpenSSH

After these steps, you will be able to connect to your server, anytime you like, but will keep port 22 closed for any Internet-wide brute-force attack on your SSH.

All you need to do is to remember the port sequence!