SSH hardening is the process of locking down the OpenSSH server daemon (sshd) through `/etc/ssh/sshd_config` so only authorized users with cryptographic keys or certificates can establish remote shell sessions [1]. Most Linux servers ship with permissive defaults that allow password guessing, TCP tunneling, and broad user access out of the box. This guide walks Linux system administrators and DevOps engineers through the specific `sshd_config` directives that eliminate credential brute-forcing, prevent accidental remote lockouts on Ubuntu and RHEL, and establish a clean audit trail.
Key Takeaways for SSH Hardening
- First-match-wins parsing: OpenSSH uses the first value it encounters for any directive, meaning cloud-init files in `/etc/ssh/sshd_config.d/` often override settings placed at the bottom of `/etc/ssh/sshd_config` [1].
- Kill password authentication completely: Setting
PasswordAuthentication nois not enough on its own; you must also setKbdInteractiveAuthentication noandAuthenticationMethods publickeyso PAM modules cannot re-enable password prompts [1], [3]. - Disable direct root logins for auditability: Setting
PermitRootLogin noforces administrators to authenticate with individual accounts before elevating privileges viasudo, preserving accountability in system logs [3], [4]. - Always validate before reloading: Run
sudo sshd -tto check syntax andsudo sshd -Tto inspect the effective merged configuration while keeping a second root terminal open [2]. - Restrict lateral movement primitives: Disable unused TCP, X11, and agent forwarding (`AllowTcpForwarding no`, `AllowAgentForwarding no`, `X11Forwarding no`) so a compromised workstation or server cannot easily pivot across internal subnets [1].
Definition — What is SSH Hardening? SSH hardening is the systematic restriction of the OpenSSH daemon configuration (/etc/ssh/sshd_config) to enforce public-key or certificate authentication, disable direct root logins, limit access to explicit user groups and source IP ranges, remove weak cryptographic algorithms, and disable unnecessary port and agent forwarding features [1], [3].
Which sshd_config directives should you change first?
Effective SSH hardening starts by changing five core sshd_config directives first: AuthenticationMethods publickey, PasswordAuthentication no, PermitRootLogin no, AllowGroups, and LogLevel VERBOSE [1], [3]. Together, these five settings eliminate automated credential stuffing, block direct root access, restrict which local accounts can open a shell, and log the exact key fingerprint used for every session.
When you open `/etc/ssh/sshd_config` on a fresh Debian, Ubuntu, or Red Hat Enterprise Linux (RHEL) system, most lines are commented out with a `#`. Those comments do not represent disabled settings; they show the compiled-in OpenSSH defaults [1]. However, modern Linux distributions rarely rely on a single flat file anymore. Before editing anything, you need to understand how `sshd` actually reads its configuration.
Unlike Apache or Nginx—where the last directive in a file usually wins—OpenSSH uses a strict first-match-wins parser [1]. For every configuration keyword in `sshd_config`, the daemon records the very first value it sees and silently ignores any conflicting value for that same keyword later in the file. If `/etc/ssh/sshd_config` contains `Include /etc/ssh/sshd_config.d/*.conf` at the top of the file, any drop-in file created by your cloud provider (such as `50-cloud-init.conf` on Ubuntu) is parsed before the rest of `/etc/ssh/sshd_config`.
That single quirk breaks more SSH hardening rollouts than any syntax error. An administrator adds `PasswordAuthentication no` at the very bottom of `/etc/ssh/sshd_config`, restarts the service, and assumes passwords are dead—while `50-cloud-init.conf` at the top of the include chain quietly keeps `PasswordAuthentication yes` active. Making `sshd_config` part of a broader Linux server hardening baseline requires verifying the entire include chain rather than blindly appending lines to the bottom of the file.
The diagram below illustrates how SSH hardening directives are evaluated by the `sshd` parser from top to bottom, including drop-in files and conditional `Match` blocks.
sshd_config first-match-wins evaluation order across drop-in files, global settings, and conditional Match blocks [1], [2].To make sure your SSH hardening changes actually take effect, inspect `/etc/ssh/sshd_config.d/` first (`ls -la /etc/ssh/sshd_config.d/`). Either remove conflicting cloud-init overrides or place your hardened rules in `/etc/ssh/sshd_config.d/00-hardening.conf` so they are read first. The table below summarizes the high-impact `sshd_config` directives every administrator should review, their OpenSSH defaults, the recommended hardened values, and the operational risk of misconfiguring each one.
| Directive | OpenSSH Default | Hardened Value | Security Effect & Lockout Risk |
|---|---|---|---|
PermitRootLogin |
prohibit-password (or yes on older distros) |
no |
Blocks direct root SSH sessions [1]. High lockout risk if you have not verified a non-root user with working SSH keys and sudo rights. |
PasswordAuthentication |
yes |
no |
Disables standard password authentication [1]. High lockout risk if `~/.ssh/authorized_keys` permissions are wrong. |
KbdInteractiveAuthentication |
yes |
no |
Stops PAM challenge-response prompts from asking for passwords even when PasswordAuthentication is no [1] (unless using PAM-based 2FA/TOTP). |
AuthenticationMethods |
any |
publickey |
Explicitly requires public-key authentication to succeed before granting access [3]. |
PermitEmptyPasswords |
no |
no |
Explicitly forbids accounts with empty password hashes from authenticating [1]. Low lockout risk. |
AllowGroups |
(Unset — all groups allowed) | sshusers |
Restricts SSH login strictly to members of the specified UNIX group [1]. High lockout risk if your admin user is not added to the group first. |
MaxAuthTries |
6 |
3 or 4 |
Caps authentication attempts per connection [1]. Medium risk: if your local `ssh-agent` holds 5+ keys, the server drops you before reaching the right key unless `IdentitiesOnly yes` is set on the client. |
LoginGraceTime |
120 (seconds) |
30 |
Closes unauthenticated sockets after 30 seconds to reduce connection exhaustion [1]. |
LogLevel |
INFO |
VERBOSE |
Records the SHA256 fingerprint of the SSH public key used to authenticate each session [3]. Zero lockout risk. |
DisableForwarding |
no |
yes (on non-jump hosts) |
Disables X11, `ssh-agent`, TCP, and Unix domain socket forwarding in one directive [1]. Do not enable on jump hosts or servers where developers rely on `ssh -L` port forwards. |
How do you disable password and root login without locking yourself out?
To disable password authentication and direct root login during SSH hardening without locking yourself out, generate an Ed25519 key pair first, copy the public key to a non-root administrative account with verified sudo privileges, confirm key-based login in a second terminal, and only then set PasswordAuthentication no and PermitRootLogin no in sshd_config [1], [3].
Skipping any step in that sequence is how administrators turn a five-minute maintenance window into an out-of-band console recovery ticket. Before touching `sshd_config` on Ubuntu, Debian, or RHEL, prepare your client key and verify your non-root account permissions.
Step 1: Generate an Ed25519 key and install it on your non-root admin user
For modern SSH hardening, Mozilla's OpenSSH guidelines and CISA's Cybersecurity Performance Goals recommend moving away from password-based access in favor of strong public-key cryptography [3], [5]. On your local workstation, generate an Ed25519 key protected by a passphrase (or an `ed25519-sk` hardware security key if you use FIDO2 tokens):
# Generate an Ed25519 key with 100 KDF rounds on your workstation
ssh-keygen -t ed25519 -a 100 -C "admin@workstation-2026" -f ~/.ssh/id_ed25519_prod
# Copy the public key to your non-root administrative account (using RFC 5737 example IP)
ssh-copy-id -i ~/.ssh/id_ed25519_prod.pub deploy@198.51.100.25
Once logged into the target server as `deploy`, verify three things before editing `sshd_config`:
- Directory and file permissions: OpenSSH's `StrictModes` (enabled by default) refuses public-key authentication if your home directory, `~/.ssh`, or `~/.ssh/authorized_keys` is writable by group or others [1]. Ensure `~/.ssh` is `700` (`drwx------`) and `~/.ssh/authorized_keys` is `600` (`-rw-------`).
- Verified `sudo` escalation: Run `sudo -v` or `sudo whoami` as your non-root user and confirm you know the local `sudo` password (or that your environment explicitly configures passwordless `sudo` with SSH key presence).
- Why `PermitRootLogin no` matters for forensics: Even if root only uses SSH keys (`PermitRootLogin prohibit-password`), three administrators sharing `/root/.ssh/authorized_keys` all land in a shell with UID `0`. As Mozilla's security guidance notes, OpenSSH does not natively log the kernel-side audit session ID across all platforms unless paired with `LogLevel VERBOSE` and `auditd` [3]. Forcing administrators to log in as `alice` or `bob` and run `sudo` aligns directly with NIST SP 800-123 server accountability controls [4].
Step 2: Shut the PAM backdoor when disabling passwords
A common trap when configuring SSH key-only login on Ubuntu and Debian is setting `PasswordAuthentication no` while leaving `UsePAM yes` and `KbdInteractiveAuthentication yes` untouched. Under OpenSSH, Pluggable Authentication Modules (PAM) can trigger keyboard-interactive challenge-response prompts that ask the user for their system password anyway [1]. To guarantee that only cryptographic keys are accepted, set all four authentication directives explicitly:
# Enforce public-key authentication and block password fallbacks
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
ChallengeResponseAuthentication no
PermitEmptyPasswords no
AuthenticationMethods publickey
Note on OpenSSH versions: In OpenSSH 8.7 and newer, `KbdInteractiveAuthentication` replaced the older alias `ChallengeResponseAuthentication` [1]. Setting `KbdInteractiveAuthentication no` alongside `AuthenticationMethods publickey` ensures that no password prompt is ever offered unless you intentionally configure multi-factor SSH (`AuthenticationMethods publickey,keyboard-interactive:pam`). Strengthening remote authentication with hardware-backed keys also complements broader phishing-resistant MFA and FIDO2 access controls across your identity perimeter.
Should you change the SSH port?
Changing the default SSH port (`Port 22`) is not a real security control and should never substitute for proper SSH hardening, though moving SSH to a high port can reduce background scanner noise in `/var/log/auth.log` on standalone internet-facing VPS hosts [1]. Against targeted adversaries or fast internet-wide scanners like Masscan and ZMap, a non-standard port provides zero cryptographic protection.
Security teams have argued about changing `Port 22` for twenty years because people conflate log noise reduction with access control. Here is the practical reality from running production Linux fleets:
- When changing Port 22 helps: On a small, standalone cloud VPS exposed directly to `0.0.0.0/0` without an upstream VPN or cloud security group, opportunistic bots hammer TCP port 22 thousands of times an hour. Moving SSH to a high port inside the system/registered range reduces junk failed-login entries in `/var/log/auth.log` or `journald` by over 95%.
- Why changing Port 22 can actually hurt on multi-user systems: TCP port `22` is inside the privileged port range (`1–1023`), which only the `root` user can bind to on Linux. If you move `sshd` to an unprivileged port above `1023` (such as `Port 2222`) on a shared host and the `sshd` daemon ever crashes or stops, a restricted local user who compromises a web container on that same host could bind a rogue SSH listener to port `2222` to intercept incoming connections.
- Operational friction in enterprise environments: On Red Hat Enterprise Linux, AlmaLinux, and Rocky Linux with SELinux in `Enforcing` mode, changing `Port` in `sshd_config` causes `sshd` to fail on restart with a `Permission denied` socket bind error unless you first register the new port with `semanage port -a -t ssh_port_t -p tcp 2222`. It also breaks automated Ansible playbooks, Git remotes, and SCP scripts unless every client updates its `~/.ssh/config`.
Our editorial verdict on Port 22: Keep `Port 22` in production environments. Once you enforce `AuthenticationMethods publickey` and `PasswordAuthentication no` as part of your SSH hardening baseline, opportunistic password scanners fail during pre-authentication negotiation without ever touching PAM. If you want port 22 invisible to the public internet, put the server behind WireGuard, Tailscale, or an IP-restricted cloud firewall—and follow a dedicated network segmentation best practices design rather than relying on port obscurity.
How do you restrict users, groups and source IPs (AllowUsers, Match)?
During SSH hardening, you restrict account and network access in `sshd_config` using `AllowGroups` or `AllowUsers` to whitelist specific UNIX identities, paired with conditional `Match Address` or `Match User` blocks at the bottom of the file to bind administrative or automation accounts to trusted source IP subnets [1].
Even with public-key authentication enforced, not every account on a Linux system should be allowed to request an SSH session. Service accounts (`www-data`, `postgres`, `redis`) or forgotten legacy user accounts might accidentally accumulate an `~/.ssh/authorized_keys` file during a migration or after a partial web application compromise.
Evaluation order: DenyUsers, AllowUsers, DenyGroups, AllowGroups
According to the official OpenBSD `sshd_config(5)` specification, OpenSSH evaluates access control directives in a strict four-step sequence regardless of the order they appear in the file [1]:
DenyUsersAllowUsersDenyGroupsAllowGroups
Managing a dedicated UNIX group (`AllowGroups sshusers`) scales far better than editing `AllowUsers` every time an engineer joins or leaves your team. Create the group, add your administrative user to it, and verify group membership before reloading `sshd`:
# Create the dedicated SSH access group and add your admin account
sudo groupadd sshusers
sudo usermod -aG sshusers deploy
# Verify 'deploy' is listed in the group before editing sshd_config
id deploy
If you also want to lock specific users to fixed bastion or VPN IP ranges directly inside `AllowUsers`, OpenSSH supports the `USER@HOST` pattern using CIDR notation [1]:
# Only allow 'deploy' from the corporate VPN subnet and 'ansible' from the management host
AllowUsers deploy@198.51.100.0/24 ansible@192.0.2.10
Using conditional Match blocks for SFTP and automation accounts
In `sshd_config`, a `Match` block introduces conditional overrides that apply when specific criteria (`User`, `Group`, `Address`, `LocalAddress`, `LocalPort`, or `RDomain`) are met [1]. Because every line after a `Match` declaration belongs to that conditional block until either the next `Match` line or the end of the file, all `Match` blocks must be placed at the very end of `/etc/ssh/sshd_config`.
For example, during SSH hardening, you can globally disable TCP forwarding (`DisableForwarding yes`) for regular users or restricted SFTP accounts while permitting your bastion administrator group to use port forwarding from a trusted management subnet (and aligning your perimeter with a zero trust architecture implementation):
# Global default: block all TCP, agent, and X11 forwarding
DisableForwarding yes
# Place Match blocks at the very bottom of /etc/ssh/sshd_config
Match Group sftponly
ChrootDirectory /srv/sftp/%u
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
Match User ansible Address 192.0.2.10/32
AuthenticationMethods publickey
AllowTcpForwarding no
PermitTTY no
Which ciphers, key exchange and MACs should you allow?
Modern SSH hardening restricts `sshd_config` to elliptic-curve and large-prime Diffie-Hellman key exchange (`curve25519-sha256`, `diffie-hellman-group16-sha512`, `sntrup761x25519-sha512@openssh.com`), Authenticated Encryption with Associated Data (AEAD) ciphers (`chacha20-poly1305@openssh.com`, `aes256-gcm@openssh.com`), and Encrypt-then-MAC (`-etm@openssh.com`) message authentication codes [1], [3].
Before negotiating a session, the SSH client and server agree on four cryptographic primitives: Host Key algorithms (proving server identity), Key Exchange (`KexAlgorithms`), symmetric encryption (`Ciphers`), and data integrity (`MACs`). In December 2023, researchers disclosed the **Terrapin prefix-truncation attack (CVE-2023-48795)** against the SSH binary packet protocol, which exploited sequence number manipulation when `chacha20-poly1305@openssh.com` or CBC-mode ciphers were paired with `*-etm@openssh.com` MAC modes. OpenSSH 9.6 and backported distribution patches resolved CVE-2023-48795 by introducing the `strict KEX` pseudo-algorithm (`kex-strict-s-v00@openssh.com`), which resets packet sequence numbers after key exchange and blocks unauthenticated handshake messages.
In addition to keeping your `openssh-server` package patched for strict KEX, explicit SSH hardening removes legacy SHA-1 key exchanges (`diffie-hellman-group1-sha1`, `diffie-hellman-group14-sha1`), 1024-bit NIST P-256/P-384 curves where you prefer DJB curves, and non-ETM/CBC ciphers. Furthermore, strip out legacy DSA (`ssh-dss`) and SHA-1 RSA (`ssh-rsa`) host keys so your server only presents Ed25519 and RSA-SHA2 (3072-bit or 4096-bit) host keys [3].
The table below compares the recommended modern cryptographic suites for SSH hardening in `sshd_config` against legacy algorithms that should be removed.
| Cryptographic Category | Recommended Hardened Algorithms (OpenSSH 8.5+) | Weak / Legacy Algorithms to Exclude | Why It Matters |
|---|---|---|---|
Key Exchange (KexAlgorithms) |
sntrup761x25519-sha512@openssh.com (OpenSSH 9.0+), curve25519-sha256, curve25519-sha256@libssh.org, diffie-hellman-group16-sha512, diffie-hellman-group18-sha512, diffie-hellman-group-exchange-sha256 |
diffie-hellman-group1-sha1, diffie-hellman-group14-sha1, diffie-hellman-group-exchange-sha1 |
Eliminates small 1024-bit DH primes (Logjam) and collision-prone SHA-1 handshakes [3]; adds hybrid post-quantum key exchange on modern OpenSSH. |
Symmetric Ciphers (Ciphers) |
chacha20-poly1305@openssh.com, aes256-gcm@openssh.com, aes128-gcm@openssh.com, aes256-ctr, aes192-ctr, aes128-ctr |
3des-cbc, aes128-cbc, aes192-cbc, aes256-cbc, arcfour |
Prefers AEAD ciphers (GCM and ChaCha20-Poly1305) that combine encryption and integrity; drops CBC-mode ciphers vulnerable to plaintext recovery [3]. |
Message Authentication Codes (MACs) |
hmac-sha2-512-etm@openssh.com, hmac-sha2-256-etm@openssh.com, umac-128-etm@openssh.com |
hmac-md5, hmac-sha1, umac-64@openssh.com, non-ETM MACs |
Enforces Encrypt-then-MAC (-etm) with 256/512-bit SHA-2 hashes when non-AEAD CTR ciphers are negotiated [3]. |
Host Key Files (HostKey) |
/etc/ssh/ssh_host_ed25519_key, /etc/ssh/ssh_host_rsa_key (3072+ bit, SHA-2 signatures) |
ssh_host_dsa_key, 1024-bit RSA keys, ssh-rsa (SHA-1 signature scheme) |
Prevents server impersonation via weak host key signatures [2], [3]. |
You can inspect which algorithms your installed OpenSSH binary supports before adding them to `sshd_config` by querying `ssh -Q kex`, `ssh -Q cipher`, and `ssh -Q mac`. If you manage older OpenSSH 8.2/8.4 servers (such as Ubuntu 20.04 LTS), omit `sntrup761x25519-sha512@openssh.com`, as hybrid Streamlined NTRU Prime + X25519 key exchange was introduced in OpenSSH 8.5 and made default in OpenSSH 9.0.
How do you test and roll back safely (sshd -t, second session)?
To test and roll back SSH hardening changes safely, keep an active root or `sudo` shell open in Terminal 1, back up `/etc/ssh/sshd_config`, run `sudo sshd -t` to validate syntax and `sudo sshd -T` to verify the merged runtime directives, reload `sshd`, and test login from a brand-new Terminal 2 session before closing Terminal 1 [2].
Why does keeping Terminal 1 open save you? Because the OpenSSH daemon forks a separate child process for every already-authenticated connection [2]. Reloading or restarting the main `sshd` listener (`systemctl reload ssh` on Debian/Ubuntu or `systemctl reload sshd` on RHEL/Fedora) only affects new incoming connections—it does not terminate your existing shell. As long as you never close Terminal 1 until Terminal 2 successfully connects and escalates via `sudo`, a misconfiguration in `sshd_config` takes ten seconds to undo.
The workflow diagram below shows the exact two-terminal procedure for applying and verifying SSH hardening in `sshd_config` with zero lockout risk.
sshd -t, sshd -T, and negative authentication checks [2].Complete Before-and-After `sshd_config` Configuration Block
Below is a side-by-side look at a typical default `/etc/ssh/sshd_config` versus a production-ready SSH hardening baseline (`sshd_config best practices`) tested on Ubuntu 22.04/24.04 LTS, Debian 12, and RHEL 9 (OpenSSH 8.9+):
# =====================================================================
# BEFORE: Typical Permissive Default /etc/ssh/sshd_config
# =====================================================================
Include /etc/ssh/sshd_config.d/*.conf
#Port 22
#PermitRootLogin prohibit-password
#MaxAuthTries 6
#PubkeyAuthentication yes
PasswordAuthentication yes
KbdInteractiveAuthentication yes
UsePAM yes
X11Forwarding yes
#AllowTcpForwarding yes
#LogLevel INFO
# =====================================================================
# AFTER: Hardened /etc/ssh/sshd_config (or /etc/ssh/sshd_config.d/00-hardening.conf)
# =====================================================================
Port 22
AddressFamily inet
Protocol 2
# 1. Host Keys (Ed25519 + 3072/4096-bit RSA only; no DSA or ECDSA)
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
# 2. Authentication & Root Restrictions
PermitRootLogin no
PubkeyAuthentication yes
AuthenticationMethods publickey
PasswordAuthentication no
PermitEmptyPasswords no
KbdInteractiveAuthentication no
KerberosAuthentication no
GSSAPIAuthentication no
UsePAM yes
# 3. Access Control & Connection Rate Limits
AllowGroups sshusers
LoginGraceTime 30
MaxAuthTries 3
MaxSessions 4
MaxStartups 10:30:60
ClientAliveInterval 300
ClientAliveCountMax 2
# 4. Disable Unnecessary Forwarding & Tunneling Primitives
DisableForwarding yes
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
PermitTunnel no
GatewayPorts no
PermitUserEnvironment no
# 5. Audit Logging (Logs SSH key SHA256 fingerprint on every login)
SyslogFacility AUTHPRIV
LogLevel VERBOSE
# 6. Modern Cryptographic Suites (OpenSSH 8.9+ / 9.x)
KexAlgorithms sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha256
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
HostKeyAlgorithms ssh-ed25519,ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512,rsa-sha2-256
Exact validation commands (`sshd -t` and `sshd -T`)
After saving your configuration, run these three verification commands in Terminal 1 before reloading the service [2]:
# 1. Check syntax and host key sanity (silent output = PASS)
sudo sshd -t
# 2. Dump the effective merged configuration after all Include files
sudo sshd -T | grep -E "permitrootlogin|passwordauthentication|kbdinteractiveauthentication|authenticationmethods|allowgroups|loglevel"
# 3. Simulate a connection from a specific user, host, and IP to test Match rules
sudo sshd -T -C user=deploy,host=prod-db-01,addr=198.51.100.25 | grep -E "allowtcpforwarding|authenticationmethods"
Confirm that `sudo sshd -T` outputs `permitrootlogin no`, `passwordauthentication no`, `kbdinteractiveauthentication no`, `authenticationmethods publickey`, and `loglevel VERBOSE`. Remember that on Ubuntu 22.04+ and Debian 12+, the systemd service unit is named `ssh.service` (`sudo systemctl reload ssh`), whereas on RHEL, Rocky Linux, AlmaLinux, and Fedora it is named `sshd.service` (`sudo systemctl reload sshd`). Also note that Ubuntu 22.10+ uses systemd socket activation (`ssh.socket`) by default if you ever modify `ListenAddress` or `Port`.
Lockout-Safe SSH Hardening Checklist
Use this step-by-step SSH hardening checklist whenever you provision or audit a Linux server:
- [ ] Confirm non-root admin user: Verified a dedicated non-root user exists and can execute `sudo whoami` -> `root`.
- [ ] Verify SSH key permissions: Confirmed `~/.ssh` is mode `700` and `~/.ssh/authorized_keys` is mode `600`, owned by the target user.
- [ ] Check group membership: Confirmed the admin user is in the group specified by `AllowGroups` (`id username`).
- [ ] Audit `/etc/ssh/sshd_config.d/`: Checked for cloud-init drop-in files (`50-cloud-init.conf`) that might override `PasswordAuthentication` due to first-match-wins parsing [1].
- [ ] Keep Terminal 1 open: Backed up `/etc/ssh/sshd_config` to `/etc/ssh/sshd_config.bak` inside an active `sudo` session.
- [ ] Run syntax and effective config tests: Executed `sudo sshd -t` (zero errors) and verified `sudo sshd -T` output [2].
- [ ] Test positive and negative logins in Terminal 2: Verified key login works, `sudo` works, and `ssh -o PubkeyAuthentication=no` is rejected with `Permission denied (publickey)`.
- [ ] Verify key fingerprint logging: Checked `/var/log/auth.log` or `journalctl -u ssh -n 20` to confirm `Accepted publickey for deploy ... SHA256:...` appears under `LogLevel VERBOSE` [3].
Even with a hardened `sshd_config`, you should monitor `/var/log/auth.log` or `/var/log/secure` alongside your endpoint telemetry so that any unauthorized key usage or lateral movement triggers your incident response plan and feeds into your living-off-the-land (LOTL) detection queries. For additional system-level controls, explore our complete security hardening guide.
Methodology & Scope Limits (Editorial Analysis): We verified every directive, default value, and command flag in this guide against the upstream OpenBSD `sshd_config(5)` and `sshd(8)` manual pages [1], [2] and Mozilla's OpenSSH configuration baseline [3]. Our analysis and configuration blocks target OpenSSH 8.9 through 9.x on Debian/Ubuntu and RHEL-family distributions. We did not test commercial SSH servers (such as Tectia), legacy Dropbear embedded daemons, or FIPS 140-3 kernel-mode crypto policies on RHEL (which automatically override `Ciphers`, `MACs`, and `KexAlgorithms` via `/etc/crypto-policies/back-ends/opensshserver.config` and reject non-FIPS algorithms like `chacha20-poly1305@openssh.com` and `curve25519-sha256`).
What should you do this week?
Do not wait for a compliance audit to find out that `50-cloud-init.conf` left password authentication open on your internet-facing hosts. Run `sudo sshd -T | grep -E "permitrootlogin|passwordauthentication|kbdinteractiveauthentication|authenticationmethods|loglevel"` across your five most important Linux servers this week. On any host where `passwordauthentication yes` or `permitrootlogin yes` appears in the output, schedule a 15-minute window to deploy the two-terminal hardening rollout above.
Related topics in this series: [INTERNAL LINK: Linux auth.log Analysis: Detect SSH Brute-Force Attacks] | [INTERNAL LINK: Linux Bastion Host Hardening] | [INTERNAL LINK: Fail2ban SSH Configuration]
Sources & References
- OpenBSD Project — sshd_config(5) OpenSSH Daemon Configuration File Manual Page: https://man.openbsd.org/sshd_config
- OpenBSD Project — sshd(8) OpenSSH Daemon Manual Page (`-t` and `-T` flags): https://man.openbsd.org/sshd.8
- Mozilla Information Security — OpenSSH Security Guidelines (Server Configuration, Key Management & Audit Logging): https://infosec.mozilla.org/guidelines/openssh
- National Institute of Standards and Technology (NIST) — Special Publication 800-123: Guide to General Server Security: https://csrc.nist.gov/pubs/sp/800/123/final
- Cybersecurity and Infrastructure Security Agency (CISA) — Cross-Sector Cybersecurity Performance Goals (CPGs): https://www.cisa.gov/cross-sector-cybersecurity-performance-goals

Leave a Comment (Authenticated Users)