First things to do after ssh’ing into a fresh system

For simplicity I just assume a Debian system.

Update the system

apt-get update 
apt-get upgrade

I usually also make sure ‘vim’ is installed: apt-get install vim

Create user

adduser

I’ll refer to that user later as [user].

Generate/upload SSH public key

Generate an SSH key pair on your local machine, if you don’t already have one.

ssh-keygen

Then copy the public key to the server:

ssh-copy-id [user]@[host]

Restrict SSH access

/etc/ssh/sshd_config

LoginGraceTime 2m
PermitRootLogin no
StrictModes yes
MaxAuthTries 2

# only allow this user to connect
AllowUsers [user]

# only allow public key auth
PubkeyAuthentication yes
PasswordAuthentication no

Setup a firewall

Using ‘ufw’ (easier)

apt-get install ufw

ufw default deny incoming
ufw allow ssh

ufw enable

Using ‘iptables’ directly (bit more complex)

Create file ‘/etc/iptables_rules’ with following content

# Generated by iptables-save v1.6.1
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [91:8576]
:SSHATTACK - [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -m recent --set --name SSH --mask 255.255.255.255 --rsource
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -m recent --update --seconds 600 --hitcount 3 --name SSH --mask 255.255.255.255 --rsource -j SSHATTACK
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A SSHATTACK -j LOG --log-prefix "[iptables] SSH attack" --log-level 3
-A SSHATTACK -j DROP
COMMIT

This will also log (/var/log/syslog) brute force attacks on the SSH port, and block an attacker for 600 seconds after 3 failed login attempts.

Apply the firewall rules: iptables-restore /etc/iptables_rules

Enable /etc/rc.local functionality again and load iptables rules on reboot

Create /etc/rc.local

#!/bin/sh -e

iptables-restore /etc/iptables_rules

exit 0

systemctl start rc-local