How to configure auditd in Linux

How to Configure auditd in Linux Linux system auditing is a critical component of security monitoring and compliance requirements in enterprise environments. The audit daemon (auditd) provides comprehensive logging capabilities that track system calls, file access, user activities, and security events. This guide will walk you through the complete process of configuring auditd in Linux, from basic installation to advanced rule creation and management. Table of Contents - [Introduction to Linux Auditing](#introduction-to-linux-auditing) - [Prerequisites and Requirements](#prerequisites-and-requirements) - [Installing auditd](#installing-auditd) - [Understanding auditd Components](#understanding-auditd-components) - [Basic Configuration](#basic-configuration) - [Creating Audit Rules](#creating-audit-rules) - [Advanced Configuration Options](#advanced-configuration-options) - [Practical Examples and Use Cases](#practical-examples-and-use-cases) - [Managing Audit Logs](#managing-audit-logs) - [Performance Considerations](#performance-considerations) - [Troubleshooting Common Issues](#troubleshooting-common-issues) - [Best Practices](#best-practices) - [Conclusion](#conclusion) Introduction to Linux Auditing The Linux Audit Framework provides a way to track security-relevant information about your system. When properly configured, auditd can monitor file access, system calls, network connections, user authentication, and administrative activities. This capability is essential for: - Security monitoring: Detecting unauthorized access attempts and suspicious activities - Compliance requirements: Meeting standards like PCI DSS, HIPAA, SOX, and government regulations - Forensic analysis: Investigating security incidents and system breaches - Change tracking: Monitoring modifications to critical system files and configurations - User accountability: Tracking user actions for administrative oversight The audit system consists of kernel-level components that capture events and user-space tools that configure rules and process logs. Understanding how to properly configure these components is crucial for maintaining a secure and compliant Linux environment. Prerequisites and Requirements Before configuring auditd, ensure your system meets the following requirements: System Requirements - Linux Distribution: Most modern distributions (RHEL, CentOS, Ubuntu, Debian, SUSE) - Kernel Support: Linux kernel 2.6 or later with audit support enabled - Root Access: Administrative privileges for installation and configuration - Disk Space: Adequate storage for audit logs (varies based on audit scope) - Memory: Sufficient RAM for audit buffer management Checking Kernel Audit Support Verify that your kernel supports auditing: ```bash Check if audit is enabled in kernel grep CONFIG_AUDIT /boot/config-$(uname -r) Check current audit status auditctl -s Verify audit system calls are available grep audit /proc/kallsyms | head -5 ``` Required Packages The audit system typically requires these packages: - `audit`: Core audit daemon and utilities - `audit-libs`: Audit library files - `audit-libs-devel`: Development libraries (optional) - `audispd-plugins`: Additional audit dispatcher plugins Installing auditd Installation methods vary by distribution. Here are the most common approaches: Red Hat/CentOS/Fedora ```bash Install audit packages sudo yum install audit audit-libs or for newer versions sudo dnf install audit audit-libs Enable and start the service sudo systemctl enable auditd sudo systemctl start auditd ``` Ubuntu/Debian ```bash Update package list sudo apt update Install audit daemon sudo apt install auditd audispd-plugins Enable and start the service sudo systemctl enable auditd sudo systemctl start auditd ``` SUSE/openSUSE ```bash Install audit packages sudo zypper install audit audit-devel Enable and start the service sudo systemctl enable auditd sudo systemctl start auditd ``` Verifying Installation After installation, verify that auditd is running correctly: ```bash Check service status sudo systemctl status auditd Verify audit daemon is listening sudo auditctl -s Check audit log location ls -la /var/log/audit/ ``` Understanding auditd Components The Linux audit system consists of several key components: Core Components 1. Kernel Audit Subsystem: Captures audit events at the kernel level 2. auditd: The audit daemon that receives and logs audit events 3. auditctl: Command-line tool for configuring audit rules 4. ausearch: Tool for searching audit logs 5. aureport: Tool for generating audit reports 6. audispd: Audit event dispatcher for real-time processing Configuration Files - `/etc/audit/auditd.conf`: Main daemon configuration - `/etc/audit/rules.d/audit.rules`: Audit rules file - `/etc/audit/audit.rules`: Legacy rules file (symbolic link) - `/var/log/audit/audit.log`: Primary audit log file Understanding Audit Events Audit events contain structured information including: - Timestamp: When the event occurred - Event Type: Category of audit event (SYSCALL, PATH, USER_AUTH, etc.) - Process Information: PID, executable name, command line - User Context: UID, GID, security context - Object Information: Files, network connections, system resources Basic Configuration Configuring the Audit Daemon The main configuration file `/etc/audit/auditd.conf` controls daemon behavior: ```bash Edit the main configuration file sudo nano /etc/audit/auditd.conf ``` Key configuration parameters: ```conf Log file location and rotation log_file = /var/log/audit/audit.log log_format = RAW log_group = root priority_boost = 4 flush = INCREMENTAL_ASYNC freq = 50 Disk space management space_left = 75 space_left_action = SYSLOG admin_space_left = 50 admin_space_left_action = SUSPEND disk_full_action = SUSPEND disk_error_action = SUSPEND Log rotation settings max_log_file = 30 max_log_file_action = ROTATE num_logs = 5 Network settings (for remote logging) tcp_listen_port = 60 tcp_listen_queue = 5 tcp_max_per_addr = 1 ``` Essential Configuration Options Explained Log Management Options: - `log_file`: Specifies the audit log file location - `log_format`: Sets the log format (RAW, NOLOG) - `max_log_file`: Maximum size of individual log files in MB - `num_logs`: Number of log files to keep in rotation Disk Space Management: - `space_left`: MB of free space that triggers space_left_action - `space_left_action`: Action when space_left threshold is reached - `admin_space_left`: Critical space threshold for administrative action - `disk_full_action`: Action when disk becomes full Performance Options: - `flush`: How often to write data to disk - `freq`: Events between explicit flushes to disk - `priority_boost`: Priority boost for audit daemon Creating Audit Rules Audit rules define what events to monitor. Rules can be temporary (active until reboot) or permanent (loaded at boot). Rule Types 1. Control Rules: Configure audit system behavior 2. File System Rules: Monitor file and directory access 3. System Call Rules: Monitor specific system calls Basic Rule Syntax ```bash Temporary rules (active until reboot) sudo auditctl -w /path/to/file -p permissions -k key_name Permanent rules (add to /etc/audit/rules.d/audit.rules) -w /path/to/file -p permissions -k key_name ``` File System Watch Rules Monitor file and directory access: ```bash Watch /etc/passwd for any access -w /etc/passwd -p wa -k passwd_changes Watch /etc/shadow for read/write/execute/attribute changes -w /etc/shadow -p rwxa -k shadow_changes Monitor SSH configuration -w /etc/ssh/sshd_config -p wa -k ssh_config Watch critical system directories -w /bin -p wa -k binaries -w /sbin -p wa -k system_binaries -w /usr/bin -p wa -k user_binaries -w /usr/sbin -p wa -k user_system_binaries ``` Permission flags: - `r`: Read access - `w`: Write access - `x`: Execute access - `a`: Attribute change System Call Rules Monitor specific system calls: ```bash Monitor file deletion attempts -a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -k delete Monitor network connections -a always,exit -F arch=b64 -S socket -S connect -S accept -k network Monitor privilege escalation -a always,exit -F arch=b64 -S setuid -S setgid -S setreuid -S setregid -k privilege_escalation Monitor process execution -a always,exit -F arch=b64 -S execve -k process_execution ``` User and Login Monitoring Track user authentication and session events: ```bash Monitor user authentication -w /var/log/faillog -p wa -k logins -w /var/log/lastlog -p wa -k logins -w /var/log/tallylog -p wa -k logins Monitor user/group modifications -w /etc/group -p wa -k group_changes -w /etc/passwd -p wa -k passwd_changes -w /etc/gshadow -p wa -k gshadow_changes -w /etc/shadow -p wa -k shadow_changes Monitor sudo usage -w /var/log/sudo.log -p wa -k sudo_log -w /etc/sudoers -p wa -k sudo_changes ``` Advanced Configuration Options Implementing Comprehensive Audit Rules Create a comprehensive audit configuration in `/etc/audit/rules.d/audit.rules`: ```bash Delete all existing rules -D Set buffer size -b 8192 Set failure mode (0=silent, 1=printk, 2=panic) -f 1 Monitor system calls by unauthorized users -a always,exit -F arch=b64 -S adjtimex -S settimeofday -S stime -k time_change -a always,exit -F arch=b32 -S adjtimex -S settimeofday -S stime -k time_change Monitor network environment changes -a always,exit -F arch=b64 -S sethostname -S setdomainname -k network_modifications -a always,exit -F arch=b32 -S sethostname -S setdomainname -k network_modifications Monitor AppArmor/SELinux events -w /etc/apparmor/ -p wa -k apparmor_changes -w /etc/apparmor.d/ -p wa -k apparmor_changes Monitor cron jobs -w /etc/cron.allow -p wa -k cron -w /etc/cron.deny -p wa -k cron -w /etc/cron.d/ -p wa -k cron -w /etc/cron.daily/ -p wa -k cron -w /etc/cron.hourly/ -p wa -k cron -w /etc/cron.monthly/ -p wa -k cron -w /etc/cron.weekly/ -p wa -k cron -w /etc/crontab -p wa -k cron -w /var/spool/cron/crontabs/ -k cron Make rules immutable (must be last rule) -e 2 ``` Filtering and Exclusions Reduce audit noise by filtering out unnecessary events: ```bash Exclude specific users from auditing -a never,user -F uid=ntp -a never,exit -F uid=ntp Exclude specific processes -a never,exit -F exe=/usr/bin/updatedb Exclude based on success/failure -a always,exit -F arch=b64 -S open -F success=0 -k failed_file_open ``` Remote Audit Logging Configure centralized audit logging: ```bash In /etc/audit/auditd.conf on client log_format = RAW name_format = HOSTNAME Configure audisp to forward logs Edit /etc/audisp/audisp-remote.conf remote_server = 192.168.1.100 port = 60 local_port = any transport = tcp ``` Practical Examples and Use Cases Example 1: PCI DSS Compliance Configuration For Payment Card Industry compliance: ```bash Monitor access to cardholder data locations -w /var/www/html/payments -p rwxa -k cardholder_data -w /opt/payment_app -p rwxa -k payment_application Monitor administrative access -w /etc/sudoers -p wa -k admin_access -w /etc/sudoers.d/ -p wa -k admin_access Monitor authentication mechanisms -w /etc/pam.d/ -p wa -k pam_changes -w /etc/nsswitch.conf -p wa -k auth_changes Monitor network configuration -w /etc/hosts -p wa -k network_config -w /etc/resolv.conf -p wa -k network_config Monitor system time changes -a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time_change -w /etc/localtime -p wa -k time_change ``` Example 2: Monitoring Database Server Comprehensive auditing for database servers: ```bash Monitor database files -w /var/lib/mysql -p rwxa -k database_files -w /var/lib/postgresql -p rwxa -k database_files Monitor database configuration -w /etc/mysql -p wa -k db_config -w /etc/postgresql -p wa -k db_config Monitor database service files -w /etc/systemd/system/mysql.service -p wa -k db_service -w /etc/systemd/system/postgresql.service -p wa -k db_service Monitor backup locations -w /backup/database -p rwxa -k db_backup Monitor database user access -a always,exit -F uid=mysql -k mysql_user_actions -a always,exit -F uid=postgres -k postgres_user_actions ``` Example 3: Web Server Security Monitoring Monitor web server for security events: ```bash Monitor web content directories -w /var/www -p wa -k web_content -w /var/log/apache2 -p wa -k apache_logs -w /var/log/nginx -p wa -k nginx_logs Monitor web server configuration -w /etc/apache2 -p wa -k apache_config -w /etc/nginx -p wa -k nginx_config Monitor SSL certificates -w /etc/ssl/certs -p wa -k ssl_certs -w /etc/ssl/private -p wa -k ssl_private Monitor CGI and script execution -a always,exit -F dir=/var/www/cgi-bin -F perm=x -k cgi_execution ``` Managing Audit Logs Searching Audit Logs Use `ausearch` to query audit logs effectively: ```bash Search by key ausearch -k passwd_changes Search by user ID ausearch -ui 1000 Search by process ID ausearch -p 1234 Search by time range ausearch -ts 10:00:00 -te 11:00:00 Search for failed events ausearch -m USER_LOGIN -sv no Search for specific system calls ausearch -sc open -f /etc/passwd Combine multiple criteria ausearch -ts today -k network_modifications -i ``` Generating Audit Reports Use `aureport` for comprehensive reporting: ```bash Generate summary report aureport Authentication report aureport -au Login report aureport -l Process execution report aureport -x File access report aureport -f Network events report aureport -n Time-based reports aureport -ts yesterday -te today Failed events report aureport --failed ``` Log Rotation and Management Configure proper log rotation to manage disk space: ```bash Create logrotate configuration sudo nano /etc/logrotate.d/audit Content of audit logrotate file /var/log/audit/audit.log { daily rotate 30 compress delaycompress missingok notifempty create 0600 root root postrotate /sbin/service auditd restart endscript } ``` Performance Considerations Optimizing Audit Performance Audit logging can impact system performance. Consider these optimizations: Buffer Management ```bash Increase audit buffer size for high-volume systems -b 16384 Adjust flush settings in auditd.conf flush = DATA freq = 20 ``` Rule Optimization ```bash Use specific filters to reduce event volume -a always,exit -F arch=b64 -S openat -F dir=/etc -k etc_access Exclude high-volume, low-value events -a never,exit -F dir=/proc -a never,exit -F dir=/sys ``` System Resource Monitoring Monitor audit system impact: ```bash Check audit queue status auditctl -s Monitor audit daemon resource usage ps aux | grep auditd top -p $(pgrep auditd) Check disk I/O impact iotop -p $(pgrep auditd) ``` Performance Tuning Parameters Key parameters for performance optimization: ```conf In /etc/audit/auditd.conf Reduce disk I/O flush = INCREMENTAL_ASYNC freq = 50 Optimize for high-volume environments priority_boost = 4 disp_qos = lossy Network performance for remote logging tcp_client_max_idle = 0 ``` Troubleshooting Common Issues Common Problems and Solutions Problem 1: Audit Rules Not Loading Symptoms: Rules don't appear when running `auditctl -l` Solutions: ```bash Check syntax of rules file auditctl -R /etc/audit/rules.d/audit.rules Check for syntax errors grep -n "^-" /etc/audit/rules.d/audit.rules Verify file permissions ls -la /etc/audit/rules.d/audit.rules Reload rules manually sudo auditctl -R /etc/audit/rules.d/audit.rules ``` Problem 2: Audit Logs Not Generated Symptoms: No entries in `/var/log/audit/audit.log` Solutions: ```bash Check if auditd is running systemctl status auditd Verify audit is enabled in kernel auditctl -s Check disk space df -h /var/log/audit Review auditd configuration sudo nano /etc/audit/auditd.conf Check for errors in system logs journalctl -u auditd -f ``` Problem 3: High CPU Usage Symptoms: auditd consuming excessive CPU resources Solutions: ```bash Review and optimize audit rules auditctl -l | wc -l Remove unnecessary rules auditctl -D auditctl -R /etc/audit/rules.d/audit.rules Increase buffer size auditctl -b 32768 Adjust flush frequency Edit /etc/audit/auditd.conf freq = 100 ``` Problem 4: Disk Space Issues Symptoms: Audit logs filling up disk space Solutions: ```bash Implement log rotation sudo nano /etc/logrotate.d/audit Configure space management in auditd.conf space_left = 100 space_left_action = EMAIL admin_space_left = 50 admin_space_left_action = HALT Archive old logs tar -czf audit_logs_$(date +%Y%m%d).tar.gz /var/log/audit/audit.log.* ``` Debugging Audit Issues Enable debug mode for troubleshooting: ```bash Start auditd in debug mode sudo auditd -f -l -n -d Check kernel audit messages dmesg | grep -i audit Monitor real-time audit events sudo ausearch -ts now -i | tail -f Verify rule syntax auditctl -R /etc/audit/rules.d/audit.rules -v ``` Best Practices Security Best Practices 1. Principle of Least Privilege: Only audit what's necessary for security and compliance 2. Secure Log Storage: Protect audit logs from tampering and unauthorized access 3. Regular Review: Establish procedures for regular audit log review 4. Centralized Logging: Implement centralized audit log collection for enterprise environments 5. Backup and Retention: Maintain appropriate backup and retention policies Configuration Best Practices Rule Organization ```bash Organize rules by category in separate files /etc/audit/rules.d/10-base-config.rules /etc/audit/rules.d/20-file-access.rules /etc/audit/rules.d/30-network-monitoring.rules /etc/audit/rules.d/40-user-monitoring.rules /etc/audit/rules.d/99-finalize.rules ``` Documentation Standards ```bash Comment your rules for maintainability Monitor critical system files for PCI compliance -w /etc/passwd -p wa -k passwd_changes Track privilege escalation attempts - SOX requirement -a always,exit -F arch=b64 -S setuid -S setgid -k privilege_escalation ``` Testing Procedures ```bash Test rules before production deployment 1. Load rules in test environment auditctl -R /etc/audit/rules.d/test.rules 2. Generate test events touch /tmp/test_file rm /tmp/test_file 3. Verify events are captured ausearch -k test_key -ts recent 4. Monitor performance impact auditctl -s ``` Operational Best Practices Monitoring and Alerting ```bash Create monitoring scripts for audit health #!/bin/bash audit_health_check.sh Check if auditd is running if ! systemctl is-active --quiet auditd; then echo "CRITICAL: auditd is not running" exit 2 fi Check disk space SPACE_LEFT=$(df /var/log/audit | awk 'NR==2 {print $4}') if [ $SPACE_LEFT -lt 1000000 ]; then echo "WARNING: Low disk space for audit logs" exit 1 fi Check for recent audit events RECENT_EVENTS=$(ausearch -ts today | wc -l) if [ $RECENT_EVENTS -eq 0 ]; then echo "WARNING: No audit events today" exit 1 fi echo "OK: Audit system healthy" exit 0 ``` Change Management 1. Version Control: Store audit rules in version control systems 2. Change Testing: Test rule changes in non-production environments 3. Rollback Procedures: Maintain procedures for rolling back problematic changes 4. Documentation: Document all changes with business justification Compliance Mapping Create mapping documents for compliance requirements: ```bash Example compliance mapping PCI DSS Requirement 10.2.1 - User access to cardholder data -w /var/www/html/payments -p rwxa -k pci_10_2_1 HIPAA - Access to PHI -w /opt/medical_records -p rwxa -k hipaa_phi_access SOX - Financial data access -w /opt/financial_app -p rwxa -k sox_financial_access ``` Conclusion Configuring auditd in Linux is a critical skill for system administrators and security professionals. This comprehensive guide has covered the essential aspects of audit system configuration, from basic installation to advanced rule creation and performance optimization. Key Takeaways 1. Start Simple: Begin with basic file and directory monitoring before implementing complex system call auditing 2. Plan for Scale: Consider performance implications and disk space requirements when designing audit policies 3. Regular Maintenance: Implement proper log rotation, monitoring, and review procedures 4. Compliance Focus: Align audit configurations with specific compliance requirements 5. Documentation: Maintain clear documentation of audit rules and their business justification Next Steps After implementing basic audit configuration, consider these advanced topics: - Integration with SIEM: Forward audit logs to Security Information and Event Management systems - Custom Audit Plugins: Develop custom audit event processors using the audit dispatcher - Automated Response: Implement automated responses to critical audit events - Multi-System Correlation: Correlate audit events across multiple systems for comprehensive security monitoring Recommended Resources - Official Documentation: Linux Audit Documentation (`man auditd`, `man auditctl`) - Security Frameworks: NIST Cybersecurity Framework, CIS Controls - Compliance Standards: PCI DSS, HIPAA, SOX audit requirements - Community Resources: Linux audit mailing lists and security forums By following the practices and procedures outlined in this guide, you'll be well-equipped to implement effective audit logging that enhances your Linux system security posture while meeting compliance requirements. Remember that audit configuration is an iterative process that should evolve with your organization's security needs and threat landscape. The investment in properly configured audit logging pays dividends in security incident response, compliance reporting, and overall system accountability. Start with the basics, test thoroughly, and gradually expand your audit coverage as you gain experience with the system's capabilities and performance characteristics.