Skip to content
Visual explainer 2h to learn 4 steps

Hardening sshd

Disable root and password logins and restrict who can connect.

By Invicly Tech, , in Linux Administration (RHCSA-style). About 10 minutes to read.

Topic 28 of 42

In short

Internet-facing SSH servers are attacked constantly. Disabling root and password logins, restricting which users may connect and rate-limiting failed attempts removes most of the risk. Always validate the config and test from a second session before closing your current one.

Explained simply

Any server with SSH open to the internet gets login attempts from bots within minutes. They try common user names and passwords all day. Hardening means changing the SSH server settings so these attempts can never succeed.

The two biggest steps are simple. Stop root from logging in directly, and stop passwords from working at all, so only SSH keys get in. A bot can guess a weak password, but it cannot guess a private key.

Next you limit who may connect. A rule like AllowGroups sshusers means only members of that group can log in, even if other accounts exist. A tool called fail2ban watches the log and blocks addresses that fail too often.

The danger is locking yourself out. So you always test the config file before applying it, reload instead of restart, and keep your current session open while you try a new login from a second window.

Press Play on a diagram to walk through it one step at a time.

FlowChanging sshd safely
  1. 1
    Confirm key login works

    Test from your client first.

  2. 2
    Write a drop-in

    /etc/ssh/sshd_config.d/50-hardening.conf.

  3. 3
    Validate

    sudo sshd -t prints nothing if valid.

  4. 4
    Reload

    systemctl reload sshd keeps sessions alive.

  5. 5
    Test in a new session

    Keep the old one open until it works.

SequenceA bot meets a hardened server
Bot
sshd
fail2ban
Firewall
  1. 1Try root with a password
    Bot to sshd: Try root with a password
  2. 2Refused: no root, no passwords
    sshd to Bot: Refused: no root, no passwords
  3. 3Failures appear in the journal
    sshd to fail2ban: Failures appear in the journal
  4. 45 failures in 10 minutes counted
    fail2ban to fail2ban: 5 failures in 10 minutes counted
  5. 5Add a ban rule for the bot's IP
    fail2ban to Firewall: Add a ban rule for the bot's IP
  6. 6Next connection is dropped
    Bot to Firewall: Next connection is dropped

In depth

How sshd reads its configuration

The SSH server, sshd, reads /etc/ssh/sshd_config. On RHEL 9 and current Ubuntu, that file starts with Include /etc/ssh/sshd_config.d/*.conf, so drop-in files are read first, in alphabetical order. For most options sshd keeps the first value it sees, so an earlier file wins over a later one.

This creates a real trap. Cloud images often ship 50-cloud-init.conf with PasswordAuthentication yes. A file called 50-hardening.conf sorts after it and loses. Name your file 01-hardening.conf, or check the result. sshd -T prints the settings sshd will actually use, which is the only reliable answer.

  • sudo sshd -T | grep -Ei 'permitroot|passwordauth|allowgroups' shows effective values
  • sudo sshd -t checks syntax and prints nothing when it is valid
  • ls /etc/ssh/sshd_config.d/ to see who else sets options
FlowWhich value wins
  1. 1
    Include runs first

    sshd_config.d/*.conf in name order

  2. 2
    01-hardening.conf

    PasswordAuthentication no: kept

  3. 3
    50-cloud-init.conf

    PasswordAuthentication yes: ignored

  4. 4
    Rest of sshd_config

    Only fills options not yet set

  5. 5
    Check with sshd -T

    Shows the final values

The settings that matter

PermitRootLogin no blocks root completely. The OpenSSH default is prohibit-password, which still lets root in with a key; no is stricter and forces admins to log in as themselves and use sudo, which leaves an audit trail.

PasswordAuthentication no turns off password logins. Also set KbdInteractiveAuthentication no, because keyboard-interactive is another way to ask for a password through PAM. MaxAuthTries 3 (default 6) cuts attempts per connection, and LoginGraceTime 30 (default 120 seconds) drops slow, half-open logins sooner. Never disable PubkeyAuthentication, which is how you get in.

  • PermitRootLogin no
  • PasswordAuthentication no and KbdInteractiveAuthentication no
  • MaxAuthTries 3, LoginGraceTime 30
  • X11Forwarding no unless someone needs it

Restricting users and using Match blocks

AllowUsers and AllowGroups are allow lists: if one is set, everyone not listed is refused. DenyUsers and DenyGroups do the opposite. When several are set, sshd checks them in a fixed order: DenyUsers, AllowUsers, DenyGroups, then AllowGroups. A group list is easier to maintain, since adding a person is just usermod -aG sshusers.

Match blocks apply settings to some connections only. For example, Match Address 10.0.0.0/8 followed by PasswordAuthentication yes allows passwords from the internal network only. A Match block lasts until the next Match or the end of the file, so put Match blocks at the very end. Test them with sshd -T -C user=ana,host=x,addr=10.0.0.5.

fail2ban: blocking repeat offenders

fail2ban reads logs, counts failures per IP address, and adds a firewall rule to ban addresses that fail too often. Each service has a jail. Settings go in /etc/fail2ban/jail.local, never jail.conf, which updates overwrite. The defaults are maxretry 5 failures within findtime 10m, which earns a bantime of 10m.

On RHEL, install fail2ban from EPEL; it bans through firewalld. On Ubuntu it is in the main archive. With key-only logins, fail2ban mostly reduces log noise and load rather than preventing break-ins, but it still helps against password spraying on other services. Whitelist your own office IP with ignoreip so a typo does not ban you.

  • sudo fail2ban-client status sshd shows failures and banned IPs
  • sudo fail2ban-client set sshd unbanip 203.0.113.7 lifts a ban
  • backend = systemd reads sshd messages from the journal

Changing the port safely

Moving SSH from port 22 to, say, 2222 does not add real security, but it cuts bot noise in the logs. On RHEL with SELinux enforcing, sshd may only bind ports labelled ssh_port_t, so first run semanage port -a -t ssh_port_t -p tcp 2222. Then open the port with firewall-cmd --permanent --add-port=2222/tcp and firewall-cmd --reload, set Port 2222, run sshd -t, and reload.

On Ubuntu 24.04, sshd is started by a systemd socket. After changing the port, run systemctl daemon-reload and systemctl restart ssh.socket. In every case, test the new port from a second terminal before closing the old session.

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Disable root and password logins~30m
  2. 2
    Restrict users with AllowGroups~30m
  3. 3
    Validate config with sshd -t~30m
  4. 4
    Rate-limit attacks with fail2ban~30m

Key points

  • PermitRootLogin no and PasswordAuthentication no are the two biggest wins.
  • AllowGroups sshusers limits logins to one group.
  • If you change the port on RHEL, label it with semanage port and open it in the firewall.
  • fail2ban bans IPs after repeated failures.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
sudo tee /etc/ssh/sshd_config.d/50-hardening.conf <<EOF
PermitRootLogin no
PasswordAuthentication no
AllowGroups sshusers
MaxAuthTries 3
EOF
sudo groupadd -f sshusers && sudo usermod -aG sshusers ana
sudo sshd -t && sudo systemctl reload sshd

A hardening drop-in; sshd keeps the first value it reads, so drop-ins override sshd_config.

Harden a fresh cloud VM without losing access

You have a new Ubuntu VM and are logged in with a key as ana. Step 1: add ana to a new group sshusers. Step 2: write a drop-in that sorts first. Step 3: check the syntax and the effective values; cloud-init's file no longer wins. Step 4: reload ssh, which keeps your session alive. Step 5: from a second terminal, prove a key login works and a password login is refused, and only then close the first session.

bash
sudo groupadd -f sshusers && sudo usermod -aG sshusers ana
sudo tee /etc/ssh/sshd_config.d/01-hardening.conf <<'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
AllowGroups sshusers
MaxAuthTries 3
EOF
sudo sshd -t && sudo sshd -T | grep -Ei 'permitroot|passwordauth|allowgroups'
sudo systemctl reload ssh      # the unit is sshd on RHEL
# second terminal:
ssh ana@vm 'echo ok'
ssh -o PubkeyAuthentication=no ana@vm   # must fail

Turn on fail2ban for SSH on RHEL 9

Step 1: enable EPEL and install fail2ban. Step 2: create jail.local with an sshd jail, a longer ban, and your admin network in ignoreip. Step 3: start the service. Step 4: check the jail status, which lists current failures and bans. If you ban yourself, unban from the console.

bash
sudo dnf install -y epel-release   # on RHEL use the EPEL rpm from Fedora
sudo dnf install -y fail2ban
sudo tee /etc/fail2ban/jail.local <<'EOF'
[sshd]
enabled  = true
backend  = systemd
maxretry = 4
bantime  = 1h
ignoreip = 127.0.0.1/8 10.0.0.0/24
EOF
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd

Quick reference

  • sudo sshd -t: syntax check; sudo sshd -T: print the effective settings
  • Drop-ins in /etc/ssh/sshd_config.d are read first; the first value for an option wins
  • PermitRootLogin no plus PasswordAuthentication no removes most risk
  • Also set KbdInteractiveAuthentication no so PAM cannot ask for a password
  • systemctl reload sshd (RHEL) or ssh (Ubuntu) keeps open sessions alive
  • New SSH port on RHEL: semanage port -a -t ssh_port_t -p tcp 2222, then open it in firewalld
  • fail2ban-client status sshd lists banned IPs; set sshd unbanip IP lifts a ban
  • Keep one session open until a fresh login works

Common mistakes

  • Disabling passwords before key login works and locking yourself out.
  • Restarting sshd with a syntax error instead of running sshd -t first.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You add PasswordAuthentication no in 60-hardening.conf, but 50-cloud-init.conf sets it to yes. What happens?

Question 2

2What is the OpenSSH default for PermitRootLogin?

Question 3

3Which command shows the settings sshd will really use after all files are merged?

Question 4

4You moved SSH to port 2222 on RHEL and sshd fails to start with a bind error. What is the most likely missing step?

Question 5

5Where should you put your own fail2ban settings?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Find out whether root login and password login are currently allowed on your server, without reading the files by eye.

  2. Exercise 2medium

    Allow SSH only for members of group sshusers, then prove a user outside the group is refused.

  3. Exercise 3hard

    Allow password logins only from the internal network 10.0.0.0/8 while keeping them off for everyone else.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does changing the SSH port make my server secure?
No. It only reduces noise from bots that scan port 22. Real protection comes from key-only logins, no root login and a small allow list.
What if I lock myself out of SSH?
Use the console your hypervisor or cloud provider offers, fix the drop-in file and reload sshd. This is why you keep one session open while testing.
Do I still need fail2ban if passwords are disabled?
It is less important, because bots cannot guess a key. It still cuts log noise and load, and it protects any other service that does accept passwords.
What is the difference between reload and restart for sshd?
Reload tells the running sshd to reread its config; existing sessions stay open either way, but reload avoids a moment with no listener. If the new config is broken, a restart can leave you with no running sshd at all.

Go deeper

ShareXLinkedInWhatsApp