aide文件入侵检测

使用AIDE进行文件夹及文件的MD5值效验;判断文件是否被篡改

yum install aide -y 

根据需求修改/etc/aide.conf配置文件

初始化校验数据库

 aide -i  && mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz

效验

aide

发现文件正常改动更新效验库

aide --update  &&   mv /var/lib/aide/aide.db.gz /var/lib/aide/aide.db.gz-`date +"%F"`
mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz

通过添加计划任务实现每日入侵巡检:

效果图:

aide文件入侵检测

所有服务器同步脚本/data/bin/files_testing.sh

#!/bin/bash
date=`date -d "1 day ago" +"%F"`
backupdir="/data/backup/aide"
AIDE="/sbin/aide"
MV="/bin/mv"
newfile="/var/lib/aide/aide.db.new.gz"
file="/var/lib/aide/aide.db.gz"
if [[ ! -d $backupdir ]]; then
    mkdir $backupdir -p
fi
$AIDE > ${backupdir}/log 2>&1
cat ${backupdir}/log |grep -E "File|added|removed|changed"   #根据情况进行条件过滤

$AIDE --update > /dev/null 2>&1
$MV ${file} ${backupdir}/${date}-aide.db.gz
$MV  ${newfile} ${file}

添加计划任务脚本files_testing.py

# -*- coding: utf-8 -*-

import time
import threading
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import urllib2, urllib, json, re

#邮件配置
email_host='xxx'
email_prot=465
email_user='xxx'
enail_passwd='xxx'
#salt-API接口配置
salt_api_host="http://127.0.0.1:58080"
salt_api_user="salt"
salt_api_pass="salt"
cmd='/data/bin/files_testing.sh '
#发送邮件列表
to_list=["xx.com","xx.com","xx.com"]
#邮件主题(正常)
title="%s  xxx文件巡检报告"%(time.strftime('%Y-%m-%d', time.localtime(time.time())))

#平台及主机定义
host_list=["xxx","xxx","xxx","xxx","xxx"]
class saltAPI():
    def __init__(self,host,user,password):
        self.sat_url = host
        self.sat_user = user
        self.sat_password =password
        self.salt_token = self.salt_login()

    def salt_login(self):
        params = {'eauth': 'pam', 'username': self.sat_user, 'password': self.sat_password}
        encode = urllib.urlencode(params)
        obj = urllib.unquote(encode)
        headers = {'X-Auth-Token': ''}
        url = self.sat_url + '/login'
        req = urllib2.Request(url, obj, headers)
        opener = urllib2.urlopen(req)
        content = json.loads(opener.read())
        token = content['return'][0]['token']
        return token

    def postRequest(self, obj, prefix='/'):
        url = self.sat_url + prefix
        headers = {'X-Auth-Token': self.salt_token}
        req = urllib2.Request(url, obj, headers)
        opener = urllib2.urlopen(req)
        content = json.loads(opener.read())
        return content['return']

    def saltCmd(self, params):
        obj = urllib.urlencode(params)
        obj, number = re.subn("arg\d", 'arg', obj)
        res = self.postRequest(obj)
        return res

def send_mail(to_list,subject,content):
    msg = MIMEText(content,'html',_charset='utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = email_user
    msg['to'] = to_list
    try:
        s = smtplib.SMTP_SSL()
        s.connect(email_host,email_prot)
        s.login(email_user,enail_passwd)
        s.sendmail(email_user,to_list,msg.as_string())
        s.close()
        return True
    except Exception,e:
        print str(e)
        return False

#初始化saltAPI接口
salt=saltAPI(host=salt_api_host,user=salt_api_user,password=salt_api_pass)
#监控接口

backup_info=[]
def salt_get(host):
    info = ""
    for i in  salt.saltCmd({'client': 'local', 'fun': 'cmd.run','tgt':host,'arg':cmd})[0][host].split('\n'):
        info += '<p>%s</p>'%(i)
    cmd_info=dict(dict({'hostname':host,'info':info}).items())
    if cmd_info['info']:
        backup_info.append(cmd_info)

for host in host_list:
    agent=threading.Thread(target=salt_get,args=(host,))
    agent.setDaemon(True)
    agent.start()
agent.join()
time.sleep(60)
```
    #定义邮件html
    html = u"""
    <style type="text/css">
    table.gridtable {
        font-family: verdana,arial,sans-serif;
        font-size:15px;
        color:#333333;
        border-width: 1px;
        border-color: #666666;
        border-collapse: collapse;
    }
    table.gridtable th {
        border-width: 1px;
        padding: 12px;
        border-style: solid;
        border-color: #666666;
        background-color: #dedede;
    }
    table.gridtable td {
        border-width: 1px;
        padding: 12px;
        border-style: solid;
        border-color: #666666;
        background-color: #ffffff;
    }
    </style>
    <div>
    <table class="gridtable">
    <tr><th>主机名</th> <th>改动的文件</th>
    <tr>
        """
    backup_info.sort()
    for i in backup_info:
            html = html + u"""
            <tr>
            <td>%s</td>  <td>%s</td>
        </tr>
            """%(i['hostname'],i['info'])
    html+=u"""
    </table>
    </div>
    """
    for i in to_list:
        if backup_info:
            send_mail(i,title,html)
        else:
            send_mail(i,title,'当天没有核心文件更改')

修改脚本发件人配置,收件人列表to_list,主机列表host_list

添加计划任务:

45 23 * * * /bin/python /data/bin/files_testing.py

猜你喜欢

转载自blog.51cto.com/11889458/2107280