Linux Server Hardening: Steps and Best Practices
Securing a Linux system goes far beyond installing firewalls or setting strong passwords—it’s about building a resilient, well-configured environment that can withstand evolving threats. Linux server hardening means reinforcing your system’s defenses by minimizing vulnerabilities, tightening configurations, and continuously monitoring for potential risks. In simple terms, it’s the process of making a Linux server more secure by reducing its attack surface.
Linux already provides several built-in mechanisms that form the first line of defense.
Features such as file permissions, SELinux (Security-Enhanced Linux), AppArmor, and iptables/firewalld give administrators strong foundational control over what processes, users, and network services can do.
These tools, when properly configured, can effectively isolate critical system components and prevent unauthorized access.
Example – Checking SELinux Status:
sestatus
This command shows whether SELinux is enforcing, permissive, or disabled — an essential first step in validating your system’s baseline security.
Always keep SELinux or AppArmor enabled in enforcing mode in production environments. Disabling them might simplify debugging, but it also removes an important layer of protection.
While built-in features are powerful, add-on hardening tools and frameworks extend Linux’s security posture even further.
Tools like Lynis, Fail2ban, and AIDE (Advanced Intrusion Detection Environment) automate auditing and anomaly detection, helping administrators quickly identify misconfigurations or unusual activity.
Example – Running a Basic Security Audit with Lynis:
sudo lynis audit system
After execution, [Lynis] (/docs/freebsd-tutorials/how-to-configure-security-event-audit-on-freebsd#how-to-perform-audit-using-lynis) performs a detailed scan and provides a comprehensive security report with recommendations for system hardening.
Use automation tools such as Ansible or Puppet to apply hardening policies consistently across multiple Linux servers. This ensures that best practices are not only documented but also reproducible.
Server hardening is not a one-time setup. As new vulnerabilities emerge and software evolves, configurations that were secure last year might become exploitable tomorrow.
Maintaining a secure Linux environment means continuously applying patches, updating configurations, and auditing systems.
Regular reviews using tools like OpenSCAP or CIS Benchmarks can ensure that your infrastructure stays compliant with current security standards.
Example – Scanning for Vulnerabilities with OpenSCAP:
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis /usr/share/xml/scap/ssg/content/ssg-rhel9-ds.xml
This command evaluates your Linux system against the CIS benchmark profile and provides a detailed compliance report.
Avoid treating hardening checklists as static documents. Instead, integrate continuous security validation into your DevOps or CI/CD workflows.
Linux server hardening is both an art and a discipline—balancing performance, usability, and security in a constantly shifting landscape.
Built-in features provide the foundation, third-party tools strengthen the perimeter, and continuous auditing keeps systems compliant and trustworthy.
By viewing hardening as an ongoing cycle rather than a single event, administrators can ensure their Linux environments remain secure, stable, and resilient against modern cyber threats.
What is Linux Server Hardening?
Linux server hardening is the process of strengthening a Linux operating system by minimizing vulnerabilities, tightening access controls, and removing unnecessary components that could be exploited by attackers.
In simple terms, it means locking down your Linux environment so that only what’s essential for business operations remains active—every unused service, open port, or permissive configuration is disabled.
Hardening transforms a default Linux installation into a secure, resilient, and compliance-ready system, significantly reducing the likelihood of unauthorized access, data breaches, and malware infections.
For organizations, it’s not just a technical measure—it’s a foundational cybersecurity discipline that ensures critical infrastructure and applications are protected against both internal and external threats.
Every Linux server—from a simple web host to a cloud-based Kubernetes node—becomes a potential target the moment it’s deployed.
Attackers constantly scan the internet for misconfigurations, outdated packages, and weak credentials. Even a single open SSH port or forgotten test service can become an entry point.
Hardening mitigates these risks by:
- Minimizing the number of active services and open ports,
- Restricting user privileges and enforcing least-privilege principles,
- Applying secure configurations for system files and network daemons,
- Ensuring consistency and compliance across hybrid and cloud environments.
For businesses and IT teams, this means:
- Reduced risk of ransomware, privilege escalation, or data theft,
- Improved uptime and stability through consistent, controlled configurations,
- Compliance readiness with frameworks like ISO 27001, NIST 800-53, and CIS Benchmarks.
Treat Linux hardening as a baseline requirement—not an optional enhancement. It’s the first and most crucial step in building a secure production environment.
A Linux server left in its default state can easily become a liability. Even minor oversights—like an open Telnet port or outdated package—can lead to full system compromise.
Common examples include:
- Exposed services: Unused ports (e.g., FTP, Telnet) left accessible to the internet.
- Weak credentials: Reused or simple passwords make brute-force attacks trivial.
- Unpatched vulnerabilities: Old kernels or software containing known CVEs.
- Excessive permissions: Sensitive files readable or writable by unintended users.
- No monitoring: Malicious activity remaining undetected for weeks or months.
Example – Checking Open Ports with netstat:
sudo netstat -tuln
This command lists all open ports and listening services—helping you identify unnecessary ones that should be closed.
Every unnecessary port increases your attack surface. Disable or remove all services that are not strictly required for the server’s function.
Operating System (OS) Hardening in Linux focuses on securing the core layers of the operating system—the kernel, user accounts, file system, and network stack.
It’s about transforming a general-purpose Linux OS into a purpose-built, hardened platform that runs only what’s necessary.
Here are key technical steps:
-
Apply Security Patches Regularly: Keep your system current to close known vulnerabilities.
-
sudo apt update && sudo apt upgrade -y: This ensures the latest kernel and package-level patches are applied.
-
Disable Unused Services: Unnecessary services increase exposure. Disable them.
-
sudo systemctl disable telnet
-
jsx sudo systemctl stop telnet: Telnet is insecure; replace it with SSH for encrypted communication.
-
Implement Least Privilege Access: Restrict user permissions to the bare minimum required.
-
sudo adduser developer: Creates a standard user without administrative privileges.
-
Configure Firewall Rules: Limit inbound and outbound connections to essential ports only.
-
sudo ufw enable
-
sudo ufw allow ssh
-
sudo ufw deny 23: Activates UFW, allows SSH (port 22), and blocks insecure Telnet.
System security doesn’t end at the operating system. True hardening extends to applications, network layers, and continuous monitoring.
Integrating tools and frameworks adds automation and detection capabilities:
-
Fail2ban: Prevents brute-force login attempts.
-
AIDE (Advanced Intrusion Detection Environment): Detects unauthorized file changes.
-
SELinux / AppArmor: Enforces mandatory access controls across processes.
Example – Enabling SELinux Enforcement:
sudo setenforce 1
This activates SELinux enforcement mode, ensuring strict process-level security.
Never disable SELinux or AppArmor in production unless absolutely necessary. Doing so removes a vital layer of system protection.
Linux server hardening is not a one-time setup—it’s an ongoing discipline that evolves with every software update, new user, or configuration change.
By following structured hardening steps, enforcing least privilege, patching regularly, and monitoring continuously, administrators can significantly reduce exposure to modern cyber threats.
Ultimately, hardening transforms a Linux system from being merely functional into being trustworthy, resilient, and enterprise-ready—a true stronghold for business-critical operations.
What is the First Step in Hardening a Linux System?
Hardening a Linux system begins with one fundamental principle: start secure, stay secure.
The very first steps lay the foundation for everything that follows — if your base system isn’t clean, updated, and minimal, no amount of configuration later will make it truly safe.
Here’s how to begin hardening a Linux system the right way:
1. Update the System and Apply Security Patches
Keeping your system up-to-date is the single most important step in hardening.
Outdated packages often contain known vulnerabilities that attackers exploit within hours of disclosure.
Example – Update and upgrade packages:
sudo apt update && sudo apt upgrade -y
or for RHEL-based systems:
sudo dnf update -y
These commands ensure all installed packages are current, applying security patches and kernel updates automatically.
Configure automatic updates for security packages using tools like unattended-upgrades (Debian/Ubuntu) or dnf-automatic (RHEL/Fedora). This minimizes the window of exposure.
2. Remove Unnecessary Software and Services
A smaller system footprint means fewer potential attack surfaces. Every package you don’t need is a potential vulnerability—either today or tomorrow.
Example – Remove unused packages:
sudo apt remove telnet ftp rsh -y
sudo apt autoremove -y
The first command removes legacy network services (Telnet, FTP, RSH) that transmit data in plain text—a major security risk.
The second command, autoremove, cleans up any leftover dependencies no longer needed by the system, ensuring a leaner and safer configuration.
Example – Disable unwanted services:
sudo systemctl disable cups
sudo systemctl stop cups
This ensures that unused daemons like printing services or legacy protocols aren’t running in the background.
Many exploits depend on forgotten or unnecessary background services. The fewer components running, the safer your system becomes.
3. Verify System Integrity and Baseline Configuration
Before proceeding further, it’s good practice to know exactly what’s running and what’s installed.
This helps you establish a clean baseline—useful for audits, compliance checks, and intrusion detection later.
Example – List active services and startup daemons:
Knowing which services start automatically helps identify unnecessary background processes that increase your server’s attack surface.
This command lists all enabled services and daemons configured to start at boot.
sudo systemctl list-unit-files --type=service | grep enabled
Example – Check listening network ports:
Attackers often scan for open ports to find potential entry points.
This command shows all network ports currently listening for incoming connections, along with their associated services.
sudo ss -tuln
Documenting these outputs helps track configuration drift over time.
4. Set Up Basic Security Tools
Once your base system is clean and updated, it’s time to enable core security components:
- Firewall: Controls inbound/outbound traffic (ufw, firewalld).
- Fail2ban: Protects against brute-force attacks.
- AIDE: Monitors file integrity.
Example – Enable UFW Firewall:
sudo ufw enable
sudo ufw default deny incoming
sudo ufw allow ssh
This blocks all connections by default except SSH, creating a basic but effective security perimeter.
Skipping the basics often leads to the biggest compromises.
Most successful attacks exploit unpatched vulnerabilities or unused open services — both preventable with these simple first steps.
A properly hardened baseline ensures that your Linux system starts from a secure state, minimizing future risks and simplifying ongoing maintenance.
Think of these steps as “locking the doors and windows” before installing the alarm system. Security configurations and monitoring tools only make sense after your foundation is solid.
What Security Features does Linux Provide Out of the Box?
Linux is often described as “secure by default,” and for good reason. Unlike many operating systems that require additional software or third-party tools for basic protection, Linux includes multiple security layers out of the box—built directly into its kernel and core utilities.
These features work together to provide robust default protection even before any manual hardening or custom configurations are applied.
1. File Permissions and Ownership
At the foundation of Linux security lies its powerful file permission and ownership system.
Every file and directory is associated with three key permissions—read (r), write (w), and execute (x)—applied to three types of users: owner, group, and others.
This model ensures that users and processes can only access what they’re explicitly allowed to, limiting damage from user mistakes or malware infections.
Example – View file permissions:
ls -l /etc/passwd
You’ll see an output similar to:
-rw-r--r-- 1 root root 2000 Oct 10 12:00 /etc/passwd
Here, only the root user can modify the file, while all others can read it.
This principle of least privilege protects system-critical files and binaries from unauthorized modification—a core element of Linux’s built-in defense strategy.
Regularly review permissions for sensitive directories like /etc, /usr/bin, and /var/log. Adjust permissions using chmod and chown only when absolutely necessary.
2. Discretionary and Mandatory Access Controls
Beyond basic permissions, Linux provides advanced access control frameworks such as SELinux (Security-Enhanced Linux) and AppArmor.
These are Mandatory Access Control (MAC) systems—they enforce strict security policies that limit what applications and processes can access, even if an attacker gains a foothold.
Example – Check SELinux status:
Sestatus
This command displays the current operational state of SELinux on your system.
Output:
SELinux status: enabled
Current mode: enforcing
This confirms that SELinux is both enabled and actively enforcing security policies on your system.
When enabled, SELinux or AppArmor confines processes within predefined policies, preventing them from accessing files or executing commands beyond their assigned privileges.
This greatly reduces the impact of zero-day exploits and privilege escalation attacks.
Keep SELinux or AppArmor in enforcing mode in production environments. Disabling them might make troubleshooting easier but weakens system protection.
3. Firewall and Network Protection
Linux comes with a built-in firewall system that controls inbound and outbound traffic using tools like iptables or firewalld.
These firewalls filter network packets based on rules, ports, and protocols—acting as the first line of defense against unauthorized access.
Example – List current firewall rules:
To list all active iptables rules:
sudo iptables -L
or for systems using firewalld:
sudo firewall-cmd --list-all
By default, most Linux distributions deny unsolicited incoming connections and allow only established sessions, ensuring a secure networking baseline even before customization.
Apply the principle of “default deny.” Allow only the ports and services you truly need (for example, SSH on port 22, HTTPS on 443).
4. Privilege Separation and the sudo Mechanism
Unlike some operating systems that allow users to perform administrative tasks freely, Linux strictly separates root privileges from normal users.
The sudo command lets users perform administrative actions temporarily and with accountability—requiring authentication and logging every privileged command.
Example – Running a privileged command safely:
sudo systemctl restart ssh
This structure minimizes the risk of accidental system-wide changes or privilege abuse.
It also provides an audit trail for administrative actions, a feature often missing or less transparent in non-Unix systems.
Never log in directly as root. Use ```jsx sudo to maintain traceability and control over administrative access.
5. Process Isolation and Kernel-Level Security
Linux’s kernel includes several mechanisms that isolate processes and control resource access:
-
Namespaces isolate system resources (network, users, filesystems) for each process.
-
cgroups (Control Groups) limit resource usage per process or container.
-
seccomp filters restrict the system calls available to an application.
These kernel-level technologies are the foundation of container security in tools like Docker, Kubernetes, and Podman — making Linux inherently suited for modern cloud environments.
6. Logging and Auditing
Linux offers comprehensive logging through journald, syslog, and auditd.
These systems record all major system events, user actions, and authentication attempts — essential for incident response and compliance auditing.
Example – View recent log entries:
sudo journalctl -xe
With centralized logging, administrators can quickly detect unusual patterns, such as repeated failed logins or unauthorized privilege escalations.
Regularly monitor /var/log/auth.log and journalctl outputs. Combine with automated tools like fail2ban to block malicious IPs.
Together, these built-in components create multiple layers of defense — often called defense-in-depth.
Even a fresh Linux installation benefits from this layered architecture:
-
File permissions protect system integrity.
-
MAC frameworks (SELinux/AppArmor) prevent unauthorized process actions.
-
Firewalls control external access.
-
sudo ensures safe administrative control.
-
Logging and auditing provide visibility and accountability.
This means a Linux system starts off secure, even before additional hardening or third-party tools are introduced.
Compared to other platforms:
-
Windows relies heavily on antivirus software and GUI-driven policies for security.
-
macOS offers strong sandboxing but restricts deep administrative customization.
-
Linux, being open-source and modular, exposes every layer for configuration — giving administrators complete transparency and control over security behavior.
In Linux, you can directly see, modify, and extend every security mechanism yourself.
This openness, combined with community-driven patching, makes Linux one of the fastest systems to respond to emerging threats.
Out of the box, Linux provides a robust, multi-layered defense system that most other operating systems achieve only through additional tools.
From permissions and firewalls to SELinux and auditing, every layer of Linux security is designed to prevent, detect, and contain threats before they escalate.
When these native protections are combined with proper hardening practices — such as regular patching, access control, and monitoring — Linux becomes not just a secure operating system, but a resilient cybersecurity platform.
How Can User Accounts and Permissions Be Hardened in Linux?
Hardening user accounts and permissions in Linux means enforcing strict control over who can access the system, what they can do, and how those actions are tracked.
It’s the cornerstone of a secure Linux environment because most breaches stem not from sophisticated exploits, but from weak, mismanaged, or forgotten user accounts.
In practical terms, account and permission hardening involves:
- Limiting user privileges to only what’s required for their role (least privilege principle),
- Removing or disabling unnecessary and default accounts,
- Enforcing strong authentication and password policies,
- Regularly auditing permissions and system access logs.
By securing user access properly, you prevent insider threats, privilege escalation, and unauthorized access — the three most common causes of Linux system compromise.
In Linux, every process runs under a user account, whether it’s a person logging in or a daemon executing a background task. That means a single compromised user can open the door to system-wide exploitation if permissions are too broad.
Common risks of weak account security include:
- Privilege Escalation: A non-admin user gains root privileges due to misconfigured ```jsx sudo access.
- Orphaned Accounts: Old user accounts from former employees remain active and exploitable.
- Shared Credentials: Multiple people using the same account eliminate accountability.
- Weak Passwords: Simple or reused passwords are easy targets for brute-force attacks.
Every user, permission, and group setting in Linux contributes to your security posture—ignoring them often leads to silent vulnerabilities that attackers exploit first.
Treat account and permission management as a living process, not a one-time setup. Each system update or personnel change should trigger a user audit.
1. Apply the Principle of Least Privilege
The least privilege principle (PoLP) means that users should only have the minimum access necessary to perform their duties. This dramatically reduces the impact of any compromised account or malicious insider.
Example – Creating a non-root user:
sudo adduser developer
This command creates a new user named developer, assigns them a home directory (/home/developer), and prompts you to set a password.
Example – Granting limited sudo access:
sudo usermod -aG
sudo developer
The user developer is now a member of the sudo group, allowing them to execute administrative commands with explicit authorization.
Even with sudo rights, actions are logged, making it easier to audit administrative activity.
Avoid giving direct root access to anyone—instead, use sudo for controlled privilege elevation.
Never share the root password or enable direct root login via SSH. This is one of the most common misconfigurations in compromised Linux systems.
2. Remove or Disable Unnecessary Accounts
Many Linux distributions ship with default system or service accounts. Some are essential, while others might remain unused and pose security risks if left active.
Example – List all system accounts:
cut -d: -f1 /etc/passwd
Displays a list of all user accounts registered on the system, including both normal and system users (like root, daemon, www-data, etc.).
Example – Lock an unused account:
sudo usermod -L olduser
The account olduser is now locked. Its password hash in /etc/shadow is prefixed with !, which disables login attempts until explicitly unlocked.
Example – Remove a user completely:
sudo deluser olduser
Deletes the olduser account, its home directory, and associated mail spool. This ensures no residual data or access tokens remain on the system. Regularly reviewing active accounts helps eliminate dormant credentials that could be exploited by attackers.
Integrate account cleanup into your patch or maintenance schedule. Inactive users should be disabled automatically after a defined period.
3. Enforce Strong Authentication Policies
Even the best access controls are ineffective if passwords are weak. Linux provides native tools to enforce password complexity, rotation, and lockout policies.
Example – Edit password aging and complexity:
sudo vim /etc/login.defs
This file controls system-wide password rules such as expiration, minimum days between changes, and warning periods before expiry.
Recommended settings:
PASS_MAX_DAYS 90
PASS_MIN_DAYS 7
PASS_WARN_AGE 14
PASS_MAX_DAYS 90 → Forces users to change their password every 90 days.
PASS_MIN_DAYS 7 → Prevents immediate password reuse, enforcing at least a 7-day interval between changes.
PASS_WARN_AGE 14 → Notifies users 14 days before their password expires, giving them time to update credentials.
Example – Lock an account after failed login attempts (using pam_tally2):
sudo vim /etc/pam.d/common-auth
This file controls how the Pluggable Authentication Modules (PAM) stack handles user logins across the system.
Add this line:
auth required pam_tally2.so deny=5 onerr=fail unlock_time=300
This locks the user for 5 minutes after 5 failed attempts, deterring brute-force attacks.
For production servers, consider integrating multi-factor authentication (MFA) or SSH key-based logins instead of passwords.
4. Audit and Monitor User Activity
Regular auditing ensures that user permissions match their roles and helps identify anomalies early. Use built-in Linux tools to check logins, last activity, and permission changes.
Example – Check recent login history:
lastlog
Outputs a table showing the last login date, time, and source IP for all accounts.
Example – View failed login attempts:
sudo journalctl -u ssh -p err
Displays only error-priority logs (-p err) related to the SSH service.
Example – Review sudo usage:
sudo cat /var/log/auth.log | grep
These logs provide invaluable visibility into who’s doing what on your system — crucial for compliance, forensics, and proactive security.
5. Manage File and Directory Permissions Wisely
Misconfigured file permissions are one of the easiest paths for attackers to gain access to sensitive data.
Ensure that only authorized users can read or modify critical files.
Example—Restrict access to sensitive directories:
sudo chmod 700 /root
sudo chmod 600 /etc/ssh/sshd_config
chmod 700 /root → Restricts access to the root user only; others cannot read, write, or execute inside the root home directory.
chmod 600 /etc/ssh/sshd_config → Ensures only root can read or modify the SSH server configuration file, preventing unauthorized tampering.
Example – Set correct ownership:
sudo chown root:root /etc/passwd
Ensures both the file owner and group are set to root, which prevents unauthorized modification of the system’s user account database.Without this, a non-privileged user could alter login information — potentially granting themselves administrative access.
Always verify permissions with:
ls -l /etc/
This ensures configuration files, logs, and private data aren’t exposed to unauthorized users.
User and permission hardening is one of the most effective—yet often overlooked—aspects of Linux security.
While tools like firewalls and SELinux protect against external threats, user mismanagement remains the root cause of most compromises. By enforcing least privilege, removing defaults, tightening password policies, and auditing activity, administrators can drastically reduce risk and ensure accountability across all systems.
How Does SSH Hardening Improve Linux Server Security?
SSH hardening is the process of securing the Secure Shell (SSH) service—the most common entry point for system administrators.Although SSH encrypts connections, default configurations often leave systems vulnerable to brute-force attempts, credential theft, or unauthorized remote access. Hardening SSH means reinforcing how authentication works, restricting who can log in, and reducing exposure to automated attacks.
In simple terms, it’s about tightening the front door of your server—ensuring only trusted users with secure credentials can get in.
Attackers constantly scan the internet for open SSH ports (usually port 22).
Common exploits include:
-
Brute-forcing weak or reused passwords.
-
Exploiting misconfigured permissions on SSH keys.
-
Taking advantage of enabled root logins.
-
Using outdated OpenSSH versions with known vulnerabilities.
Every weak SSH setup shortens the time it takes for an attacker to gain control of your server.
Most brute-force bots detect and attack SSH ports within minutes of exposure. Always harden SSH before connecting a server to the public internet.
Practical SSH Hardening Steps
1. Disable Root Login
By default, root logins are allowed over SSH-a dangerous practice.
To disable it, open the SSH configuration file:
sudo vim /etc/ssh/sshd_config
Inside the file, locate and modify this line:
PermitRootLogin no
This ensures even if attackers guess your root password, they can't log in remotely.
Attackers must compromise a normal user account first, reducing the risk of total system takeover.
2. Use Key-Based Authentication Instead of Passwords
SSH keys are far more secure than passwords because they rely on asymmetric cryptography.
To generate a new SSH key pair on your local machine:
ssh-keygen -t ed25519
Then, copy your public key to the server:
ssh-copy-id user@server_ip
This disables password-based logins and replaces them with unique cryptographic credentials. Even if attackers know your username, they can't connect without your private key file.
3. Change the Default SSH Port
Attackers often target port 22. Changing it won't stop all attacks, but it significantly reduces automated scanning.
Edit your SSH configuration again:
sudo vim /etc/ssh/sshd_config
Find and update this line:
Port 2222
Restart the SSH service:
sudo systemctl restart ssh
Only users who know the new port can attempt connections - reducing bot traffic and failed login attempts.
4. Enable Fail2ban for Brute-Force Protection
Fail2ban monitors authentication logs and bans IPs that show malicious activity, such as repeated failed logins.
Install it using:
sudo apt install fail2ban -y
Once installed, Fail2ban automatically begins protecting SSH by adding dynamic firewall rules. Attackers get blocked after a few failed attempts, making brute-force attacks virtually impossible.
SSH hardening transforms your remote access method from a potential attack vector into a trusted administrative channel. By disabling root login, replacing passwords with keys, changing default ports, and enabling active protection tools, you build a multi-layered defense that dramatically reduces unauthorized access attempts.
How Can You Minimize the Attack Surface by Disabling Services in Linux?
The attack surface of a Linux system refers to every point where an attacker might gain unauthorized access — including open ports, active services, and installed applications.
The more software you run, the more opportunities you create for attackers to exploit.
Minimizing the attack surface means shutting down or removing everything your server doesn’t actually need, leaving only the essential components required for its intended role.
In short:
Fewer services = Fewer vulnerabilities = A smaller target.
Every unnecessary background service — such as old print daemons, file-sharing tools, or legacy protocols like FTP and Telnet — increases the number of open ports and potential exploits.
For example:
-
An unused Telnet service might allow plaintext logins.
-
A forgotten FTP daemon could expose credentials or files.
-
A CUPS printer service on a web server adds attackable code you don’t need.
Attackers often rely on these overlooked components to establish a foothold before escalating privileges.
Start every server deployment with a minimal OS installation. Add software only as business needs demand, not the other way around.
Step 1: List All Running Services
Before disabling anything, you need to know what’s active.
Use systemctl to list all currently running system services:
sudo systemctl list-units --type=service --state=running
You’ll see a list of services like sshd.service, cron.service, or cups.service. Review each one and identify what’s actually needed for your system’s function.
Step 2: Identify Services Listening on Network Ports
Sometimes, background processes open network ports that you might not be aware of.
Use the following command to view active listening ports:
sudo ss -tuln
This command displays all TCP and UDP ports currently in use, along with the process IDs.
You can easily identify unnecessary open ports (like 21 for FTP or 23 for Telnet) that should be closed to reduce exposure.
Step 3: Stop and Disable Unnecessary Services
Once you identify non-essential services, stop them immediately and disable them at boot time.
For example, to disable the CUPS printing service:
sudo systemctl stop cups
sudo systemctl disable cups
The service stops running and won’t start automatically after reboot. Your system’s footprint becomes smaller and more secure.
Step 4: Remove Unused Packages Completely
Disabling a service helps, but removing it entirely eliminates its files, binaries, and dependencies.
To uninstall insecure or legacy packages like Telnet, FTP, or RSH:
sudo apt remove telnet ftp rsh -y
sudo apt autoremove -y
The software and all its residual components are removed, ensuring no outdated code remains available for exploitation.
Step 5: Verify the Cleanup
After disabling and removing unnecessary software, verify again which services and ports are active:
sudo systemctl list-unit-files --type=service | grep enabled
and
sudo ss -tuln
Only essential services (like SSH or Nginx) should remain active. Everything else should be disabled or removed.
Additional Recommendations
-
Regularly audit services—especially after updates or new software installations.
-
Use firewall rules to further restrict network access to essential ports.
-
Implement change management so any service activation is tracked and approved.
-
Integrate with automation tools like Ansible or Puppet to enforce minimal configurations at scale.
Reducing your Linux system’s attack surface is one of the simplest yet most impactful hardening steps. By disabling unnecessary services and removing outdated packages, you drastically decrease potential entry points for attackers. Every background process you eliminate is one less door for an intruder to knock on.
What Role Do Firewalls Play in Linux Server Hardening?
A firewall acts as the first line of defense in Linux server hardening. It monitors and controls network traffic based on predefined security rules—deciding which packets can enter or leave your system.
In simple terms, a firewall is like a digital gatekeeper: it allows trusted communication while blocking anything suspicious, reducing the chance that malicious traffic ever reaches your applications or data. When properly configured, Linux firewalls can block intrusion attempts, stop data leaks, and prevent brute-force attacks long before they reach the operating system level.Every server connected to a network faces continuous probing—attackers and bots constantly scan IP ranges, looking for open ports or vulnerable services.
Without a firewall, all open ports on your server are directly exposed to the internet.
Firewalls mitigate this by:
-
Blocking unauthorized inbound traffic.
-
Allowing only specific, necessary services (like SSH, HTTP, HTTPS).
-
Preventing data exfiltration from compromised applications.
-
Logging and auditing network activity for threat analysis.
Think of a firewall as your “front door lock.” Even if everything inside your house (system) is secure, leaving the door open invites trouble.
Step 1: Enable the Default Firewall
Most modern Linux distributions include UFW (Uncomplicated Firewall) or firewalld as a default firewall management tool.
The first step is simply to turn it on.
To enable UFW (Ubuntu/Debian):
sudo ufw enable
The firewall starts enforcing existing rules immediately. If none exist yet, all incoming traffic will be blocked except essential outbound connections.
For RHEL/Fedora-based systems using firewalld:
sudo systemctl enable firewalld
sudo systemctl start firewalld
firewalld begins actively managing network zones and enforcing default deny policies.
Step 2: Allow Trusted Connections
After enabling the firewall, allow traffic only for essential services—for instance, SSH for remote management and HTTPS for web access.
To allow SSH (port 22) and HTTPS (port 443):
sudo ufw allow ssh
sudo ufw allow 443/tcp
Your server accepts connections only through these specific ports. Any attempt to connect to other ports will be silently dropped.
For firewalld, use:
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
These commands add permanent firewall rules and reload them without downtime.
