예제 #1
0
    def _get_peid_signatures(self):
        """Gets PEID signatures.
        @return: matched signatures or None.
        """
        if not self.pe:
            return None

        try:
            sig_path = os.path.join(CUCKOO_ROOT, "data",
                                    "peutils", "UserDB.TXT")
            signatures = peutils.SignatureDatabase(sig_path)
            return signatures.match_all(self.pe, ep_only=True)
        except:
            return None
예제 #2
0
파일: pescanner.py 프로젝트: um-dsp/MalEvol
    def __init__(self, data, yara_rules=None, peid_sigs=None):
        self.pedata = data

        # initialize YARA rules if provided
        if yara_rules and sys.modules.has_key('yara'):
            self.rules = yara.compile(yara_rules)
        else:
            self.rules = None

        # initialize PEiD signatures if provided
        if peid_sigs:
            self.sigs = peutils.SignatureDatabase(peid_sigs)
        else:
            self.sigs = None
예제 #3
0
 def peid(self):
     pe_matches = dict()
     userdb_file_dir_path = path.join(path.dirname(__file__), 'data',
                                      'UserDB.TXT')
     signatures = peutils.SignatureDatabase(userdb_file_dir_path)
     packer = []
     matches = signatures.match_all(self.pe, ep_only=True)
     if matches:
         map(packer.append, [s[0] for s in matches])
     pe_matches["peid_signature_match"] = packer
     pe_matches["is_probably_packed"] = peutils.is_probably_packed(self.pe)
     pe_matches["is_suspicious"] = peutils.is_suspicious(self.pe)
     pe_matches["is_valid"] = peutils.is_valid(self.pe)
     return pe_matches
예제 #4
0
def main_s(pe, ch, f, name):

    exescan = ExeScan(pe, name)
    # store reports in folders
    #if os.path.exists(MD5):
    #    report_name = str(MD5)+".txt"
    #    report_name = os.path.join(MD5,report_name)
    #else:
    #    os.mkdir(MD5)
    #    report_name = str(MD5)+".txt"
    #    report_name = os.path.join(MD5,report_name)
    #handle = open(report_name,'a')
    strings = f.readlines()
    #print(strings)
    #sys.exit(0)
    mf = open("API.txt", "r")
    MALAPI = mf.readlines()
    signature = peutils.SignatureDatabase("userdb.txt")
    check = signature.match_all(pe, ep_only=True)

    #exescan.header()
    #exescan.importtab()
    #exescan.exporttab()
    #exescan.anomalis()
    exescan.malapi(MALAPI, strings)
    #stx.StringE()

    #if ch == "-i":
    #    exescan.base(check)
    #    exescan.importtab()
    #    exescan.exporttab()
    #elif ch == "-b":
    #    exescan.base(check)
    #elif ch == "-m":
    #    exescan.base(check)
    #    exescan.malapi(MALAPI,strings)
    #elif ch == "-p":
    #    exescan.base(check)
    #    exescan.header()
    #elif ch == "-a":
    #    exescan.base(check)
    #    exescan.anomalis()
    #    exescan.malapi(MALAPI,strings)
    #    stx.StringE()
    #else:
    #    print()
    mf.close()
    #handle.close()
    return MD5
예제 #5
0
def POE(logdir, target, logging, debug):

    newlogentry = ''
    full_dump = ''
    matches = ''
    output = logdir + 'FullDump.txt'
    signaturedb = '/opt/static/UserDB.txt'
    if (logging == True):
        LOG = logger()

    FI = fileio()
    SIG = peutils.SignatureDatabase(signaturedb)
    PEX = pefile.PE(target.filename)

    if (logging == True):
        newlogentry = 'PEiD Signature (...if signature database present):'
        LOG.WriteLog(logdir, target.filename, newlogentry)

    if (signaturedb != ''):
        matches = SIG.match_all(PEX, ep_only=True)

        print '[*] Signature Matches: ' + str(matches)

        if (logging == True):
            newlogentry = 'Signature: ' + '<strong>' + str(
                matches) + '</strong>'
            LOG.WriteLog(logdir, target.filename, newlogentry)

            newlogentry = 'Sample Attribute Sections:'
            LOG.WriteLog(logdir, target.filename, newlogentry)

    for section in PEX.sections:
        if (debug == True):
            print '[DEBUG] ' + section.Name + ' Virtual Address: ' + str(
                hex(section.VirtualAddress)) + ' Virtual Size: ' + str(
                    hex(section.Misc_VirtualSize)) + ' Raw Data Size: ' + str(
                        section.SizeOfRawData)

    try:
        for entry in PEX.DIRECTORY_ENTRY_IMPORT:
            for imp in entry.imports:
                if (debug == True):
                    print '[DEBUG] imp address and name: ' + str(
                        hex(imp.address)) + str(imp.name)
    except Exception, e:
        print '[-] Unable to process DIRECTORY_ENTRY_IMPORT object: ', e
        if (logging == True):
            newlogentry = 'Unable to process DIRECTORY_ENTRY_IMPORT object'
            LOG.WriteLog(logdir, target.filename, newlogentry)
예제 #6
0
    def analyze(self):
        with open(
                './../tools/peid/db_signatures.txt',
                encoding="ISO-8859-1",
        ) as f:
            try:
                sig_data = f.read()
                signatures = peutils.SignatureDatabase(data=sig_data)

                pe = pefile.PE(self.malware.path)
                matches = signatures.match(pe, ep_only=True)
                return matches
            except Exception as e:
                print(e)
                return 'error'
예제 #7
0
    def __init__(self, files, yara_rules=None, peid_sigs=None):
        self.files = files

        # initialize YARA rules if provided
        if yara_rules and sys.modules.has_key('yara'):
            self.rules = yara.compile(yara_rules)
        else:
            self.rules = None

        # initialize PEiD signatures if provided
        if peid_sigs:
            self.sigs = peutils.SignatureDatabase(peid_sigs)
        else:
            self.sigs = None
            print("PEiD no inicializado")
예제 #8
0
파일: pe.py 프로젝트: youngjun-chang/viper
        def get_signatures():
            userdb_path = None
            for path_attempt in ['/usr/share/viper/peid/UserDB.TXT', os.path.join(VIPER_ROOT, 'data/peid/UserDB.TXT')]:
                if os.path.exists(path_attempt):
                    userdb_path = path_attempt
                    break

            if not userdb_path:
                return

            with open(userdb_path, 'rt', encoding='ISO-8859-1') as f:
                sig_data = f.read()

            signatures = peutils.SignatureDatabase(data=sig_data)

            return signatures
예제 #9
0
파일: scanner.py 프로젝트: 5l1v3r1/malice-2
    def _build_peid_matches(self, scan_result):
        import peutils
        pe_matches = dict()
        UserDB_FILE_DIR_PATH = path.join(path.dirname(__file__), 'file',
                                         '../pe/data/UserDB.TXT')
        signatures = peutils.SignatureDatabase(UserDB_FILE_DIR_PATH)

        packer = []
        matches = signatures.match_all(scan_result, ep_only=True)
        if matches:
            map(packer.append, [s[0] for s in matches])
        pe_matches["peid_signature_match"] = packer
        pe_matches["is_probably_packed"] = peutils.is_probably_packed(
            scan_result)
        pe_matches["is_suspicious"] = peutils.is_suspicious(scan_result)
        pe_matches["is_valid"] = peutils.is_valid(scan_result)
        return pe_matches
예제 #10
0
파일: pe.py 프로젝트: wgee1/malzoo
    def packer_detect(self):  
        """ attempt to detect the packer used """
        if self.pe != False:
            signatures  = peutils.SignatureDatabase(self.userdb)
            matches     = signatures.match_all(self.pe, ep_only=True)  
            result      = ''
            
            if matches != None:
                for match in matches:
                    m       = ','.join(match)
                    result  = result+m

                return result
            else:
                return None
        else:
            return None
예제 #11
0
def peid_load():
    try:
        # todo: allow user's peid db
        # db_file = args.db instead of ''
        # or maybe do this in main and pass as arg
        db_file = ''
        if db_file == '':
            db_file = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                   'userdb.txt')
        if os.path.exists(db_file):
            return peutils.SignatureDatabase(db_file)
        else:
            print('problem loading peid database file')
            return
    except:
        print('problem loading peid database file')
        return
예제 #12
0
def Main():
    global oLogger

    try:
        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    except:
        pass

    oParser = optparse.OptionParser(usage='usage: %prog [options] [file/directory]\nEnvironment variable for options: PECHECK_OPTIONS\n' + __description__, version='%prog ' + __version__)
    oParser.add_option('-d', '--db', default='', help='the PeID user db file, default userdb.txt in same directory as pecheck')
    oParser.add_option('-s', '--scan', action='store_true', default=False, help='scan folder')
    oParser.add_option('-e', '--entropy', type=float, default=7.0, help='the minimum entropy value for a file to be listed in scan mode (default 7.0)')
    oParser.add_option('-y', '--yara', help="YARA rule-file, @file or directory to check streams (YARA search doesn't work with -s option)")
    oParser.add_option('--yarastrings', action='store_true', default=False, help='Print YARA strings')
    oParser.add_option('-g', '--getdata', type=str, default='', help='Get data from the PE file (example 0x1234,0x100)')
    oParser.add_option('-D', '--dump', action='store_true', default=False, help='perform dump')
    oParser.add_option('-x', '--hexdump', action='store_true', default=False, help='perform hex dump')
    oParser.add_option('-a', '--asciidump', action='store_true', default=False, help='perform ascii dump')
    oParser.add_option('-S', '--strings', action='store_true', default=False, help='perform strings dump')
    oParser.add_option('-o', '--overview', type=str, default='', help='Accepted value: r for overview of resources')
    (options, args) = oParser.parse_args(GetArgumentsUpdatedWithEnvironmentVariable('PECHECK_OPTIONS'))

    if len(args) > 1 or options.overview != '' and options.overview != 'r':
        oParser.print_help()
        print('')
        print('  Source code put in the public domain by Didier Stevens, no Copyright')
        print('  Use at your own risk')
        print('  https://DidierStevens.com')
        return

    else:
        try:
            dbfile = options.db
            if dbfile == '':
                dbfile = os.path.join(os.path.dirname(sys.argv[0]), 'userdb.txt')
            signatures = peutils.SignatureDatabase(dbfile)
        except:
            signatures = None
        if len(args) == 0:
            SingleFile('', signatures, options)
        elif options.scan:
            oLogger = CSVLogger('pecheck', ('Filename', 'Entropy', 'Sections', 'Executable sections', 'Executable and writable sections', 'Size AuthentiCode', 'Stored CRC', 'Calculated CRC', 'CRC anomaly', 'Compile date', 'CompanyName', 'ProductName', 'MD5'))
            ScanFiles(args[0], signatures, options.entropy)
        else:
            SingleFile(args[0], signatures, options)
예제 #13
0
def matchSignatures(pe):
    peid = peutils.SignatureDatabase('peid_sigs/userdb.txt')

    matches = peid.match(pe, ep_only=True)

    if matches is None:
        print "\t[!] Nothing found, scanning more than ep..."
        matches = peid.match(pe, ep_only=False)

    print "[*] Found:"
    if matches is not None:
        if len(matches) == 1:
            print "\t" + str(matches)
        else:
            for match in matches:
                print "\t" + str(match[0]) + "\t" + str(match[1])
    else:
        print "\tNo Matches"
def get_packer_signature(pe, userdb):
    print('==========get packer signatures=================')
    packer_name = ""
    sig = peutils.SignatureDatabase(userdb)
    a = sig.generate_section_signatures(pe, userdb)
    matches = sig.match_all(pe, ep_only=True)

    arr = []
    if matches is None:
        print('')

    elif matches:
        print(matches)
        for i in matches:
            #print("pacekr_siganature i is : ", i)
            if i not in arr:
                arr.append(i)
    return arr
예제 #15
0
    def __init__(self, files, peid_sigs=None):
        self.files = files
        # initialize YARA rules if provided

        # initialize PEiD signatures if provided
        if peid_sigs:
            try:
                self.sigs = peutils.SignatureDatabase(peid_sigs)
            except:
                self.sigs = None
        else:
            self.sigs = None

        # initialize python magic (file identification)
        # magic interface on python <= 2.6 is different than python >= 2.6
        if 'magic' in sys.modules:
            if sys.version_info <= (2, 6):
                self.ms = magic.open(magic.MAGIC_NONE)
                self.ms.load()
예제 #16
0
    def activate(self, stoq):

        self.stoq = stoq

        parser = argparse.ArgumentParser()
        parser = StoqArgs(parser)

        worker_opts = parser.add_argument_group("Plugin Options")
        worker_opts.add_argument("-r",
                                 "--peidrules",
                                 dest="peidrules",
                                 help="Path to peid rules file")

        options = parser.parse_args(self.stoq.argv[2:])

        super().activate(options=options)

        self.signatures = peutils.SignatureDatabase(self.peidrules)

        return True
    def do_pkinfo(self, args):
        """
        Get pe's packer info

        Usage:
            pkinfo file
        """
        argv = self.checkargs(args, 1)

        if argv == None: return

        fn = argv[0]
        if not os.path.isfile(fn):
            print "*invalid* file : %s" % fn
            return

        pe  = pefile.PE(fn)
        sig = peutils.SignatureDatabase( SIG_FILE )
        pk  = sig.match(pe)
        print "[pkinfo] %s : %s" % (fn, pk)
예제 #18
0
    def each(self, target):
        self.results = dict()
        try:
            # lief analysis
            binary = lief.parse(target)
            binary_dict = json.loads(lief.to_json(binary), parse_int=str)
            self.results.update(binary_dict)

            # packet detect using pefile (PEiD sigs)
            # sig file obtained here https://github.com/erocarrera/pefile/blob/wiki/PEiDSignatures.md
            # named after date downloaded & added to FAME
            signatures = peutils.SignatureDatabase(PE_ID_SIGS_FILE)
            pe = pefile.PE(target, fast_load=True)
            matches = signatures.match(pe, ep_only=True)
            packer_dict = {'packers': matches}
            self.results.update(packer_dict)

        except:
            self.log('error', traceback.print_exc())
        return True
예제 #19
0
    def __init__(
        self,
        host,
        port,
        user,
        password,
        threshold=40,
        secure=False,
        filepath=None,
        filename=None,
        folder_path=None,
    ):
        """Connects to neo4j database, loads options and set connectors.
        @raise CuckooReportError: if unable to connect.
        """
        self.threshold = int(threshold)
        self.graph = Graph(host=host,
                           user=user,
                           password=password,
                           secure=secure,
                           port=port)
        self.filepath = filepath
        self.filename = filename
        self.folder_path = folder_path
        self.scout = ApiScout()
        self.scout.setBaseAddress(0)
        self.scout.loadWinApi1024(
            os.path.abspath(os.path.join(os.path.dirname(__file__))) + os.sep +
            "data" + os.sep + "winapi1024v1.txt")

        self.magictest = magic.Magic(uncompress=True)
        CWD = os.path.abspath(os.path.dirname(__file__))
        USERDB = os.path.join(CWD, os.path.normpath("data/UserDB.TXT"))
        with open(USERDB, "rt") as f:
            sig_data = f.read()
            self.signatures = peutils.SignatureDatabase(data=sig_data)

        if self.folder_path:
            self.files = self.get_files(folder_path)
def worker(folder):
    print("Start {}".format(folder))
    _n = 0
    _m = 0
    list_all = os.listdir(folder)#该文件夹下所有病毒文件
    list_f_info = []
    for f in list_all:
        if len(f) == 64:#如果是病毒文件
            sha256 = str(f)
            f = folder + f
            #print(f)
            str_cmd = "file {}".format(f)
            f_type = os.popen(str_cmd).read().strip().split("/")[-1]
            f_type = f_type.split(":")[-1]
            if f_type.find("PE32") != -1:#找到了
                _n +=1
                try:
                    pe = pefile.PE(f)
                except AttributeError as e:
                    print(e)
                    check = None
                except pefile.PEFormatError as e:
                    print(f)
                    print(e)
                    check = None
                else:
                    signature  = peutils.SignatureDatabase("userdb.txt")
                    check = signature.match_all(pe,ep_only = True)
                    if check:
                        _m +=1
                f_info = sha256 + "," + str(check)
                #print(f_info)
                list_f_info.append(f_info)
    f_csv = folder + "f_pack_info.csv"
    with open(f_csv, "w") as f:
        for item in list_f_info:
            f.write("{}\n".format(item))
    print("Finished {}: {}".format(folder, len(list_f_info)))
    return {_n:_m}
예제 #21
0
def main_s(pe, ch, f, name):
    global handle
    exescan = ExeScan(pe, name)
    (MD5, SHA1, SHA256, data) = exescan.hashes()
    # store reports in folders
    if os.path.exists(MD5):
        report_name = str(MD5) + ".txt"
        report_name = os.path.join(MD5, report_name)
    else:
        os.mkdir(MD5)
        report_name = str(MD5) + ".txt"
        report_name = os.path.join(MD5, report_name)
    handle = open(report_name, 'a')
    greet()
    log("\n\n[+] File: %s" % name)
    log("\n\t[*] MD5 	: %s" % MD5)
    log("\t[*] SHA-1 	: %s" % SHA1)
    log("\t[*] SHA-256	: %s" % SHA256)
    # check file type (exe, dll)
    if pe.is_exe():
        log("\n[+] File Type: EXE")
    elif pe.is_dll():
        log("\n[+] File Type: DLL")
    strings = f.readlines()
    mf = open("API.txt", "r")
    MALAPI = mf.readlines()
    signature = peutils.SignatureDatabase("userdb.txt")
    check = signature.match_all(pe, ep_only=True)
    if ch == "-i":
        exescan.base(check)
        exescan.importtab()
        exescan.exporttab()

    else:
        print()
    mf.close()
    handle.close()
    return config.error
예제 #22
0
def checkPacker(pyew, doprint=True, args=None):
    """ Check if the PE file is packed """
    if pyew.pe is None:
        return

    sig = peutils.SignatureDatabase(
        os.path.join(os.path.dirname(__file__), "UserDB.TXT"))
    matches = sig.match_all(pyew.pe, ep_only=True)
    if not matches:
        if doprint:
            print "***No match"
        return

    if doprint:
        for match in matches:
            print "".join(match)

    if len(matches) == 0:
        if doprint:
            print "***No match"
        return

    return matches
예제 #23
0
    def peid(self, args, file, opts):
        try:
            pe = pefile.PE(file.file_path)  # pylint: disable=invalid-name, no-member
            userdb_path = path.join(path.dirname(__file__), 'userdb.txt')
            sigs = peutils.SignatureDatabase(userdb_path)
        except Exception as err:
            raise error.CommandWarning('unable to parse with pefile: %s' % err)

        try:
            matches = sigs.match_all(pe, ep_only=True)
        except Exception:
            raise error.CommandWarning('error matching peid signatures')

        # Matches returns a list of lists, hence the stupid indexing
        output = []
        if not matches:
            pass
        elif len(matches) == 1:
            output += [str(matches[0][0])]
        else:
            for match in matches:
                output += [match[0]]
        return output
예제 #24
0
    def analyze(self, filepath=None, data=None, sigs=None):
        self.filepath = filepath
        self.data = data
        self.pe = None
        if sigs:
            self.sigs = peutils.SignatureDatabase(sigs)
        else:
            self.sigs = None
        if (self.filepath and self.data is not None) or \
           (self.filepath is None and self.data is None):
            log.error("either filepath ({0}) ".format(self.filepath) +
                      "and data ({0}) should be set".format(self.data))
            return None
        elif self.filepath and not os.path.exists(self.filepath):
            log.error("file {0} does not exist".format(self.filepath))
            return None

        try:
            if self.filepath is not None:
                self.pe = pefile.PE(self.filepath)
            elif self.data is not None:
                self.pe = pefile.PE(data=self.data)
        except pefile.PEFormatError:
            return None

        results = {}
        results["peid_signatures"] = self._get_peid_signatures()
        results["pe_imports"] = self._get_imported_symbols()
        results["pe_exports"] = self._get_exported_symbols()
        results["pe_sections"] = self._get_sections()
        results["pe_resources"] = self._get_resources()
        results["pe_versioninfo"] = self._get_versioninfo()
        nb_dll = len([x for x in results["pe_imports"] if x.get("dll")])
        results["imported_dll_count"] = nb_dll

        return results
예제 #25
0
    print 'yara-python is not installed, see http://code.google.com/p/yara-project/'

has_res = 0  # For Suspecious Resources
high_entropy = 0  # checking for high entropy sections
has_ep_out = 0  # cheks Entry point for bad entries
has_antivm = 0  # antivm checks
has_kernelmode_imports = 0  # ntoskernel imports
has_antidbg = 0  # anti_dbg_imp

good_ep_sections = ['.text', '.code', 'CODE', 'INIT', 'PAGE']
anti_dbg_imp = ['NtQueryInformationProcess', 'NtSetInformationThread',
                'IsDebuggerPresent', 'CheckRemoteDebugger']

kernel_loads = []  # for holding kernel32 imports

sigs = peutils.SignatureDatabase(peid)


def check_antidbg(pe):
    for entry in pe.DIRECTORY_ENTRY_IMPORT:
        if (entry.dll == "ntdll.dll"):
            for imp in entry.imports:
                for i in anti_dbg_imp:
                    if(imp.name == i):
                        has_antidbg = 1


def check_kernel_mode(pe):
    for entry in pe.DIRECTORY_ENTRY_IMPORT:
        if (entry.dll == "ntoskrnl.exe"):
            has_kernelmode_imports = 1
예제 #26
0
 def __init__(aSelf, aPatternFile):
     with open(aPatternFile, "rt", encoding="utf8") as db:
         aSelf._sig = peutils.SignatureDatabase(data=db.read())
 if fl.read(2) == "MZ":
     print full_filename + " is an executable"
     pe = pefile.PE(full_filename)
     for entry in pe.DIRECTORY_ENTRY_IMPORT:
         for imp in entry.imports:
             fnname = str(imp.name)
             if re.match('^Crypt', fnname):
                 print '\t', entry.dll, hex(
                     imp.address), imp.name
                 i = 1
             else:
                 i = 0
                 pass
     if i == 0:
         print "No Crypt dll's found in IAT, perhaps packed or benign\n"
         signatures = peutils.SignatureDatabase('userdb.txt')
         matches = signatures.match_all(pe, ep_only=True)
         print "Likely packers:\n"
         print matches
     print "Running Scan on " + full_filename + "for Crypto Constants...\n"
     cmd = ['C:\Python27\signsrch\signsrch.exe', full_filename]
     res = subprocess.Popen(cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
     j = 0
     while True:
         text = res.stdout.readline()
         if not text:
             break
         if "offset" in text:
             j = 1
예제 #28
0
def main():
    version = "1.5"
    parser = ArgumentParser(description="Used to check PEid databases against files in Python")
    parser.add_argument("-D", "--database",
                        dest="alt_db", help="use alternate signature database DB", metavar="DB")
    parser.add_argument("-J", "--JSON",
                        dest="json_out", help="print terse output as JSON", action="store_true")
    parser.add_argument("-P", "--peid",
                        dest="peid", help="print PEiD matches", action="store_true")
    parser.add_argument("-V", "--version",
                        dest="version", help="show version number", default=False, action="store_true")
    parser.add_argument("-a", "--all",
                        dest="show_all", help="show all PE info", default=False, action="store_true")
    parser.add_argument("-d", "--disasm",
                        dest="disasm", help="disassemble the first X bytes after EP", metavar="X", type=int)
    parser.add_argument("-e", "--extract-sig",
                        dest="extract_sig", help="extracts the digital signature", default=False, action="store_true")
    parser.add_argument("-m", "--all-matches",
                        dest="show_matches", help="show all signature matches", default=False, action="store_true")
    parser.add_argument("-p", "--pretty-print",
                        dest="pretty_print", help="pretty print JSON document", default=False, action="store_true")
    parser.add_argument("-t", "--terse",
                        dest="terse", help="give a short listing of various PE properties", default=False, action="store_true")
    parser.add_argument("files", nargs='+', help='Files to analyze')
    
    args = parser.parse_args()
    
    if args.version:
        print "Packerid.py version ",version,"\n Copyright (c) 2007, Jim Clausing, forked by Sconzo"
        sys.exit(0)

    if args.alt_db and (args.peid | args.show_all | args.show_matches):
        signatures = peutils.SignatureDatabase(args.alt_db)
    elif (args.peid | args.show_all | args.show_matches):
        signatures = peutils.SignatureDatabase('/usr/local/etc/userdb.txt')

    json_out = False
    if args.json_out:
        json_out = True

    file_json = {}
    for file in vars(args)['files']:
        j_output = {}
        try:
            pe = pefile.PE(file)
        except Exception as e:
            sys.stderr.write("[*] Error with %s - %s\n" %(file, str(e)))
            continue
   
        if not args.terse: 
            if args.show_all|args.show_matches:
                matches = signatures.match_all(pe, ep_only = True)
                t = []
                if matches == None or len(matches) == 0:
                    if not json_out: print "None"
                else:
                    t = set()
                    for m in matches:
                        t.add(m[0])
                    if json_out: j_output['PEid'] = t
                    else: print "\t" + ", ".join(t)
            elif args.peid:
                matches = signatures.match(pe, ep_only = True)
                if matches == None:
                    if not json_out: print "None"
                else:
                    if json_out: j_output['PEid'] = matches[0]
                    else: print matches[0]
    
        if args.show_all:
            print pe.dump_info()
    
        if args.terse:
            if args.peid:
                matches = signatures.match_all(pe, ep_only = True)
                if matches == None or len(matches) == 0:
                    if json_out: j_output['PEiD'] = ["None"]
                    else: print "PEiD\n\tNone"
                else:
                    t = set()
                    for m in matches:
                        t.add(m[0])
                    if json_out: j_output['PEiD'] = t 
                    else: print "PEiD\n\t" + ", ".join(t)
   
            if json_out:
                j_output['Entry Point Address'] = hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint)
                j_output['Image Base Address'] = hex(pe.OPTIONAL_HEADER.ImageBase) 
                j_output['Linker Version'] = {}
                j_output['Linker Version']['Major'] = pe.OPTIONAL_HEADER.MajorLinkerVersion
                j_output['Linker Version']['Minor'] = pe.OPTIONAL_HEADER.MinorLinkerVersion
                j_output['OS Version'] = {}
                j_output['OS Version']['Major'] = pe.OPTIONAL_HEADER.MajorOperatingSystemVersion
                j_output['OS Version']['Minor'] = pe.OPTIONAL_HEADER.MinorOperatingSystemVersion 
            else:
                print "Entry Point Address\n\t%s" %(hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint))
                print "Image Base Address\n\t%s" %(hex(pe.OPTIONAL_HEADER.ImageBase))
                print "Linker Version\n\t%d.%d" %(pe.OPTIONAL_HEADER.MajorLinkerVersion,pe.OPTIONAL_HEADER.MinorLinkerVersion)
                print "OS Version\n\t%d.%d" %(pe.OPTIONAL_HEADER.MajorOperatingSystemVersion,pe.OPTIONAL_HEADER.MinorOperatingSystemVersion)

            if pe.FILE_HEADER.Machine == 0x14c: 
                if json_out: j_output['Machine'] = 'x86'
                else: print "Machine\n\tx86"
            elif pe.FILE_HEADER.Machine == 0x14d:
                if json_out: j_output['Machine'] = '486'
                else: print "Machine\n\t486"
            elif pe.FILE_HEADER.Machine == 0x14e:
                if json_out: j_output['Machine'] = 'Pentium'
                else: print "Machine\n\tPentium"
            elif pe.FILE_HEADER.Machine == 0x0200:
                if json_out: j_output['Machine'] = 'AMD64 only'
                else: print "Machine\n\tAMD64 only\n"
            elif pe.FILE_HEADER.Machine == 0x8664:
                if json_out: j_output['Machine'] = '64b'
                else: print "Machine\n\t64b"
            else:
                if json_out: j_output['Machine'] = 'Unknown'
                else: print "Machine\n\tUnknown"

            try:
               if json_out: j_output['Compile Time'] = "%s UTC" %(time.asctime(time.gmtime(pe.FILE_HEADER.TimeDateStamp))) 
               else: print 'Compile Time\n\t%s UTC' %(time.asctime(time.gmtime(pe.FILE_HEADER.TimeDateStamp)))
            except ValueError, e:
               if json_out: j_output['Compile Time'] = "Invalid Time" %(time.asctime(time.gmtime(pe.FILE_HEADER.TimeDateStamp))) 
               else: print 'Compile Time\n\tInvalid Time' %(time.asctime(time.gmtime(pe.FILE_HEADER.TimeDateStamp)))
            try:
                if json_out: j_output['Checksum'] =  pe.IMAGE_OPTIONAL_HEADER.CheckSum
                else: print "Checksum\t%s" %(pe.IMAGE_OPTIONAL_HEADER.CheckSum)
            except AttributeError as e:
                pass

            if not json_out:
                print "Sections"
            section_info = {}
            for section in pe.sections:
                name = ""
                # occasionally a nul sneaks in, don't print from the nul to eos
                if "\0" in section.Name:
                    nul = section.Name.index("\0")
                    name = section.Name[:nul]
                if json_out:
                    section_info[name] = {}
                    section_info[name]['VirtualAddress'] = hex(section.VirtualAddress) 
                    section_info[name]['VirtualSize'] = hex(section.Misc_VirtualSize)
                    section_info[name]['RawDataSize'] = hex(section.SizeOfRawData) 
                else: print "\t%s %s %s %s" %(name, hex(section.VirtualAddress), hex(section.Misc_VirtualSize), section.SizeOfRawData)
            if json_out: j_output['Sections'] = section_info

            if not json_out:
                print "Imports"
            try:
                import_info = {}
                for entry in pe.DIRECTORY_ENTRY_IMPORT:
                    if not json_out: print "\t" + entry.dll
                    import_info[entry.dll] = {}
                    for imp in entry.imports:
                        if json_out:
                            import_info[entry.dll]['address'] = imp.address
                            if imp.ordinal == None: import_info[entry.dll]['name'] = imp.name
                            else: import_info[entry.dll]['ordinal'] = imp.ordinal
                        else: print '\t\t%s %s' %(hex(imp.address), (imp.name if imp.ordinal == None else "("+str(imp.ordinal)+")"))
                if len(import_info) > 0:
                    j_output['Imports'] = import_info 
            except AttributeError as e:
                if not json_out: print "\tNone"

            if not json_out:
                print "Exports"
            try:
                export_info = {}
                if len(pe.DIRECTORY_ENTRY_EXPORT.symbols) > 0:
                    for exp in pe.DIRECTORY_ENTRY_EXPORT.symbols:
                        if json_out:
                            export_info[exp.name] = {}
                            export_info[exp.name]['address'] = hex(exp.address)
                            export_info[exp.name]['ordinal'] = exp.ordinal
                        else: print '\t\t%s %s (%s)' %(hex(exp.address), exp.name, exp.ordinal)
                    j_output['Exports'] = export_info
                else:
                    print "\tNone"
            except AttributeError as e:
                print "\tNone"

            sig_info = get_sig(file, pe, args.extract_sig)
            if sig_info:
                if json_out:
                    j_output['Signature'] = sig_info
                else:
                    print "Digital Signature\n\t%s" + "\n\t".join(sig_info)

            if args.disasm and not json_out:
                print "Dissassembly"

        if args.disasm:
            asm = []
            ep = pe.OPTIONAL_HEADER.AddressOfEntryPoint
            ep_ava = ep+pe.OPTIONAL_HEADER.ImageBase
            data = pe.get_memory_mapped_image()[ep:ep+args.disasm]
            #
            # Determine if the file is 32bit or 64bit
            #
            mode = CS_MODE_32
            if pe.OPTIONAL_HEADER.Magic == 0x20b:
                mode = CS_MODE_64

            md = Cs(CS_ARCH_X86, mode)
            for (address, size, mnemonic, op_str) in md.disasm_lite(data, 0x1000):
                if json_out: 
                    t = {}
                    t['address'] = address
                    t['mnemonic'] = mnemonic
                    t['op_str'] = op_str
                    asm.append(t)
                else: 
                    if args.terse:
                        print "\t0x%x:\t%s\t%s" %(address, mnemonic, op_str)
                    else:
                        print "0x%x:\t%s\t%s" %(address, mnemonic, op_str)
            if json_out:
                j_output['Disassembly'] = asm

        file_json[file] = j_output
예제 #29
0
                  dest="version",
                  help="show version number",
                  default=False,
                  action="store_true")

(options, args) = parser.parse_args()

if options.version:
    print "Packerid.py version ", version, "\n Copyright (c) 2007, Jim Clausing"
    sys.exit(0)

if len(args) < 1:
    parser.error("no files specified")

if options.alt_db:
    signatures = peutils.SignatureDatabase(options.alt_db)
else:
    signatures = peutils.SignatureDatabase('/usr/local/etc/userdb.txt')

for file in args:

    try:
        pe = pefile.PE(file)
    except:
        print file, ":  ### ERROR ###"
        continue

    if options.show_all | options.show_matches:
        matches = signatures.match_all(pe, ep_only=True)
    else:
        matches = signatures.match(pe, ep_only=True)
예제 #30
0
def main_s(pe, ch, f, name):
    #global handle
    filesize = os.stat(name).st_size
    filesize = filesize / 1024
    filesize = str(filesize) + "KB"

    atime = os.stat(name).st_atime
    mtime = os.stat(name).st_mtime
    ctime = os.stat(name).st_ctime
    dateArray = datetime.datetime.fromtimestamp(atime)
    atime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
    dateArray = datetime.datetime.fromtimestamp(mtime)
    mtime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
    dateArray = datetime.datetime.fromtimestamp(ctime)
    ctime = dateArray.strftime("%Y--%m--%d %H:%M:%S")

    exescan = ExeScan(pe, name)
    (MD5, SHA1, SHA256, data) = exescan.hashes()
    stx = StringAndThreat(MD5, data)
    # store reports in folders
    #if os.path.exists(MD5):
    #    report_name = str(MD5)+".txt"
    #    report_name = os.path.join(MD5,report_name)
    #else:
    #    os.mkdir(MD5)
    #    report_name = str(MD5)+".txt"
    #    report_name = os.path.join(MD5,report_name)
    #handle = open(report_name,'a')
    greet()
    log("\n\n[+] 文件名 : %s" % name)
    log("\n\t[*] MD5 	: %s" % MD5)
    log("\t[*] SHA-1 	: %s" % SHA1)
    log("\t[*] SHA-256	: %s" % SHA256)
    log("\t[*] 文件访问时间      : %s" % atime)
    log("\t[*] 文件内容修改时间      : %s" % mtime)
    #log("\t[*] 文件属性修改时间      : %s" % ctime)
    log("\t[*] 文件大小      : %s" % filesize)
    #check file type (exe, dll)
    if pe.is_exe():
        log("\n[+] 文件类型: EXE")
    elif pe.is_dll():
        log("\n[+] 文件类型: DLL")
    else:
        log("\n 不是PE文件结构")
        return 2
    strings = f.readlines()
    mf = open("API.txt", "r")
    MALAPI = mf.readlines()
    signature = peutils.SignatureDatabase("userdb.txt")
    check = signature.match_all(pe, ep_only=True)

    exescan.base(check)
    #exescan.header()
    #exescan.importtab()
    #exescan.exporttab()
    exescan.malapi(MALAPI, strings)
    exescan.anomalis()
    #stx.StringE()

    #if ch == "-i":
    #    exescan.base(check)
    #    exescan.importtab()
    #    exescan.exporttab()
    #elif ch == "-b":
    #    exescan.base(check)
    #elif ch == "-m":
    #    exescan.base(check)
    #    exescan.malapi(MALAPI,strings)
    #elif ch == "-p":
    #    exescan.base(check)
    #    exescan.header()
    #elif ch == "-a":
    #    exescan.base(check)
    #    exescan.anomalis()
    #    exescan.malapi(MALAPI,strings)
    #    stx.StringE()
    #else:
    #    print()
    mf.close()
    #handle.close()
    return MD5