How to use the pefile.MACHINE_TYPE function in pefile

To help you get started, we’ve selected a few pefile examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github moyix / panda-malrec / scripts / runmal.py View on Github external
sample_md5 = md5_for_file(sample_file)
logging.info("MD5: {0}".format(sample_md5))

# Make the CD image
iso_file = os.path.join(basedir, 'iso', run_id + '.iso')
logging.info("Creating CD image {0}".format(iso_file))
genisoimage = ['/usr/bin/genisoimage', '-iso-level', '4', '-l', '-R', '-J', '-o', iso_file, sample_file]
logging.info(str(genisoimage))
isoproc = subprocess.Popen(genisoimage, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = isoproc.communicate()
logging.info(stdout)
logging.info(stderr)

# Check architecture of PE file
pe = pefile.PE(sample_file, fast_load=True)
if pe.FILE_HEADER.Machine == pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']:
    logging.info("Sample detected as 64-bit")
    is_64bit = True
elif pe.FILE_HEADER.Machine == pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_I386']:
    logging.info("Sample detected as 32-bit")
    is_64bit = False
else:
    logging.error("Unknown sample type: %#x" % pe.FILE_HEADER.Machine)
    sys.exit(1)

# Copy the qcow
if is_64bit:
    master_qcow = os.path.join(basedir, 'qcow', 'win7_64.base.qcow2')
else:
    master_qcow = os.path.join(basedir, 'qcow', 'win7.base.qcow2')
new_qcow = os.path.join(basedir, 'qcow', 'win7.{0}.qcow2').format(instance)
shutil.copyfile(master_qcow, new_qcow)
github deadbits / malware-analysis-scripts / getstatic-mini.py View on Github external
machine = pe.FILE_HEADER.Machine
    except Exception as err:
        print '[warn] file is not a PE. skipping some checks: %s' % err
        pe = False
        pass

    all_results = OrderedDict(
        [
            ('MD5',             get_hash(file_name, 'md5')),
            ('SHA1',            get_hash(file_name, 'sha1')),
            ('SHA256',          get_hash(file_name, 'sha256')),
            ('Type',            commands.getoutput('file %s' % file_name).split(file_name + ': ')[1]),
            ('Size',            (os.path.getsize(file_name))/1000),
            ('SSDeep',          get_ssdeep(file_name)),
            #('ImpHash',        pe.get_imphash()),
            ('Arch',            pefile.MACHINE_TYPE[machine] if pe is not False else 'NA'),
            ('Entry Point',     hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint) if pe is not False else 'NA'),
            ('Compiled',        datetime.datetime.fromtimestamp(pe.FILE_HEADER.TimeDateStamp) if pe is not False else 'NA'),
            ('Start Address',   grep_saddress(file_name) if pe is not False else 'NA')
        ]
    )

    print '\n[ %s ]' % file_name
    for key, value in all_results.iteritems():
        if key == 'Compiled' or key == 'Entry Point' or key == 'Start Address':
            print '%s:\t\t%s' % (key, value)
        else:
            print '%s:\t\t\t%s' % (key, value)

    if subfile:
        print '\n'
        check_subfile(file_name)
github mtivadar / qiew / plugins / format / pe.py View on Github external
def hintDisasm(self):

        if self.PE.FILE_HEADER.Machine & pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64'] == pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']:
            return DisasmViewMode.Disasm_x86_64bit

        if self.PE.FILE_HEADER.Machine & pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_I386'] == pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_I386']:
            return DisasmViewMode.Disasm_x86_32bit

        return DisasmViewMode.Disasm_x86_32bit
github malice-plugins / pescan / malice / __init__.py View on Github external
self.pe.OPTIONAL_HEADER.MinorLinkerVersion)
            info['os_version'] = "{:02d}.{:02d}".format(self.pe.OPTIONAL_HEADER.MajorOperatingSystemVersion,
                                                        self.pe.OPTIONAL_HEADER.MinorOperatingSystemVersion)
            data = []
            for data_directory in self.pe.OPTIONAL_HEADER.DATA_DIRECTORY:
                if data_directory.Size or data_directory.VirtualAddress:
                    data.append({
                        'name': data_directory.name[len("IMAGE_DIRECTORY_ENTRY_"):],
                        'virtual_address': hex(data_directory.VirtualAddress),
                        'size': data_directory.Size
                    })
            self.results['data_directories'] = data
        if hasattr(self.pe, 'FILE_HEADER'):
            info['number_of_sections'] = self.pe.FILE_HEADER.NumberOfSections
            info['machine_type'] = "{} ({})".format(
                hex(self.pe.FILE_HEADER.Machine), pefile.MACHINE_TYPE[self.pe.FILE_HEADER.Machine])
        if hasattr(self.pe, 'RICH_HEADER') and self.pe.RICH_HEADER is not None:
            rich_header_info = []
            values_list = self.pe.RICH_HEADER.values
            for i in range(0, len(values_list) / 2):
                line = {
                    'tool_id': values_list[2 * i] >> 16,
                    'version': values_list[2 * i] & 0xFFFF,
                    'times used': values_list[2 * i + 1]
                }
                rich_header_info.append(line)
            self.results['rich_header_info'] = rich_header_info
        self.results['info'] = info
github PUNCH-Cyber / stoq-plugins-public / v1 / worker / peinfo / peinfo / peinfo.py View on Github external
def get_machinetype(self):
        """
        Determine the required machine type

        """

        try:
            return pefile.MACHINE_TYPE[self.pe.FILE_HEADER.Machine]
        except:
            return None
github qilingframework / qiling / qiling / arch / filetype.py View on Github external
def ql_pe_check_archtype(path):
    pe = pefile.PE(path, fast_load=True)
    ostype = None
    arch = None

    machine_map = {
        pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_I386']      :   QL_X86,
        pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']     :   QL_X8664,
        pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_ARM']       :   QL_ARM,
        pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_THUMB']     :   QL_ARM,
        #pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_ARM64']     :   QL_ARM64       #pefile does not have the definition for IMAGE_FILE_MACHINE_ARM64
        0xAA64                                              :   QL_ARM64        #Temporary workaround for Issues #21 till pefile gets updated
    }
    # get arch
    arch = machine_map.get(pe.FILE_HEADER.Machine)

    if arch:
        ostype = QL_WINDOWS
    else:
        ostype = None        

    return arch, ostype
github angr / cle / cle / backends / pe / pe.py View on Github external
def check_compatibility(cls, spec, obj):
        if hasattr(spec, 'read') and hasattr(spec, 'seek'):
            pe = pefile.PE(data=spec.read(), fast_load=True)
        else:
            pe = pefile.PE(spec, fast_load=True)

        arch = archinfo.arch_from_id(pefile.MACHINE_TYPE[pe.FILE_HEADER.Machine])
        return arch == obj.arch
github PUNCH-Cyber / stoq-plugins-public / v2 / peinfo / peinfo / peinfo.py View on Github external
def get_machinetype(self, pe):
        """
        Determine the required machine type

        """

        try:
            return pefile.MACHINE_TYPE[pe.FILE_HEADER.Machine]
        except:
            return None
github JPCERTCC / MalConfScan / utils / ursnifscan.py View on Github external
p_data["Server " + str(i)] = c2

                            if pe.FILE_HEADER.Machine in (pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_IA64'], pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']):
                                serpent_key_offset = m.start(8) + unpack("=I", data[m.start(7):m.start(7) + 4])[0]
                            else:
                                serpent_key_offset = unpack("=I", data[m.start(8):m.start(8) + 4])[0] - imagebase
                            try:
                                serpent_key = self.decode_data(data, pe, serpent_key_offset)
                            except:
                                serpent_key = "Decode fail"
                            p_data["Serpent key"] = serpent_key

                    for pattern in RSA_PATTERNS:
                        m = re.search(pattern, data)
                        if m:
                            if pe.FILE_HEADER.Machine in (pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_IA64'], pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']):
                                rsa_key_offset = m.start(2) + unpack("=I", data[m.start(1):m.start(1) + 4])[0]
                                rsa_key = data[rsa_key_offset + 4:rsa_key_offset + 0x44]

                                rsa_mod = data[rsa_key_offset + 0x44:rsa_key_offset + 0x84]
                            else:
                                rsa_key_offset = unpack("=I", data[m.start(1):m.start(1) + 4])[0] - imagebase
                                rsa_key = data[rsa_key_offset:rsa_key_offset + 0x40]

                                mod_offset = unpack("=I", data[m.start(4):m.start(4) + 4])[0] - imagebase
                                rsa_mod = data[mod_offset:mod_offset + 0x40]
                            p_data["RSA key"] = rsa_key.encode("hex")
                            p_data["RSA modulus"] = rsa_mod.encode("hex")

                    config_data.append(p_data)

                yield task, vad_base_addr, end, hit, memory_model, config_data