sshd_config and Fail2ban
Level 3 · Locking the door
How to switch off password and root logins in sshd_config. How to check the change took hold, and ban guessers with fail2ban.
Course contentsLesson 6 of 9
Level 1 · Connecting
Level 2 · Keys and shortcuts
Level 3 · Locking the door
Level 4 · Moving files
Level 5 · Reaching further
After this lesson you can
- Switch off password login safely
- Check the setting sshd really uses
- Install fail2ban to ban guessers
14 mincovers 4 glossary entries
Worth reading first: The SSH Config File
How to shut out password guessers
Any server on the internet gets password guesses on port 22 within minutes of starting. The fix is in sshd_config, the SSH settings file in /etc/ssh. Two lines matter most. One switches off all password logins, so only keys work: PasswordAuthentication no. The other keeps root out: PermitRootLogin no.
Password authentication is the old way to log in, by typing a password. A bot can try thousands of them a day. With it switched off, the bot has nothing to guess, because no password will ever be accepted.
The file belongs to root, so you edit it with sudo. Before you reload sshd, check the file with sudo sshd -t. It prints nothing if all is well, and names the line if not.
Keep your current login open while you test. Open a second window and log in again. If that works, you are safe. If it fails, you still have the first window to undo the change.
Ubuntu has a trap here. Small files in /etc/ssh/sshd_config.d are read first, and the first value sshd finds for each setting wins. A file left by the host can say PasswordAuthentication yes and beat your line. sudo sshd -T prints the values sshd really uses.
Fail2ban adds a guard. It reads the login log and counts failures from each address. By default, 5 failures within 10 minutes get that address banned for 10 minutes. On Ubuntu it watches SSH as soon as it is installed.
A common mistake is to switch off passwords before your key works. Then nobody can get in. Log in with the key first, in a second window, and only then change the setting.
$ sudo sshd -T | grep -E '^(passwordauthentication|permitrootlogin)'
passwordauthentication no
permitrootlogin no
$ sudo systemctl reload sshWorked example
Emma checks her log
Emma's new server is 2 days old. Its login log already shows 4,300 failed password guesses from 160 addresses.
She logs in with her key in a second window, sets PasswordAuthentication no, and confirms it with sudo sshd -T. Then she installs fail2ban. The guesses still arrive, but none can ever work.
The words for this lesson4
Check yourself
You set PasswordAuthentication no, but passwords still work. What do you check?
Finished this lesson?
Marking it complete also marks its 4 glossary entries learned, which updates your roadmap and your saved page. 0 are already marked.