In today’s digital landscape, securing your server is of utmost importance to protect sensitive data and ensure the smooth operation of your business. One critical aspect of server security is securing SSH (Secure Shell) access. SSH allows users to remotely connect to a server over an insecure network like the Internet. In this article, we will explore how you can harden your server’s SSH access using advanced OpenSSH features. By implementing these measures, you can control SSH client activity, set connection trust levels, jail specific users to directories, and implement access intervals to protect your server from common SSH attacks.
Prerequisites
Before we dive into the details, let’s go over a few prerequisites to ensure a smooth implementation of the steps outlined in this guide.
- Deploy a development server on Shape.host: To test the configuration changes, it’s recommended to set up a development server. Shape.host provides reliable Linux SSD VPS services that are perfect for this purpose.
- SSH Access: Make sure you have SSH access to your server. If you don’t already have SSH access, you can set it up by following the documentation provided by Shape.host.
- Create a Non-Root Sudo User: It is considered best practice to create a non-root sudo user for administrative tasks. This adds an extra layer of security by limiting the privileges of user accounts. To create a non-root sudo user, follow the instructions provided by Shape.host.
With these prerequisites in place, we can now move on to hardening our server’s SSH access.
SSH Configuration Overview
To harden your SSH server, we need to make changes to the main OpenSSH configuration file, located at /etc/ssh/sshd_config
. This file contains various configuration options that control how your SSH server functions. Before making any changes, it’s essential to create a backup of the original configuration file. You can do this by running the following command:
$ sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.ORIG
This command creates a copy of the original configuration file, allowing you to revert any changes if needed.
Now let’s explore the different ways we can secure our server’s SSH access.
Control SSH Access
The first step in securing SSH access is to apply controls on the authentication process. By controlling how users can log in and how long a session stays idle, we can protect our server from SSH brute force attacks.
To edit the SSH configuration file, run the following command:
$ sudo nano /etc/ssh/sshd_config
This command opens the configuration file in the Nano text editor. If you prefer a different text editor, feel free to use your preferred one.
Generate Strong SSH Key Pairs
SSH keys provide a more secure method of authentication compared to passwords. To generate a strong SSH key pair, you can use the ssh-keygen
utility. For example, to generate an ED25519 key pair, run the following command on your local machine:
$ ssh-keygen -t ed25519 -f /path/to/key/file
Replace /path/to/key/file
with the desired location and filename for your key pair.
Once the key pair is generated, you need to copy the public key to your server. You can do this by running the following command:
$ cat ~/.ssh/id_rsa.pub | ssh shapehost@your_server_ip "mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod -R go= ~/.ssh && cat >> ~/.ssh/authorized_keys"
Make sure to replace shapehost
with your non-root sudo username and your_server_ip
with the IP address or domain name of your server.
Disable Password Logins
One common method used by attackers to gain unauthorized access to SSH servers is brute-forcing passwords. To mitigate this risk, it’s recommended to disable password-based logins and only allow SSH key-based authentication.
To disable password-based logins, find the following configuration line in the SSH configuration file:
PasswordAuthentication yes
Change it to:
PasswordAuthentication no
This change ensures that only SSH key-based authentication is allowed, significantly reducing the risk of password-related attacks.
Disable Root Login
Granting SSH access to the root user can be risky, as it provides full administrative privileges. To enhance server security, it’s best to disable SSH access for the root user and use non-root sudo users instead.
To disable root login, find the following directive in the SSH configuration file:
PermitRootLogin yes
Change it to:
PermitRootLogin no
Alternatively, you can allow root login only using SSH keys by changing the directive to:
PermitRootLogin prohibit-password
This configuration allows root login using SSH keys but not the root password, providing an extra layer of security.
Change the Default SSH Port
By default, SSH uses port 22 for remote connections. Attackers often target this default port when scanning for vulnerable servers. Changing the default port can help protect your server from these automated scans.
To change the default SSH port, find the following commented configuration line in the SSH configuration file:
#Port 22
Uncomment the line by removing the #
character and change the port number to your desired value. For example, if you want to use port 9010, the line should look like this:
Port 9010
Save the file and close the text editor.
After changing the SSH port, you need to allow incoming SSH connections on the new port through the firewall. If you are using the UFW firewall, you can run the following command:
$ sudo ufw allow 9010/tcp
Replace 9010
with the port number you specified in the SSH configuration file.
Finally, reload the firewall to apply the changes:
$ sudo ufw reload
To test the SSH connection on the new port, open a new terminal window and run the following command:
$ ssh -p 9010 shapehost@your_server_ip
Make sure to replace shapehost
with your non-root sudo username and your_server_ip
with the IP address or domain name of your server. If the connection is successful, you have successfully changed the SSH port.
Set Up Idle Timeouts
Idle SSH connections pose a security risk, as they can be exploited by malicious users to gain unauthorized access to client machines. To mitigate this risk, it’s important to set up idle timeouts that automatically close inactive SSH connections.
To configure idle timeouts, find the following commented configuration line in the SSH configuration file:
#ClientAliveInterval 0
Uncomment the line by removing the #
character and change the value to your desired timeout interval in seconds. For example, to set the timeout to 300 seconds (5 minutes), the line should look like this:
ClientAliveInterval 300
Next, find the following commented configuration line:
#ClientAliveCountMax 3
Uncomment the line and change the value to the number of times the server should send a message to check if the client is still active before closing the connection. For example, to set the count to 3, the line should look like this:
ClientAliveCountMax 3
Save the file and close the text editor.
To apply the changes, restart the SSH daemon by running the following command:
$ sudo systemctl restart sshd
With idle timeouts configured, SSH connections will automatically close if there is no activity for the specified duration.
Limit Login Attempts
Limiting login attempts is crucial for preventing brute-force attacks on your server. By restricting the number of failed login attempts, you can mitigate the risk of unauthorized access and protect server performance.
To limit the maximum number of login attempts, find the following commented configuration line in the SSH configuration file:
#MaxAuthTries 6
Uncomment the line and change the value to your desired maximum number of login attempts. For example, to limit the attempts to 2, the line should look like this:
MaxAuthTries 2
Save the file and close the text editor.
In addition to limiting login attempts, you can also reduce the login grace period to prevent delayed authentication attempts. Find the following commented configuration line in the SSH configuration file:
#LoginGraceTime 2m
Uncomment the line and change the value to your desired grace period in minutes. For example, to set the grace period to 30 seconds, the line should look like this:
LoginGraceTime 30
Save the file and close the text editor.
Finally, to limit the number of unauthenticated connections, find the following commented configuration line in the SSH configuration file:
#MaxStartups 10:30:100
Uncomment the line and change the values to your desired limits. The values represent the following:
- The first number is the maximum number of unauthenticated connections before randomly rejecting further new connections.
- The second number is the maximum number of seconds to randomly delay the response to new connections.
- The third number is the maximum number of unauthenticated connections before the SSH server refuses new connections.
For example, to set the limits to 5:30:10, the line should look like this:
MaxStartups 5:30:10
Save the file and close the text editor.
With these configurations in place, you have limited login attempts and reduced the risk of brute-force attacks on your server.
Limit the Number of Active Sessions per User
To prevent excessive resource usage and unauthorized access, you can limit the number of active SSH sessions per user. This helps maintain server performance and ensures that users are not abusing their privileges.
To restrict the number of active sessions per user, find the following commented configuration line in the SSH configuration file:
#MaxSessions 10
Uncomment the line and change the value to your desired maximum number of active sessions per user. For example, to set the limit to 5, the line should look like this:
MaxSessions 5
Save the file and close the text editor.
With this configuration, users will only be able to have a specified number of active SSH sessions simultaneously.
Restrict SSH User Actions
In addition to controlling SSH access, you can further enhance server security by restricting the actions that users can perform. By limiting the commands, SSH keys, or command sets that users can utilize, you can minimize the potential impact of unauthorized access.
User and Group Restrictions
To apply custom rules to individual users or groups, you can use the Match
directive in the SSH configuration file.
To restrict a specific user to run a specific command, add the following configuration block at the end of the SSH configuration file:
Match User shapehost
ForceCommand "top"
In this example, the user shapehost
is restricted to running only the top
command. When the user logs in, the top
command is automatically executed, and the session ends when the command is completed.
To restrict a user to running a specific script, create the script and specify its path in the configuration block:
#!/bin/bash echo "Welcome to the restricted script!" # Add your desired commands here exit 0
Save the script on your server and grant execute permissions using the following command:
$ chmod +x /path/to/script.sh
Next, add the following configuration block to the SSH configuration file:
Match User shapehost
ForceCommand "/path/to/script.sh"
In this example, the user shapehost
is restricted to running only the specified script when logging in.
You can also apply restrictions to a specific user group by using the Match Group
directive. For example:
Match Group admins
ForceCommand "ls"
In this case, users belonging to the admins
group will only be able to execute the ls
command when logging in.
SSH Key Restrictions
To add an extra layer of security, you can attach restrictions to individual SSH keys. This allows you to control the actions that can be performed using specific keys.
To apply SSH key-specific restrictions, locate the SSH public key in the ~/.ssh/authorized_keys
file. Each line represents a single SSH key.
To restrict a user to running a specific command with an SSH key, add the restriction before the key. For example:
command="ls" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJKexZIv1Gz6pavF8c4mXbQx3hYj7Xh3c7I2Xp6xO+ user@example.com
In the above example, the user associated with the SSH key will only be able to execute the ls
command when logging in.
You can also restrict users to a set of commands or scripts by creating a custom script that presents a menu of available options. For example:
#!/bin/bash echo "Please select an option:" echo "1. Command 1" echo "2. Command 2" echo "3. Command 3" read -p "Enter your choice: " choice case $choice in 1) /path/to/command1 ;; 2) /path/to/command2 ;; 3) /path/to/command3 ;; *) echo "Invalid option" exit 1 ;; esac exit 0
Save the script on your server and grant execute permissions using the following command:
$ chmod +x /path/to/script.sh
Next, add the configuration line to the authorized_keys
file, specifying the path to the script:
command="/path/to/script.sh" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJKexZIv1Gz6pavF8c4mXbQx3hYj7Xh3c7I2Xp6xO+ user@example.com
With these configurations, you can restrict user actions and ensure that only authorized commands or scripts can be executed.
Chroot System Users
Another powerful feature provided by OpenSSH is the ability to jail system users to specific directories. This restricts their access to only the specified directories, adding an extra layer of security to your server.
To jail a specific user to a directory, add the following configuration block to the SSH configuration file:
Match User shapehost ChrootDirectory /home/shapehost
In this example, the user shapehost
will be restricted to the /home/shapehost
directory. They will not have access to any files or directories outside of their designated jail.
To jail an entire user group, use the Match Group
directive instead:
Match Group admins ChrootDirectory /home/jail
In this case, all users belonging to the admins
group will be restricted to the /home/jail
directory.
After configuring the jail, you may need to link any shared resources to the jail directory. For example, if you want to share files from the /opt/files
directory with the jailed user, you can create a symbolic link:
$ sudo ln -s /opt/files/home/shapehost/files
Make sure to replace /home/shapehost
with the actual jail directory and /opt/files
with the path to the shared files.
Finally, adjust the permissions of the linked directory to ensure that the jailed user has the necessary access:
$ sudo chmod 755 /home/shapehost/files
With these configurations, you can effectively jail users to specific directories, limiting their access to only authorized locations.
SSH Warning Banner
Displaying a warning banner when users establish an SSH connection can help communicate important policies, legal rights, and system usage rules. This ensures that users are aware of their responsibilities and obligations when accessing the server.
To set up an SSH warning banner, create a text file with your desired message. For example, create a file named ssh-banner.txt
with the following content:
************************************************************************ WARNING: This is aprivate computer. Unauthorized access is prohibited. All activities onthis system are monitored and loggedfor security purposes. Please ensure that you have proper authorization to accessthis server. ************************************************************************
Save the file in a location accessible to the SSH server, such as /etc/ssh/ssh-banner.txt
.
Next, open the SSH configuration file:
$ sudo nano /etc/ssh/sshd_config
Scroll to the end of the file and add the following directive:
Banner /etc/ssh/ssh-banner.txt
Save the file and close the text editor.
To apply the changes, restart the SSH daemon:
$ sudo systemctl restart sshd
With this configuration, the warning banner will be displayed to users when they establish an SSH connection to the server.
Conclusion
In this article, we have explored various advanced OpenSSH features that can help secure your server’s SSH access. By implementing these measures, you can control user access, limit login attempts, change the default SSH port, set up idle timeouts, restrict user actions, and jail users to specific directories. These configurations add an extra layer of security to your server and help protect your sensitive data.
Remember to regularly update your server and SSH software to stay protected against any potential vulnerabilities. Additionally, always follow best practices for server security and keep yourself informed about the latest security trends and techniques.
Shape.host offers reliable Linux SSD VPS services that can help you secure and optimize your server infrastructure. With their scalable and secure cloud hosting solutions, you can focus on growing your business without worrying about your server’s security.
When it comes to server security, it’s crucial to stay proactive and regularly reassess your configurations to ensure the highest level of protection. By implementing the advanced OpenSSH features discussed in this article, you can significantly enhance your server’s security posture and protect your valuable data.