Linux Server Security Audit Tutorial
Overview and objectives
A system security audit finds weaknesses before attackers do. This guide shows how to run a thorough audit on a Linux server or small fleet. You will learn how to prepare, scan, verify, and remediate issues. Each section gives clear checks, tools, and simple commands you can run today.
Objectives:
- Create a reliable inventory of assets and services.
- Verify proper user and privilege controls.
- Harden authentication and remote access.
- Check filesystem integrity and file permissions.
- Validate network and firewall settings.
- Ensure services and packages are secure and patched.
- Enable effective logging and monitoring.
- Run vulnerability scans and map findings to risks and controls.
- Prepare an incident response and compliance report.
Use this as a practical checklist that can be repeated regularly or adapted for compliance needs.
Preparing the audit environment and tools
Start with a safe, controlled environment to run tests. Do not run intrusive scans on production systems without approval.
Set up:
- A separate workstation for audit work, ideally air-gapped from production changes.
- Backups or snapshots of systems you will test, so you can roll back if needed.
- Remote access with two separate accounts: one for audits, one for any emergency changes.
Essential tools (free and common):
- nmap — network and port scanning.
- ss or netstat — local socket checks.
- lynis — general system audit and hardening suggestions.
- osquery — live OS inventory queries.
- AIDE or Tripwire — filesystem integrity.
- auditd / ausearch — kernel-level auditing.
- OpenVAS/Greenbone or Nessus — vulnerability scanning.
- grep, awk, find — simple file and config checks.
Keep tools updated. Document versions and test commands in a lab before running in production.
Asset discovery and inventory
Know what you have before auditing. An accurate inventory prevents blind spots.
Steps to build inventory:
- Use network scanning (nmap -sP or -sn) to find hosts on your subnet.
- Query DHCP and DNS servers for assigned addresses and names.
- Use configuration management data (Ansible, Chef, Puppet) and cloud APIs to list resources.
- Run osquery or similar on hosts to gather installed packages, running services, and kernel versions.
Inventory entries should include:
- Hostname, IP, MAC.
- Operating system and kernel version.
- Installed packages and versions.
- Open ports and listening services.
- Physical or virtual location and owner.
Keep the inventory in a searchable format (CSV, JSON, CMDB). Make audits repeatable by scripting discovery and storing outputs for comparison.
User accounts, groups, and access controls
Weak user management causes many breaches. Audit accounts and group memberships regularly.
Checks to perform:
- List human accounts: awk -F: ‘$3 >= 1000 {print $1}’ /etc/passwd (adjust for distro).
- Find accounts with no password or locked passwords: sudo passwd -S username or check /etc/shadow.
- Identify accounts with UID 0: awk -F: ‘($3 == 0) {print $1}’ /etc/passwd.
- Review sudoers and included files: sudo cat /etc/sudoers; sudo ls /etc/sudoers.d/.
- Check group membership for sensitive groups (wheel, adm, sudo).
- Remove or disable unused service accounts.
- Ensure password policies exist (minimum length, complexity, expiration) in /etc/login.defs and PAM configs.
Recommendations:
- Enforce least privilege; only give sudo where needed.
- Use group-based privileges, not broad account sharing.
- Require unique, audited accounts for human access.
Authentication, SSH hardening, and privilege escalation
Remote access is high risk. Harden SSH and limit how credentials are used.
SSH hardening steps:
- Disable root login over SSH: set PermitRootLogin no in /etc/ssh/sshd_config.
- Use key-based auth and disable password auth: PasswordAuthentication no.
- Restrict allowed ciphers and use modern KEX and MAC settings.
- Limit users or groups that can connect: AllowUsers or AllowGroups.
- Set idle and session timeouts: ClientAliveInterval and ClientAliveCountMax.
- Run sshd on a non-standard port only if it reduces noise (not a security measure by itself).
Privilege escalation checks:
- List sudoers with sudo -l for each admin account.
- Search for SUID/SGID binaries and review them: find / -perm /6000 -type f -exec ls -l {} ;.
- Inspect PATH and environment handling in scripts run by privileged services.
- Check for world-writable files in sensitive directories: find /etc -xdev -perm -0002 -type f -exec ls -l {} ;.
Where possible, use multi-factor authentication for privileged accounts and centralize auth with LDAP or an identity provider.
Filesystem integrity, permissions, and SUID/SGID checks
File integrity and permissions protect critical binaries and configs.
Integrity steps:
- Install AIDE and initialize a baseline on a known-good system.
- Schedule regular AIDE checks and review diffs against the baseline.
- For package-managed files, verify package integrity: rpm -Va or debsums -s.
Permissions and SUID/SGID:
- Find all SUID/SGID binaries: find / -perm /6000 -type f -ls.
- Review each binary for necessity and known vulnerabilities.
- Fix incorrect permissions: restore default modes from packages or set conservative permissions (chmod 750 or 700 where appropriate).
- Look for world-writable files and directories: find / -xdev -type d -perm -0002 -ls.
Protect sensitive directories like /etc, /var/log, and /boot by limiting access to system users only.
Network security, firewall, and port management
Strict network controls limit exposure and reduce attack surface.
Network checks:
- List listening ports and associated services: ss -tulnpe or netstat -tulpen.
- Use nmap from a trusted host to scan open ports and service versions (nmap -sV -O host).
- Review firewall rules: nft list ruleset, iptables -L -n -v, or ufw status verbose.
Firewall and segmentation:
- Allow only required ports and source ranges.
- Apply host-based firewall rules as a backstop to network ACLs.
- Segment management networks and sensitive services from general user networks.
- Block outbound connections when not required to reduce data exfiltration risk.
Monitor changes to firewall and network configs and log connection attempts for later analysis.
Service hardening and daemon configuration
Default service settings are often unsafe. Harden each daemon based on role.
Service checklist:
- Disable or remove unused services and packages.
- Run services with the least privilege (dedicated users, read-only file access).
- Limit exposed interfaces to necessary addresses (e.g., bind to 127.0.0.1 for local-only services).
- Configure TLS for network services and use strong certificates and ciphers.
- Restrict API or admin endpoints with authentication and network controls.
- Use systemd sandboxing options where available (ProtectSystem, NoNewPrivileges, PrivateTmp).
Review common services:
- Web servers: disable directory listing, enable secure headers, limit modules.
- Databases: bind only to internal networks, require strong auth, encrypt in-transit.
- Mail: protect against open relays and enforce auth.
Document config changes so they survive updates and are reproducible.
Patch management and package integrity verification
Patching reduces risk from known vulnerabilities. Have a clear, repeatable patch process.
Patch process:
- Maintain a central inventory and track supported versions.
- Test patches in a staging environment before production.
- Use scheduled maintenance windows and automated tooling (yum, apt, zypper, or orchestration).
- Apply security updates promptly for critical CVEs; batch lower-risk fixes thoughtfully.
Integrity verification:
- Verify packages after installation: rpm -Va or debsums.
- Use signed repositories and enforce GPG signature checks.
- For containers, rebuild images from known-base images and scan images for vulnerabilities.
Keep rollback plans ready. Record change logs and link patches to vulnerability advisories.
Logging, monitoring, and audit trails
Logs are essential for detection and investigation. Ensure they are reliable and retained.
Logging setup:
- Centralize logs to a separate, hardened server or SIEM.
- Configure rsyslog, syslog-ng, or journald forwarding with TLS.
- Ensure auditd records critical events: user logins, sudo usage, file changes for sensitive files.
Key monitoring elements:
- Monitor authentication failures and account lockouts.
- Alert on changes to sudoers, SSH configs, or SUID binaries.
- Track kernel and application errors that may indicate exploitation.
Retention and integrity:
- Retain logs per compliance needs and ensure tamper resistance (append-only storage, WORM, or signed logs).
- Rotate logs and test log collection to prevent gaps.
Tune alerts to reduce noise and focus on actionable events.
Vulnerability scanning, risk assessment, and remediation
Scanning finds issues, but risk assessment tells you what to fix first.
Scanning approach:
- Use authenticated scans where possible to get deeper insight (credentials to scan hosts).
- Run both network scanners (nmap, OpenVAS) and host-level checks (Lynis, CIS benchmark scripts).
- Prioritize findings by CVSS, exploitability, and business impact.
Risk assessment:
- Classify findings into Critical, High, Medium, Low.
- Consider exposure: internet-facing critical services get top priority.
- Map vulnerabilities to compensating controls (firewalls, monitoring) to adjust risk.
Remediation:
- For critical issues, plan immediate mitigations (patch, disable service, tighten firewall).
- For systemic issues, schedule engineering fixes and track in a ticketing system.
- Re-scan after remediation to confirm fixes.
Document decisions and residual risk for stakeholders.
Incident response, reporting, and compliance mapping
Be ready to act when you find active threats or serious weaknesses.
Incident response basics:
- Have an IR playbook that defines roles, contact lists, and escalation paths.
- Preserve evidence: isolate affected systems but avoid wiping logs.
- Contain the threat first, then eradicate root causes, and finally recover services.
Reporting:
- Produce clear executive summaries that state impact, scope, and remediation actions.
- Include technical appendices with timestamps, logs, and commands used.
- Track incidents and lessons learned to improve defenses and processes.
Compliance mapping:
- Map audit findings to relevant frameworks: CIS Benchmarks, NIST CSF/800-53, ISO 27001, HIPAA, or PCI-DSS as required.
- For each finding, note the control that it affects and the remediation state.
- Use this mapping to produce compliance evidence and to prioritize work based on regulatory needs.
Regularly revisit the IR playbook and run tabletop exercises to keep the team ready.
Final note
A security audit is a cycle, not a one-time task. Repeat these steps regularly, keep tools and inventories current, and focus fixes on the highest-risk items first. Small, consistent improvements reduce exposure and make incidents easier to detect and respond to.
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