misp-dashboard/zmq_subscriber.py

158 lines
4.9 KiB
Python
Raw Normal View History

#!/usr/bin/env python3.5
2017-10-20 16:55:07 +02:00
import time, datetime
import zmq
import redis
import random
import configparser
import argparse
import os
import sys
import json
2017-10-13 15:03:09 +02:00
import geoip2.database
configfile = os.path.join(os.environ['VIRTUAL_ENV'], '../config.cfg')
cfg = configparser.ConfigParser()
cfg.read(configfile)
2017-10-11 10:47:11 +02:00
zmq_url = cfg.get('RedisLog', 'zmq_url')
channel = cfg.get('RedisLog', 'channel')
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect(zmq_url)
2017-10-13 15:03:09 +02:00
socket.setsockopt_string(zmq.SUBSCRIBE, '')
channelDisp = cfg.get('RedisMap', 'channelDisp')
redis_server = redis.StrictRedis(
2017-10-11 10:47:11 +02:00
host=cfg.get('RedisLog', 'host'),
port=cfg.getint('RedisLog', 'port'),
db=cfg.getint('RedisLog', 'db'))
serv_coord = redis.StrictRedis(
host=cfg.get('RedisMap', 'host'),
port=cfg.getint('RedisMap', 'port'),
db=cfg.getint('RedisMap', 'db'))
2017-10-13 15:03:09 +02:00
path_to_db = "/home/sami/Downloads/GeoLite2-City_20171003/GeoLite2-City.mmdb"
reader = geoip2.database.Reader(path_to_db)
2017-10-11 10:47:11 +02:00
channel_proc = "CoordToProcess"
def publish_log(zmq_name, name, content):
to_send = { 'name': name, 'log': json.dumps(content), 'zmqName': zmq_name }
2017-10-24 11:29:32 +02:00
redis_server.publish(channel, json.dumps(to_send))
2017-10-13 15:03:09 +02:00
def ip_to_coord(ip):
resp = reader.city(ip)
2017-10-20 16:55:07 +02:00
lat = float(resp.location.latitude)
lon = float(resp.location.longitude)
# 0.0001 correspond to ~10m
# Cast the float so that it has the correct float format
lat_corrected = float("{:.4f}".format(lat))
lon_corrected = float("{:.4f}".format(lon))
return { 'coord': {'lat': lat_corrected, 'lon': lon_corrected}, 'full_rep': resp }
2017-10-13 15:03:09 +02:00
def getCoordAndPublish(zmq_name, supposed_ip, categ):
2017-10-24 11:29:32 +02:00
try:
rep = ip_to_coord(supposed_ip)
coord = rep['coord']
coord_dic = {'lat': coord['lat'], 'lon': coord['lon']}
coord_list = [coord['lat'], coord['lon']]
now = datetime.datetime.now()
today_str = str(now.year)+str(now.month)+str(now.day)
keyname = 'GEO_' + today_str
serv_coord.zincrby(keyname, coord_list)
to_send = {
"coord": coord,
"categ": categ,
"value": supposed_ip,
"country": rep['full_rep'].country.name,
"specifName": rep['full_rep'].subdivisions.most_specific.name,
"cityName": rep['full_rep'].city.name,
2017-10-24 17:07:47 +02:00
"regionCode": rep['full_rep'].country.iso_code,
2017-10-24 11:29:32 +02:00
}
serv_coord.publish(channelDisp, json.dumps(to_send))
except ValueError:
print("can't resolve ip")
##############
## HANDLERS ##
##############
def handler_log(zmq_name, jsonevent):
2017-10-13 15:03:09 +02:00
print('sending', 'log')
return
def handler_keepalive(zmq_name, jsonevent):
2017-10-13 15:03:09 +02:00
print('sending', 'keepalive')
to_push = [ jsonevent['uptime'] ]
publish_log(zmq_name, 'Keepalive', to_push)
2017-10-13 15:03:09 +02:00
def handler_event(zmq_name, jsonevent):
#print(jsonevent)
2017-10-23 15:44:16 +02:00
#fields: threat_level_id, id, info
2017-10-13 15:03:09 +02:00
jsonevent = jsonevent['Event']
2017-10-24 11:29:32 +02:00
#redirect to handler_attribute
if 'Attribute' in jsonevent:
attributes = jsonevent['Attribute']
if attributes is list:
for attr in attributes:
handler_attribute(zmq_name, attr)
else:
handler_attribute(zmq_name, jsonevent)
2017-10-23 15:44:16 +02:00
2017-10-13 15:03:09 +02:00
def handler_attribute(zmq_name, jsonattr):
2017-10-20 16:55:07 +02:00
jsonattr = jsonattr['Attribute']
print(jsonattr)
2017-10-23 15:44:16 +02:00
to_push = []
for field in json.loads(cfg.get('Log', 'fieldname_order')):
print(field)
2017-10-24 15:17:52 +02:00
if type(field) is list:
to_add = cfg.get('Log', 'char_separator').join([ jsonattr[subField] for subField in field ])
else:
to_add = jsonattr[field]
to_push.append(to_add)
2017-10-13 15:03:09 +02:00
#try to get coord
2017-10-20 16:55:07 +02:00
if jsonattr['category'] == "Network activity":
getCoordAndPublish(zmq_name, jsonattr['value'], jsonattr['category'])
2017-10-13 15:03:09 +02:00
publish_log(zmq_name, 'Attribute', to_push)
def process_log(zmq_name, event):
2017-10-13 15:03:09 +02:00
event = event.decode('utf8')
topic, eventdata = event.split(' ', maxsplit=1)
jsonevent = json.loads(eventdata)
dico_action[topic](zmq_name, jsonevent)
2017-10-13 15:03:09 +02:00
def main(zmqName):
2017-10-13 15:03:09 +02:00
while True:
content = socket.recv()
content.replace(b'\n', b'') # remove \n...
zmq_name = zmqName
process_log(zmq_name, content)
2017-10-13 15:03:09 +02:00
dico_action = {
"misp_json": handler_event,
"misp_json_self": handler_keepalive,
"misp_json_attribute": handler_attribute,
"misp_json_sighting": handler_log,
"misp_json_organisation": handler_log,
"misp_json_user": handler_log,
"misp_json_conversation": handler_log
2017-10-13 15:03:09 +02:00
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='A zmq subscriber. It subscribe to a ZNQ then redispatch it to the misp-dashboard')
parser.add_argument('-n', '--name', required=False, dest='zmqname', help='The ZMQ feed name', default="Misp Standard ZMQ")
args = parser.parse_args()
main(args.zmqname)
2017-10-13 15:03:09 +02:00
reader.close()