misp-modules/bin/misp-modules.py

136 lines
4.9 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Core MISP expansion modules loader and web service
#
# Copyright (C) 2016 Alexandre Dulaunoy
# Copyright (C) 2016 CIRCL - Computer Incident Response Center Luxembourg
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import tornado.web
import importlib
import json
2016-02-17 21:35:54 +01:00
import logging
2016-03-25 15:39:55 +01:00
import fnmatch
2016-04-12 09:37:02 +02:00
import argparse
import re
2016-02-17 21:35:54 +01:00
2016-03-25 15:39:55 +01:00
def init_logger():
log = logging.getLogger('misp-modules')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
2016-03-25 15:39:55 +01:00
log.addHandler(handler)
log.setLevel(logging.INFO)
return log
2016-03-25 15:39:55 +01:00
def load_helpers(helpersdir='../helpers'):
sys.path.append(helpersdir)
hhandlers = {}
helpers = []
for root, dirnames, filenames in os.walk(helpersdir):
if os.path.basename(root) == '__pycache__':
continue
if re.match(r'^\.', os.path.basename(root)):
continue
for filename in fnmatch.filter(filenames, '*.py'):
helpername = filename.split(".")[0]
hhandlers[helpername] = importlib.import_module(helpername)
selftest= hhandlers[helpername].selftest()
if selftest is None:
helpers.append(helpername)
log.info('Helpers loaded {} '.format(filename))
else:
log.info('Helpers failed {} due to {}'.format(filename, selftest))
2016-03-25 15:39:55 +01:00
def load_modules(mod_dir):
sys.path.append(mod_dir)
mhandlers = {}
modules = []
for root, dirnames, filenames in os.walk(mod_dir):
if os.path.basename(root) == '__pycache__':
continue
2016-04-26 16:36:26 +02:00
if os.path.basename(root).startswith("."):
continue
2016-03-25 15:39:55 +01:00
for filename in fnmatch.filter(filenames, '*.py'):
if filename == '__init__.py':
continue
modulename = filename.split(".")[0]
moduletype = os.path.split(modulesdir)[1]
modules.append(modulename)
2016-04-26 16:40:03 +02:00
try:
mhandlers[modulename] = importlib.import_module(os.path.basename(root) + '.' + modulename)
except Exception as e:
log.warning('MISP modules {0} failed due to {1}'.format(modulename, e))
continue
2016-03-25 15:39:55 +01:00
log.info('MISP modules {0} imported'.format(modulename))
mhandlers['type:' + modulename] = moduletype
return mhandlers, modules
2016-02-24 02:50:35 +01:00
class ListModules(tornado.web.RequestHandler):
def get(self):
ret = []
for module in modules:
x = {}
x['name'] = module
2016-02-24 02:50:35 +01:00
x['type'] = mhandlers['type:' + module]
x['mispattributes'] = mhandlers[module].introspection()
x['meta'] = mhandlers[module].version()
ret.append(x)
2016-02-17 21:35:54 +01:00
log.debug('MISP ListModules request')
self.write(json.dumps(ret))
2016-02-24 00:52:38 +01:00
2016-02-24 02:50:35 +01:00
class QueryModule(tornado.web.RequestHandler):
def post(self):
jsonpayload = self.request.body.decode('utf-8')
2016-02-24 02:50:35 +01:00
x = json.loads(jsonpayload)
2016-02-17 21:35:54 +01:00
log.debug('MISP QueryModule request {0}'.format(jsonpayload))
ret = mhandlers[x['module']].handler(q=jsonpayload)
self.write(json.dumps(ret))
2016-03-25 15:39:55 +01:00
if __name__ == '__main__':
if os.path.dirname(__file__) is not '':
os.chdir(os.path.dirname(__file__))
2016-04-12 09:37:02 +02:00
argParser = argparse.ArgumentParser(description='misp-modules server')
argParser.add_argument('-t', default=False, action='store_true', help='Test mode')
argParser.add_argument('-p', default=6666, help='misp-modules TCP port (default 6666)')
2016-04-29 10:10:22 +02:00
argParser.add_argument('-l', default='localhost', help='misp-modules listen address (default localhost)')
2016-04-12 09:37:02 +02:00
args = argParser.parse_args()
port = args.p
2016-04-29 10:10:22 +02:00
listen = args.l
2016-03-25 15:39:55 +01:00
modulesdir = '../modules'
helpersdir = '../helpers'
2016-03-25 15:39:55 +01:00
log = init_logger()
load_helpers(helpersdir=helpersdir)
2016-03-25 15:39:55 +01:00
mhandlers, modules = load_modules(modulesdir)
service = [(r'/modules', ListModules), (r'/query', QueryModule)]
2016-03-25 15:39:55 +01:00
application = tornado.web.Application(service)
2016-04-29 10:10:22 +02:00
application.listen(port, address=listen)
log.info('MISP modules server started on {0} port {1}'.format(listen, port))
2016-04-12 09:37:02 +02:00
if args.t:
2016-04-11 11:24:20 +02:00
log.info('MISP modules started in test-mode, quitting immediately.')
sys.exit()
2016-03-25 15:39:55 +01:00
tornado.ioloop.IOLoop.instance().start()