2017-08-23 15:36:13 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
import abc
|
2017-12-21 18:46:28 +01:00
|
|
|
import sys
|
|
|
|
import datetime
|
2017-08-23 15:36:13 +02:00
|
|
|
import json
|
2017-08-24 19:21:52 +02:00
|
|
|
from json import JSONEncoder
|
2017-08-23 15:36:13 +02:00
|
|
|
import collections
|
2017-08-25 16:08:05 +02:00
|
|
|
import six # Remove that import when discarding python2 support.
|
2017-11-08 03:10:04 +01:00
|
|
|
import logging
|
2018-08-09 18:11:45 +02:00
|
|
|
from enum import Enum
|
2017-11-08 03:10:04 +01:00
|
|
|
|
2018-01-08 11:59:32 +01:00
|
|
|
from .exceptions import PyMISPInvalidFormat
|
|
|
|
|
|
|
|
|
2017-11-08 03:10:04 +01:00
|
|
|
logger = logging.getLogger('pymisp')
|
2017-08-23 15:36:13 +02:00
|
|
|
|
2017-08-28 19:01:53 +02:00
|
|
|
if six.PY2:
|
2018-08-08 11:19:24 +02:00
|
|
|
logger.warning("You're using python 2, it is strongly recommended to use python >=3.6")
|
2017-08-28 19:01:53 +02:00
|
|
|
|
2018-01-03 14:36:10 +01:00
|
|
|
# This is required because Python 2 is a pain.
|
|
|
|
from datetime import tzinfo, timedelta
|
|
|
|
|
|
|
|
class UTC(tzinfo):
|
|
|
|
"""UTC"""
|
|
|
|
|
|
|
|
def utcoffset(self, dt):
|
|
|
|
return timedelta(0)
|
|
|
|
|
|
|
|
def tzname(self, dt):
|
|
|
|
return "UTC"
|
|
|
|
|
|
|
|
def dst(self, dt):
|
|
|
|
return timedelta(0)
|
|
|
|
|
2017-08-28 19:01:53 +02:00
|
|
|
|
2018-08-09 18:11:45 +02:00
|
|
|
class Distribution(Enum):
|
|
|
|
your_organisation_only = 0
|
|
|
|
this_community_only = 1
|
|
|
|
connected_communities = 2
|
|
|
|
all_communities = 3
|
|
|
|
sharing_group = 4
|
|
|
|
inherit = 5
|
|
|
|
|
|
|
|
|
|
|
|
class ThreatLevel(Enum):
|
|
|
|
high = 1
|
|
|
|
medium = 2
|
|
|
|
low = 3
|
|
|
|
undefined = 4
|
|
|
|
|
|
|
|
|
|
|
|
class Analysis(Enum):
|
|
|
|
initial = 0
|
|
|
|
ongoing = 1
|
|
|
|
completed = 2
|
|
|
|
|
|
|
|
|
2018-08-28 23:30:07 +02:00
|
|
|
def _int_to_str(d):
|
|
|
|
# transform all integer back to string
|
|
|
|
for k, v in d.items():
|
|
|
|
if isinstance(v, (int, float)) and not isinstance(v, bool):
|
|
|
|
d[k] = str(v)
|
|
|
|
return d
|
|
|
|
|
|
|
|
|
2017-08-24 19:21:52 +02:00
|
|
|
class MISPEncode(JSONEncoder):
|
|
|
|
|
|
|
|
def default(self, obj):
|
|
|
|
if isinstance(obj, AbstractMISP):
|
|
|
|
return obj.jsonable()
|
2018-03-27 14:57:07 +02:00
|
|
|
elif isinstance(obj, datetime.datetime):
|
|
|
|
return obj.isoformat()
|
2018-08-09 18:11:45 +02:00
|
|
|
elif isinstance(obj, Enum):
|
|
|
|
return obj.value
|
2017-08-24 19:21:52 +02:00
|
|
|
return JSONEncoder.default(self, obj)
|
|
|
|
|
|
|
|
|
2017-08-23 15:36:13 +02:00
|
|
|
@six.add_metaclass(abc.ABCMeta) # Remove that line when discarding python2 support.
|
|
|
|
class AbstractMISP(collections.MutableMapping):
|
|
|
|
|
2017-09-12 16:46:06 +02:00
|
|
|
__not_jsonable = []
|
2017-08-23 15:36:13 +02:00
|
|
|
|
2017-12-12 17:34:09 +01:00
|
|
|
def __init__(self, **kwargs):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""Abstract class for all the MISP objects"""
|
2017-12-12 17:34:09 +01:00
|
|
|
super(AbstractMISP, self).__init__()
|
2017-12-22 14:49:14 +01:00
|
|
|
self.__edited = True # As we create a new object, we assume it is edited
|
2017-12-12 17:34:09 +01:00
|
|
|
|
2018-08-10 19:04:02 +02:00
|
|
|
if kwargs.get('force_timestamps') is not None:
|
|
|
|
# Ignore the edited objects and keep the timestamps.
|
|
|
|
self.__force_timestamps = True
|
|
|
|
else:
|
|
|
|
self.__force_timestamps = False
|
|
|
|
|
2018-01-08 11:59:32 +01:00
|
|
|
# List of classes having tags
|
|
|
|
from .mispevent import MISPAttribute, MISPEvent
|
|
|
|
self.__has_tags = (MISPAttribute, MISPEvent)
|
|
|
|
if isinstance(self, self.__has_tags):
|
|
|
|
self.Tag = []
|
|
|
|
setattr(AbstractMISP, 'add_tag', AbstractMISP.__add_tag)
|
|
|
|
setattr(AbstractMISP, 'tags', property(AbstractMISP.__get_tags, AbstractMISP.__set_tags))
|
|
|
|
|
2017-12-21 18:46:28 +01:00
|
|
|
@property
|
2017-09-18 16:37:55 +02:00
|
|
|
def properties(self):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""All the class public properties that will be dumped in the dictionary, and the JSON export.
|
|
|
|
Note: all the properties starting with a `_` (private), or listed in __not_jsonable will be skipped.
|
|
|
|
"""
|
2017-09-12 16:46:06 +02:00
|
|
|
to_return = []
|
|
|
|
for prop, value in vars(self).items():
|
|
|
|
if prop.startswith('_') or prop in self.__not_jsonable:
|
|
|
|
continue
|
|
|
|
to_return.append(prop)
|
|
|
|
return to_return
|
2017-08-23 15:36:13 +02:00
|
|
|
|
|
|
|
def from_dict(self, **kwargs):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""Loading all the parameters as class properties, if they aren't `None`.
|
|
|
|
This method aims to be called when all the properties requiring a special
|
|
|
|
treatment are processed.
|
|
|
|
Note: This method is used when you initialize an object with existing data so by default,
|
|
|
|
the class is flaged as not edited."""
|
2017-09-12 16:46:06 +02:00
|
|
|
for prop, value in kwargs.items():
|
|
|
|
if value is None:
|
2017-08-23 15:36:13 +02:00
|
|
|
continue
|
2017-09-12 16:46:06 +02:00
|
|
|
setattr(self, prop, value)
|
2017-12-20 12:43:31 +01:00
|
|
|
# We load an existing dictionary, marking it an not-edited
|
2017-12-21 18:46:28 +01:00
|
|
|
self.__edited = False
|
2017-09-12 16:46:06 +02:00
|
|
|
|
|
|
|
def update_not_jsonable(self, *args):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""Add entries to the __not_jsonable list"""
|
2017-09-12 16:46:06 +02:00
|
|
|
self.__not_jsonable += args
|
|
|
|
|
|
|
|
def set_not_jsonable(self, *args):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""Set __not_jsonable to a new list"""
|
2017-09-12 16:46:06 +02:00
|
|
|
self.__not_jsonable = args
|
2017-08-23 15:36:13 +02:00
|
|
|
|
|
|
|
def from_json(self, json_string):
|
|
|
|
"""Load a JSON string"""
|
2018-03-15 12:04:23 +01:00
|
|
|
self.from_dict(**json.loads(json_string))
|
2017-08-23 15:36:13 +02:00
|
|
|
|
|
|
|
def to_dict(self):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""Dump the lass to a dictionary.
|
|
|
|
This method automatically removes the timestamp recursively in every object
|
|
|
|
that has been edited is order to let MISP update the event accordingly."""
|
2017-08-23 15:36:13 +02:00
|
|
|
to_return = {}
|
2017-12-21 18:46:28 +01:00
|
|
|
for attribute in self.properties:
|
2017-08-23 15:36:13 +02:00
|
|
|
val = getattr(self, attribute, None)
|
|
|
|
if val is None:
|
|
|
|
continue
|
2018-01-03 14:36:10 +01:00
|
|
|
elif isinstance(val, list) and len(val) == 0:
|
|
|
|
continue
|
2017-12-21 18:46:28 +01:00
|
|
|
if attribute == 'timestamp':
|
2018-08-10 19:04:02 +02:00
|
|
|
if not self.__force_timestamps and self.edited:
|
2017-12-21 18:46:28 +01:00
|
|
|
# In order to be accepted by MISP, the timestamp of an object
|
|
|
|
# needs to be either newer, or None.
|
|
|
|
# If the current object is marked as edited, the easiest is to
|
|
|
|
# skip the timestamp and let MISP deal with it
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
val = self._datetime_to_timestamp(val)
|
2017-08-23 15:36:13 +02:00
|
|
|
to_return[attribute] = val
|
2018-08-28 23:30:07 +02:00
|
|
|
to_return = _int_to_str(to_return)
|
2017-08-23 15:36:13 +02:00
|
|
|
return to_return
|
|
|
|
|
2017-08-24 19:21:52 +02:00
|
|
|
def jsonable(self):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""This method is used by the JSON encoder"""
|
2017-08-24 19:21:52 +02:00
|
|
|
return self.to_dict()
|
|
|
|
|
2017-08-23 15:36:13 +02:00
|
|
|
def to_json(self):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""Dump recursively any class of type MISPAbstract to a json string"""
|
2018-01-03 14:36:10 +01:00
|
|
|
return json.dumps(self, cls=MISPEncode, sort_keys=True, indent=2)
|
2017-08-23 15:36:13 +02:00
|
|
|
|
|
|
|
def __getitem__(self, key):
|
2017-12-12 17:34:09 +01:00
|
|
|
try:
|
|
|
|
return getattr(self, key)
|
|
|
|
except AttributeError:
|
|
|
|
# Expected by pop and other dict-related methods
|
|
|
|
raise KeyError
|
2017-08-23 15:36:13 +02:00
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
2017-09-12 16:46:06 +02:00
|
|
|
setattr(self, key, value)
|
2017-08-23 15:36:13 +02:00
|
|
|
|
|
|
|
def __delitem__(self, key):
|
2017-09-12 16:46:06 +02:00
|
|
|
delattr(self, key)
|
2017-08-23 15:36:13 +02:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return iter(self.to_dict())
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(self.to_dict())
|
2017-12-20 12:43:31 +01:00
|
|
|
|
|
|
|
@property
|
|
|
|
def edited(self):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""Recursively check if an object has been edited and update the flag accordingly
|
|
|
|
to the parent objects"""
|
2017-12-21 18:46:28 +01:00
|
|
|
if self.__edited:
|
|
|
|
return self.__edited
|
|
|
|
for p in self.properties:
|
|
|
|
if self.__edited:
|
|
|
|
break
|
2018-01-05 19:17:25 +01:00
|
|
|
val = getattr(self, p)
|
|
|
|
if isinstance(val, AbstractMISP) and val.edited:
|
2017-12-21 18:46:28 +01:00
|
|
|
self.__edited = True
|
2018-01-05 19:17:25 +01:00
|
|
|
elif isinstance(val, list) and all(isinstance(a, AbstractMISP) for a in val):
|
|
|
|
if any(a.edited for a in val):
|
2017-12-21 18:46:28 +01:00
|
|
|
self.__edited = True
|
2017-12-20 12:43:31 +01:00
|
|
|
return self.__edited
|
|
|
|
|
|
|
|
@edited.setter
|
|
|
|
def edited(self, val):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""Set the edit flag"""
|
2017-12-20 12:43:31 +01:00
|
|
|
if isinstance(val, bool):
|
|
|
|
self.__edited = val
|
|
|
|
else:
|
|
|
|
raise Exception('edited can only be True or False')
|
|
|
|
|
|
|
|
def __setattr__(self, name, value):
|
2017-12-21 18:46:28 +01:00
|
|
|
if name in self.properties:
|
2017-12-20 12:43:31 +01:00
|
|
|
self.__edited = True
|
|
|
|
super(AbstractMISP, self).__setattr__(name, value)
|
2017-12-21 18:46:28 +01:00
|
|
|
|
|
|
|
def _datetime_to_timestamp(self, d):
|
2017-12-22 14:49:14 +01:00
|
|
|
"""Convert a datetime.datetime object to a timestamp (int)"""
|
2018-01-03 14:36:10 +01:00
|
|
|
if isinstance(d, (int, str)) or (sys.version_info < (3, 0) and isinstance(d, unicode)):
|
2017-12-21 18:46:28 +01:00
|
|
|
# Assume we already have a timestamp
|
2018-08-28 23:30:07 +02:00
|
|
|
return int(d)
|
2017-12-21 18:46:28 +01:00
|
|
|
if sys.version_info >= (3, 3):
|
2018-01-03 14:36:10 +01:00
|
|
|
return int(d.timestamp())
|
2017-12-21 18:46:28 +01:00
|
|
|
else:
|
2018-01-03 14:36:10 +01:00
|
|
|
return int((d - datetime.datetime.fromtimestamp(0, UTC())).total_seconds())
|
2018-01-08 11:59:32 +01:00
|
|
|
|
|
|
|
def __add_tag(self, tag=None, **kwargs):
|
|
|
|
"""Add a tag to the attribute (by name or a MISPTag object)"""
|
|
|
|
if isinstance(tag, str):
|
|
|
|
misp_tag = MISPTag()
|
|
|
|
misp_tag.from_dict(name=tag)
|
|
|
|
elif isinstance(tag, MISPTag):
|
|
|
|
misp_tag = tag
|
|
|
|
elif isinstance(tag, dict):
|
|
|
|
misp_tag = MISPTag()
|
|
|
|
misp_tag.from_dict(**tag)
|
|
|
|
elif kwargs:
|
|
|
|
misp_tag = MISPTag()
|
|
|
|
misp_tag.from_dict(**kwargs)
|
|
|
|
else:
|
|
|
|
raise PyMISPInvalidFormat("The tag is in an invalid format (can be either string, MISPTag, or an expanded dict): {}".format(tag))
|
2018-09-23 23:39:20 +02:00
|
|
|
if misp_tag not in self.tags:
|
|
|
|
self.Tag.append(misp_tag)
|
|
|
|
self.edited = True
|
2018-01-08 11:59:32 +01:00
|
|
|
|
|
|
|
def __get_tags(self):
|
|
|
|
"""Returns a lost of tags associated to this Attribute"""
|
|
|
|
return self.Tag
|
|
|
|
|
|
|
|
def __set_tags(self, tags):
|
|
|
|
"""Set a list of prepared MISPTag."""
|
|
|
|
if all(isinstance(x, MISPTag) for x in tags):
|
|
|
|
self.Tag = tags
|
|
|
|
else:
|
|
|
|
raise PyMISPInvalidFormat('All the attributes have to be of type MISPTag.')
|
|
|
|
|
2018-09-23 23:39:20 +02:00
|
|
|
def __eq__(self, other):
|
|
|
|
if isinstance(other, AbstractMISP):
|
|
|
|
return self.to_dict() == other.to_dict()
|
|
|
|
elif isinstance(other, dict):
|
|
|
|
return self.to_dict() == other
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
2018-01-08 11:59:32 +01:00
|
|
|
|
|
|
|
class MISPTag(AbstractMISP):
|
|
|
|
def __init__(self):
|
|
|
|
super(MISPTag, self).__init__()
|
|
|
|
|
|
|
|
def from_dict(self, name, **kwargs):
|
|
|
|
self.name = name
|
|
|
|
super(MISPTag, self).from_dict(**kwargs)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
if hasattr(self, 'name'):
|
|
|
|
return '<{self.__class__.__name__}(name={self.name})'.format(self=self)
|
|
|
|
return '<{self.__class__.__name__}(NotInitialized)'.format(self=self)
|