Hardening SSH configuration
It's advisable to enforce SSH protocol version 2, disable rsh emulation, disconnect idle user sessions, and log INFO level information. Configure each line as seen below. Additionally if you want to reduce log spam of failed access attempts, you can move the listening port to something other than 22.
vi /etc/ssh/sshd_config
Port 2222
PasswordAuthentication no
ChallengeResponseAuthentication no
PermitRootLogin no
Protocol 2
LogLevel INFO
IgnoreRhosts yes
PermitEmptyPasswords no
UsePAM no
MaxAuthTries 6
ClientAliveInterval 300
ClientAliveCountMax 3
AllowGroups ssh_users
If you would like some clarification into the options being set, you can checkout linux-audit's comprehensive detailing of each.[1]
Note | |
If you are running RHEL or CentOS, moving the SSH port will set off SELinux and prevent the SSH daemon from ever starting up, so you need to make SELinux aware of the new port. | |
|
Save the changes made in the sshd_config file and check the validity by running test mode. If there are any errors detected, then it will flag them in output.
sshd -t
You may also need to configure iptables to allow an exception for the new port for IPv4 and IPv6 connections.
iptables -A INPUT -p tcp --dport 2222 -j ACCEPT
ip6tables -A INPUT -p tcp --dport 2222 -j ACCEPT
- Save the configuration for Debian systems.
- Save the configuration for RHEL / CentOS systems.
netfilter-persistent save
netfilter-persistent reload
service iptables save
Reload the SSH daemon service.
systemctl restart sshd
Keep your current console with the active SSH session open. Open a second console and verify that SSH is working. Go ahead and SSH into the server with your new user specified (using "sid" below as an example.)
ssh -p 2222 sid@server-ip-address
If you find yourself in a situation where you're unable to SSH into your server, then switch back to the previous console window with the active session and verify that your sshd_config is correct. If you are completely locked out, then you may have to resort to the access console from your VPS provider or physical access to the server to determine the cause.
Once you've verified that SSH is working, make the sshd_config immuntable to prevent any tampering and reload the SSH daemon.
chattr -R +i /etc/ssh/sshd_config
systemctl restart sshd
Notes
If you're having trouble with the SSH daemon starting up, you can typically narrow down the cause with journalctl.
journalctl -u sshd
If you changed the SSH port as seen in the previous examples, you can use the following command from your host to remote into your server. Port 2222 is used as the example.
ssh -p 2222 sid@vps-ip-address
If you need to modify an immutable file, you will have to unset the chattr attribute first.
chattr -i /path/to/file
References
1. https://linux-audit.com/audit-and-harden-your-ssh-configuration/#ssh-security-settings
[Return to top]