Wednesday, 5 February 2025

How to Secure Your Linux VPS: Essential Best Practices for Maximum Protection

A Linux VPS (Virtual Private Server) is a powerful and flexible solution for hosting websites, applications, and business services. However, without proper security measures, your VPS can become an easy target for hackers, malware, and other cyber threats. From brute-force attacks to unauthorized access, cybercriminals are constantly searching for vulnerabilities to exploit.

To ensure your VPS remains secure, it is crucial to implement robust security practices. In this guide, we’ll walk you through the best practices to protect your Linux VPS from potential threats, ensuring optimal performance and safety. Whether you’re a beginner or an experienced system administrator, these steps will help you fortify your server and minimize security risks.

1. Choosing a Secure VPS Provider

The foundation of a secure Linux VPS starts with selecting a reliable VPS provider that prioritizes security. A well-secured hosting environment reduces the risk of cyber threats and ensures a stable server performance.

Key Features to Look for in a Secure VPS Provider

  1. DDoS Protection: A VPS provider should offer built-in Distributed Denial-of-Service (DDoS) protection to safeguard against traffic floods that can disrupt your server.
  2. Regular Backups: Automatic backups help you restore your server in case of data loss or security breaches.
  3. Firewall and Network Security: A good provider includes advanced firewall options to prevent unauthorized access.
  4. 24/7 Monitoring & Support: A provider with real-time monitoring and responsive customer support ensures that any security threats are quickly addressed.
  5. Isolated Virtualization Technology: Ensure the VPS provider uses KVM, OpenVZ, or Hyper-V for better security and resource isolation.

Recommended VPS Provider

For a secure and reliable VPS hosting experience, 99RDP offers top-tier Linux VPS solutions with advanced security features, including:
DDoS protection to shield your server from cyberattacks.
High-performance infrastructure with optimized security settings.
Fast SSD storage and dedicated resources for better performance.
24/7 customer support to help you resolve security concerns.

By choosing a VPS provider like 99RDP, you get a secure and high-performance Linux VPS that ensures your data is well protected.

2. Updating and Patching Your System Regularly

One of the most critical steps in securing your Linux VPS is keeping your operating system and software up to date. Outdated software often contains vulnerabilities that attackers can exploit. Regular updates ensure that security patches are applied, reducing the risk of potential breaches.

Why Updates Matter?

  • Fixes security vulnerabilities.
  • Enhances system stability and performance.
  • Closes backdoors that attackers could use to gain access.

How to Update Your Linux VPS?

The process of updating your Linux VPS depends on the distribution (Ubuntu, Debian, CentOS, etc.). Here’s how you can keep your system up to date:

For Debian/Ubuntu-Based Systems

Use the following commands to update and upgrade your system:

sudo apt update && sudo apt upgrade -y

To enable automatic security updates, install unattended-upgrades:

sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades
For CentOS/RHEL-Based Systems

Use the following command to update all installed packages:

sudo yum update -y   # For CentOS 7 and older
sudo dnf update -y   # For CentOS 8, RHEL 8+

To enable automatic updates:

sudo yum install yum-cron  # For CentOS 7
sudo systemctl enable --now yum-cron

For CentOS 8+, use:

sudo dnf install dnf-automatic
sudo systemctl enable --now dnf-automatic.timer

Kernel Updates for Better Security

Updating the Linux kernel is crucial for security improvements. You can check your current kernel version with:

uname -r

To install a new kernel:

  • Ubuntu/Debian:
    sudo apt install linux-generic
    
  • CentOS/RHEL:
    sudo yum install kernel
    

After installing a new kernel, reboot your system to apply changes:

sudo reboot

Automating Updates for Convenience

To ensure your system stays updated without manual intervention, you can schedule updates using cron jobs or enable automatic update services like unattended-upgrades on Debian/Ubuntu or dnf-automatic on CentOS/RHEL.

By regularly updating your VPS, you eliminate vulnerabilities before they can be exploited. Keeping your system patched and updated is a simple yet effective security measure that every VPS owner must follow.

3. Configuring SSH for Enhanced Security

Secure Shell (SSH) is the primary method for accessing a Linux VPS, but it is also a common attack target. Hackers often use brute-force attacks to guess SSH login credentials. To enhance security, it’s essential to harden SSH access with best practices.

a) Change the Default SSH Port

By default, SSH runs on port 22, making it an easy target for automated attacks. Changing the port adds an extra layer of security.

How to Change the SSH Port?

  1. Open the SSH configuration file:
    sudo nano /etc/ssh/sshd_config
    
  2. Find the line that says:
    #Port 22
    
  3. Change it to a different, unused port (e.g., 2222 or 5000):
    Port 2222
    
  4. Save the file (CTRL + X, then Y, and press Enter).
  5. Restart SSH service to apply changes:
    sudo systemctl restart ssh
    

💡 Note: Ensure the new SSH port is allowed in your firewall before restarting SSH.

b) Disable Root Login

Logging in as root directly is risky because root has unlimited access to the system. Instead, use a non-root user with sudo privileges.

How to Disable Root Login?

  1. Edit the SSH configuration file:
    sudo nano /etc/ssh/sshd_config
    
  2. Locate and modify the following line:
    PermitRootLogin no
    
  3. Save the file and restart SSH:
    sudo systemctl restart ssh
    

💡 Tip: If you haven't created a non-root user yet, do it before disabling root login:

sudo adduser newuser
sudo usermod -aG sudo newuser

Then, log in using:

ssh newuser@your-server-ip -p 2222

c) Enforce SSH Key-Based Authentication

Instead of passwords, use SSH key authentication for better security. SSH keys are nearly impossible to brute-force.

Generating SSH Key Pair

Run the following command on your local machine:

ssh-keygen -t rsa -b 4096

This generates two files:

  • id_rsa (Private Key – Keep this secure)
  • id_rsa.pub (Public Key – Upload this to your VPS)

Uploading SSH Key to Your VPS

Copy the public key to your VPS:

ssh-copy-id -i ~/.ssh/id_rsa.pub newuser@your-server-ip -p 2222

Alternatively, manually add it to the ~/.ssh/authorized_keys file:

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

Disable Password Authentication

Once SSH key authentication is set up, disable password logins for added security:

  1. Edit the SSH config file:
    sudo nano /etc/ssh/sshd_config
    
  2. Set the following values:
    PasswordAuthentication no
    
  3. Restart SSH:
    sudo systemctl restart ssh
    

d) Use Fail2Ban to Prevent Brute-Force Attacks

Fail2Ban monitors authentication logs and bans IPs with multiple failed login attempts.

Installing Fail2Ban

For Debian/Ubuntu:

sudo apt install fail2ban -y

For CentOS/RHEL:

sudo yum install epel-release -y
sudo yum install fail2ban -y

Configuring Fail2Ban for SSH

  1. Create a new config file:
    sudo nano /etc/fail2ban/jail.local
    
  2. Add the following content:
    [sshd]
    enabled = true
    port = 2222
    maxretry = 5
    bantime = 600
    findtime = 600
    
  3. Restart Fail2Ban to apply changes:
    sudo systemctl restart fail2ban
    

Final Thoughts

By securing SSH access, you significantly reduce the risk of unauthorized access to your VPS. These steps—changing the SSH port, disabling root login, enforcing key-based authentication, and enabling Fail2Ban—create a strong security foundation for your Linux VPS.

4. Implementing a Firewall for Additional Protection

A firewall is a critical security component that helps block unauthorized access to your Linux VPS by controlling inbound and outbound network traffic. By properly configuring a firewall, you can allow only necessary services and block everything else, reducing the risk of attacks.

a) Choosing a Firewall for Your Linux VPS

There are three main firewall options for Linux:

  1. UFW (Uncomplicated Firewall) – Ideal for Ubuntu/Debian users.
  2. firewalld – Default for CentOS/RHEL-based distributions.
  3. iptables – Advanced firewall, but requires manual rule management.

b) Setting Up UFW (Recommended for Ubuntu/Debian)

UFW (Uncomplicated Firewall) simplifies firewall management.

Step 1: Install UFW (if not installed)

sudo apt install ufw -y

Step 2: Allow Essential Services

Before enabling UFW, allow SSH access (change port if modified earlier):

sudo ufw allow 2222/tcp

Allow other necessary services:

sudo ufw allow 80/tcp   # HTTP
sudo ufw allow 443/tcp  # HTTPS
sudo ufw allow 3306/tcp # MySQL (Only if needed)

Step 3: Enable and Verify UFW

sudo ufw enable
sudo ufw status verbose

💡 Tip: If you get locked out of SSH, use a VPS console from 99RDP to access your server.

c) Setting Up firewalld (For CentOS/RHEL Users)

Step 1: Install firewalld (if not installed)

sudo yum install firewalld -y
sudo systemctl enable --now firewalld

Step 2: Allow Essential Services

sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Step 3: Check Firewall Status

sudo firewall-cmd --list-all

d) Configuring iptables (For Advanced Users)

If you prefer iptables, here’s a basic setup:

sudo iptables -A INPUT -p tcp --dport 2222 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
sudo iptables-save | sudo tee /etc/iptables/rules.v4

💡 Note: iptables rules reset after reboot unless explicitly saved.

e) Enabling DDoS Protection with Fail2Ban

To prevent brute-force and DDoS attacks, Fail2Ban (which we configured earlier) helps detect and block suspicious activity. You can add more filters for web services to protect against bots.

For example, to protect Apache or Nginx, add this to /etc/fail2ban/jail.local:

[nginx-http-auth]
enabled = true
port = http,https
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 5
bantime = 600

Then restart Fail2Ban:

sudo systemctl restart fail2ban

Final Thoughts

By setting up a firewall and configuring Fail2Ban, you create a strong security perimeter around your Linux VPS. Firewalls restrict access to only necessary services, reducing the risk of intrusions.

5. Disabling Unused Services and Ports for Better Security

One of the most effective ways to secure your Linux VPS is to disable unused services and close unnecessary ports. Open ports can serve as entry points for attackers, and unnecessary services may introduce vulnerabilities that can be exploited. By minimizing your system’s attack surface, you significantly reduce security risks.

a) Identifying Open Ports and Running Services

To check which ports are open on your VPS, you can use the following commands:

Using netstat (For Older Systems)

sudo netstat -tulnp

Using ss (For Newer Systems)

sudo ss -tulnp

This will display active network connections, the listening ports, and the services running on them.

Alternatively, you can use nmap (install if not available):

sudo apt install nmap -y  # Debian/Ubuntu
sudo yum install nmap -y  # CentOS/RHEL

nmap -sT -O localhost

💡 Tip: Ports like 21 (FTP), 23 (Telnet), 25 (SMTP), and others should be disabled unless you specifically need them.

b) Disabling Unused Services

To list running services:

sudo systemctl list-units --type=service

To stop a service that you don’t need:

sudo systemctl stop <service-name>

To disable it permanently:

sudo systemctl disable <service-name>

For example, if Telnet or FTP is running and you don’t need it, disable them:

sudo systemctl stop telnet
sudo systemctl disable telnet
sudo systemctl stop vsftpd
sudo systemctl disable vsftpd

c) Closing Unused Ports with UFW (For Debian/Ubuntu Users)

To deny access to a specific port:

sudo ufw deny 23/tcp  # Blocks Telnet
sudo ufw deny 21/tcp  # Blocks FTP
sudo ufw reload

To see firewall rules:

sudo ufw status numbered

If you accidentally block an important port, remove it using:

sudo ufw delete <rule-number>

d) Closing Unused Ports with firewalld (For CentOS/RHEL Users)

To block a port:

sudo firewall-cmd --permanent --remove-port=21/tcp
sudo firewall-cmd --permanent --remove-port=23/tcp
sudo firewall-cmd --reload

To verify changes:

sudo firewall-cmd --list-all

e) Removing Unused Packages for Better Security

Unused software packages may have vulnerabilities. Remove unnecessary packages using:

For Debian/Ubuntu:

sudo apt autoremove --purge

For CentOS/RHEL:

sudo yum autoremove

To find and remove old dependencies:

sudo apt-get clean && sudo apt-get autoclean

Final Thoughts

By disabling unused services and closing unnecessary ports, you eliminate potential security risks and improve server performance. Regularly reviewing running services and open ports ensures that your Linux VPS is only running what is essential for its operation.

6. Enabling Intrusion Detection and Monitoring for Proactive Security

Even with strong security measures in place, continuous monitoring is crucial to detect suspicious activity, unauthorized access, and potential security breaches. Implementing intrusion detection and monitoring tools on your Linux VPS helps you stay ahead of threats before they cause damage.

a) Setting Up Fail2Ban for Intrusion Prevention

As mentioned earlier, Fail2Ban is an essential tool that detects and blocks repeated failed login attempts, preventing brute-force attacks. If you haven’t installed it yet, follow these steps:

Installing Fail2Ban

For Ubuntu/Debian:

sudo apt install fail2ban -y

For CentOS/RHEL:

sudo yum install epel-release -y
sudo yum install fail2ban -y

Configuring Fail2Ban for SSH and Other Services

Create a local configuration file:

sudo nano /etc/fail2ban/jail.local

Add the following configuration:

[sshd]
enabled = true
port = 2222
maxretry = 5
bantime = 600
findtime = 600

For Nginx/Apache protection, add:

[nginx-http-auth]
enabled = true
port = http,https
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 5
bantime = 600

Restart Fail2Ban to apply changes:

sudo systemctl restart fail2ban
sudo systemctl enable fail2ban

Check banned IPs:

sudo fail2ban-client status sshd

b) Installing RKHunter for Rootkit Detection

Rootkits are a dangerous form of malware that can give attackers unauthorized control over your system. RKHunter (Rootkit Hunter) scans your system for suspicious activities.

Installing RKHunter

For Ubuntu/Debian:

sudo apt install rkhunter -y

For CentOS/RHEL:

sudo yum install epel-release -y
sudo yum install rkhunter -y

Running a Rootkit Scan

Manually scan your system:

sudo rkhunter --check

To update its database:

sudo rkhunter --update

Enable daily automatic scans:

sudo nano /etc/cron.daily/rkhunter

Add this line:

rkhunter --check --quiet

Save and exit (CTRL + X, then Y, and press Enter).

c) Installing ClamAV for Malware Detection

ClamAV is an open-source antivirus engine that scans your Linux VPS for malware and viruses.

Installing ClamAV

For Ubuntu/Debian:

sudo apt install clamav clamav-daemon -y

For CentOS/RHEL:

sudo yum install epel-release -y
sudo yum install clamav clamav-update -y

Updating ClamAV Database

sudo freshclam

Running a Scan for Malware

sudo clamscan -r /home

For a full system scan:

sudo clamscan -r --remove /

Schedule daily scans:

sudo nano /etc/cron.daily/clamscan

Add this:

clamscan -r --remove /

Save and exit (CTRL + X, then Y, and press Enter).

d) Setting Up Logwatch for Log Monitoring

Logwatch is a log analysis tool that helps track unusual system activity by summarizing logs and sending daily reports.

Installing Logwatch

For Ubuntu/Debian:

sudo apt install logwatch -y

For CentOS/RHEL:

sudo yum install logwatch -y

Running Logwatch Manually

sudo logwatch --detail high --mailto youremail@example.com --range today

To enable daily reports, edit the cron job:

sudo nano /etc/cron.daily/00logwatch

Ensure it contains:

/usr/sbin/logwatch --output mail --mailto youremail@example.com --detail high

Final Thoughts

By enabling intrusion detection and monitoring, you create an active defense system for your Linux VPS. Tools like Fail2Ban, RKHunter, ClamAV, and Logwatch ensure that any suspicious activity is detected and mitigated before it causes harm.

7. Using Strong Authentication and User Management for Better Security

Securing your Linux VPS involves more than just firewalls and monitoring tools; it also requires strong authentication methods and proper user management. Weak passwords and improper user permissions can lead to unauthorized access, making your server vulnerable to attacks.

a) Enforcing Strong Password Policies

1. Set Minimum Password Strength

Ensure all users on your VPS use strong passwords by enforcing password complexity rules.

Install the libpam-pwquality package:

sudo apt install libpam-pwquality -y  # Ubuntu/Debian
sudo yum install pam_pwquality -y     # CentOS/RHEL

Edit the password quality configuration file:

sudo nano /etc/security/pwquality.conf

Modify or add the following lines:

minlen = 12        # Minimum password length
dcredit = -1       # Require at least one digit
ucredit = -1       # Require at least one uppercase letter
lcredit = -1       # Require at least one lowercase letter
ocredit = -1       # Require at least one special character

Save and exit (CTRL + X, then Y, and press Enter).

2. Force Users to Change Passwords Regularly

To expire passwords after a set number of days (e.g., 90 days):

sudo chage -M 90 username

To force an immediate password change on next login:

sudo passwd --expire username

b) Setting Up Two-Factor Authentication (2FA) for SSH

Two-Factor Authentication (2FA) adds an extra layer of security by requiring a one-time code in addition to the password.

1. Install Google Authenticator

sudo apt install libpam-google-authenticator -y  # Ubuntu/Debian
sudo yum install google-authenticator -y        # CentOS/RHEL

2. Configure Google Authenticator

Run:

google-authenticator

You’ll see a QR code that can be scanned with Google Authenticator (or another OTP app). Answer the prompts as follows:

  • Time-based tokens (TOTP)?y
  • Update .google_authenticator file?y
  • Disallow multiple uses?y
  • Increase security by delaying logins?y
  • Rate limit logins?y

3. Enable 2FA for SSH

Edit PAM settings:

sudo nano /etc/pam.d/sshd

Add this line at the end:

auth required pam_google_authenticator.so

Edit the SSH configuration file:

sudo nano /etc/ssh/sshd_config

Find and modify these lines:

ChallengeResponseAuthentication yes
UsePAM yes

Save the file and restart SSH:

sudo systemctl restart sshd

Now, when logging in via SSH, you’ll need both your password and the 2FA code.

c) Managing User Permissions and sudo Access

Using least privilege access ensures users have only the permissions they need to perform their tasks.

1. Create a New User Instead of Using Root

If you haven’t created a non-root user, do it now:

sudo adduser newuser

Give the user sudo privileges:

sudo usermod -aG sudo newuser  # Ubuntu/Debian
sudo usermod -aG wheel newuser  # CentOS/RHEL

2. Restrict sudo Access to Specific Commands

To limit a user’s sudo access, edit the sudoers file:

sudo visudo

Add the following rule:

newuser ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx

This allows newuser to restart Nginx but nothing else.

3. Prevent Users from Switching to Root

To disable direct root login:

sudo nano /etc/ssh/sshd_config

Set:

PermitRootLogin no

Restart SSH:

sudo systemctl restart sshd

4. List and Remove Unused Users

To see all users:

cut -d: -f1 /etc/passwd

To remove an old user:

sudo deluser username

To delete their home directory as well:

sudo deluser --remove-home username

Final Thoughts

By enforcing strong authentication and managing user access properly, you significantly reduce security risks. Using strong passwords, 2FA, and limiting sudo privileges ensures that only authorized users can access critical system functions.

8. Setting Up Automatic Backups to Protect Data

No matter how secure your Linux VPS is, data loss can occur due to hardware failures, cyberattacks, or accidental deletions. Implementing a regular backup strategy ensures that you can quickly restore your system in case of any disaster.

a) Choosing a Backup Strategy

There are different backup strategies based on frequency and storage location:

  1. Full Backups – Copies the entire system (ideal for weekly/monthly backups).
  2. Incremental Backups – Backs up only changed files (faster and efficient for daily backups).
  3. Remote Backups – Stores backups on an external server (prevents data loss in case of local failures).
  4. Automated Snapshots – Some VPS providers (like 99RDP) offer VPS snapshots for quick recovery.

💡 Recommendation: Use both local and remote backups for maximum safety.

b) Using rsync for Local and Remote Backups

rsync is a powerful tool for syncing files and creating backups.

1. Install rsync (if not installed)

sudo apt install rsync -y  # Ubuntu/Debian
sudo yum install rsync -y  # CentOS/RHEL

2. Create a Local Backup

Run this command to back up the /var/www directory to /backup:

rsync -av --delete /var/www /backup

To back up your entire VPS:

rsync -av --exclude={"/proc","/sys","/dev","/run","/tmp","/mnt","/media","/lost+found"} / /backup

3. Automate Backups with Cron Jobs

To schedule daily backups at 2 AM, edit the cron job file:

sudo crontab -e

Add this line:

0 2 * * * rsync -av --delete /var/www /backup

This will back up your website files daily.

c) Backing Up to a Remote Server Using rsync

To send backups to a remote server (Replace with your actual remote IP & user):

rsync -avz -e "ssh -p 2222" /backup user@remote-server:/remote/backup

To automate this, create a cron job:

0 3 * * * rsync -avz -e "ssh -p 2222" /backup user@remote-server:/remote/backup

This syncs local backups to a remote server every night at 3 AM.

d) Using tar for Compressed Backups

To create a compressed archive of important directories:

tar -czvf /backup/website-backup.tar.gz /var/www

To restore a tar backup:

tar -xzvf /backup/website-backup.tar.gz -C /

e) Using Bacula for Enterprise-Level Backup Management

If you need advanced backup management, install Bacula, a powerful backup tool.

1. Install Bacula on Ubuntu/Debian

sudo apt install bacula -y

2. Install Bacula on CentOS/RHEL

sudo yum install bacula-client -y

After installation, configure backup directories and schedules in /etc/bacula/bacula-dir.conf.

f) Automating Database Backups (MySQL/MariaDB/PostgreSQL)

For MySQL/MariaDB, automate daily backups with this cron job:

sudo crontab -e

Add this:

0 1 * * * mysqldump -u root -p'password' --all-databases | gzip > /backup/db-backup-$(date +\%F).sql.gz

For PostgreSQL backups:

0 1 * * * pg_dumpall -U postgres | gzip > /backup/pg-backup-$(date +\%F).sql.gz

g) Using Cloud Storage for Backup Storage

To back up to Google Drive, Dropbox, or AWS S3, use rclone.

1. Install rclone

sudo apt install rclone -y  # Ubuntu/Debian
sudo yum install rclone -y  # CentOS/RHEL

2. Configure rclone

Run:

rclone config

Follow the setup to connect your cloud storage.

3. Backup to Cloud

rclone copy /backup remote:backup-folder

To schedule automatic backups, add this to cron jobs:

0 4 * * * rclone sync /backup remote:backup-folder

This syncs backups to cloud storage at 4 AM daily.

Final Thoughts

Setting up automated backups is crucial to prevent data loss. By using rsync, tar, Bacula, database backups, and cloud storage, you ensure that your Linux VPS can be restored quickly and efficiently in case of failure.

9. Securing Web Applications and Databases

Web applications and databases are often the most targeted components of a Linux VPS. Cybercriminals exploit vulnerabilities in website code, misconfigured databases, and outdated software to launch attacks. Properly securing your web applications and databases ensures data integrity, confidentiality, and availability.

a) Keeping Web Server Software Updated

If you use Apache, Nginx, or LiteSpeed, keeping them updated helps fix security vulnerabilities.

Update Nginx

For Debian/Ubuntu:

sudo apt update && sudo apt upgrade nginx -y

For CentOS/RHEL:

sudo yum update nginx -y

Update Apache

For Debian/Ubuntu:

sudo apt update && sudo apt upgrade apache2 -y

For CentOS/RHEL:

sudo yum update httpd -y

Check the version after updating:

nginx -v   # For Nginx
apache2 -v # For Apache

b) Enabling HTTPS with Let’s Encrypt SSL

An SSL certificate encrypts data between users and your VPS, preventing MITM (Man-in-the-Middle) attacks.

1. Install Certbot

For Apache:

sudo apt install certbot python3-certbot-apache -y

For Nginx:

sudo apt install certbot python3-certbot-nginx -y

2. Get a Free SSL Certificate

For Apache:

sudo certbot --apache

For Nginx:

sudo certbot --nginx

3. Auto-Renew SSL

Certbot automatically renews SSL certificates, but you can check:

sudo certbot renew --dry-run

c) Securing Database Servers (MySQL/MariaDB/PostgreSQL)

Databases often store sensitive user information. Leaving them unprotected can lead to SQL injections, data breaches, and unauthorized access.

1. Disable Remote Access to Databases

By default, databases listen on all network interfaces, making them vulnerable to remote attacks.

Edit MySQL configuration:

sudo nano /etc/mysql/my.cnf  # Ubuntu/Debian
sudo nano /etc/my.cnf        # CentOS/RHEL

Find this line:

bind-address = 127.0.0.1

Ensure it is not set to 0.0.0.0. Restart MySQL:

sudo systemctl restart mysql

For PostgreSQL, edit:

sudo nano /var/lib/pgsql/data/postgresql.conf

Find and modify:

listen_addresses = 'localhost'

Restart PostgreSQL:

sudo systemctl restart postgresql

2. Use Strong Database Passwords

Change weak database passwords using:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'StrongPassword123!';
FLUSH PRIVILEGES;

For PostgreSQL:

ALTER USER postgres WITH PASSWORD 'StrongPassword123!';

3. Remove Default and Unused Databases

By default, MySQL/MariaDB installations include unnecessary databases. Remove them:

mysql -u root -p -e "DROP DATABASE test;"
mysql -u root -p -e "DELETE FROM mysql.user WHERE User='';"
mysql -u root -p -e "FLUSH PRIVILEGES;"

4. Limit User Privileges

Give users only the access they need. Avoid using root for applications.

Create a restricted database user:

CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'SecurePass!';
GRANT SELECT, INSERT, UPDATE, DELETE ON database_name.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;

d) Preventing SQL Injection and Web Attacks

1. Use a Web Application Firewall (WAF)

A WAF protects against SQL injections, XSS, and DDoS attacks.

For Apache, install ModSecurity:

sudo apt install libapache2-mod-security2 -y
sudo a2enmod security2
sudo systemctl restart apache2

For Nginx, use NAXSI:

sudo apt install libnginx-mod-naxsi -y
sudo systemctl restart nginx

2. Protect Against SQL Injection

  • Use prepared statements instead of raw SQL queries.
  • Never trust user input; sanitize and validate all inputs.
  • Set strict database permissions.

Example of prepared statements in PHP:

$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();

3. Hide PHP Errors

Displaying PHP errors exposes sensitive system information. Disable them in:

sudo nano /etc/php/7.4/apache2/php.ini  # Change version as needed

Find and update:

display_errors = Off
log_errors = On

Restart Apache or Nginx:

sudo systemctl restart apache2  # For Apache
sudo systemctl restart nginx    # For Nginx

e) Implementing Content Security Policy (CSP) for Web Security

A Content Security Policy (CSP) helps prevent XSS attacks by restricting which resources (scripts, styles, images) are allowed to load.

For Apache, add this to your virtual host config:

Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline';"

For Nginx, add this inside the server {} block:

add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline';";

Restart the web server:

sudo systemctl restart apache2
sudo systemctl restart nginx

Final Thoughts

Securing web applications and databases ensures that attackers cannot exploit vulnerabilities to compromise your Linux VPS. By:
✔ Keeping web server software updated
Enforcing SSL encryption
Restricting database access
Preventing SQL injection and XSS attacks

You significantly improve security and performance.

10. Regular Security Audits and Best Practices

Even after implementing strong security measures, your Linux VPS needs continuous monitoring and audits to identify potential weaknesses. Regular security audits help detect misconfigurations, vulnerabilities, and unauthorized access before attackers exploit them.

a) Running Lynis for a Comprehensive Security Audit

Lynis is a powerful security auditing tool that scans your system for security weaknesses and provides recommendations.

1. Install Lynis

For Ubuntu/Debian:

sudo apt install lynis -y

For CentOS/RHEL:

sudo yum install epel-release -y
sudo yum install lynis -y

2. Perform a Security Scan

Run the following command to scan your system:

sudo lynis audit system

Lynis will analyze your VPS and provide a security score along with recommendations to fix vulnerabilities.

b) Checking System Logs for Unusual Activity

Reviewing system logs helps detect potential security threats.

1. View SSH Login Attempts

sudo cat /var/log/auth.log | grep "sshd"

For CentOS/RHEL:

sudo cat /var/log/secure | grep "sshd"

2. Check System Logs for Errors and Warnings

sudo journalctl -p err -b

3. Monitor User Activity

To list recent logins:

last

To see users currently logged in:

w

c) Enabling Automatic Security Updates

Keeping your system updated is one of the easiest ways to improve security.

1. Enable Automatic Updates on Ubuntu/Debian

sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure unattended-upgrades

To manually apply security updates:

sudo apt update && sudo apt upgrade -y

2. Enable Automatic Updates on CentOS/RHEL

sudo yum install yum-cron -y
sudo systemctl enable --now yum-cron

d) Using Tripwire for File Integrity Monitoring

Tripwire monitors files for unauthorized changes, helping detect intrusions and tampering.

1. Install Tripwire

For Ubuntu/Debian:

sudo apt install tripwire -y

For CentOS/RHEL:

sudo yum install epel-release -y
sudo yum install tripwire -y

2. Initialize Tripwire

sudo tripwire --init

To manually check file integrity:

sudo tripwire --check

e) Conducting Regular Penetration Testing

Penetration testing (pen-testing) helps simulate real-world attacks to find vulnerabilities.

1. Install Nikto (Web Security Scanner)

sudo apt install nikto -y

Run a scan against your web server:

nikto -h http://yourdomain.com

2. Scan for Open Ports with Nmap

sudo apt install nmap -y
nmap -sV -p- your-server-ip

f) Hardening the Kernel with sysctl

Modify system parameters to enhance security:

Edit sysctl configuration:

sudo nano /etc/sysctl.conf

Add the following lines:

net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0

Apply the changes:

sudo sysctl -p

g) Restricting Access with AppArmor or SELinux

AppArmor (Ubuntu/Debian):

sudo apt install apparmor-profiles -y
sudo aa-status

SELinux (CentOS/RHEL):

sudo yum install policycoreutils -y
sudo sestatus

To enforce SELinux:

sudo setenforce 1

Final Thoughts

Regular security audits ensure that your Linux VPS remains protected against new threats and vulnerabilities. By:
✔ Running Lynis for system audits
✔ Monitoring logs and user activity
✔ Enforcing automatic updates
✔ Using Tripwire for file integrity monitoring
✔ Conducting penetration tests

You can proactively detect and prevent security risks before they cause harm.

🎯 Final Conclusion

Securing your Linux VPS is an ongoing process, and following the best practices outlined in this guide will help protect your server from attacks.

🔒 Recap of Key Security Measures:

✅ Choose a secure VPS provider (99RDP)
✅ Keep your system updated
✅ Harden SSH access
✅ Implement a firewall and Fail2Ban
✅ Disable unused services and ports
✅ Enable intrusion detection and monitoring
✅ Use strong authentication & user management
✅ Automate backups to prevent data loss
✅ Secure web applications and databases
✅ Conduct regular security audits and penetration testing

By staying proactive with security, your Linux VPS will remain safe, stable, and optimized.

🚀 Protect Your VPS Today & Stay Secure!

0 comments:

Post a Comment

Popular Posts

Blog Archive