Once an OpenSSH instance with default configurations is exposed to the public internet,it immediately becomes a target for continuous automated scanning and brute-force attacks.In one documented instance,an attacker used a leaked credential dictionary to successfully brute-force the root account of a jump server that still permitted password-based authentication.Running the security audit tool`ssh-audit`on a server with default settings typically reveals`[fail]`-level warnings regarding weak algorithms,as well as`[warn]`-level policy recommendations—covering areas such as key exchange,encryption algorithms,MAC(Message Authentication Code)methods,and authentication mechanisms.
The goal of the following configuration process is not merely to achieve"sufficient"security,but to reach a state where`ssh-audit`reports zero`[fail]`and zero`[warn]`entries.
Step 1:Establish a Baseline with`ssh-audit`
Before modifying any configurations,identify the existing vulnerabilities.`ssh-audit`does not need to be installed on the target server;it can be executed from any machine by pointing it at the target IP address and port:
pip install ssh-audit
ssh-audit-p 22<your-server-ip>
In the output,`[fail]`entries indicate algorithms that are known to be flawed or susceptible to downgrade attacks and must be removed.`[warn]`entries highlight configurations that deviate from security best practices—for example,having password authentication enabled or allowing root logins.Use this initial output as a baseline;as you apply changes,re-run`ssh-audit`to verify that the number of`[fail]`and`[warn]`entries decreases.
Step 2:Hardening the Authentication Layer—Addressing`[warn]`-Level Policy Issues
The most common`[warn]`alerts from`ssh-audit`stem from"password authentication enabled"and"root login permitted."These issues must be addressed before adjusting cryptographic algorithms;otherwise,tightening the algorithms might inadvertently lock you out of the server.
First,ensure that key-based authentication is working correctly,then disable password authentication.Generate an Ed25519 key pair locally,add the public key to the server's`~/.ssh/authorized_keys`file,and ensure that the`~/.ssh`directory has permissions set to`700`and the`authorized_keys`file to`600`.Open a new terminal and,after successfully logging in using an SSH key,edit the`/etc/ssh/sshd_config`file:
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
It is recommended to set`PermitRootLogin`to`no`,and instead log in as a standard user before escalating privileges via`sudo`.If root access via SSH key must be retained,set it to`prohibit-password`rather than`yes`;this ensures that password-based authentication is completely disabled,allowing root access only via an SSH key.
Additionally,tighten the authentication window to limit the number of attempts available for brute-force attacks:
MaxAuthTries 3
LoginGraceTime 20
AuthenticationMethods publickey
Setting`AuthenticationMethods publickey`enforces public-key-only authentication,providing a secondary layer of verification alongside`PasswordAuthentication no`.This will also resolve any authentication-related warnings flagged by`ssh-audit`.
Step 3:Hardening at the cryptographic algorithm level—eliminating all warnings categorized as`[fail]`.
Warnings at the`[fail]`level typically pertain to weak Key Exchange(KEX)algorithms,CBC-mode encryption,and SHA-1-based Message Authentication Codes(MACs).Common default configurations—such as`diffie-hellman-group14-sha1`,`aes128-cbc`,and`hmac-sha1`—are considered vulnerable,as they can be exploited or downgraded by modern tools.Depending on the strictness of the audit,the`ecdh-nistp*`family of KEX algorithms may also be flagged by`ssh-audit`.Explicitly narrow down the set of algorithms in`sshd_config`,retaining only modern options with no known vulnerabilities:
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
HostKeyAlgorithms ssh-ed25519,rsa-sha2-512
The rationale behind this configuration is clear:for KEX(Key Exchange),only Curve25519 is kept—the current recommended default that balances security and performance.For ciphers,only AEAD modes(`chacha20-poly1305`and`AES-GCM`)are retained,completely excluding CBC modes.For MACs,only ETM(Encrypt-then-MAC)variants are kept,avoiding the risks associated with schemes that perform verification after encryption.
Tightening`HostKeyAlgorithms`requires corresponding adjustments to the host key files.If ECDSA is disabled in the configuration but the line`HostKey/etc/ssh/ssh_host_ecdsa_key`remains in`/etc/ssh/sshd_config`,the SSH service will still load and advertise the ECDSA key.The correct approach is to either comment out that`HostKey`line or,after verifying that`ssh_host_ed25519_key`and`ssh_host_rsa_key`exist,remove the ECDSA key file.
Additionally,if any Diffie-Hellman moduli smaller than 3071 bits are present on the server,`ssh-audit`will flag them with a warning.You can use the following command to filter`/etc/ssh/moduli`,keeping only those entries with sufficient strength:
awk'$5>=3071'/etc/ssh/moduli>/etc/ssh/moduli.safe
mv/etc/ssh/moduli.safe/etc/ssh/moduli
Step 4:Tightening the Session and Forwarding Layers
Some`[warn]`findings from`ssh-audit`relate to permissive configurations at the session layer.Disabling unnecessary forwarding features can further reduce the attack surface:
X11Forwarding no
AllowTcpForwarding no
AllowAgentForwarding no
ClientAliveInterval 300
ClientAliveCountMax 2
The combination of`ClientAliveInterval 300`and`ClientAliveCountMax 2`ensures that idle connections are automatically terminated after approximately 10 minutes,preventing"half-open"connections from consuming resources over long periods.
Step 5:Fail2Ban—Runtime Protection,Not a Substitute for Algorithmic Auditing
`ssh-audit`evaluates static configurations;it cannot tell you whether you are currently under a brute-force attack.`Fail2Ban`addresses runtime issues by monitoring authentication logs and automatically imposing temporary bans on IP addresses that exhibit multiple failed login attempts within a short timeframe.
After installation,enable SSH protection by configuring`/etc/fail2ban/jail.local`:
[sshd]
enabled=true
port=ssh
logpath=%(sshd_log)s
maxretry=3
bantime=3600
Here,`maxretry=3`triggers a ban after three failed attempts,and`bantime=3600`sets the ban duration to one hour.For sources that engage in persistent scanning,you may consider extending the`bantime`.You can use`fail2ban-client status sshd`to view the list of currently banned IP addresses and related statistics.
It is important to note that`Fail2Ban`does not alter the results of an`ssh-audit`.Weak cryptographic algorithms,enabled password authentication,and permitted root logins must all be addressed within the`sshd_config`file.`Fail2Ban`serves as an additional layer of runtime defense against brute-force attacks,assuming that your base configuration is already secure.Step 6:Verification—Re-auditing with`ssh-audit`and Self-Checking Configuration
After making changes,do not simply run`systemctl restart sshd`and consider the task complete.Perform two checks first:
First,verify the configuration syntax:
sshd-t
If there is no output,the configuration syntax is correct.If any errors appear,address them based on the provided prompts before proceeding.
Second,confirm the effective configuration valuesusing`sshd-T`:
sshd-T|grep-E'permitrootlogin|passwordauthentication|kexalgorithms|ciphers|macs'
The output of`sshd-T`reflects the configuration as actually parsed by the SSH service,which helps identify cases where a setting defined in a configuration file has been overridden by an`Include`directive.
Third,re-run`ssh-audit`:
ssh-audit-p<your_SSH_port><your_server_IP>
Ideally,the number of`[fail]`and`[warn]`entries should be zero.If any remain,address them one by one according to the specific suggestions provided by`ssh-audit`—each flag corresponds to a clear,actionable configuration setting.Throughout the process of modifying your SSH configuration,keep your current session open;only close it after verifying that you can successfully log in via a new terminal session using the updated configuration.
Underlying Network:Measurement Accuracy and Link Quality
While the audit results from`ssh-audit`are not inherently affected by network quality,the verification process following configuration changes—as well as the runtime protection provided by`fail2ban`—rely implicitly on the stability of the underlying network link.If the server’s return path experiences significant packet loss during evening peak hours,`ssh-audit`probes initiated from a remote location might time out,leading to a false"connection failed"report.Similarly,network jitter could delay log collection for`fail2ban`,potentially impacting the timeliness of its blocking decisions.
The core logic behind SSH security auditing is to ensure that the service advertises only the algorithms and authentication methods you have explicitly chosen.Establish a baseline using`ssh-audit`.First,disable password authentication and root login to eliminate any`[warn]`entries;then,specify explicit lists for KEX,ciphers,and MACs to resolve all`[fail]`findings.Simultaneously,remove outdated host keys and weak DH moduli.Finally,implement`fail2ban`to provide runtime protection,and re-run`ssh-audit`to verify that all warnings and failures have been cleared.By following this procedure,a server with a default configuration can be brought to a hardened state that is both auditable and verifiable.
EN
CN