0%

Rotate and Compress audit Logs Daily

I recently worked on compliance-related requirements and installed the audit service on an operating system. One of the requirements was to archive audit logs regularly, so I looked into how to rotate audit logs by time rather than by size.

I found a Red Hat knowledge base article called How to implement audit log rotation with compression based on time instead of size. The notes below extract the parts that are actually needed.

Since auditd does not support date-based rotation directly, the first step is to disable its default size-based rotation behavior. Edit /etc/audit/auditd.conf and change:

1
max_log_file_action = ROTATE

to:

1
max_log_file_action = ignore

Then restart the service:

1
systemctl restart auditd

After this change, auditd will no longer rotate its own logs automatically. At that point, create a script under /etc/cron.daily, for example audit_log, with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/bin/bash
export PATH=/sbin:/bin:/usr/sbin:/usr/bin

FORMAT="%F_%T" # Customize timestamp format as desired, per `man date`
# %F_%T will lead to files like: audit.log.2015-02-26_15:43:46
COMPRESS=gzip # Change to bzip2 or xz as desired
KEEP=5 # Number of compressed log files to keep
ROTATE_TIME=5 # Amount of time in seconds to wait for auditd to rotate its logs. Adjust this as necessary

rename_and_compress_old_logs() {
for file in $(find /var/log/audit/ -name 'audit.log.[0-9]'); do
timestamp=$(ls -l --time-style="+${FORMAT}" ${file} | awk '{print $6}')
newfile=${file%.[0-9]}.${timestamp}
mv -v ${file} ${newfile}
${COMPRESS} -v ${newfile}
done
}

delete_old_compressed_logs() {
rm -v $(find /var/log/audit/ -regextype posix-extended -regex '.*audit\.log\..*(xz|gz|bz2)$' | sort -n | head -n -${KEEP})
}

rename_and_compress_old_logs
service auditd rotate
sleep $ROTATE_TIME
rename_and_compress_old_logs
delete_old_compressed_logs

Then make the script executable:

1
chmod +x audit_log

After that, cron can call it once per day, rename the rotated audit logs based on time, compress them, and keep only the most recent files.

If you want to test the behavior manually, just run:

1
/etc/cron.daily/audit_log

During the first few runs, rm may complain because there are not enough historical files yet. That is expected and can be ignored.

如果我的文字帮到了您,那么可不可以请我喝罐可乐?