Secure Your Ubuntu Server

In today's interconnected world, server security is paramount. Whether you're running a personal website, a small business application, or a large-scale enterprise system, securing your Ubuntu server is crucial to safeguarding sensitive data, ensuring uptime, and mitigating cyber threats. In this blog post, we'll explore essential practices to bolster the security of your Ubuntu server and protect it against potential vulnerabilities and attacks.

1. Regular Software Updates

Keeping your Ubuntu server up-to-date with the latest security patches is fundamental to maintaining its security posture. Ubuntu releases regular updates and security patches to address known vulnerabilities and enhance system stability. Set up automatic updates or regularly check for updates using the apt package manager to ensure your server is protected against emerging threats. 

sudo apt update

sudo apt upgrade


2. Configure Firewall

Ubuntu comes with a built-in firewall tool called ufw (Uncomplicated Firewall), which allows you to manage firewall rules with ease. Configure ufw to allow only necessary incoming and outgoing traffic while blocking unauthorized access. Start by enabling ufw, allowing SSH (if applicable), and then selectively enable other services as needed.

 

sudo ufw enable

sudo ufw allow ssh


3. Secure SSH Access

Secure Shell (SSH) is a common method for remote server administration, but it's also a prime target for attackers. Strengthen SSH access by disabling root login, using SSH key-based authentication, and changing the default SSH port to a non-standard one to reduce exposure to automated scans.

sudo nano /etc/ssh/sshd_config

# NAME: LALATENDU HARDENED OPENSSH CONFIGURATION

# AUTHOR: LALATENDU

# DATE CREATED: MARCH 02, 2024

# LAST UPDATED: MARCH 02, 2024



########## Binding ##########

#ListenAddress 0.0.0.0

#ListenAddress ::


# Only listen to IPv4

#AddressFamily inet


# Only listen to IPv6

# AddressFamily inet6


########## Features ##########


# ACCEPT LOCALE-RELATED ENVIRONMENT VARIABLES

AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES

AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT

AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE

AcceptEnv XMODIFIERS


# Specify the port for SSH. Change this to a non-standard port to reduce exposure to automated scans.

Port 6594


# Protocol versions to support. Disable SSH Protocol 1 for security reasons.

# Ensure SSH server only uses SSH protocol version 2

# SSHv1 contains security issues and should be avoided at all costs

# Although SSHv1 is disabled by default after OpenSSH 7.0, this option is specified to ensure compatibility with older versions of OpenSSH server


Protocol 2


# Disable root login via SSH to prevent direct root access.

PermitRootLogin no


# Disable tun device forwarding

PermitTunnel no


# Override default of no subsystems

# Path to the sftp-server binary depends on your distribution

# Subsystem sftp /usr/lib/openssh/sftp-server

# Subsystem sftp /usr/libexec/openssh/sftp-server

Subsystem sftp internal-sftp


# Disable password-based authentication in favor of SSH key-based authentication.

PasswordAuthentication no


# PAM authentication enabled to make password authentication available

# remove this if password authentication is not needed

# UsePAM yes


# Set the maximum idle time in seconds before a session is terminated

ClientAliveInterval 300

# NUMBER OF CLIENT ALIVE MESSAGES SENT WITHOUT CLIENT RESPONDING

ClientAliveCountMax 2


# Prevent remote hosts from connecting to forwarded ports

# Forwarded ports are forced to bind to 127.0.0.1 instead of 0.0.0.0

GatewayPorts no




# This setting disables all forwarding features in SSH, overriding any other forwarding switches.

# Setting DisableForwarding to 'yes' ensures that no forwarding is permitted, including TCP, StreamLocal, and tun device forwarding.

DisableForwarding yes



# Specify the path to the authorized keys file. This is where SSH public keys for authentication are stored.

AuthorizedKeysFile      .ssh/authorized_keys .ssh/authorized_keys2


# Limit SSH access to specific users or groups, if applicable.

AllowUsers lalatendu


# To prevent StreamLocal (Unix-domain socket) forwarding in your SSH configuration, use the following directive

AllowStreamLocalForwarding no


# Specify the list of ciphers and MAC algorithms to use. This can enhance security by disabling weaker Cryptography algorithms.

Ciphers aes256-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr,chacha20-poly1305@openssh.com

MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com


# Limit the maximum number of authentication attempts per connection to mitigate brute-force attacks.

MaxAuthTries 3


# SET THE MAXIMUM NUMBER OF CONCURRENT SSH SESSIONS ALLOWED PER USER | ALLOW A MAXIMUM OF TWO MULTIPLEXED SESSIONS OVER A SINGLE TCP CONNECTION

MaxSessions 2


# Disable empty passwords.

PermitEmptyPasswords no


# Set the maximum authentication lifetime (time until reauthentication) in seconds.

MaxAuthAge 600


# Set the maximum login grace time (time allowed for login after authentication) in seconds.

LoginGraceTime 30


# Set the maximum number of authentication failures before the connection is dropped.

MaxStartups 3:50:10


# Enable strict mode to enhance security by checking file permissions and ownership of the user's home directory and .ssh directory.

StrictModes yes


# Disable X11 forwarding to prevent X11 GUI applications from being forwarded over SSH.

X11Forwarding no


# Disallow TCP port forwarding over SSH tunnels

# Note: Disabling TCP forwarding does not prevent users from creating port forwarding via other means

# Users with interactive login shell privileges can still establish their own SSH tunnels

AllowTcpForwarding no


# Enable strict mode for enhanced security

StrictModes yes


# PREVENT SSH TRUST RELATIONSHIPS FROM ALLOWING LATERAL MOVEMENTS

IgnoreRhosts yes


# Log SSH environment variables for auditing

PrintMotd yes

PrintLastLog yes



# Set the banner message displayed before login. You can use this to warn unauthorized users.

Banner /etc/issue.net


# Enable compression for faster data transfer over SSH.

# Compression yes


# COMPRESSION BEFORE ENCRYPTION MIGHT CAUSE SECURITY ISSUES

Compression no


# Set the logging level for SSH connections. Adjust as needed for your logging requirements.

LogLevel VERBOSE


# Specify the MAC algorithms for key exchange. This can enhance security by disabling weaker algorithms.

KexAlgorithms curve25519-sha256@libssh.org

# KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256

HostKeyAlgorithms ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com

PubkeyAcceptedKeyTypes ssh-ed25519,ssh-rsa

#AuthenticationMethods publickey,keyboard-interactive


# Disable SSH agent forwarding

AllowAgentForwarding no


#USE HOST-BASED AUTHENTICATION: IMPLEMENT HOST-BASED AUTHENTICATION IF IT'S SUITABLE FOR YOUR ENVIRONMENT. #THIS CAN PROVIDE AN ADDITIONAL LAYER OF SECURITY. ADD THE FOLLOWING LINE IF DESIRED


HostbasedAuthentication no



# Enable Pubkey Authentication

PubkeyAuthentication yes


# Disable TCP KeepAlive

TCPKeepAlive no

# Challenge-Response authentication backend is not configured by default

ChallengeResponseAuthentication no

MaxSessionsPerUser 2

UsePrivilegeSeparation sandbox

Banner /etc/issue.net



# Disable DNS lookup during SSH connection | DISABLE REVERSE DNS LOOKUPS

UseDNS no


# Allow SSH access for a specific user from a specific IP address

Match Address 192.168.1.100

    AllowUsers lalatendu

    #AllowTcpForwarding yes

    PermitOpen any

    PermitRootLogin no

    X11Forwarding yes

    PasswordAuthentication no

    

########## Authentication ##########


# permit only the specified users to login

#AllowUsers lalatendu


# permit only users within the specified groups to login

#AllowGroups lalatendu


DenyUsers ubuntu centos admin

DenyGroups docker


#Limit Access with TCP Wrapper: Use TCP wrappers (/etc/hosts.allow and /etc/hosts.deny) to control access to #SSH based on IP addresses or hostnames.

# In /etc/hosts.allow

#sshd: 192.168.1.0/24

# In /etc/hosts.deny

#sshd: ALL

#LogLevel VERBOSE



sudo systemctl restart ssh

4. Implement Fail2ban

Fail2ban is a powerful intrusion prevention tool that monitors system logs for suspicious authentication attempts and blocks IP addresses that exhibit malicious behaviour. Install Fail2ban and configure it to monitor SSH authentication logs to prevent brute-force attacks.

 

sudo apt install fail2ban


Configure Fail2ban by editing its configuration files located in /etc/fail2ban/. Typically, the SSH jail configuration is in jail.local. Customize settings according to your security requirements.

5. Setting up Multi-Factor Authentication (MFA) for SSH

Setting up multi-factor authentication (MFA) for SSH on Ubuntu 22.04 involves using a combination of SSH key-based authentication along with an additional authentication factor, such as a one-time password (OTP) generated by a mobile app like Google Authenticator or Authy. Here's a step-by-step guide to set up MFA for SSH on Ubuntu 22.04:

Install Required Packages:

First, make sure your system is up to date:

sudo apt update && sudo apt upgrade -y

Install the necessary packages:

sudo apt install libpam-google-authenticator -y

Configure SSH to Allow OTP Authentication:

Edit the SSH configuration file:

sudo nano /etc/ssh/sshd_config

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

Make sure the following lines are uncommented and set as shown:

AuthenticationMethods publickey,password publickey,keyboard-interactive

ChallengeResponseAuthentication yes

UsePAM yes

Save and close the file, then restart SSH:

sudo systemctl restart sshd

Configure Google Authenticator for Your User:

Run the Google Authenticator setup for your user:

google-authenticator

Follow the on-screen prompts to configure Google Authenticator. You'll be asked several questions, including whether to generate backup codes, whether to require a time-based token, etc. Answer them according to your preferences.

Configure PAM to Use Google Authenticator:

Edit the PAM configuration file for SSH:

sudo nano /etc/pam.d/sshd

sudo cp /etc/pam.d/sshd /etc/pam.d/sshd.bak

Find the line @include common-auth and comment it out by adding a # character as the first character on the line. This tells PAM not to prompt for a password:

# Standard Un*x password updating.

#@include common-auth

@include common-password

auth required pam_google_authenticator.so nullok

auth required pam_permit.so

Restart SSH:

After making changes to the PAM configuration, restart SSH:

sudo systemctl restart sshd

Test MFA Authentication:

Try logging in via SSH. You should now be prompted for your OTP after entering your SSH key passphrase.

Optional: Backup Google Authenticator Codes:

It's essential to back up the QR code or the secret key generated during the Google Authenticator setup process. This ensures that you can regain access in case you lose your phone or can't access the app.

That's it! You've now set up multi-factor authentication (MFA) for SSH on Ubuntu 22.04. Each time you log in via SSH, you'll need to provide both your SSH key passphrase and the one-time password generated by Google Authenticator.

6. Harden System Settings

Take additional steps to harden your Ubuntu server's security by implementing best practices such as:

Conclusion

Securing your Ubuntu server is an ongoing process that requires diligence, vigilance, and a proactive approach to cybersecurity. By following these essential practices and staying informed about emerging threats, you can significantly reduce the risk of security breaches, data loss, and system compromise.

Remember, server security is not a one-time task but a continuous effort. Regularly assess your server's security posture, apply updates promptly, and adapt your security measures to evolving threats to keep your Ubuntu server resilient and protected in today's dynamic threat landscape.