Example #1
0
def parseFile(filename: str):
    """
    Iterate the list of Mach-Os and call macholibre.parse against each file
    Argument: the list of lists with Mach-O files
    """
    try:
        print(f"[ ] Parsing {filename}")
        data = parse(filename)
        data["filepath"] = filename
        data["entropy"] = calculateEntropy(filename)
        sha256 = data["hashes"]["sha256"]
        vtresults = client.get_object(f"/files/{sha256}")
        data["vtresults"] = vtresults
        packed = pack_file(filename, sha256)
        if packed:
            basename = sha256 + ".json"
            out_file = os.path.join(args.outdir, basename)
            with open(out_file, "w") as f:
                f.write(json.dumps(data))
            datap = parse(packed)
            datap["filepath"] = packed
            datap["entropy"] = calculateEntropy(packed)
            datap["vtresults"] = vtresults
            basenamep = sha256 + ".packed.json"
            out_filep = os.path.join(args.outdir, basenamep)
            with open(out_filep, "w") as f:
                f.write(json.dumps(datap))
    except Exception as e:
        print(f"[-] Failed to parse {filename}: {e}")
Example #2
0
    def scan(self, data, file, options, expire_at):
        tmp_directory = options.get('tmp_directory', '/tmp/')

        self.event['total'] = {'objects': 0}
        self.event.setdefault('abnormalities', [])
        self.event.setdefault('objects', [])

        with tempfile.NamedTemporaryFile(dir=tmp_directory) as tmp_data:
            tmp_data.write(data)
            tmp_data.flush()

            macho_dictionary = macholibre.parse(tmp_data.name)
            for (key, value) in macho_dictionary.items():
                if key == 'abnormalities' and value not in self.event[
                        'abnormalities']:
                    self.event['abnormalities'].append(value)
                elif key == 'macho':
                    self.event['total']['objects'] = 1
                    self._macho_parse(self, value)
                elif key == 'universal':
                    for (x, y) in value.items():
                        if key == 'machos':
                            self.event['total']['objects'] = len(y)
                            for macho in y:
                                self._macho_parse(self, macho)
Example #3
0
    def scan(self, file_object, options):
        tempfile_directory = options.get("tempfile_directory", "/tmp/")

        self.metadata["total"] = {"objects": 0}
        self.metadata.setdefault("abnormalities", [])
        self.metadata.setdefault("objects", [])

        with tempfile.NamedTemporaryFile(
                dir=tempfile_directory) as strelka_file:
            strelka_filename = strelka_file.name
            strelka_file.write(file_object.data)
            strelka_file.flush()

            macho_dictionary = macholibre.parse(strelka_filename)
            for (key, value) in macho_dictionary.items():
                if key == "abnormalities" and value not in self.metadata[
                        "abnormalities"]:
                    self.metadata["abnormalities"].append(value)
                elif key == "macho":
                    self.metadata["total"]["objects"] = 1
                    self._macho_parse(self, value)
                elif key == "universal":
                    for (x, y) in value.items():
                        if key == "machos":
                            self.metadata["total"]["objects"] = len(y)
                            for macho in y:
                                self._macho_parse(self, macho)
Example #4
0
def META_MACHO(s, buff):
    tmpfd, tmpfile = mkstemp()
    tmpf = os.fdopen(tmpfd, 'wb')

    try:
        #Writing the buffer to a temp file
        tmpf.write(buff)
        tmpf.close()
        dictionary = macholibre.parse(tmpfile)
    finally:
        #Remove it to save space
        os.remove(tmpfile)

    if dictionary.has_key('name'):
        #The name doesn't make sense with the temp file
        dictionary.pop('name')

    # META_BASIC_INFO already hs this informaton
    if dictionary.has_key('hashes'):
        dictionary.pop('hashes')
    if dictionary.has_key('size'):
        dictionary.pop('size')
    dictionary['architecutures'] = []

    #Macholibre either has macho or universal
    if dictionary.has_key('macho'):
        popMachoKeys(dictionary['macho'])
        dictionary['Universal'] = False
        macho = dictionary.pop('macho')
        #I need it twice so there's no point in searching

        # Makes the key Macho + the cputype from the macho dictionary, if it has that key. Also replaces spaces with '_'
        machoKey = "macho_" + macho['cputype'].replace(
            ' ', '_') if macho.has_key('cputype') else 'macho'
        dictionary['machos'] = [{machoKey: macho}]
        dictionary['architecutures'].append(
            macho['subtype'] if macho.has_key('subtype') else '')

        del macho, machoKey

    elif dictionary.has_key('universal'):
        #Universal has embedded machos
        if dictionary['universal'].has_key('machos'):
            dictionary['Universal'] = True
            dictionary['machos'] = []

            for index, macho in enumerate(dictionary['universal']['machos']):
                popMachoKeys(macho)
                hasCPU = macho.has_key('cputype')
                # Does the same thing but make sure not to overwrite the indexes if neither has 'cputype' as a key
                machoKey = "macho_" + macho['cputype'].replace(
                    ' ', '_') if hasCPU else 'macho_' + str(index)
                if macho.has_key('subtype'):
                    dictionary['architecutures'].append(macho['subtype'])
                dictionary['machos'].append({machoKey: macho})
            dictionary.pop('universal')

    return dictionary