Generate key

(user@local)_$: ssh-keygen -b 4096

If you don’t want to have that key ‘associated’* with your user and your host, you can ‘associate’ it with your email account:

(user@local)_$: ssh-keygen -b 4096 -C "user@example.com"

(*) It is not really associated with anything, it is just a comment to identify your keys more easily.

Copy key

Copy the keys from local to remote

# a)
(user@local)_$: ssh-copy-id -i .ssh/id_rsa.pub user@remote
# b)
(user@local)_$: cat ~/.ssh/id_rsa.pub | ssh user@remote 'cat >> ~/.ssh/authorized_keys'

Passwordless SSH access

(root@remote)_$: passwd -l user     # Remove password access
(user@local)_$: ssh user@remote     # Check access with SSH key

Check fingerprint

(user@remote)_$: for file in $(find /etc/ssh -name "*.pub"); do ssh-keygen -lf $file; done

Check that the fingerprint being displayed is in the list. Usually, the hostkey used as fingerprint is the RSA, so we can directly check for that one:

(user@remote)_$: for file in $(find /etc/ssh -name "*.pub"); do ssh-keygen -lf $file; done | grep "RSA" | cut -d ' ' -f 2,5
(user@local)_$: ssh-keygen -l -F <remote host>

Key removal

When you receive this message:

Warning: the ECDSA host key for 'somehost' differs from the key for the IP address '12.34.56.78'
Offending key for IP in /home/user/.ssh/known_hosts:48

and you are very sure it can’t be a MITM attack, you can delete the offending key:

# a)
_$: ssh-keygen -f "/home/user/.ssh/known_hosts" -R somehost
# b)
_$: sed -i 48d /home/user/.ssh/known_hosts

Change SSH default port

Warning: This is security through obscurity. Also, remember to change it to a privileged port (<1024) because running SSH in a non-privileged port makes it even less secure, no more.

_$: cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
/etc/ssh/sshd_config:
---------------------
...
Port 999
/etc/iptables.up.rules:
-----------------------
...
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22   -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 999  -j ACCEPT
...
_$: service fail2ban stop
_$: iptables-restore /etc/iptables.up.rules
_$: service fail2ban start
_$: service sshd restart

Check there is no SSH server on port 22:

_$: nmap -Pn -p22 <IP address>

PORT   STATE  SERVICE
22/tcp closed ssh