PyMISP/pymisp/tools/machoobject.py

116 lines
4.7 KiB
Python
Raw Normal View History

2017-08-25 16:08:05 +02:00
#!/usr/bin/env python3
from __future__ import annotations
2017-08-25 16:08:05 +02:00
import logging
2024-01-31 12:15:08 +01:00
from hashlib import md5, sha1, sha256, sha512
from io import BytesIO
2020-01-23 10:27:40 +01:00
from pathlib import Path
2024-01-31 12:15:08 +01:00
from typing import Any
from ..exceptions import InvalidMISPObject
2020-02-07 11:51:44 +01:00
from . import FileObject
2024-01-31 12:15:08 +01:00
from .abstractgenerator import AbstractMISPObjectGenerator
2023-04-19 10:47:41 +02:00
import lief
2017-08-25 16:08:05 +02:00
try:
2020-01-23 10:27:40 +01:00
import pydeep # type: ignore
2017-08-25 16:08:05 +02:00
HAS_PYDEEP = True
except ImportError:
HAS_PYDEEP = False
2020-02-07 11:51:44 +01:00
logger = logging.getLogger('pymisp')
2024-01-31 12:15:08 +01:00
def make_macho_objects(lief_parsed: lief.MachO.Binary,
misp_file: FileObject,
standalone: bool = True,
default_attributes_parameters: dict[str, Any] = {}) -> tuple[FileObject, MachOObject, list[MachOSectionObject]]:
2020-02-07 11:51:44 +01:00
macho_object = MachOObject(parsed=lief_parsed, standalone=standalone, default_attributes_parameters=default_attributes_parameters)
misp_file.add_reference(macho_object.uuid, 'includes', 'MachO indicators')
macho_sections = []
for s in macho_object.sections:
macho_sections.append(s)
return misp_file, macho_object, macho_sections
2017-08-25 16:08:05 +02:00
2017-08-28 19:01:53 +02:00
class MachOObject(AbstractMISPObjectGenerator):
2017-08-25 16:08:05 +02:00
2024-01-31 12:15:08 +01:00
__macho: lief.MachO.Binary
def __init__(self, parsed: lief.MachO.Binary | lief.MachO.FatBinary | None = None, # type: ignore[no-untyped-def]
filepath: Path | str | None = None,
pseudofile: BytesIO | list[int] | None = None,
**kwargs) -> None:
"""Creates an MachO object, with lief"""
2021-10-26 02:37:12 +02:00
super().__init__('macho', **kwargs)
2017-08-25 16:08:05 +02:00
if not HAS_PYDEEP:
logger.warning("pydeep is missing, please install pymisp this way: pip install pymisp[fileobjects]")
2017-08-25 16:08:05 +02:00
if pseudofile:
if isinstance(pseudofile, BytesIO):
2024-01-31 12:15:08 +01:00
m = lief.MachO.parse(obj=pseudofile)
2017-08-25 16:08:05 +02:00
elif isinstance(pseudofile, bytes):
2024-01-31 12:15:08 +01:00
m = lief.MachO.parse(raw=list(pseudofile))
2024-01-22 13:45:25 +01:00
elif isinstance(pseudofile, list):
2024-01-31 12:15:08 +01:00
m = lief.MachO.parse(raw=pseudofile)
2017-08-25 16:08:05 +02:00
else:
raise InvalidMISPObject(f'Pseudo file can be BytesIO or bytes got {type(pseudofile)}')
2024-01-31 12:15:08 +01:00
if not m:
raise InvalidMISPObject('Unable to parse pseudofile')
self.__macho = m.at(0)
2017-08-25 16:08:05 +02:00
elif filepath:
2024-01-31 12:15:08 +01:00
if m := lief.MachO.parse(filepath):
self.__macho = m.at(0)
2017-08-25 16:08:05 +02:00
elif parsed:
# Got an already parsed blob
2024-01-22 13:45:25 +01:00
if isinstance(parsed, lief.MachO.FatBinary):
2024-01-31 12:15:08 +01:00
self.__macho = parsed.at(0)
elif isinstance(parsed, lief.MachO.Binary):
self.__macho = parsed
2017-08-25 16:08:05 +02:00
else:
raise InvalidMISPObject(f'Not a lief.MachO.Binary: {type(parsed)}')
2017-08-25 16:08:05 +02:00
self.generate_attributes()
2024-01-31 12:15:08 +01:00
def generate_attributes(self) -> None:
self.add_attribute('type', value=str(self.__macho.header.file_type).split('.')[1])
2017-08-25 16:08:05 +02:00
# General information
if self.__macho.has_entrypoint:
self.add_attribute('entrypoint-address', value=self.__macho.entrypoint)
2017-08-25 16:08:05 +02:00
# Sections
self.sections = []
if self.__macho.sections:
2017-08-25 16:08:05 +02:00
pos = 0
for section in self.__macho.sections:
s = MachOSectionObject(section, standalone=self._standalone, default_attributes_parameters=self._default_attributes_parameters)
self.add_reference(s.uuid, 'includes', f'Section {pos} of MachO')
2017-08-25 16:08:05 +02:00
pos += 1
self.sections.append(s)
2017-08-28 19:01:53 +02:00
self.add_attribute('number-sections', value=len(self.sections))
2017-08-25 16:08:05 +02:00
2017-08-28 19:01:53 +02:00
class MachOSectionObject(AbstractMISPObjectGenerator):
2017-08-25 16:08:05 +02:00
2024-01-31 12:15:08 +01:00
def __init__(self, section: lief.MachO.Section, **kwargs) -> None: # type: ignore[no-untyped-def]
"""Creates an MachO Section object. Object generated by MachOObject."""
2017-08-25 16:08:05 +02:00
# Python3 way
# super().__init__('pe-section')
super().__init__('macho-section', **kwargs)
self.__section = section
self.__data = bytes(self.__section.content)
2017-08-25 16:08:05 +02:00
self.generate_attributes()
2024-01-31 12:15:08 +01:00
def generate_attributes(self) -> None:
self.add_attribute('name', value=self.__section.name)
2024-01-31 12:15:08 +01:00
self.add_attribute('size-in-bytes', value=self.__section.size)
if int(self.__section.size) > 0:
self.add_attribute('entropy', value=self.__section.entropy)
self.add_attribute('md5', value=md5(self.__data).hexdigest())
self.add_attribute('sha1', value=sha1(self.__data).hexdigest())
self.add_attribute('sha256', value=sha256(self.__data).hexdigest())
self.add_attribute('sha512', value=sha512(self.__data).hexdigest())
2017-08-25 16:08:05 +02:00
if HAS_PYDEEP:
self.add_attribute('ssdeep', value=pydeep.hash_buf(self.__data).decode())