概述
等保要求,數據庫啟用日志審計。Mysql8上面使用開源插件audit-plugin-for-mysql(MariaDB的審計插件不用折騰了,無論直接使用還是編譯使用,在Mysql8上都不行)
插件下載
- 日志審計插件下載地址:
https://codeload.github.com/Vettabase/audit-plugin-for-mysql/zip/refs/heads/mysql-8.0
插件安裝
-
- 解壓下載文件
unzip audit-plugin-for-mysql-mysql-8.0.zip
-
- 找到mysql插件存儲目錄
mysql> SHOW VARIABLES LIKE 'plugin_dir';
+---------------+--------------------------+
| Variable_name | Value |
+---------------+--------------------------+
| plugin_dir | /usr/lib64/mysql/plugin/ |
+---------------+--------------------------+
1 row in set (0.01 sec)mysql>
-
- 拷貝插件并賦權
cp audit-plugin-for-mysql-mysql-8.0/build/server_audit.so /usr/lib64/mysql/plugin/
chown mysql:mysql /usr/lib64/mysql/plugin/server_audit.so
chmod 755 /usr/lib64/mysql/plugin/server_audit.so
-
- 編輯Mysql配置文件
vim /etc/my.cnf# 配置server_audit 參數,根據實際情況調整
plugin_load_add = server_audit
#plugin_load_add = server_audit.so # 確保插件開機加載
server_audit = FORCE_PLUS_PERMANENT # 防止插件被卸載:cite[5]:cite[9]
server_audit_logging = ON
server_audit_events = 'CONNECT,QUERY_DDL,QUERY_DCL'
server_audit_file_path = /var/log/mysql/audit.log
server_audit_file_rotate_size = 0 # 禁用
server_audit_file_rotations = 0 # 禁用
#server_audit_excl_users = root # 排除root用戶
-
- 安裝插件
mysql> INSTALL PLUGIN server_audit SONAME 'server_audit.so';
Query OK, 0 rows affected (0.09 sec)mysql>
-
- 檢查審計日志
[root@centos7-05145 mysql]# ll /var/log/mysql
總用量 72
-rw-r----- 1 mysql mysql 4760 6月 24 10:00 audit.log
-rw-r----- 1 mysql mysql 19094 6月 24 09:12 mysql_3306-error.log
-rw-r----- 1 mysql mysql 43378 6月 24 09:53 mysql_3306-slow.log
配置日志保存
- 創建 logrotate配置文件
vim /etc/logrotate.d/mysql_audit
- 添加以下內存并保存(本機配置185天是示例,保存6個月日志請考慮合理備份方案)
- 如果要求日志保存嚴謹,請不要使用copytruncate方式,請參考以下postrotate示例
/var/log/mysql/audit.log {# 每天輪轉一次daily# 保留185天的日志rotate 185# 壓縮舊日志compress# 延遲1天壓縮delaycompress# 如果日志不存在也不報錯missingok# 空日志不輪轉notifempty# 復制后截斷原文件(避免重啟)copytruncate# 使用mysql賬號操作su mysql mysql# 設置文件日期后綴dateextdateformat -%Y%m%d
}
#/var/log/mysqld.log {
# create 640 mysql mysql
# notifempty
# daily
# rotate 5
# missingok
# compress
# postrotate
# # just if mysqld is really running
# if test -x /usr/bin/mysqladmin && \
# /usr/bin/mysqladmin ping &>/dev/null
# then
# /usr/bin/mysqladmin flush-logs
# fi
# endscript
#}
- 檢查cron狀態(確保開機運行)
systemctl status crond● crond.service - Command SchedulerLoaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)Active: active (running) since 五 2025-05-23 10:52:13 CST; 1 months 1 days agoMain PID: 1331 (crond)CGroup: /system.slice/crond.service└─1331 /usr/sbin/crond -n5月 23 10:52:13 centos7-172-028-002-001 systemd[1]: Started Command Scheduler.
5月 23 10:52:13 centos7-172-028-002-001 crond[1331]: (CRON) INFO (Syslog will be used instead of sendmail.)
5月 23 10:52:13 centos7-172-028-002-001 crond[1331]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 79% if used.)
5月 23 10:52:13 centos7-172-028-002-001 crond[1331]: (CRON) INFO (running with inotify support)