Best Practices for Ubuntu Server Security 2025
Introduction and Security Principles
Linux server hardening protects data, services, and users by reducing risks and making attacks harder. Good security follows a few clear principles: minimize what runs, give the least privileges needed, layer protections, log everything useful, and assume breaches will happen. These ideas guide choices from installation to incident response.
This article shows practical, tested steps for securing Linux systems. Each section gives clear actions and examples you can apply to servers, virtual machines, and containers.
Secure Installation and Minimal Base System
Start security at install time. A minimal, well-configured base reduces the attack surface and makes ongoing maintenance easier.
- Choose a minimal distribution image or use the “minimal install” option.
- Avoid installing recommended or optional packages unless required.
- Partition sensibly. Put /var, /tmp, and /home on separate partitions when possible.
- Use full-disk encryption (LUKS) for laptops and servers storing sensitive data.
- Use secure mount options in /etc/fstab such as
noexec,nodev,nosuidfor non-root filesystems when appropriate. - Enable Secure Boot and keep firmware up to date.
Example fstab mount options:
/dev/sdb1 /data ext4 defaults,noexec,nodev,nosuid 0 2
Install only trusted packages from official repos. If you need third-party software, prefer signed packages and reproducible builds.
User and Access Management
Control who can access systems and what they can do.
- Create separate accounts for people and services. Never share accounts.
- Apply the principle of least privilege: give users only the rights they need.
- Use meaningful groups to manage permissions rather than giving many users sudo.
- Enforce strong password rules with /etc/login.defs and PAM settings (lockout, expiration).
- Use chage to set password expirations and account inactivity.
- Lock or remove unused accounts and set secure home directory permissions (
chmod 700 /home/user).
Commands examples:
adduser alice
usermod -aG deploy alice
chage -M 90 alice # force password change every 90 days
passwd -l olduser # lock an account
Keep a clear user lifecycle process: request → approve → provision → revoke.
Authentication and Privilege Separation
Use strong authentication and careful privilege separation to limit damage if an account is compromised.
- Prefer SSH key authentication and disable password authentication where possible.
- Use multi-factor authentication (MFA) for interactive and privileged access.
- Use sudo instead of direct root logins. Restrict sudo to specific commands when possible.
- Use service accounts for automated tasks and avoid using human accounts for automation.
- Use PAM controls to limit concurrent sessions and enforce 2FA.
Sudo best practices:
- Keep a small sudoers list and use
visudo. - Use
Defaults log_outputand per-command logging where available. - Avoid NOPASSWD except for carefully controlled scripts.
Secure SSH Configuration and Remote Access
SSH is the most common remote access vector. Lock it down.
Recommended sshd_config settings:
Protocol 2
PermitRootLogin no
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM yes
MaxAuthTries 3
AllowUsers alice deploy@10.0.0.0/8
ClientAliveInterval 300
ClientAliveCountMax 2
Additional practices:
- Use a bastion or jump host for admin access and log connections there.
- Use hardware tokens (YubiKey) or FIDO2 for high assurance.
- Rate-limit and block repeated failed attempts with fail2ban or firewall rules.
- If you must allow passwords, use account lockout for repeated failures and short-lived VPN access instead of exposing SSH to the internet.
Network Security and Firewall Configuration
Network rules limit who can reach services and reduce lateral movement.
- Default to deny: allow only needed ports and IP ranges.
- Use host-based firewall (nftables/iptables, ufw, or firewalld) to enforce rules.
- Segment networks: separate management, application, and database traffic.
- Use VPNs or private networks for administration and sensitive services.
- Harden TCP/IP settings via sysctl to resist common network attacks.
Example nftables minimal policy:
table inet filter {
chain input {
type filter hook input priority 0;
ct state established,related accept
iif lo accept
ip protocol icmp accept
tcp dport {22,443} ct state new accept
counter drop
}
}
Recommended sysctl network hardening:
net.ipv4.ip_forward = 0
net.ipv4.conf.all.rp_filter = 1
net.ipv4.tcp_syncookies = 1
net.ipv6.conf.all.disable_ipv6 = 1 # if you are not using IPv6
Consider intrusion prevention systems and internal IDS for deeper network visibility.
Package Management and Patch Automation
Keeping software updated is one of the most effective controls.
- Use the distribution’s package manager and signed repositories.
- Enable automatic security updates for patch windows you can tolerate (e.g., unattended-upgrades on Debian/Ubuntu or yum-cron on RHEL).
- Test updates in staging before deploying to production.
- Track CVEs and subscribe to vendor security alerts.
- Use kernel live-patching solutions (Canonical Livepatch, kpatch) for critical systems that cannot reboot quickly.
Automation example (Debian/Ubuntu):
apt install unattended-upgrades
dpkg-reconfigure --priority=low unattended-upgrades
Keep third-party and container images updated and scanned.
Container and Virtualization Security
Containers and VMs introduce their own risks. Secure both layers.
Containers:
- Use minimal base images and official or signed images.
- Scan images for vulnerabilities with tools like Trivy or Clair.
- Run containers as non-root users and drop capabilities.
- Use read-only filesystems and seccomp profiles.
- Enforce resource limits with cgroups.
- Use AppArmor or SELinux policies for container isolation.
- Avoid mounting sensitive host directories into containers.
Example Docker run flags:
--user 1001:1001 --read-only --cap-drop ALL --cap-add CHOWN
Virtualization:
- Keep hypervisor and management tools patched.
- Isolate management networks and restrict access to the virtualization API.
- Use secure storage and network isolation for VMs.
- Limit VM escape risk by minimizing exposed host resources and applying SELinux/AppArmor on hosts.
For orchestration (Kubernetes), enable Pod Security Policies (or replacements like OPA/Gatekeeper), network policies, and image admission controls.
Kernel and System Service Hardening
Tighten the kernel and system services to prevent misuse.
- Apply secure sysctl values and lock them to a configuration file.
- Disable unnecessary kernel modules.
- Protect /proc and /sys where possible and restrict access to kernel tunables.
- Mount /tmp with
noexec,nodev,nosuidor use systemd’s PrivateTmp where appropriate. - Use SELinux or AppArmor in enforcing mode and maintain targeted policies.
- Harden systemd services by adding options such as
ProtectSystem=full,PrivateTmp=yes,NoNewPrivileges=true, andReadOnlyPaths=in unit files for untrusted services.
Example systemd unit snippet:
[Service]
PrivateTmp=true
ProtectSystem=full
NoNewPrivileges=true
Audit system services regularly and remove or disable those not needed.
Monitoring, Logging, and Intrusion Detection
You cannot secure what you cannot see. Logging and monitoring catch problems early.
- Centralize logs to a remote, immutable store (syslog server, Elasticsearch, or cloud logging).
- Configure log retention and secure access to logs.
- Use auditd for kernel-level auditing of file accesses and privileged actions.
- Deploy file-integrity tools like AIDE or tripwire and schedule regular checks.
- Use IDS/IPS tools (Suricata, Zeek) and host-based agents (OSSEC/Wazuh, Falco).
- Monitor metrics (CPU, memory, I/O, network) with Prometheus and alert with sensible thresholds.
- Create meaningful alerts to avoid alert fatigue and tune them over time.
Logging examples:
- Audit user sudo activity and SSH logins.
- Alert on unexpected privilege escalations, new listening services, or changes to critical binaries.
Backup, Recovery, and Incident Response
Prepare for failure and intrusions with tested plans and reliable backups.
- Follow the 3-2-1 backup rule: three copies, two different media, one offsite.
- Encrypt backups at rest and in transit.
- Automate regular backups and verify restores frequently.
- Define Recovery Time Objective (RTO) and Recovery Point Objective (RPO) for each service.
- Maintain an incident response plan that includes roles, contact lists, containment steps, and forensic procedures.
- Keep forensic-ready snapshots and avoid making changes to compromised systems before imaging.
- Practice tabletop exercises and runbooks for common scenarios (ransomware, data breach, privilege escalation).
Document who can authorize restores, how to bring systems back, and how to communicate during incidents.
Compliance, Auditing, and Documentation
Audits and documentation turn security into a repeatable, auditable process.
- Use benchmarks like CIS, DISA STIGs, or vendor guidance as baselines.
- Maintain an inventory of systems, software versions, and exposures.
- Use configuration management (Ansible, Salt, Puppet) to enforce and record desired states.
- Keep detailed change logs and approval records for configuration changes.
- Run regular audits and produce evidentiary reports for compliance needs.
- Store runbooks, SOPs, and architecture diagrams in a secure, versioned place.
Automation helps with consistent evidence collection — automated scans, compliance checks, and report exports reduce manual work.
Prioritized Checklist (Quick Actions)
- Use a minimal install and enable disk encryption.
- Disable root SSH login; use key-based auth and MFA.
- Limit open network ports and apply a default-deny firewall policy.
- Enable automatic security updates after testing.
- Run services with least privilege and use sudo for admin tasks.
- Enable auditd, centralize logs, and deploy file-integrity checks.
- Back up critical data offsite and test restores regularly.
- Document configurations and run periodic compliance checks.
Follow these actions first, then build in monitoring, automation, and incident response capabilities.
Final Notes
Security is continuous. Apply layered defenses, test regularly, and keep documentation current. Start with the highest-impact controls (patching, access control, logging, and backups) and expand into deeper hardening like kernel tunables, container policies, and compliance automation. Small, consistent steps make systems safer and easier to manage over time.
About Jack Williams
Jack Williams is a WordPress and server management specialist at Moss.sh, where he helps developers automate their WordPress deployments and streamline server administration for crypto platforms and traditional web projects. With a focus on practical DevOps solutions, he writes guides on zero-downtime deployments, security automation, WordPress performance optimization, and cryptocurrency platform reviews for freelancers, agencies, and startups in the blockchain and fintech space.
Leave a Reply