2019独角兽企业重金招聘Python工程师标准>>>
【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扫描端口程序,则会收到报警信息。