Skip to content
ShellOps Daily

Linux server hardening, systemd, and Bash automation tips

Server Security

How to Secure Your SSH Server

Victor Novak8 min read

Securing your secure ssh server is crucial for protecting your system from unauthorized access and potential breaches. SSH, while a powerful tool for remote management, is often a target for attackers due to its widespread use and default configurations that can be easily exploited. By implementing strong security practices, you can significantly reduce the risk of compromise and ensure your server remains resilient against common threats.

This article provides a comprehensive guide to hardening your secure ssh server by addressing key vulnerabilities and configuring your SSH settings effectively. From disabling root login to enforcing key-based authentication, each step is designed to enhance your server's security without compromising usability.

Whether you're a system administrator, DevOps engineer, or VPS user, the practical steps outlined here will help you configure a more secure SSH environment. By following these best practices, you'll be better equipped to defend your infrastructure against potential attacks and maintain a higher level of system integrity.

Understanding SSH Vulnerabilities

SSH is a critical protocol for remote access, but its widespread use makes it a frequent target for attackers. Many security incidents stem from vulnerabilities that are often overlooked or left unaddressed. Understanding these risks is the first step in securing your SSH server and protecting your system from exploitation.

Common SSH Attack Vectors

Brute force attacks are one of the most common threats to SSH servers. Attackers attempt to guess login credentials by repeatedly trying different combinations of usernames and passwords. These attacks are often automated and can quickly exhaust system resources if not mitigated. Weak passwords, especially those that are short or based on predictable patterns, make it easier for attackers to gain access. Additionally, misconfigured permissions, such as overly permissive file or directory settings, can allow unauthorized users to access sensitive data or execute malicious code.

Why Default SSH Settings Are Risky

The default configuration of SSH servers is often insecure and can expose your system to a range of risks. For example, allowing root login by default provides attackers with direct access to the most privileged account, increasing the likelihood of a successful breach. Similarly, the default port (22) is well-known, making it a prime target for scanning and exploitation. Many systems also fail to apply security patches promptly, leaving them exposed to known vulnerabilities. By understanding these default risks, you can take proactive steps to modify and secure your SSH configuration.

Disabling Root Login and Restricting User Access

Disabling root login and restricting user access is a fundamental step in securing your SSH server. By eliminating direct access to the root account, you significantly reduce the risk of unauthorized system-wide changes and potential breaches. Instead, use specific users with limited permissions to perform administrative tasks, ensuring better control and accountability.

  1. Edit the `/etc/ssh/sshd_config` file to set `PermitRootLogin no` to disable root login.
  2. Create dedicated user accounts with sudo privileges for administrative tasks.
  3. Use the `AllowUsers` directive to specify which users can log in via SSH.
  4. Restart the SSH service to apply configuration changes with `systemctl restart ssh`.

Configuring PermitRootLogin

Configuring `PermitRootLogin` is crucial for limiting access to the root account. Setting this parameter to `no` prevents direct login attempts, reducing the attack surface. This ensures that any administrative actions must be performed through authorized users with sudo privileges, enhancing security.

Setting Up AllowUsers

Setting up `AllowUsers` allows you to define which users can access the SSH service, further narrowing down potential threats. By specifying usernames, you ensure that only trusted individuals can log in, reducing the risk of unauthorized access. This approach aligns with the principle of least privilege, granting users only the permissions necessary to perform their tasks.

Changing the Default SSH Port

Changing the default SSH port from 22 to a non-standard port is a simple yet effective way to reduce the risk of automated attacks. While port 22 is widely used, it is also frequently targeted by brute-force attempts and scanning tools. By selecting a less common port, you make it harder for attackers to find and exploit your SSH service.

  1. Choose a non-standard port that is not commonly used by other services. Avoid ports that are already reserved for other protocols or applications to prevent conflicts and ensure the new port is available.
  2. Update your SSH configuration file to reflect the new port number. Edit the /etc/ssh/sshd_config file and change the Port directive to your selected port, then restart the SSH service to apply the changes.
  3. Adjust your firewall rules to allow traffic on the new port. Ensure that the firewall is configured to accept incoming connections on the new port number while blocking all other unnecessary ports.
  4. Test the new port configuration to confirm it is working correctly. Use an SSH client to connect to the server using the new port and verify that access is successful and no errors are encountered.

Selecting a New Port

Selecting a new port requires careful consideration to avoid conflicts with other services and ensure it remains open. While there is no universally 'safe' port, it is advisable to choose a port above 1024, as these are typically not reserved for system processes. Avoid using ports that are commonly associated with other protocols, such as 80 (HTTP) or 443 (HTTPS), to reduce the chance of accidental interference.

Updating Firewall Rules

Updating firewall rules is a critical step to ensure your new port is accessible. If you are using a tool like UFW or iptables, you will need to add a rule that allows traffic on the new port. It is also important to ensure that the firewall is configured to block all other unnecessary ports to maintain a secure network environment.

Implementing Fail2Ban for Brute Force Protection

Fail2Ban is a powerful tool that helps protect your SSH server from brute force attacks by monitoring log files and automatically banning IP addresses that exhibit suspicious behavior. By integrating Fail2Ban into your security strategy, you can significantly reduce the risk of unauthorized access attempts.

  1. Install Fail2Ban using your package manager, such as apt-get install fail2ban on Debian-based systems.
  2. Edit the jail.local configuration file to define rules for banning IPs based on failed SSH login attempts.
  3. Set the bantime parameter to determine how long an IP is banned for repeated failures.
  4. Ensure the fail2ban-action is configured to use a firewall like iptables or ufw for blocking IPs.

Installing Fail2Ban

Installing Fail2Ban is the first step in setting up automated protection against SSH brute force attacks. Most Linux distributions provide Fail2Ban through their package repositories, making it easy to install with a single command. Once installed, Fail2Ban runs as a service and continuously monitors system logs for signs of malicious activity.

Configuring Fail2Ban for SSH

Configuring Fail2Ban for SSH involves editing the jail.local file to customize how the tool responds to failed login attempts. This file allows you to specify the maximum number of failed attempts allowed before an IP is banned, the duration of the ban, and the action to take when an IP is flagged. Proper configuration ensures that Fail2Ban effectively blocks malicious traffic while minimizing false positives.

Enabling SSH Key-Based Authentication

Enabling SSH key-based authentication significantly enhances the security of your SSH server by replacing password-based logins with cryptographic authentication. This method reduces the risk of brute force attacks and unauthorized access, making it a best practice for securing remote access.

  1. Generate a key pair using an SSH key generator tool like ssh-keygen.
  2. Copy the public key to the server using the ssh-copy-id command or manually.
  3. Modify the SSH configuration file to disable password authentication.
  4. Restart the SSH service to apply the new configuration.

Generating SSH Keys

Generating SSH keys involves creating a private and public key pair. The private key should be kept secure on the client machine, while the public key is added to the server's authorized_keys file. This process ensures that only the owner of the private key can authenticate to the server.

Setting Up Key-Based Login

Setting up key-based login requires configuring the SSH daemon to accept public keys. This is done by editing the /etc/ssh/sshd_config file and setting PasswordAuthentication to no. Once this is done, the server will only allow access through the SSH keys, effectively blocking password-based logins.

Monitoring and Logging SSH Activity

Monitoring and logging SSH activity is essential for detecting and responding to security threats. By capturing detailed session data and analyzing patterns, administrators can identify suspicious behavior and unauthorized access attempts. Effective logging ensures transparency and helps maintain compliance with security standards.

Configuring SSH Logging

To enable verbose logging, modify the `/etc/ssh/sshd_config` file by setting `LogLevel VERBOSE`. This provides detailed records of authentication attempts, connection events, and session activity. After making changes, restart the SSH service with `systemctl restart ssh` to apply the new settings. Tools like `journalctl` or `auditd` can then be used to access and analyze these logs, offering insights into system-level SSH interactions.

Analyzing SSH Logs for Security

Regularly reviewing SSH logs is crucial for identifying anomalies such as repeated failed login attempts, unexpected user activity, or unauthorized access. Use `journalctl -u ssh` or `auditd` to filter and examine logs for suspicious patterns. Establish a routine to scan logs for unusual entries, such as failed authentication attempts from unknown IP addresses, which could indicate brute force attacks or reconnaissance efforts. This proactive approach strengthens the security posture of your SSH server.

Frequently Asked Questions

How do I disable root login on SSH?

To disable root login, edit the /etc/ssh/sshd_config file and set PermitRootLogin to no. Save the file and restart the SSH service to apply the changes.

What is the best way to prevent brute force attacks on SSH?

The best way is to use Fail2Ban to automatically block IP addresses after multiple failed login attempts, which helps prevent unauthorized access.

Can I use SSH key-based authentication with multiple users?

Yes, each user can have their own SSH key pair. You can manage these keys by placing them in the ~/.ssh/authorized_keys file for each user.

How do I monitor SSH login attempts for suspicious activity?

Enable logging in the /etc/ssh/sshd_config file by setting LogLevel to VERBOSE. Regularly review the /var/log/auth.log file for any suspicious login attempts.

Final Thoughts on SSH Security

Securing your SSH server involves multiple steps, such as disabling root login, changing the default port, and enabling key-based authentication. These measures significantly reduce the risk of unauthorized access and brute force attacks.

To ensure your SSH server remains protected, regularly review logs and update your security configurations. Implementing tools like Fail2Ban can provide an additional layer of defense against potential threats.