Common options to change for better SSH resilience.
Don't lock yourself out
Be careful changing these options! You should have working, reliable SSH key-based login on a non-root account before you change these!
You may benefit from keeping an SSH connection open in the background while you make these changes until you confirm you’re able to log in on a new session. That way, if you can’t log in on a new session, you can use that background one to recover whatever you just goofed.
In /etc/ssh/sshd_config:
LoginGraceTime 2m— timeout if the client does not authenticate within this periodPermitRootLogin no— don’t allow root login over SSH, periodStrictModes yes— enforce permissions ofauthorized_keysand other such things in.sshare correctMaxAuthTries 1— ditch connection after one failed auth attemptIgnoreRhosts yes— don’t care about what the user wants, they’re doing things our wayPasswordAuthentication no— must use SSH keys, no passwords allowedPermitEmtpyPasswords no— why would you ever want this???
Post-quantum cryptography
tl;dr: make sure you’re using OpenSSL 9.0 or newer. When possible, prefer an ED25519 key over RSA.
See also
User whitelist
If you want to configure a whitelist of who can connect at all:
in /etc/ssh/sshd_config:
UsePAM yes
In /etc/pam.d/ssh:
Order matters
PAM files are sequential! Unless you know what you’re doing and/or have made other changes to this file, this line should be last in the PAM config for SSH!
session required pam_listfile.so item=user sense=allow file=/etc/ssh/allowed_users
Finally, create /etc/ssh/allowed_users in it, list the usernames you want to allow SSH for (one per line). For example:
misha
nekoz
Email notifications
You can set up a pretty easy script to email you whenever someone logs in via SSH. I prefer to do this on cloud hosted servers where I don’t log in very often, but if someone besides me logs in, I really want to know about it.
In /etc/ssh/sshd_config:
UsePAM yes
In /etc/pam.d/ssh:
Order matters
PAM files are sequential! You almost always want this file to be last in the list, so you only get emails on successful logins. Otherwise, every failed login attempt will blow up your inbox.
session optional pam_exec.so seteuid /etc/ssh/login-notify.sh
- You can change
optionaltorequiredif you want to reject logins if the mail cannot be delivered. Personally, I didn’t do this, as I may be logging in with intent to fix a broken mail server… which would otherwise result in me being locked out.
Finally, create the referenced /etc/ssh/login-notify.sh:
#!/bin/sh
sender="ssh-notify@my.domain"
recipient="root@my.domain"
if [ "$PAM_TYPE" != "close_session" ]; then
host="`hostname`"
subject="SSH login: $PAM_USER from $PAM_HOST on $host"
message="`env`"
echo "$message" | mailx -r "$sender" -s "$subject" "$recipient"
fiDon’t forget fix permissions on the script (chmod 744 & chown root:root).
See also