Skip to content

SSH hardening: best practices for secure administrative access

Exposed SSH is the number one target for brute force. This guide shows how to harden administrative access in practice.

Reading time
12 min
Published

SSH is the main administrative door into Linux servers, which puts it among the most targeted services. An address only needs an open SSH port on the internet to start receiving brute-force attempts, around the clock. The good news is that SSH hardening is straightforward and pays off well: a few configuration changes stop the most common attacks and considerably cut the risk of compromise through this path.

The best-known SSH hardening practices come as a trio: keys, no root, and no exposure. That trio solves a lot, but a defensive approach asks for more. You still need to harden the daemon itself, choose the cryptographic algorithms, manage the key lifecycle, and understand the difference between reducing probe noise and actually containing unauthorized access. The goal is to make administrative access secure without making day-to-day operations unworkable, through strong authentication, access restrictions, and visibility.

Key-based authentication and no root login

The change with the biggest impact is to disable password authentication and use keys only. Keys eliminate password brute force, the dominant attack against exposed SSH. Disable direct root login as well. Each person logs in with an individual user and elevates privilege through sudo when needed, which keeps a record of who did what. The lines below, in sshd_config, do this job.

Excerpts from /etc/ssh/sshd_config
PermitRootLogin noPasswordAuthentication noPubkeyAuthentication yesAllowUsers deploy admin

The AllowUsers directive explicitly restricts who can log in over SSH. In the example, only the deploy and admin accounts get through, so the surface shrinks to a known set of accounts. Protect private keys with a passphrase and remove the keys that are no longer needed.

Key type and private key protection

Prefer ed25519 keys, which are short, fast, and strong. If an older system requires compatibility, use 4096-bit RSA. Avoid RSA keys smaller than 2048 bits and DSA keys, which are now discouraged. The private key should have a passphrase and live only on the operator's device, never in a repository, a container image, or a shared folder. To avoid typing the passphrase all the time, use an SSH agent: it keeps the key loaded during the session without writing the passphrase to disk, which balances security and convenience.

Every public key in authorized_keys is an access grant, and every grant needs an owner and a justification. If nobody knows whose key it is, remove it. Leaving it there "just in case" means keeping access that nobody controls. In a large fleet, managing authorized_keys through declarative configuration keeps orphaned keys from piling up on forgotten servers.

Hardening the daemon and the cryptography

Strong authentication takes care of most of the risk, but sshd itself has options that shrink the surface and the cost of probing. You can limit attempts per connection, end idle sessions, and disable features you do not use. Each of these adjustments closes a secondary path, the kind an attacker exploits once they already have a foot in the door.

Additional hardening in /etc/ssh/sshd_config
# Shrink the brute-force window and its costMaxAuthTries 3LoginGraceTime 20MaxSessions 4# End idle sessions and dead connectionsClientAliveInterval 300ClientAliveCountMax 2# Disable features that widen the attack surfaceAllowAgentForwarding noAllowTcpForwarding noX11Forwarding noPermitTunnel no

Forwarding should follow actual use. If nobody needs X11 or TCP tunneling, disabling those features removes an avenue for abuse. And if a specific workflow depends on port forwarding, allow it per user with a Match block instead of leaving it open to everyone.

Algorithms and version hygiene

When you restrict key exchange algorithms, ciphers, and MACs to a modern set, the server stops negotiating weak primitives. Current OpenSSH versions already ship with sensible defaults, so setting the list explicitly makes more of a difference on older systems or under a compliance requirement. Keeping the OpenSSH package up to date is also part of hardening. Flaws in the server itself turn up and get fixed over time, and an outdated version cancels out much of the configuration effort.

Modern cryptographic set (adjust to what your fleet supports)
KexAlgorithms curve25519-sha256,[email protected]Ciphers [email protected],[email protected]MACs [email protected],[email protected]

Validate any change in a parallel session before closing the current one. Run sshd -t to check the syntax and keep a connection open while you restart the service. If something goes wrong, you still have a way in to fix it, and you avoid the classic scenario of locking yourself out of your own server over a configuration mistake.

Exposure, bastion, and MFA

Whenever possible, do not expose SSH directly to the internet. A bastion host, or a mechanism such as Session Manager in AWS environments, concentrates and controls administrative access, and the internal servers have no SSH port open to the world. Where exposure is unavoidable, restrict it by source and consider MFA for access, which adds a second factor to the login.

  • Password login disabled and access by key only
  • Direct root login disabled
  • Accounts restricted with AllowUsers
  • No direct SSH exposure, with access through a bastion or Session Manager
  • Source restrictions when exposure is unavoidable
  • MFA considered for administrative access

Logs and brute-force protection

Centralize authentication logs in a remote destination. If they stay only on the host, whoever compromises the machine can erase their own tracks. Tools like fail2ban block sources with many failed attempts and reduce brute-force noise, which has value even with key authentication. Also monitor successful logins from unusual sources and at odd hours, because they can point to a compromised credential.

What to look for in the logs

Password brute force is noisy and easy to block. With key authentication, the signal that matters changes: it becomes more useful to track who logged in successfully, from which source and at what time, and to compare that with the expected behavior of each account. Picture a known key, accepted normally, but used from an unfamiliar address at three in the morning. The login is technically legitimate, and that is exactly the kind of event that deserves attention, because it can point to a compromised private key.

  • Successful logins from sources or at times outside the account's normal pattern
  • Service accounts showing up in unexpected interactive sessions
  • Changes to authorized_keys and to the sshd configuration files
  • Escalation through sudo right after an unusual login
  • An abnormal volume of accepted connections from the same source

In other words, blocking brute force reduces the noise, but detecting unauthorized access depends on looking at the logins that succeeded. Forward these events to the same destination that receives the rest of your security telemetry. That way SSH activity can be correlated with the rest of the environment instead of sitting isolated on each host.

SSH at scale: certificates and alternatives to static keys

The authorized_keys file works well on a handful of servers. In a large fleet, keys spread, age, and turn into orphaned access that is hard to track. Two approaches reduce this problem. The first is SSH certificates: an internal certificate authority signs short-lived certificates for users, and the servers trust the CA instead of listing keys one by one. Access expires on its own, and to revoke someone you simply stop renewing their certificate, with no need to hunt down the key on every host.

Server trusting a user CA instead of fixed keys
# In /etc/ssh/sshd_configTrustedUserCAKeys /etc/ssh/user_ca.pub# Short-lived certificates expire on their own,# so authorized_keys files stop piling up across the fleet.

The second approach takes static keys out of human access through brokered access, such as Session Manager in AWS environments or an access broker that issues temporary credentials and records the session. The gain is the same in both cases. Access expires by default, revocation happens at a central point, and there is a trail of who accessed what. And nobody has to count on the manual discipline of cleaning up old keys.

Practical checklist

  • Disable password authentication and use keys only
  • Disable direct root login
  • Use AllowUsers to restrict which accounts can log in
  • Prefer ed25519 keys, or 4096-bit RSA where older systems require it
  • Protect private keys with a passphrase and use an SSH agent
  • Remove keys that are no longer needed
  • Lower MaxAuthTries and LoginGraceTime in sshd
  • End idle sessions with the ClientAlive settings and limit the number of sessions
  • Disable agent, TCP, and X11 forwarding that nobody uses
  • Restrict the algorithms to a modern set and keep OpenSSH up to date
  • Validate each change with sshd -t while a parallel session stays open
  • Avoid exposing SSH directly and use a bastion or Session Manager
  • Restrict by source when SSH has to stay exposed
  • Evaluate MFA for administrative access
  • Centralize authentication logs in a remote destination
  • Use fail2ban and monitor successful logins outside the normal pattern
  • Evaluate SSH certificates or brokered access in large fleets

Best practices

  • Use keys instead of passwords on every server
  • Go beyond authentication and harden the daemon, with limits and fewer features turned on
  • Keep OpenSSH up to date, because configuration does not make up for a flawed version
  • Route access through a bastion and avoid direct exposure
  • Explicitly restrict who can log in over SSH
  • Treat every public key as a grant with an owner and a justification
  • Centralize authentication logs to preserve the evidence
  • Monitor successful logins as well as failed attempts
  • Add MFA where access is sensitive
  • In large fleets, prefer access that expires, through certificates or a broker
  • Standardize hardening for every new server

Common mistakes

SSH with password login enabled
The server becomes a direct target for brute force, the most common attack against SSH.
Direct root login allowed
Whoever gets in arrives with full privileges, and there is no way to trace who it was.
SSH exposed directly to the internet
The server takes constant probing and attacks for no good reason.
Agent and port forwarding enabled but unused
The surface grows, and pivoting from a compromised host gets easier.
Outdated OpenSSH
A flaw in the server itself cancels out much of the configuration hardening.
Logs kept only locally
Whoever compromises the host can erase their own trail.
Old keys never removed
Access that nobody remembers stays valid indefinitely.

Authorship and review

Cesar Gargiulo

CEO and founder of GUARDIASEC. Technical and editorial lead for the content published in this library.

Published on . Found a technical error? Write to [email protected] and we will correct it and keep a record of the change.

Frequently asked questions

Is an SSH key really better than a password?
Yes, by a wide margin. Keys eliminate password brute force, the dominant attack against exposed SSH, and they are much harder to guess. The concern then shifts: you need to protect the private key with a passphrase and control which keys have access, removing the ones that are no longer needed. Disabling passwords and using keys only is the step with the biggest impact.
Why disable root login?
Because direct root login grants maximum privilege right at the entrance, and everyone logs in as the same user, which wipes out traceability. The recommended approach is for each person to log in with their own account and elevate privilege through sudo, which records the action. That way a compromise stays limited to that account, and there is a record of who did what.
Do I need to expose SSH to manage servers?
No. In AWS environments, Session Manager gives you shell access without opening an inbound port. In other setups, a controlled bastion host concentrates access, and the internal servers have no exposed SSH. You keep administering as usual and remove the target that scanners and brute-force tools go after most.
Does fail2ban replace key authentication?
No, they complement each other. Key authentication eliminates password brute force, while fail2ban blocks sources with many failed attempts and cuts down the noise. Even with keys, it lowers the probing load and helps contain abuse, so using both together is better than relying on just one.
Does changing the default SSH port improve security?
A little, and it does not replace the controls that matter. Running SSH on a port other than 22 lowers the volume of automated probing and keeps the logs cleaner, but it does not stop anyone who runs a more thorough port scan. It is a cosmetic noise-reduction measure, useful as an extra layer and never as the main protection. The real gain comes from disabling passwords, blocking root login, restricting accounts, and avoiding direct exposure.
Which type of SSH key should I use today?
In most cases, ed25519: the keys are short, operations are fast, and the security margin is good. A 4096-bit RSA key is still valid when you need compatibility with older systems that do not support ed25519 yet. Avoid RSA below 2048 bits and DSA keys, which are now discouraged. Whatever the type, protect the private key with a passphrase and keep your SSH software up to date.
How do I avoid piling up orphaned keys across a server fleet?
Treat every public key as an access grant with a known owner, never as something permanent. On a few servers, review authorized_keys periodically and remove whatever has no owner. In large fleets, the most sustainable path is to manage keys through declarative configuration or to adopt short-lived SSH certificates, which expire on their own. Revoking then simply means not renewing, instead of hunting down the key on every host.

When to bring in specialist help

Standardizing secure administrative access and removing SSH exposure across the fleet is part of the GUARDIASEC hardening service. The work defines baselines and validates the changes without breaking operations.