系統蜜罐opencanary部署 原

【pre:】

CentOS release 6.10 |Python 2.6.6
step1:安裝 git
#yum install git
step2:安裝依賴
yum install gcc python-devel zlib-devel zlib openssl openssl-devel
setp3:pip安裝(python2.6安裝pip)
#wget https://bootstrap.pypa.io/2.6/get-pip.py
#python get-pip.py  
step4:沙盒安裝
#pip install virtualenv
step5:下載&安裝python2.7
#wget https://www.python.org/ftp/python/2.7.8/Python-2.7.8.tgz
# tar xvf Python-2.7.8.tgz
#cd Python-2.7.8
# ./configure --prefix=/usr/local/python/py278/ --with-zlib
# make && make install
step6:安裝主程序依賴twist
#cd /opt
# virtualenv py278 --python=/usr/local/python/py278/bin/python2.7
# . py278/bin/activate
# wget https://files.pythonhosted.org/packages/0f/88/18bb0eddb483033e35b1b84bdf9de4cedb8906ece178e2d921451282b3c8/Twisted-14.0.2.tar.bz2
# tar -xvf Twisted-14.0.2.tar.bz2
# cd Twisted-14.0.2
#python setup.py install

step7:安裝主程序
# pip install opencanary

修改配置文件
#vim /root/.opencanary.conf
修改sshd端口號位:8000
#vim /etc/ssh/sshd_config
重啓sshd服務
#/etc/init.d/sshd start

step8:啓動opencanaryd&驗證
# opencanaryd --start

驗證是否啓動
# ps -ef|grep opencanary

step9:覈實蜜罐是否生效

#telnet 192.168.213.130 22
查看日誌
#vim /var/tmp/opencanary.log
{"dst_host": "192.168.213.130", "dst_port": 22, "local_time": "2018-09-12 15:27:02.657861", "logdata": {"SESSION": "1"}, "logtype": 4000, "node_id": "opencanary-1", "src_host": "192.168.213.1", "src_port": 58605}

step10:編寫opencanary定時任務,並啓動定時任務

* * * * * /root/opencanary/opencanary.sh

【編寫opencanary.sh,並將此腳本放到定時任務中每分鐘執行一次,對三次握手行爲監控】
#!/bin/bash
HOSTNAME="192.168.213.130"    #數據庫信息
PORT="3306"
USERNAME="root"
PASSWORD="123456"
DBNAME="soc"         #數據庫名稱

module=4

COMMAND1="mysql -h${HOSTNAME}  -P${PORT}  -u${USERNAME} -p${PASSWORD} ${DBNAME} -N -e \"select email from soc.alarm_receiver where status = 0 and module like '%${module}%' and email != 'NULL'\""
email=`eval $COMMAND1`
email=`echo $email | sed 's/ /,/g'`
echo $email # "[email protected],[email protected]"
COMMAND2="mysql -h${HOSTNAME}  -P${PORT}  -u${USERNAME} -p${PASSWORD} ${DBNAME} -N -e \"select phone from soc.alarm_receiver where status = 0 and module like '%${module}%' and phone != 'NULL'\""
phone=`eval $COMMAND2`
array=($phone) # 數組格式
echo ${array[*]}
ip=`/sbin/ifconfig | egrep "inet addr:10." | awk '{print $2}' | awk -F : '{print $2}' | head -n 1`
#記錄已經讀取的行數
if [ ! -f "/root/opencanary/line.txt" ];then
	touch /root/opencanary/line.txt
fi
line_new=`wc -l /var/tmp/opencanary.log | awk '{print $1}'`
if [ -s "/root/opencanary/line.txt" ]; then
#if line.txt is not empty
	line_old=`cat /root/opencanary/line.txt`
	#echo $line_new $line_old
	if [ $line_old -ne $line_new ];then
		let "line_old=$line_old+1"
		if [ $line_old -eq $line_new ];then
			sed -n "${line_new}p" /var/tmp/opencanary.log > /root/opencanary/content.txt
		else
			sed -n "${line_old},${line_new}p" /var/tmp/opencanary.log > /root/opencanary/content.txt
		fi
	else
		exit
	fi	
else
#if line.txt is empty
	cat /var/tmp/opencanary.log > /root/opencanary/content.txt
fi
#Insert to Mysql
> /root/opencanary/sql.txt
while read line
do
	time_now=`date +"%Y-%m-%d %H:%M:%S"`
	#neet ; at the end of each sql
	sql="insert into syshoney_alarm(host,content,timestamp) values ('$ip','$line','$time_now');"
	echo $sql >> /root/opencanary/sql.txt
done < /root/opencanary/content.txt
mysql -h 192.168.213.130 -u root -p123456 -D soc < /root/opencanary/sql.txt

#Email 超過5條則只發前5條
count=`wc -l /root/opencanary/content.txt | awk '{print $1}'`
echo "Total count $count" > /root/opencanary/mail.txt
if [ $count -le 5  ];then
	cat /root/opencanary/content.txt >> /root/opencanary/mail.txt
else
	head -n 5 /root/opencanary/content.txt >> /root/opencanary/mail.txt
fi

/bin/mail -s "opencanary alerts" $email < /root/opencanary/mail.txt 
#time_now=`date +"%Y-%m-%d %H:%M:%S"`
echo "<${time_now}> mail to $email" >> /root/opencanary/mail.log

#短信接口告警
neirong="蜜罐監控告警,蜜罐節點IP:${ip},攻擊次數:${count}"
private_key='c6f2e0150f8b5a8655c237863588'
for data in ${array[@]}  
do  
	key=`echo -n $time_now$data$neirong$private_key|md5sum|cut -d" " -f1`
    /usr/bin/curl -d "mobile=$data&message=$neirong&business=zabbix&time=$time_now&key=$key&smsType=0" "http://api.sendmsgtophone.com/sendapi/sms" >> /root/opencanary/phone.log
    echo >> /root/opencanary/phone.log
done

#電話接口告警
eventId=`date +%s`
command="curl -H \"Content-type: application/json\" -X POST -d '{ \"app\": \"464cc725-1427-ee3f-531a-c5bc6ccc1376\", \"eventId\": \"$eventId\", \"eventType\": \"trigger\", \"alarmName\": \"蜜罐系統\", \"priority\": 3, \"alarmContent\": {\"告警系統類型\":\"蜜罐系統\",\"蜜罐節點\": \"$ip\", \"攻擊日誌數量\": \"$count\"} }' \"http://api.monitor.com/alert/api/event\""
#eval $command

echo $line_new > /root/opencanary/line.txt

step11:syn包監控腳本,並啓動

#python /root/opencanary/cap.py &

【對step10的補充,這樣這個蜜罐系統才能覆蓋所有異常掃描】
#coding:utf-8
import pcap
import dpkt
import sys
import pymysql
from DBUtils.PooledDB import PooledDB
from email.mime.text import MIMEText
import smtplib
import hashlib
import requests
import time

def send_mail(content,mailarray):
        mail_host="mail.qq.com"
        mail_user="[email protected]"
        mail_pass="1111111"
        mail_postfix="qq.com"
        msg = MIMEText(content)
        msg['From'] = "[email protected]"
        msg['Subject'] = u'【蜜罐監控告警】'
        To_mail = mailarray
        try:
                s = smtplib.SMTP()
                s.connect(mail_host)
                s.login(mail_user,mail_pass)
                s.sendmail("[email protected]", To_mail, msg.as_string())
                s.close()
                return True
        except Exception, e:
                print str(e)
                return False

def send_message(phone,content):
    time_now= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    private_key='c6f2e0150f8b5a8655c237863588'
    for data in phone:
        key = time_now + data + content + private_key
        m = hashlib.md5()
        m.update(key)
        #print m.hexdigest()
        payload = {'mobile': data, 'message': content, 'business': 'zabbix','time': time_now,'key': m.hexdigest(),'smsType': '0' }
        r = requests.post("http://api.sendmsgtophone.com/sendapi/sms", data=payload)

def Get_alarm_receiver():
    # conn = poolsql.connection() 
    # cur = conn.cursor()
    # SQL = "select email,phone from alarm_receiver where status=0 and module like '%" + str(module) + "%'"
#    cur.execute(SQL)
    # receiver = cur.fetchall()
    # cur.close()
    # conn.close()
    # email = []
    # for i in receiver:
    #     if i[0] != '':
    #         email.append(i[0])
    # phone = []
    # for i in receiver:
    #     if i[1] != '':
    #         phone.append(i[1])
    email= ['[email protected]','[email protected]']
    phone = []
    return email,phone

if __name__ == '__main__':
    host = '192.168.213.130'
    module = 4
    poolsql = PooledDB(pymysql,10,host='192.168.213.130',user='root',passwd='123456',db='soc',port=3306,charset="utf8") 
    email, phone = Get_alarm_receiver()
    pc=pcap.pcap()    #注,參數可爲網卡名,如eth0
    pc.setfilter('tcp port 6379 or 3306 or 3389 or 22 or 21 or 9200 or 80 or 8080 or 873 or 9000 or 27017 or 11211')    #設置監聽過濾器
    for ptime,pdata in pc:    #ptime爲收到時間,pdata爲收到數據
        try:
            eth = dpkt.ethernet.Ethernet(pdata)
            #print('%s %x',ptime,eth)
            ip = eth.data
            tcp = ip.data
            dstip = '%d.%d.%d.%d'%tuple(map(ord,list(ip.dst)))
            srcip = '%d.%d.%d.%d'%tuple(map(ord,list(ip.src)))
            dstport = tcp.dport
            srcport = tcp.sport
            time_local = time.localtime(int(ptime))
            dt = time.strftime("%Y-%m-%d %H:%M:%S",time_local)
            #print dt,srcip,dstport,srcport
            if tcp.flags == 2 and dstip == host:
                content = "srcip:%s,dstport:%s,srcport:%s" %(srcip,dstport,srcport)
                mailcontent = "SysHoney Node:%s\nsrcip:%s\ndstport:%s\nsrcport:%s\nTimestamp:%s" %(host,srcip,dstport,srcport,dt)
                message = "SysHoney Node:%s|srcip:%s|dstport:%s|srcport:%s|Timestamp:%s" %(host,srcip,dstport,srcport,dt)
                conn = poolsql.connection() 
                cur = conn.cursor()
                SQL = "insert into syshoney_alarm(host,content,timestamp) values ('%s','%s','%s') "%(host,content,dt)
            #    cur.execute(SQL)
            #    conn.commit()
                #s = cur.fetchall()
                #print SQL
                cur.close()
                conn.close()
                send_mail(str(mailcontent),email)
                send_message(phone,message)
        except Exception,e:
            print e
            continue

step12:用nmap驗證step10、step11聯動效果

#nmap -sS 192.168.213.130 -p 22

當不啓動cap.py腳本時,我們收不到報警郵件,啓動後,在執行nmap掃描端口程序,則會收到報警信息。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章