如何实现audit日志轮替?

RHEL-Like

1 前言

一个问题,一篇文章,一出故事。
笔者之前定义过日志的轮替,详细请参阅如下文档,

如何部署日志轮替工具logrotate?


笔者目的是让日志保存一年多,但是发现Audit不能使用logrotate工具配置,于是整理此文。

2 最佳实践

2.1 禁用audit自带的日志轮替

cp /etc/audit/auditd.conf /etc/audit/auditd.conf.default
vim /etc/audit/auditd.conf

修改如下参数,

num_logs = 390
max_log_file_action = ignore

以上参数意义,
– 参数“num_logs”设置日志保留的天数,范例设置为保留390天
– 参数“max_log_file_action”忽略auditd本身的处理
修改配置后,你需要执行以下命令使配置生效,

kill -HUP $(pidof auditd)

2.2 部署轮替脚本

cp /usr/share/doc/audit*/auditd.cron /etc/cron.daily/
chmod +x /etc/cron.daily/auditd.cron

另外,如有需要,你可以使用如下命令查看你部署的脚本,

cat /etc/cron.daily/auditd.cron

可见如下显示,

#!/bin/sh

##########
# This script can be installed to get a daily log rotation
# based on a cron job.
##########

/sbin/service auditd rotate
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t auditd "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0

以上脚本没有提供日志压缩功能,如果你需要,使用如下命令更改,

vim /etc/cron.daily/auditd.cron

配置修改如下,

#!/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}
        # Optional: remove "-v" verbose flag from next 2 lines to hide output
        mv -v ${file} ${newfile}
        ${COMPRESS} -v ${newfile}
    done
}

delete_old_compressed_logs() {
    # Optional: remove "-v" verbose flag to hide output
    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

参阅文档
===============

https://unix.stackexchange.com/questions/586518/linux-audit-log-rotation-name-and-compression-rhel-centos-7

https://joelitechlife.ca/2022/02/17/redhat-linux-audit-log-rotation/

没有评论

发表回复

RHEL-Like
如何配置rsyncd服务?

1 前言 一个问题,一篇文章,一出故事。 由于笔者想实现文件通过rsync自动传输,但是又不想使用o …

RHEL-Like
如何用pam_google_authenticator认证模块实现SSH 2FA?

1 前言 一个问题,一篇文章,一出故事。 笔者想开启2FA以便增强SSH服务的安全性,于是便整理此文 …

RHEL-Like
如何升级RHEL clamav杀毒?

1 前言 一个问题,一篇文章,一出故事。 笔者需要卸载旧的病毒软件,然后更新rpm包的病毒软件,于是 …