mysql基于init-connect+binlog完成审计功能

 

目前社区版本的mysql的审计功能仍是比较弱的,基于插件的审计目前存在于Mysql的企业版、Percona和MariaDB上,可是mysql社区版本有提供init-connect选项,基于此咱们能够用它来完成审计功能。html

init-connect参数说明:mysql

http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_init_connectsql

 

 

step1:建立用户数据库表数据库

set names utf8
create database auditlog;
create table auditlog.t_audit(
  id int not null auto_increment,
  thread_id int not null,
  login_time timestamp,
  localname varchar(50) default null,
  matchname varchar(50) default null, 
  primary key (id)
)ENGINE=InnoDB default charset=utf8 comment '审计用户登陆信息';

 

step2:受权全部的用户拥有对审计表的插入权限app

select concat("grant insert on auditlog.t_audit to '",user,"'@'",host,"';") from mysql.user;  #拼结受权语句
…… flush
privileges;

注意,之后每添加一个用户都必须受权此表的插入权限,要不会链接不上。性能

 

step3:设置init_connect参数spa

set global init_connect='insert into auditlog.t_audit(id,thread_id,login_time,localname,matchname) values(null,connection_id(),now(),user(),current_user());';
 
并在配置文件中增长以下语句:
init-connect='insert into auditlog.t_audit(id,thread_id,login_time,localname,matchname) values(null,connection_id(),now(),user(),current_user());'
以便下次重启时能生效

 

 

验证:插件

咱们登录后并删除一条记录,查看binlog,咱们能够看到此操做的thread_id为7:

 

而后咱们来查看此表t_audit表:
[zejin] 3301>select * from auditlog.t_audit;
+----+-----------+---------------------+---------------------------+-------------------------+
| id | thread_id | login_time | localname | matchname |
+----+-----------+---------------------+---------------------------+-------------------------+
| 1 | 5 | 2016-08-10 11:01:07 | user_app@192.168.1.240 | user_app@192.168.1.% |
| 2 | 6 | 2016-08-10 11:02:02 | user_app@192.168.1.236 | user_app@192.168.1.% |
| 3 | 7 | 2016-08-10 11:19:54 | user_yunwei@192.168.1.240 | user_yunwei@192.168.1.% |
+----+-----------+---------------------+---------------------------+-------------------------+
3 rows in set (0.00 sec)

 

能够看到thread_id为7的用户为user_yunwei,在192.168.1.240机器上操做删除的,完成了对数据的简单审计。
 
扩展说明:
1.init-connect只会在链接时执行,不会对数据库产生大的性能影响
2.init-connect是在链接时执行的动做命令,故能够用它来完成其它的功能,如:init_connect='SET autocommit=0'
3.init-connect不会记录拥有super权限的用户记录,为了防止init_connect语句因为语法错误或权限问题而全部用户都登录不了的状况,保证至少super用户能登录并修改此值
相关文章
相关标签/搜索