SSH

Some notes for how to harden SSH on a server

Table of contents

Overview

SSH (secure shell) is used to remotely login to machines and provides a command line interface for command execution. This file serves as a starting point for the first login to creating a new user, hardening ssh and using public-private key login.

Prerequisites

  • OpenSSH Client - installed on client machine
  • OpenSSH Server - installed on the remote machine

Create a user

Create a new account for SSH access:

sudo adduser username
sudo id username           # verify the user exists
sudo passwd username       # change password (if needed)
sudo usermod -aG sudo username

SSH key setup (client)

Generate an SSH keypair on your local machine (if you don’t have one):

ssh-keygen
# private: ~/.ssh/id_ed25519      (keep secret)
# public:  ~/.ssh/id_ed25519.pub  (shareable)

If you want to specify a name for your ssh key use the -f flag:

ssh-keygen -f ~/.ssh/name_of_the_key

This will then create your public key and private key. In order to use ssh to remotely access a server the public key must be on the server. To do this you can use the ssh-copy-id command:

The -i flag specifies the input (which key to use)

ssh-copy-id -i ~/.ssh/name_of_the_key.pub username@ip_address

SSH server configuration

Create a backup of the SSH daemon config before editing:

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

Recommended settings (edit /etc/ssh/sshd_config or a file under /etc/ssh/sshd_config.d/):

# /etc/ssh/sshd_config (examples)
PermitRootLogin no
PasswordAuthentication no
PublicKeyAuthentication yes
# Optionally change port:
# Port xxxx

Sometimes a VPS provider will have more configuration under /etc/ssh/sshd_config.d/50-cloud-init.conf, ensure the same options are set there (or removed) so they don’t override your main file.

After changes, restart and check status:

sudo systemctl restart sshd
sudo systemctl status sshd

Post-change checks

  • Keep an active session open until you’ve confirmed a new connection works.
  • Test from another client: ssh username@server.example.com
  • If locked out, restore the backup: sudo cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config && sudo systemctl restart sshd