PyMISP/pymisp/api.py

295 lines
9.8 KiB
Python
Raw Normal View History

2014-03-19 19:10:36 +01:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Python API using the REST interface of MISP """
2014-03-19 19:10:36 +01:00
2015-02-16 14:31:29 +01:00
import json
import datetime
2014-03-19 19:10:36 +01:00
import requests
import os
import base64
2014-04-14 10:55:20 +02:00
2014-04-11 18:45:52 +02:00
class PyMISP(object):
"""
Python API for MISP
:param url: URL of the MISP instance you want to connect to
:param key: API key of the user you want to use
:param ssl: can be True or False (to check ot not the validity
of the certificate. Or a CA_BUNDLE in case of self
signed certiifcate (the concatenation of all the
*.crt of the chain)
:param out_type: Type of object (json or xml)
"""
def __init__(self, url, key, ssl=True, out_type='json'):
2014-04-12 16:17:36 +02:00
self.url = url + '/events'
2014-04-11 18:45:52 +02:00
self.key = key
self.ssl = ssl
2014-04-11 18:45:52 +02:00
self.out_type = out_type
self.rest = self.url + '/{}'
def __prepare_session(self, force_out=None):
"""
Prepare the headers of the session
:param force_out: force the type of the expect output
(overwrite the constructor)
2014-04-11 18:45:52 +02:00
"""
if force_out is not None:
out = force_out
2014-03-19 19:10:36 +01:00
else:
2014-04-11 18:45:52 +02:00
out = self.out_type
session = requests.Session()
session.verify = self.ssl
2014-04-14 10:55:20 +02:00
session.headers.update(
{'Authorization': self.key,
'Accept': 'application/' + out,
'content-type': 'application/' + out})
2014-04-11 18:45:52 +02:00
return session
2015-02-16 14:31:29 +01:00
def __query(self, session, path, query):
if query.get('error') is not None:
return query
url = self.rest.format(path)
query = {'request': query}
2015-05-03 02:47:47 +02:00
print(json.dumps(query))
2015-02-16 14:31:29 +01:00
r = session.post(url, data=json.dumps(query))
return r.json()
2014-04-14 10:55:20 +02:00
# ############### REST API ################
2014-04-11 18:45:52 +02:00
def get_index(self):
"""
Return the index.
Warning, there's a limit on the number of results
"""
session = self.__prepare_session()
return session.get(self.url)
2014-04-11 18:45:52 +02:00
def get_event(self, event_id):
"""
Get an event
:param event_id: Event id to get
2014-04-11 18:45:52 +02:00
"""
session = self.__prepare_session()
return session.get(self.rest.format(event_id))
2014-04-11 18:45:52 +02:00
def add_event(self, event):
"""
Add a new event
:param event: Event as JSON object / string or XML to add
2014-04-11 18:45:52 +02:00
"""
session = self.__prepare_session()
if self.out_type == 'json':
if isinstance(event, basestring):
return session.post(self.url, data=event)
else:
return session.post(self.url, data=json.dumps(event))
else:
return session.post(self.url, data=event)
2014-04-11 18:45:52 +02:00
def update_event(self, event_id, event):
"""
Update an event
:param event_id: Event id to update
:param event: Event as JSON object / string or XML to add
2014-04-11 18:45:52 +02:00
"""
session = self.__prepare_session()
if self.out_type == 'json':
if isinstance(event, basestring):
return session.post(self.rest.format(event_id), data=event)
else:
return session.post(self.rest.format(event_id), data=json.dumps(event))
else:
return session.post(self.rest.format(event_id), data=event)
2014-04-11 18:45:52 +02:00
def delete_event(self, event_id):
"""
Delete an event
:param event_id: Event id to delete
2014-04-11 18:45:52 +02:00
"""
session = self.__prepare_session()
return session.delete(self.rest.format(event_id))
2014-04-11 18:45:52 +02:00
# ######### Create/update events through the API #########
def _create_event(self, distribution, threat_level_id, analysis, info):
# Setup details of a new event
if distribution not in [0, 1, 2, 3]:
return False
if threat_level_id not in [0, 1, 2, 3]:
return False
if analysis not in [0, 1, 2]:
return False
return {'distribution': int(distribution), 'info': info,
'threat_level_id': int(threat_level_id), 'analysis': analysis}
def upload_sample(self, event_id, filepaths, distribution, to_ids, category,
info, analysis, threat_level_id):
to_post = {'request': {'files': []}}
if not isinstance(event_id, int):
# New event
postcontent = self._create_event(distribution, threat_level_id,
analysis, info)
if postcontent:
to_post['request'].update(postcontent)
else:
# invalid new event
return False
else:
to_post['request'].update({'event_id': int(event_id)})
if to_ids not in [True, False]:
return False
to_post['request'].update({'to_ids': to_ids})
if category not in ['Payload delivery', 'Artifacts dropped',
'Payload Installation', 'External Analysis']:
return False
to_post['request'].update({'category': category})
files = []
for path in filepaths:
if not os.path.isfile(path):
continue
with open(path, 'rb') as f:
files.append({'filename': os.path.basename(path),
'data': base64.b64encode(f.read())})
to_post['request']['files'] = files
session = self.__prepare_session()
return session.post(self.rest.format('upload_sample'), data=json.dumps(to_post))
2014-04-14 10:55:20 +02:00
# ######## REST Search #########
2014-04-11 18:45:52 +02:00
def __prepare_rest_search(self, values, not_values):
"""
Prepare a search, generate the chain processed by the server
:param values: Values to search
:param not_values: Values that should not be in the response
2014-04-11 18:45:52 +02:00
"""
to_return = ''
if values is not None:
2014-04-14 10:55:20 +02:00
if not isinstance(values, list):
2014-04-11 18:45:52 +02:00
to_return += values
else:
to_return += '&&'.join(values)
if not_values is not None:
2014-04-14 10:55:20 +02:00
if len(to_return) > 0:
2014-04-11 18:45:52 +02:00
to_return += '&&!'
else:
to_return += '!'
2014-04-14 10:55:20 +02:00
if not isinstance(values, list):
2014-04-11 18:45:52 +02:00
to_return += not_values
else:
to_return += '&&!'.join(not_values)
return to_return
def search(self, values=None, not_values=None, type_attribute=None,
2015-02-16 14:31:29 +01:00
category=None, org=None, tags=None, not_tags=None, date_from=None,
date_to=None):
2014-04-11 18:45:52 +02:00
"""
Search via the Rest API
:param values: values to search for
:param not_values: values *not* to search for
:param type_attribute: Type of attribute
:param category: Category to search
:param org: Org reporting the event
:param tags: Tags to search for
:param not_tags: Tags *not* to search for
2015-02-16 14:31:29 +01:00
:param date_from: First date
:param date_to: Last date
2014-04-11 18:45:52 +02:00
"""
val = self.__prepare_rest_search(values, not_values).replace('/', '|')
tag = self.__prepare_rest_search(tags, not_tags).replace(':', ';')
2015-02-16 14:31:29 +01:00
query = {}
if len(val) != 0:
query['value'] = val
if len(tag) != 0:
query['tags'] = tag
if type_attribute is not None:
query['type'] = type_attribute
if category is not None:
query['category'] = category
if org is not None:
query['org'] = org
if date_from is not None:
if isinstance(date_from, datetime.date) or isinstance(date_to, datetime.datetime):
query['from'] = date_from.strftime('%Y-%m-%d')
else:
query['from'] = date_from
if date_to is not None:
if isinstance(date_to, datetime.date) or isinstance(date_to, datetime.datetime):
query['to'] = date_to.strftime('%Y-%m-%d')
else:
query['to'] = date_to
2014-04-11 18:45:52 +02:00
session = self.__prepare_session()
2015-02-16 14:31:29 +01:00
return self.__query(session, 'restSearch/download', query)
2014-04-11 18:45:52 +02:00
def get_attachement(self, event_id):
"""
Get attachement of an event (not sample)
:param event_id: Event id from where the attachements will
be fetched
2014-04-11 18:45:52 +02:00
"""
attach = self.url + '/attributes/downloadAttachment/download/{}'
session = self.__prepare_session()
return session.get(attach.format(event_id))
2014-04-11 18:45:52 +02:00
2014-04-14 10:55:20 +02:00
# ############## Export ###############
2014-04-11 18:45:52 +02:00
def download_all(self):
"""
Download all event from the instance
"""
xml = self.url + '/xml/download'
session = self.__prepare_session('xml')
return session.get(xml)
2014-04-11 18:45:52 +02:00
def download_all_suricata(self):
"""
Download all suricata rules events.
"""
suricata_rules = self.url + '/nids/suricata/download'
session = self.__prepare_session('rules')
return session.get(suricata_rules)
def download_suricata_rule_event(self, event_id):
"""
Download one suricata rule event.
:param event_id: ID of the event to download (same as get)
"""
template = self.url + '/nids/suricata/download/{}'
session = self.__prepare_session('rules')
return session.get(template.format(event_id))
2014-04-11 18:45:52 +02:00
def download(self, event_id, with_attachement=False):
"""
Download one event in XML
:param event_id: Event id of the event to download (same as get)
2014-04-11 18:45:52 +02:00
"""
2014-04-14 10:55:20 +02:00
template = self.url + '/events/xml/download/{}/{}'
2014-04-11 18:45:52 +02:00
if with_attachement:
2014-04-14 10:55:20 +02:00
attach = 'true'
2014-03-20 11:10:52 +01:00
else:
2014-04-14 10:55:20 +02:00
attach = 'false'
2014-04-11 18:45:52 +02:00
session = self.__prepare_session('xml')
return session.get(template.format(event_id, attach))
2014-04-11 18:45:52 +02:00
##########################################