Search

Securing Linux

1 views

Partitioning and File System Layout

When you first install a Linux distribution the way you carve up the disk can dictate how well the system keeps threats at bay for the rest of its life. A single‑mount approach is tempting for the inexperienced, but it hides vulnerabilities and complicates recovery. Instead, break the filesystem into logical units that isolate sensitive data, separate variable content from code, and let the kernel enforce mounting rules that strip unnecessary privileges. Start with a minimal root partition that holds only the core OS; keep that area as small as possible, because the fewer files you have to protect, the fewer opportunities an attacker has to exploit a buffer overflow or mis‑configured script. A typical layout might look like: / for essential binaries and configuration files, /usr for user‑land applications, /var for dynamic data such as logs, mail, databases and caches, /home for personal files, /tmp for temporary data, and /opt for add‑on packages. Each of these can be its own partition, with sizes tuned to your workload: if the system will serve web traffic, give /var a generous slice; if it’s a workstation with heavy user data, allocate more space to /home. The key is to mount the partitions with restrictive options that the kernel will enforce. For instance, mount /usr as read‑only (ro) and add nosuid to prevent SUID binaries from gaining root privileges if a compromised program is present. A common rule is to use nodev on partitions that should not interpret device files, noexec to stop executable code from being run from /tmp, and noatime on /var to reduce surface area for time‑based side‑channel attacks. These options live in /etc/fstab; a typical entry for /tmp might read: tmpfs /tmp tmpfs rw,nosuid,nodev,noexec,noatime 0 0. tmpfs ensures that temporary data disappears on reboot, removing forensic traces of an attacker’s activity. For partitions that hold logs, consider usrquota or usrjquota to limit log growth, preventing disk‑full attacks that deny service. Use the blkid command to assign UUIDs to each device, then reference those UUIDs in /etc/fstab for resiliency against device renumbering. The mount and fstab(5) manual pages are valuable references for the myriad options available; a quick glance at the man page reveals options such as bind for bind mounts, relatime for performance‑optimised time stamps, or discard for SSD wear‑leveling. Partitioning tools like fdisk, gdisk, or the graphical parted make it straightforward to create and resize partitions before installation. If you prefer scripting, parted supports command‑line flags that let you automate partition tables, which is handy for deploying identical secure configurations across many servers. Finally, remember that the bootloader’s grub.cfg or lilo.conf may need explicit references to the root partition; an out‑of‑sync entry can leave the system unable to boot or expose kernel arguments to an attacker if not protected with password="…" and restricted. Proper partitioning is the first line of defense, turning a flat disk into a series of fenced zones that make privilege escalation, data exfiltration, and accidental compromise all but impossible without a targeted approach.

Password Management and User Policies

Passwords are the most visible gatekeeper to a system, yet many administrators rely on them as the sole layer of defense. The reality is that a robust password strategy should be a dynamic, policy‑driven process that anticipates brute‑force, dictionary, and credential‑stuffing attacks. A good starting point is to enforce password complexity and length through PAM modules such as pam_pwquality.so or pam_cracklib.so. These modules can require a minimum of twelve characters, a mix of uppercase, lowercase, digits, and symbols, and a minimum number of unique characters. The /etc/security/pwquality.conf file allows fine‑tuning of these rules; setting minlen=12 and dcredit=-1 forces the use of at least one digit and increases the password strength. Password hashing itself must be strong; modern distributions use sha512crypt by default, but you can enforce it by editing /etc/pam.d/system-auth and ensuring password requisite pam_unix.so sha512 is present. Avoid simple words that appear in public dictionaries; use the cracklib-check command to test against a word list or integrate pwgen -s 16 into user provisioning scripts to generate random secrets. For servers that host sensitive services, consider two‑factor authentication. Tools such as libpam-google-authenticator or pam_oath add a time‑based one‑time password (TOTP) layer that defeats offline cracking. Even if a password is stolen, an attacker still needs a second factor. Additionally, set an account lockout policy with pam_tally2 or pam_faillock to prevent unlimited login attempts. A typical rule is to lock the account after five failed tries and require a system reboot or an administrator’s intervention to unlock. This simple measure thwarts credential‑stuffing attacks from compromised credential databases. The password aging system in /etc/login.defs should enforce a maximum password age of 90 days and a minimum of 7 days, with a 7‑day warning period before expiry. Prompt users to change passwords proactively keeps stale credentials from being a liability. For high‑privilege accounts, avoid shared passwords and enforce single‑user accounts. If you must use a shared account for an application, set a sudo entry that limits the commands available and requires a password for every use. Finally, ensure that user home directories are encrypted if they contain personal data; tools like ecryptfs or cryptsetup --cipher aes-xts-plain64 provide per‑user encryption that is transparent yet secure. Password management is not a one‑off configuration; regularly audit your PAM stack, rotate secrets, and review account policies to keep the defense up to date with evolving attack techniques.

Service Selection and Daemon Hardening

Every daemon running on a Linux box is a potential attack vector; the more services you keep active, the larger the footprint an adversary can exploit. A disciplined approach to service hardening starts with a clean slate: during installation, choose a minimal server profile and then add only the services that are absolutely required. The classic example is to replace telnet with ssh. SSH uses strong public‑key cryptography by default, encrypts all traffic, and can be forced to accept only key‑based logins by setting PasswordAuthentication no in /etc/ssh/sshd_config. For file transfer, the older ftp daemon is a security liability; use vsftpd or pure-ftpd with chrooted virtual users and TLS encryption enabled via ssl_enable=YES. If your system requires mail services, skip the legacy sendmail in favor of postfix or exim, both of which provide better access controls, TLS support, and easier spam filtering. Similarly, replace rsh and rcp with ssh or sftp whenever possible. The firewalld or ufw tools can be used to expose only the ports your services need; for instance, open port 22 for SSH, 80/443 for HTTP/HTTPS, and block everything else. If a service has known security problems, isolate it behind a dedicated VLAN or place it in a DMZ. For example, a public web server should not run the same machine that hosts critical database services. After you install a new daemon, review its configuration for any default settings that enable root access or expose debug interfaces. Many daemons ship with “listen on all interfaces” enabled; restrict them to or the specific subnet you control. Disable or remove any unused modules or plugins; for Apache, the mod_proxy and mod_ssl modules are only needed if you require proxying or TLS, and each added module expands the attack surface. Use systemctl list-unit-files | grep enabled to audit which services are enabled at boot. For services that need to run under a non‑root user, create dedicated system users with minimal privileges and use the User directive in .service files. This approach keeps the privilege boundary tight. Finally, keep your services up to date; most security patches are distributed through the package manager. Enable unattended upgrades if your environment permits, or set a regular reminder to run apt update && apt upgrade or the equivalent for your distribution. A minimal, well‑configured service list reduces the attack surface, makes auditing easier, and gives you a clearer view of the system’s actual exposure.

Boot Loader and Secure Boot Practices

The boot loader is the first code that runs when a system powers on; if it can be tampered with, attackers can modify the kernel or install rootkits before the operating system even starts. Secure boot mechanisms, such as UEFI Secure Boot or legacy bootloader password protection, help prevent unauthorized modifications. On UEFI systems, enable the secure boot option in the firmware, and install a signed bootloader like shim or grub-efi. These loaders verify the integrity of the kernel and initramfs images using cryptographic signatures before handing control over. For systems that still use legacy BIOS, protect the boot loader file with a password by adding password="secret" and restricted to /etc/lilo.conf or the appropriate grub.cfg entry, and run grub-mkconfig -o /boot/grub/grub.cfg afterward. When using LILO, the restricted flag ensures that any attempt to override kernel parameters requires the password. However, LILO is largely obsolete; most modern distributions use GRUB2, which supports more granular access control through menuentry password protection. For example, you can set a password on a specific menu entry that runs a rescue kernel: set superusers="root" password_pbkdf2 root $1$something$. The cryptographic hash can be generated with grub-mkpasswd-pbkdf2. Beyond the boot loader, restrict the BIOS settings themselves: lock the firmware password, disable booting from USB or CD unless explicitly allowed, and enable the “Boot from secure disk” option if available. When the system boots, the kernel will check for /etc/selinux/config to enforce SELinux policies; enable Enforcing mode to add another layer that confines processes to the least privilege required for their function. In environments that require high assurance, consider using TPM (Trusted Platform Module) to attest the system’s boot state; the boot-params module can be used to load a cryptographic hash of the kernel image, ensuring any change is detected. Keep the boot loader itself up to date; most vendors ship security updates for GRUB that address vulnerabilities such as buffer overflows in the menu parser. Regularly review the boot loader configuration for exposed options - do not leave GRUB_DISABLE_RECOVERY=false unless you really need the recovery mode, because it can be used to circumvent other controls. A combination of secure boot, signed kernel images, hardened firmware, and minimal boot loader options provides a solid defense that stops attackers before they even reach the kernel’s memory space.

Vulnerability Scanning and Monitoring

Regular scans expose the hidden weaknesses that manual checks miss. A thorough vulnerability assessment begins by enumerating the open ports and services with nmap -sV -O, then cross‑referencing those results against the National Vulnerability Database (NVD) using tools like nikto for web servers or OpenVAS for general host scanning. The scan output should be fed into a SIEM (Security Information and Event Management) system for correlation; alerts for unpatched software, exposed root accounts, or unusual network activity can be automatically triaged. For Linux, lynis is a popular audit tool that runs a series of checks and produces a report highlighting missing patches, insecure file permissions, and kernel module vulnerabilities. Combining lynis with chkrootkit or rkhunter adds rootkit detection, while clamav can scan for known malware signatures. Automating these scans on a weekly basis ensures that new vulnerabilities are caught early; schedule a cron job to run lynis --quick and email the results to the security team. In addition to host‑based scanning, employ network‑based intrusion detection systems such as Snort or Suricata. These engines monitor traffic in real time, matching packet patterns against a comprehensive rule set that covers known exploits and suspicious behavior. Deploy them on a dedicated network tap or in a passive mirroring configuration so they see all inbound and outbound traffic without becoming a bottleneck. When the IDS detects a suspicious packet, configure it to trigger a system log entry and optionally send an email or Slack notification. Continuous monitoring goes hand in hand with configuration drift detection; tools like Tripwire maintain a checksum database of critical files, flagging unauthorized changes. Pair Tripwire with a version control system such as Git to store baseline configuration snapshots. On top of that, use auditd to log file access, privilege escalation attempts, and system calls that could indicate malicious activity. Combine these logs in a central aggregation point, apply log rotation and retention policies, and regularly audit them for signs of tampering. A proactive scanning and monitoring regime turns the system into a living, breathing security entity that adapts to new threats and reduces the window of vulnerability between patch publication and application.

Logging, Intrusion Detection, and Event Analysis

Logs are the fingerprints that reveal what happened on a machine; when captured, stored, and analyzed properly, they become an invaluable source for detecting and investigating intrusions. Linux ships with syslogd or rsyslog, which funnel system messages into /var/log/messages, /var/log/secure, and other subsystem logs. Customize the /etc/rsyslog.conf file to separate critical logs into dedicated files, such as .crit; .err /var/log/critical.log, or route specific services to remote syslog servers via $ActionSendTCPLog. By default, the auth.log file records all PAM authentication events; monitor it for repeated failed logins, failed sudo attempts, or account lockouts. Combine this with auditd to record every system call that modifies privileged files; filter audit logs with ausearch -m USER_AUTH -ts recent to quickly spot anomalous authentication patterns. In addition, the kernel audit framework can watch for attempted privilege escalation by tracking execve calls from unprivileged users. When logs become too noisy, employ rate‑limiting and log aggregation tools like logrotate and logwatch to maintain a manageable history. For real‑time intrusion detection, install Snort or Suricata and load rule sets that match brute‑force login attempts, port scans, or known exploitation signatures. Configure these IDS engines to trigger actions such as adding an iptables rule to drop the offending IP, or sending an alert to the security operations center. Integrate the IDS with your SIEM; the SIEM can correlate IDS alerts with syslog entries to build a full picture of an attack. For example, a port scan discovered by IDS combined with a failed SSH login sequence can confirm a target enumeration stage. Post‑incident, use log forensic tools such as grep, awk, or the log2timeline utility to reconstruct the timeline of events. Store all logs in an immutable medium - write‑once storage or a secure log server with strict ACLs - so attackers cannot simply delete evidence. Also, encrypt log files at rest using cryptsetup if they contain sensitive information. In addition to passive logging, set up active monitoring for unusual processes: use top or psacct in combination with cron alerts to detect rogue processes or unexpected high CPU usage. Regularly audit the log rotation configuration, verify integrity checks, and test log retrieval processes. By weaving together system logs, IDS alerts, and audit trails, you create a robust detective capability that turns raw data into actionable intelligence, allowing you to detect breaches early, assess damage, and refine defenses.

Encryption, System Integrity, and Physical Security

Protecting data at rest, in transit, and on the device itself is the cornerstone of a secure Linux deployment. For data at rest, use full‑disk encryption with LUKS (Linux Unified Key Setup). During installation, create a cryptsetup partition, generate an AES‑256 key, and require a passphrase at boot; this ensures that even if the hard drive is removed, the data remains unreadable without the key. For users who need encrypted home directories, ecryptfs offers a per‑user solution that automatically encrypts files as they are written to disk. When transmitting sensitive information, never rely on unencrypted protocols; replace Telnet, FTP, and HTTP with SSH, SFTP, and HTTPS, respectively. Configure OpenSSH with Protocol 2, PermitRootLogin no, and UsePrivilegeSeparation sandbox. For web services, obtain an SSL/TLS certificate from a trusted CA, enable HSTS via Strict-Transport-Security: max-age=31536000; includeSubDomains headers, and disable weak ciphers in openssl.cnf. Additionally, implement application‑level encryption for sensitive data stored in databases; use column‑level encryption with tools like pgcrypto for PostgreSQL or MySQL's AES_ENCRYPT. Beyond encryption, maintaining system integrity is essential; employ a file integrity checker such as Tripwire or AIDE to monitor critical binaries, libraries, and configuration files for unauthorized modifications. Configure the integrity tool to run nightly, compare checksums, and send alerts if discrepancies arise. For further assurance, enable kernel hardening features like grsecurity patches, seccomp profiles, or SELinux in enforcing mode. These modules enforce mandatory access control, limiting what processes can do even if compromised. Physical security cannot be ignored: keep servers in locked rooms with controlled access, install tamper‑evident seals on chassis, and use CCTV to monitor the environment. Configure the BIOS to require a password on boot and disable boot from external media. Enable TPM to bind the boot loader to a cryptographic hash, and configure the system to boot only if the measured hash matches the expected value; this prevents rootkits from loading during startup. Regularly audit the physical environment, perform vulnerability assessments on the hardware, and keep an inventory of all devices. In sum, combining strong encryption, strict integrity checks, robust access controls, and disciplined physical security creates a multi‑layered defense that withstands both digital and human adversaries.

Suggest a Correction

Found an error or have a suggestion? Let us know and we'll review it.

Share this article

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!

Related Articles