PyMISP/pymisp/tools/create_misp_object.py

59 lines
2.3 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2017-07-21 18:47:10 +02:00
# -*- coding: utf-8 -*-
2020-01-23 10:27:40 +01:00
from io import BytesIO
2020-02-07 11:51:44 +01:00
from . import FileObject
2017-08-30 12:47:32 +02:00
from ..exceptions import MISPObjectException
import logging
2020-01-23 10:27:40 +01:00
from typing import Optional
logger = logging.getLogger('pymisp')
2017-07-21 18:47:10 +02:00
try:
2023-04-19 10:47:41 +02:00
import lief
lief.logging.disable()
2017-07-21 18:47:10 +02:00
HAS_LIEF = True
2020-02-07 11:51:44 +01:00
from .peobject import make_pe_objects
from .elfobject import make_elf_objects
from .machoobject import make_macho_objects
except AttributeError:
HAS_LIEF = False
logger.critical('You need lief >= 0.11.0. The quick and dirty fix is: pip3 install --force pymisp[fileobjects]')
2017-07-21 18:47:10 +02:00
except ImportError:
HAS_LIEF = False
class FileTypeNotImplemented(MISPObjectException):
pass
2020-07-28 20:05:42 +02:00
def make_binary_objects(filepath: Optional[str] = None, pseudofile: Optional[BytesIO] = None, filename: Optional[str] = None, standalone: bool = True, default_attributes_parameters: dict = {}):
2017-12-12 17:34:09 +01:00
misp_file = FileObject(filepath=filepath, pseudofile=pseudofile, filename=filename,
2017-12-20 14:27:31 +01:00
standalone=standalone, default_attributes_parameters=default_attributes_parameters)
if HAS_LIEF and (filepath or (pseudofile and filename)):
2023-04-19 10:47:41 +02:00
if filepath:
lief_parsed = lief.parse(filepath=filepath)
elif pseudofile and filename:
lief_parsed = lief.parse(raw=pseudofile.getvalue(), name=filename)
else:
logger.critical('You need either a filepath, or a pseudofile and a filename.')
lief_parsed = None
2023-05-12 11:58:38 +02:00
if isinstance(lief_parsed, lief.lief_errors):
logger.warning('Got an error parsing the file: {lief_parsed}')
elif isinstance(lief_parsed, lief.PE.Binary):
return make_pe_objects(lief_parsed, misp_file, standalone, default_attributes_parameters)
elif isinstance(lief_parsed, lief.ELF.Binary):
return make_elf_objects(lief_parsed, misp_file, standalone, default_attributes_parameters)
elif isinstance(lief_parsed, lief.MachO.Binary):
return make_macho_objects(lief_parsed, misp_file, standalone, default_attributes_parameters)
else:
logger.critical(f'Unexpected type from lief: {type(lief_parsed)}')
if not HAS_LIEF:
logger.warning('Please install lief, documentation here: https://github.com/lief-project/LIEF')
return misp_file, None, []