PROMPT_COMMAND环境变量的作用是,在每一次执行命令之前都会执行此环境变量。
审计的原理是:
通过配置/etc/bashrc配置文件,配置PROMPT_COMMAND环境变量,从history中取出命令,写入到指定的日志文件(这里是/var/log/command/command-%Y-%m-%d.log)中。
然后通过filebeat收集,发送给logstash过滤,再给es进行存储。
/etc/bashrc
HISTFILE="/var/log/command/command-`date +%Y-%m-%d`.log"
if [ ! -d "/var/log/command/" ];then
mkdir /var/log/command/ && chmod o+wx /var/log/command/
fi
if [ ! -f ${HISTFILE} ];then
touch ${HISTFILE} && chmod 777 ${HISTFILE}
fi
export cmd_login_user=$(who am i|awk '{print $1}')
export cmd_login_ip=$(echo "$SSH_CLIENT" | awk '{print $1}')
export PROMPT_COMMAND='{ date "+%Y-%m-%d %T cmd_hostname:$HOSTNAME cmd_login_user:$cmd_login_user cmd_now_user:$USER cmd_login_ip=$cmd_login_ip cmd:$(history 1 | { read x cmd; echo "$cmd"; })";} >> $HISTFILE'
function my_history(){
if [ -f "${HISTFILE}" ];then
last_command=`grep "cmd_now_user:${LOGNAME}" ${HISTFILE} | tail -1 | awk -Fcmd_hostname: '{print $NF}'`
fi
msg="$HOSTNAME cmd_login_user:$cmd_login_user cmd_now_user:`whoami` cmd_login_ip=$cmd_login_ip cmd:$(history 1 | { read x cmd; echo "$cmd"; })"
if [ "${last_command}" != "${msg}" ];then
echo "`date +"%Y-%m-%d %H:%M:%S"` cmd_hostname:${msg}" >> ${HISTFILE}
fi
}
export PROMPT_COMMAND=my_history
filebeat
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/command/command-*.log
tags: ["linux_command"]
exclude_lines: ['^[a-z]','^[A-Z]'] #过滤掉脏数据,执行exite命令可能会出现脏数据
output.logstash:
hosts: ["19.xxx.244.xxx:5056"]
logstash
input {
beats {
port => 5056
}
}
filter {
if "linux_command" in [tags] {
dissect {
mapping => {
"message" => "%{timestamp} cmd_hostname:%{cmd_hostname} cmd_login_user:%{cmd_login_user} cmd_now_user:%{cmd_now_user} cmd_login_ip=%{cmd_login_ip} cmd:%{cmd}"
}
}
#将匹配失败的脏数据都删除
if "_dissectfailure" in [tags] {
drop {}
}
}
}
output {
if "linux_command" in [tags] {
elasticsearch {
hosts => ["19.xxx.244.xxx:9200"]
index => "linux-command-%{+YYYY.MM.dd}"
}
}
}
网友评论