Beispiel #1
0
def BasicAnalyzer(analyzeFile):
    print(f"{infoS} Analyzing: {green}{analyzeFile}{white}")
    fileType = str(pr.magic_file(analyzeFile))
    # Windows Analysis
    if "Windows Executable" in fileType or ".msi" in fileType or ".dll" in fileType or ".exe" in fileType:
        print(f"{infoS} Target OS: {green}Windows{white}\n")
        command = f"python3 Modules/winAnalyzer.py {analyzeFile}"
        os.system(command)
    # Linux Analysis
    elif "ELF" in fileType:
        print(f"{infoS} Target OS: {green}Linux{white}\n")
        command = f"readelf -a {analyzeFile} > Modules/elves.txt"
        os.system(command)
        command = f"python3 Modules/linAnalyzer.py {analyzeFile}"
        os.system(command)
    # MacOSX Analysis
    elif "Mach-O" in fileType:
        print(f"{infoS} Target OS: {green}OSX{white}\n")
        command = f"python3 Modules/osXAnalyzer.py {analyzeFile}"
        os.system(command)
    # Android Analysis
    elif "PK" in fileType or "Android" in fileType:
        print(f"{infoS} Target OS: {green}Android{white}\n")
        command = f"python3 Modules/apkAnalyzer.py {analyzeFile}"
        os.system(command)
    else:
        print(f"{infoS} File Type: {green}Non Executable{white}\n")
        command = f"python3 Modules/nonExecAnalyzer.py {analyzeFile}"
        os.system(command)
Beispiel #2
0
def BasicAnalyzer(analyzeFile):
    print(f"{infoS} Analyzing: {green}{analyzeFile}{white}")
    fileType = str(pr.magic_file(analyzeFile))
    # Windows Analysis
    if "Windows Executable" in fileType or ".msi" in fileType or ".dll" in fileType or ".exe" in fileType:
        print(f"{infoS} Target OS: {green}Windows{white}\n")
        command = f"python3 Modules/winAnalyzer.py {analyzeFile}"
        os.system(command)
    # Linux Analysis
    elif "ELF" in fileType:
        print(f"{infoS} Target OS: {green}Linux{white}\n")
        command = f"readelf -a {analyzeFile} > Modules/elves.txt"
        os.system(command)
        command = f"python3 Modules/linAnalyzer.py {analyzeFile}"
        os.system(command)
    # MacOSX Analysis
    elif "Mach-O" in fileType:
        print(f"{infoS} Target OS: {green}OSX{white}\n")
        command = f"python3 Modules/osXAnalyzer.py {analyzeFile}"
        os.system(command)
    # Android Analysis
    elif "PK" in fileType and "Java archive" in fileType:
        print(f"{infoS} Target OS: {green}Android{white}\n")
        command = f"python3 Modules/apkAnalyzer.py {analyzeFile}"
        os.system(command)
    else:
        print(
            f"{errorS} File type not supported. Make sure you are analyze executable files or document files."
        )
        print(
            f"{errorS} If you want to scan document files try {green}--docs{white} argument."
        )
        sys.exit(1)
 def test_magic_file(self):
     """File identification with magic_file          |"""
     self.assertEqual(puremagic.magic_file(TGA_FILE)[0].extension, ".tga")
     open("test_empty_file", "w").close()
     try:
         self.assertRaises(ValueError, puremagic.magic_file, "test_empty_file")
     finally:
         os.unlink("test_empty_file")
Beispiel #4
0
 def test_magic_file(self):
     """File identification with magic_file          |"""
     self.assertEqual(puremagic.magic_file(TGA_FILE)[0][0], ".tga")
     open("test_empty_file", "w").close()
     try:
         self.assertRaises(ValueError, puremagic.magic_file, "test_empty_file")
     finally:
         os.unlink("test_empty_file")
Beispiel #5
0
def _categorise_binary(fpath):
    info = puremagic.magic_file(fpath)
    mimetype = None
    for item in info:
        guess = item[1]
        if guess != u"":
            mimetype = guess
    return mimetype
Beispiel #6
0
    def detect_mime_type(clazz, filename):
        'Detect the mime type for file.'
        filename = file_check.check_file(filename)

        import puremagic
        rv = puremagic.magic_file(filename)
        if not rv:
            return None
        return clazz._find_mime_type(rv)
Beispiel #7
0
def BasicAnalyzer(analyzeFile):
    print(f"{infoS} Analyzing: {green}{analyzeFile}{white}")
    fileType = str(pr.magic_file(analyzeFile))
    # Windows Analysis
    if "Windows Executable" in fileType or ".msi" in fileType or ".dll" in fileType or ".exe" in fileType:
        print(f"{infoS} Target OS: {green}Windows{white}\n")
        command = f"python3 {sc0pe_path}/Modules/winAnalyzer.py {analyzeFile}"
        os.system(command)

    # Linux Analysis
    elif "ELF" in fileType:
        print(f"{infoS} Target OS: {green}Linux{white}\n")
        command = f"readelf -a {analyzeFile} > elves.txt"
        os.system(command)
        command = f"python3 {sc0pe_path}/Modules/linAnalyzer.py {analyzeFile}"
        os.system(command)

    # MacOSX Analysis
    elif "Mach-O" in fileType:
        print(f"{infoS} Target OS: {green}OSX{white}\n")
        command = f"python3 {sc0pe_path}/Modules/osXAnalyzer.py {analyzeFile}"
        os.system(command)

    # Android Analysis
    elif "PK" in fileType and "Java archive" in fileType:
        look = pyaxmlparser.APK(analyzeFile)
        if look.is_valid_APK() == True:
            print(f"{infoS} Target OS: {green}Android{white}")
            command = f"apkid -j {args.file} > apkid.json"
            os.system(command)
            command = f"python3 {sc0pe_path}/Modules/apkAnalyzer.py {analyzeFile}"
            os.system(command)
            if os.path.exists("apkid.json"):
                os.remove("apkid.json")
            # APP Security
            choice = str(
                input(
                    f"\n{infoS} Do you want to check target app\'s security? This process will take a while.[Y/n]: "
                ))
            if choice == "Y" or choice == "y":
                os.system(f"python3 {sc0pe_path}/Modules/apkSecCheck.py")
            else:
                pass
        else:
            print(
                f"{errorS} Qu1cksc0pe doesn\'t support archive analysis for now ;)"
            )
            sys.exit(1)
    else:
        print(
            f"{errorS} File type not supported. Make sure you are analyze executable files or document files."
        )
        print(
            f"{errorS} If you want to scan document files try {green}--docs{white} argument."
        )
        sys.exit(1)
Beispiel #8
0
def get_mimetype(fpath):
    """Return mimetype of a file."""
    try:
        possibilities = puremagic.magic_file(fpath)
    except ValueError:  # File is empty.
        return "unknown/unknown"
    if len(possibilities) > 0:
        return possibilities[0].mime_type
    else:
        return "unknown/unknown"
Beispiel #9
0
def is_filetype(filename=None, search_str=None):
    """
    Applies magic byte (header) inspection to determine if of search file type.
    """
    if not search_str:
        return False
    results = puremagic.magic_file(filename)
    for result in results:
        if search_str.lower() in result.name.lower():
            return True
    return False
Beispiel #10
0
 def _puremagic_media_type_of_file(file_path):
     array_of_type_arrays = puremagic.magic_file(file_path)
     types = list(map(lambda x: x[1], array_of_type_arrays))
     types = list(filter(lambda x: x and x != '', types))
     if len(types) == 0:
         return None
     media_type = types[0]
     if media_type == 'application/x-ipynb+json':  # All JSON files are not Jupiter notebooks
         media_type = 'application/json'
     elif media_type == 'application/x-gzip':  # deprecated
         media_type = 'application/gzip'
     return media_type
Beispiel #11
0
 def _media_type_from_magic(file_path):
     """
     Use puremagic to generate a media-type for the file, then correct its mistakes.
     """
     types = puremagic.magic_file(file_path)
     if len(types) == 0:
         return 'application/octet-stream'
     media_type = types[0][1]
     if media_type == 'application/x-ipynb+json':  # All JSON files are not Jupiter notebooks
         if file_path.endswith('.json'):
             media_type = 'application/json'
     elif media_type == 'application/x-gzip':  # deprecated
         media_type = 'application/gzip'
     return media_type
Beispiel #12
0
def ExecutableCheck(fileName):
    exe_indicator = 0
    try:
        magicNums = list(pr.magic_file(fileName))
        for mag in range(0, len(magicNums)):
            if magicNums[mag].confidence >= 0.4:
                if "executable" in str(
                        magicNums[mag].name) or "Executable" in str(
                            magicNums[mag].name):
                    exe_indicator += 1
        if exe_indicator != 0:
            return True
        else:
            return False
    except:
        pass
Beispiel #13
0
def extension_file(path: str):
    """
    Check the enconding format based on the magic number
    if file has no magic number we simply use extension.
    More advance analytics of file content is needed, potentially
    extendind to a lib like libmagic

    Args:
        path (str): File path

    Returns:
        file_extension_given: str: extension of encoding data
        magic_data : dic : any magic data information available including
                            magic number : byte
                            mime_type: str
                            name : str

    """
    file_extension_given = os.path.splitext(path)[1]

    format_file = puremagic.magic_file(path)
    if len(format_file) > 0:
        if format_file[0].confidence < 0.5:
            print("poor confidence")
            magicdata = {
                "byte_match": None,
                "mime_type": None,
                "name": None,
            }
            return file_extension_given, magicdata
        else:
            magicdata = {
                "byte_match": "{}".format(format_file[0].byte_match),
                "mime_type": format_file[0].mime_type,
                "name": format_file[0].name,
            }
            return format_file[0].extension, magicdata
    else:
        magicdata = {
            "byte_match": None,
            "mime_type": None,
            "name": None,
        }
        return file_extension_given, magicdata
Beispiel #14
0
def MagicParser(targetFile):
    # Defining table
    resTable = PrettyTable()

    # Magic byte parsing
    resCounter = 0
    resTable.field_names = [f"File Extension", "Names", "Byte Matches", "Confidence"]
    resourceList = list(pr.magic_file(targetFile))
    for res in range(0, len(resourceList)):
        extrExt = str(resourceList[res].extension)
        extrNam = str(resourceList[res].name)
        extrByt = str(resourceList[res].byte_match)
        if resourceList[res].confidence >= 0.8:
            resCounter += 1
            if extrExt == '':
                resTable.add_row([f"{red}No Extension{white}", f"{red}{extrNam}{white}", f"{red}{extrByt}{white}", f"{red}{resourceList[res].confidence}{white}"])
            else:
                resTable.add_row([f"{red}{extrExt}{white}", f"{red}{extrNam}{white}", f"{red}{extrByt}{white}", f"{red}{resourceList[res].confidence}{white}"])
    if len(resourceList) != 0:
        print(resTable)
Beispiel #15
0
def generate_preview(filepath: str, max_size=390) -> str:
    """ Detect filetype and generate a human readable text preview

    Detects filetype and returns a string if there is a compatible text
    preview method available. For text files, the preview will be the first
    `max_size` characters. For other file types, a selection of their
    metadata could be shown.
    """
    filetype = ""
    excerpt = ""
    extension = get_file_extension(filepath)

    try:
        my_file = puremagic.magic_file(filepath)
        if my_file:
            filetype = " ".join(str(i) for i in next(itertools.chain(my_file)))
    except Exception as e:
        print("FILETYPE_DETECTION_ERROR:", e)  # DEBUG
        pass

    # TODO: Check if there is a specific file preview method
    #print('EXT:', extension) # DEBUG
    #print('TYPE:', filetype) # DEBUG

    if extension in SUPPORTED_TYPES['text']:
        excerpt = generic_text_preview(filepath, max_size)

    elif extension in SUPPORTED_TYPES['image']:
        excerpt = "[Text preview for image files not implemented yet.]"

    elif extension in SUPPORTED_TYPES['pdf']:
        excerpt = "[Text preview for PDF files not implemented yet.]"

    else:
        excerpt = generic_binary_preview(filepath, max_size)

    if excerpt:
        return f"Format: {filetype}\n{excerpt}"
    else:
        return f"Format: {filetype}\n[No preview available for this file.]"
Beispiel #16
0
 def mime_type(self):
     if self._mime_type:
         return self._mime_type
     else:
         if self.auto_detect_mime_type:
             if self.path and os.path.isfile(self.path) \
             and os.access(self.path, os.R_OK):
                 m = find_mime_type_recursive(
                     puremagic.magic_file(self.path))
                 if m:
                     return m
                 else:
                     logger.warning(
                         "Can't detect mime type of file '%s'. Using default mime type: %s"
                         % (self.path, self.default_mime_type))
                     return self.default_mime_type
             elif not self.path and self.body:
                 try:
                     m = find_mime_type_recursive(
                         puremagic.magic_string(self.body))
                 except PureError:
                     m = None
                 if m:
                     return m
                 else:
                     logger.warning(
                         "Can't detect mime type of body. Using default mime type: %s"
                         % self.default_mime_type)
                     return self.default_mime_type
             else:
                 logger.warning(
                     "File '%s' isn't readable. Skipping mime type auto detection, using default mime type: %s"
                     % (self.path, self.default_mime_type))
                 return self.default_mime_type
         else:
             return self.default_mime_type
Beispiel #17
0
        for val in detector[key]:
            if val in allStrings:
                print(
                    f"{foundS} Possible programming language: {green}{key}{white}\n"
                )
                indicator += 1
                sys.exit(0)
    if indicator == 0:
        print(f"{errorS} Programming language couldn\'t detected :(\n")
        sys.exit(1)


# Execution
indmag = 0
try:
    magicNums = list(pr.magic_file(fileName))
    for mag in range(0, len(magicNums)):
        if magicNums[mag].confidence >= 0.4:
            if "executable" in str(magicNums[mag].name) or "Executable" in str(
                    magicNums[mag].name):
                indmag += 1
                LanguageDetect()
            else:
                pass
        else:
            pass
    if indmag == 0:
        print(f"{errorS} Please scan executable files.\n")
        sys.exit(1)
except:
    pass
def isELF(file):
    b = puremagic.magic_file(file)
    for x in b:
        if 'ELF' in x[-2]:
            return True
Beispiel #19
0
def Analyzer():
    allFuncs = 0
    tables = PrettyTable()
    secTable = PrettyTable()
    segTable = PrettyTable()
    resTable = PrettyTable()
    statistics = PrettyTable()

    for key in dictArr:
        for elem in dictArr[key]:
            if elem in allStrings:
                if elem != "":
                    Categs[key].append(elem)
                    allFuncs +=1
    for key in Categs:
        if Categs[key] != []:
            if key == "Information Gathering" or key == "System/Persistence" or key == "Cryptography":
                print(f"\n{yellow}[{red}!{yellow}]__WARNING__[{red}!{yellow}]{white}")

            # Printing zone
            tables.field_names = [f"Functions or Strings about {green}{key}{white}"]
            for i in Categs[key]:
                if i == "":
                    pass
                else:
                    tables.add_row([f"{red}{i}{white}"])
                    # Threat score
                    if key == "Networking":
                        scoreDict[key] += 1
                    elif key == "File":
                        scoreDict[key] += 1
                    elif key == "Process":
                        scoreDict[key] += 1
                    elif key == "Memory Management":
                        scoreDict[key] += 1
                    elif key == "Information Gathering":
                        scoreDict[key] += 1
                    elif key == "System/Persistence":
                        scoreDict[key] += 1
                    elif key == "Cryptography":
                        scoreDict[key] += 1
                    elif key == "Other/Unknown":
                        scoreDict[key] += 1
                    else:
                        pass
            print(tables)
            tables.clear_rows()

    # Gathering sections and segments
    secTable.field_names = [f"{green}Sections{white}"]
    segTable.field_names = [f"{green}Segments{white}"]

    # Sections
    sec_indicator = 0
    for se1 in sections:
        if se1 in allThings:
            if se1 != "":
                secTable.add_row([f"{red}{se1}{white}"])
                sec_indicator += 1
    if sec_indicator != 0:
        print(secTable)
    
    # Segments
    seg_indicator = 0
    for se2 in segments:
        if se2 in allThings:
            if se2 != "":
                segTable.add_row([f"{red}{se2}{white}"])
                seg_indicator += 1
    if seg_indicator != 0:
        print(segTable)

    # Resource scanner zone
    resCounter = 0
    resTable.field_names = [f"Extracted File Extensions", "Names", "Byte Matches", "Confidence"]
    resourceList = list(pr.magic_file(fileName))
    for res in range(0, len(resourceList)):
        extrExt = str(resourceList[res].extension)
        extrNam = str(resourceList[res].name)
        extrByt = str(resourceList[res].byte_match)
        if resourceList[res].confidence >= 0.4:
            resCounter += 1
            if extrExt == '':
                resTable.add_row([f"{red}No Extension{white}", f"{red}{extrNam}{white}", f"{red}{extrByt}{white}", f"{red}{resourceList[res].confidence}{white}"])
            else:
                resTable.add_row([f"{red}{extrExt}{white}", f"{red}{extrNam}{white}", f"{red}{extrByt}{white}", f"{red}{resourceList[res].confidence}{white}"])
    if len(resourceList) != 0:
        print(resTable)

    # Statistics zone
    print(f"\n{green}->{white} Statistics for: {green}{fileName}{white}")

    # Printing zone
    statistics.field_names = ["Categories", "Number of Functions"]
    statistics.add_row([f"{green}All Functions{white}", f"{green}{allFuncs}{white}"])
    for key in scoreDict:
        if scoreDict[key] == 0:
            pass
        else:
            if key == "System/Persistence" or key == "Cryptography" or key == "Information Gathering":
                statistics.add_row([f"{yellow}{key}{white}", f"{red}{scoreDict[key]}{white}"])
            else:
                statistics.add_row([f"{white}{key}", f"{scoreDict[key]}{white}"])
    print(statistics)

    # Warning about obfuscated file
    if allFuncs < 10:
        print(f"\n{errorS} This file might be obfuscated or encrypted. Try {green}--packer{white} to scan this file for packers.\n")
        sys.exit(0)
Beispiel #20
0
def Analyzer():
    threatScore = 0
    allFuncs = 0
    tables = PrettyTable()
    dllTable = PrettyTable()
    resTable = PrettyTable()
    statistics = PrettyTable()

    # categorizing extracted strings
    for key in regdict:
        for el in regdict[key]:
            if el in allStrings:
                if el != "":
                    dictCateg[key].append(el)
                    allFuncs += 1

    # printing categorized strings
    for key in dictCateg:
        if dictCateg[key] != []:

            # More important categories
            if key == "Keyboard/Keylogging" or key == "Evasion/Bypassing" or key == "System/Persistence" or key == "Cryptography" or key == "Information Gathering":
                print(
                    f"\n{yellow}[{red}!{yellow}]__WARNING__[{red}!{yellow}]{white}"
                )

            # Printing zone
            tables.field_names = [
                f"Functions or Strings about {green}{key}{white}"
            ]
            for i in dictCateg[key]:
                if i == "":
                    pass
                else:
                    tables.add_row([f"{red}{i}{white}"])

                    # Calculating threat score
                    if key == "Registry":
                        threatScore += 4
                        scoreDict[key] += 1
                    elif key == "File":
                        threatScore += 4
                        scoreDict[key] += 1
                    elif key == "Networking/Web":
                        threatScore += 6
                        scoreDict[key] += 1
                    elif key == "Keyboard/Keylogging":
                        threatScore += 7
                        scoreDict[key] += 1
                    elif key == "Process":
                        threatScore += 5
                        scoreDict[key] += 1
                    elif key == "Memory Management":
                        threatScore += 5
                        scoreDict[key] += 1
                    elif key == "Dll/Resource Handling":
                        threatScore += 6
                        scoreDict[key] += 1
                    elif key == "Evasion/Bypassing":
                        threatScore += 9
                        scoreDict[key] += 1
                    elif key == "System/Persistence":
                        threatScore += 9
                        scoreDict[key] += 1
                    elif key == "COMObject":
                        threatScore += 4
                        scoreDict[key] += 1
                    elif key == "Cryptography":
                        threatScore += 9
                        scoreDict[key] += 1
                    elif key == "Information Gathering":
                        threatScore += 7
                        scoreDict[key] += 1
                    elif key == "Other/Unknown":
                        threatScore += 1
                        scoreDict[key] += 1
                    else:
                        pass
            print(tables)
            tables.clear_rows()

    # gathering extracted dll files
    handleDll = []
    dllTable.field_names = [f"Extracted {green}DLL{white} Strings"]
    for dl in allStrings:
        if dl in dllArray:
            if dl != "":
                handleDll.append(dl)

    # Removing duplicates and printing
    if handleDll != []:
        handleDll = list(dict.fromkeys(handleDll))
        for ne in handleDll:
            dllTable.add_row([f"{red}{ne}{white}"])
        print(dllTable)

    # Resource scanner zone
    resCounter = 0
    resTable.field_names = [
        f"Extracted File Extensions", "Names", "Byte Matches", "Confidence"
    ]
    resourceList = list(pr.magic_file(fileName))
    for res in range(0, len(resourceList)):
        extrExt = str(resourceList[res].extension)
        extrNam = str(resourceList[res].name)
        extrByt = str(resourceList[res].byte_match)
        if resourceList[res].confidence >= 0.4:
            resCounter += 1
            if extrExt == '':
                resTable.add_row([
                    f"{red}No Extension{white}", f"{red}{extrNam}{white}",
                    f"{red}{extrByt}{white}",
                    f"{red}{resourceList[res].confidence}{white}"
                ])
            else:
                resTable.add_row([
                    f"{red}{extrExt}{white}", f"{red}{extrNam}{white}",
                    f"{red}{extrByt}{white}",
                    f"{red}{resourceList[res].confidence}{white}"
                ])
    if len(resourceList) != 0:
        print(resTable)

    # Statistics zone
    print(f"\n{green}->{white} Statistics for: {green}{fileName}{white}")

    # printing all function statistics
    statistics.field_names = ["Categories", "Number of Functions or Strings"]
    statistics.add_row(
        [f"{green}All Functions{white}", f"{green}{allFuncs}{white}"])
    for key in scoreDict:
        if scoreDict[key] == 0:
            pass
        else:
            if key == "Keyboard/Keylogging" or key == "Evasion/Bypassing" or key == "System/Persistence" or key == "Cryptography" or key == "Information Gathering":
                statistics.add_row(
                    [f"{yellow}{key}{white}", f"{red}{scoreDict[key]}{white}"])
            else:
                statistics.add_row(
                    [f"{white}{key}", f"{scoreDict[key]}{white}"])
    print(statistics)

    # Warning about obfuscated file
    if allFuncs < 10:
        print(
            f"\n{errorS} This file might be obfuscated or encrypted. Try {green}--packer{white} to scan this file for packers."
        )
        print(
            f"{errorS} You can also use {green}--hashscan{white} to scan this file.\n"
        )
        sys.exit(0)

    # score table
    print(
        f"\n{errorS} ATTENTION: There might be false positives in threat scaling system."
    )

    # score conditions
    if threatScore < 30:
        print(f"{thLevel}: {green}Clean{white}.\n")
    elif threatScore >= 30 and threatScore <= 200:
        print(
            f"{errorS} Attention: Use {green}--vtFile{white} argument to scan that file with VirusTotal. Do not trust that file."
        )
        print(f"{thLevel}: {yellow}Suspicious{white}.\n")
    else:
        print(f"{thLevel}: {red}Potentially Malicious{white}.\n")
Beispiel #21
0
def Analyzer():
    # Creating tables
    allFuncs = 0
    tables = PrettyTable()
    dllTable = PrettyTable()
    resTable = PrettyTable()
    statistics = PrettyTable()

    # Gathering information about sections
    pe = pf.PE(fileName)
    print(f"{infoS} Informations about Sections")
    print("-" * 40)
    for sect in pe.sections:
        print(sect.Name.decode().rstrip('\x00') + "\n|\n|---- Virtual Size: " +
              hex(sect.Misc_VirtualSize) + "\n|\n|---- Virtual Address: " +
              hex(sect.VirtualAddress) + "\n|\n|---- Size of Raw Data: " +
              hex(sect.SizeOfRawData) + "\n|\n|---- Pointer to Raw Data: " +
              hex(sect.PointerToRawData) + "\n|\n|---- Characteristics: " +
              hex(sect.Characteristics) + "\n")
    print("-" * 40)

    # categorizing extracted strings
    for key in regdict:
        for el in regdict[key]:
            if el in allStrings:
                if el != "":
                    dictCateg[key].append(el)
                    allFuncs += 1

    # printing categorized strings
    for key in dictCateg:
        if dictCateg[key] != []:

            # More important categories
            if key == "Keyboard/Keylogging" or key == "Evasion/Bypassing" or key == "System/Persistence" or key == "Cryptography" or key == "Information Gathering":
                print(
                    f"\n{yellow}[{red}!{yellow}]__WARNING__[{red}!{yellow}]{white}"
                )

            # Printing zone
            tables.field_names = [
                f"Functions or Strings about {green}{key}{white}"
            ]
            for i in dictCateg[key]:
                if i == "":
                    pass
                else:
                    tables.add_row([f"{red}{i}{white}"])

                    # Logging for summary table
                    if key == "Registry":
                        scoreDict[key] += 1
                    elif key == "File":
                        scoreDict[key] += 1
                    elif key == "Networking/Web":
                        scoreDict[key] += 1
                    elif key == "Keyboard/Keylogging":
                        scoreDict[key] += 1
                    elif key == "Process":
                        scoreDict[key] += 1
                    elif key == "Memory Management":
                        scoreDict[key] += 1
                    elif key == "Dll/Resource Handling":
                        scoreDict[key] += 1
                    elif key == "Evasion/Bypassing":
                        scoreDict[key] += 1
                    elif key == "System/Persistence":
                        scoreDict[key] += 1
                    elif key == "COMObject":
                        scoreDict[key] += 1
                    elif key == "Cryptography":
                        scoreDict[key] += 1
                    elif key == "Information Gathering":
                        scoreDict[key] += 1
                    elif key == "Other/Unknown":
                        scoreDict[key] += 1
                    else:
                        pass
            print(tables)
            tables.clear_rows()

    # gathering extracted dll files
    dllTable.field_names = [f"Linked {green}DLL{white} Files"]
    for items in pe.DIRECTORY_ENTRY_IMPORT:
        dlStr = str(items.dll.decode())
        dllTable.add_row([f"{red}{dlStr}{white}"])
    print(dllTable)

    # Resource scanner zone
    resCounter = 0
    resTable.field_names = [
        f"Extracted File Extensions", "Names", "Byte Matches", "Confidence"
    ]
    resourceList = list(pr.magic_file(fileName))
    for res in range(0, len(resourceList)):
        extrExt = str(resourceList[res].extension)
        extrNam = str(resourceList[res].name)
        extrByt = str(resourceList[res].byte_match)
        if resourceList[res].confidence >= 0.4:
            resCounter += 1
            if extrExt == '':
                resTable.add_row([
                    f"{red}No Extension{white}", f"{red}{extrNam}{white}",
                    f"{red}{extrByt}{white}",
                    f"{red}{resourceList[res].confidence}{white}"
                ])
            else:
                resTable.add_row([
                    f"{red}{extrExt}{white}", f"{red}{extrNam}{white}",
                    f"{red}{extrByt}{white}",
                    f"{red}{resourceList[res].confidence}{white}"
                ])
    if len(resourceList) != 0:
        print(resTable)

    # Statistics zone
    print(f"\n{green}->{white} Statistics for: {green}{fileName}{white}")

    # printing all function statistics
    statistics.field_names = ["Categories", "Number of Functions or Strings"]
    statistics.add_row(
        [f"{green}All Functions{white}", f"{green}{allFuncs}{white}"])
    for key in scoreDict:
        if scoreDict[key] == 0:
            pass
        else:
            if key == "Keyboard/Keylogging" or key == "Evasion/Bypassing" or key == "System/Persistence" or key == "Cryptography" or key == "Information Gathering":
                statistics.add_row(
                    [f"{yellow}{key}{white}", f"{red}{scoreDict[key]}{white}"])
            else:
                statistics.add_row(
                    [f"{white}{key}", f"{scoreDict[key]}{white}"])
    print(statistics)

    # Warning about obfuscated file
    if allFuncs < 20:
        print(
            f"\n{errorS} This file might be obfuscated or encrypted. Try {green}--packer{white} to scan this file for packers."
        )
        print(
            f"{errorS} You can also use {green}--hashscan{white} to scan this file.\n"
        )
        sys.exit(0)
Beispiel #22
0
        # Specifying target folder
        elif con_command == "set target-folder":
            foldername = str(
                input(f"{foundS} Enter full path of target folder: "))
            if os.path.isdir(foldername):
                with open(".target-folder.txt", "w") as tfolder:
                    tfolder.write(foldername)
            else:
                print(f"{errorS} Please enter a correct folder.")

        # Windows analysis
        elif con_command == "analyze windows":
            if os.path.exists(".target-file.txt"):
                filename = open(".target-file.txt", "r").read()
                print(f"\n{infoS} Analyzing: {green}{filename}{white}")
                fileType = str(pr.magic_file(filename))
                if "Windows Executable" in fileType or ".msi" in fileType or ".dll" in fileType or ".exe" in fileType:
                    print(f"{infoS} Target OS: {green}Windows{white}\n")
                    command = f"python3 {sc0pe_path}/Modules/winAnalyzer.py {filename}"
                    os.system(command)
            else:
                print(
                    f"{errorS} You must specify target file with {green}set target-file{white} command."
                )

        # Linux Analysis
        elif con_command == "analyze linux":
            if os.path.exists(".target-file.txt"):
                filename = open(".target-file.txt", "r").read()
                print(f"\n{infoS} Analyzing: {green}{filename}{white}")
                fileType = str(pr.magic_file(filename))
def test_file_field():
    tmp_file = tempfile.mktemp()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YSDgoGAf359fHt6eXh3dnV0c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIBwYFBAMCAQAAOw=='
    tmp_gif_file = tempfile.mktemp()
    tmp_gif_path = str(tmp_gif_file)
    with open(tmp_gif_path, 'bw') as f:
        f.write(base64.b64decode(gif_content))
        f.close()

    m = puremagic.magic_file(tmp_gif_path)
    assert find_mime_type_recursive(m) == 'image/gif'

    jpg_content = b'/9j/4QlQaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjYtYzEzOCA3OS4xNTk4MjQsIDIwMTYvMDkvMTQtMDE6MDk6MDEgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiLz4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA8P3hwYWNrZXQgZW5kPSJ3Ij8+/+0ALFBob3Rvc2hvcCAzLjAAOEJJTQQlAAAAAAAQ1B2M2Y8AsgTpgAmY7PhCfv/bAIQAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQICAgICAgICAgICAwMDAwMDAwMDAwEBAQEBAQECAQECAgIBAgIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD/90ABAAE/+4ADkFkb2JlAGTAAAAAAf/AABEIABwAHgMAEQABEQECEQH/xABfAAEBAQADAAAAAAAAAAAAAAAJCwUDBwgBAQAAAAAAAAAAAAAAAAAAAAAQAAEEAgICAwADAAAAAAAAAAQCAwUGAQcACAkREhMUFSMyEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMAAAERAhEAPwCf/wABDeiGuKFuWJ7B6hkIwsvbmxKpRYXVcmBF1uTNgIoS6sTezJUdy2kAwkIhmDixclSGSgXmAMEN/qYZefXgMnyRkUcrsyYuo0WP1pODa81zEbUpURWwahFRO0q7Wx65YDB63FBgQ8ZI2SMiQJWVwE0kF6aOMeHytlxDig8EcD//0J//AAE+8QEw3E93KqyrDWXZzWO8oERLrbTyXDD9TWxYzGGXnG2nXCHB/rRjOf8ASsZx6zjGcBj+WoEhvvDsaeIYaHXeKnqW6pQw628OpE3q6p4+0dbSlI+t1QuVfHGVfFWcp95zj3kDZ4H/0Z//AAGC8avWe7Q+y9ZdjbWRVI2nEDWt6vUUi2jg7iu8IZGyNRFudGoTbgcvO1Ia2FfmILaLEdQ2KU838kM+1h3X5bOvB+1t7X7b+jWIZGvNR6focPM0i0WyHD3OyPSY78Nwm11MkxyWtcdBHPEYIkR1vYyOE4v2pKUqWAJcD//Sn/8AATjTPaK7Vvr4JZiavr+3WfreLIUrU1guMRNy5sDUthSLzdjr5ArNjBh5OMdatRiG0PCq+KFpTnKsITjAc+wuyNpnutcbsBuo0CBvVvritDn22CjrEzLg6vDVKiE1qI/kLRJAgjS6YlCyf6V+nnXVs4aU5nPAMDgf/9k='
    tmp_jpg_file = tempfile.mktemp()
    tmp_jpg_path = str(tmp_jpg_file)
    with open(tmp_jpg_path, 'bw') as f:
        f.write(base64.b64decode(jpg_content))
        f.close()

    m = puremagic.magic_file(tmp_jpg_path)
    assert find_mime_type_recursive(m) == 'image/jpeg'

    png_content = b'iVBORw0KGgoAAAANSUhEUgAAAB4AAAAcCAYAAAB2+A+pAAABS2lUWHRYTUw6Y29tLmFkb2JlLn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nmZiYIBAIMBwOLTF+lLEsy8iyTKVSYXFxkWg0Sq1WG7/4+fkZWZbxeDw0Gg2Ab4/TdyHw74/XKLG7u0soFKJWq1GtVpFlGZfLRSwW4+zsDIBut8tgMODk5OR/WSPV2G63s729TSKR4OPjg7m5OXK5HIIgEAqFOD8/x+FwEIlEiMVi2Gw2+v0+p6enfyZOJBKsrq5yeHjI4+Mj8/PzxONxAoEAPp8Pt9tNq9Uim83idDpZWloinU5zdXVFu93+kjlSjVVVxeVyEQ6H0TSNfD6PoihcXFxwcHCAoiiEQiGKxSJ3d3fA50Vis32f10gZ39/fUy6XcTqdJJNJ+v0+kiSRTqdpt9s4nU6KxSKZTAbDMBBFkaenJ+r1+rfMkZtrY2ODRCIBfDaQYRjouo6u6ySTSer1OjabjVAoRKlUIpfL8fb29udigNnZWaanpzFNk8vLS3q93u93y8vLqKpKv9/n5ubm29r+F78AmGZ4Lz2bZYkAAAAASUVORK5CYII='
    tmp_png_file = tempfile.mktemp()
    tmp_png_path = str(tmp_png_file)
    with open(tmp_png_path, 'bw') as f:
        f.write(base64.b64decode(png_content))
        f.close()

    m = puremagic.magic_file(tmp_png_path)
    assert find_mime_type_recursive(m) == 'image/png'

    b = FileField()
    b.path = tmp_path
    d = b.to_dict()
    assert len(d) == 3
    assert d['Body'] == b'this is a test'
    assert d['Name'] == os.path.basename(tmp_path)
    assert d['MimeType'] == 'text/plain'

    b = FileField(name='test.txt', path=tmp_path, mime_type='weird/odd')
    d = b.to_dict()
    assert len(d) == 3
    assert d['Name'] == 'test.txt'
    assert d['Body'] == b'this is a test'
    assert d['MimeType'] == 'weird/odd'

    b = FileField(name='test.txt', mime_type='empty/body')
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == 'test.txt'
    assert d['Body'] == bytes()
    assert d['MimeType'] == 'empty/body'

    b = FileField(path=tmp_path)
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == os.path.basename(tmp_path)
    assert d['Body'] == b'this is a test'
    assert d['MimeType'] == 'text/plain'

    b = FileField(name='some.txt', body=b'custom body')
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == 'some.txt'
    assert d['Body'] == b'custom body'
    assert d['MimeType'] == 'text/plain'

    b = FileField(name='some.txt',
                  body=b'custom body',
                  mime_type='custom/mime')
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == 'some.txt'
    assert d['Body'] == b'custom body'
    assert d['MimeType'] == 'custom/mime'

    b = FileField({
        'name': 'some1.txt',
        'body': b'custom1 body',
        'mime_type': 'custom/mime1'
    })
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == 'some1.txt'
    assert d['Body'] == b'custom1 body'
    assert d['MimeType'] == 'custom/mime1'

    b = FileField({
        'Name': 'some2.txt',
        'Body': b'custom2 body',
        'MimeType': 'custom/mime2'
    })
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == 'some2.txt'
    assert d['Body'] == b'custom2 body'
    assert d['MimeType'] == 'custom/mime2'

    b = FileField({'path': tmp_path})
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == os.path.basename(tmp_path)
    assert d['Body'] == b'this is a test'
    assert d['MimeType'] == 'text/plain'

    b = FileField({'Path': tmp_gif_path, 'Name': 'file.gif'})
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == 'file.gif'
    assert d['Body'] == base64.b64decode(gif_content)
    assert d['MimeType'] == 'image/gif'

    b = FileField({'Path': tmp_jpg_path, 'Name': 'file.jpg'})
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == 'file.jpg'
    assert d['Body'] == base64.b64decode(jpg_content)
    assert d['MimeType'] == 'image/jpeg'

    b = FileField({'path': tmp_png_path, 'Name': 'file.png'})
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == 'file.png'
    assert d['Body'] == base64.b64decode(png_content)
    assert d['MimeType'] == 'image/png'

    b = FileField({
        'path': tmp_png_path,
        'Name': 'file.png',
        'MimeType': 'custom/mime'
    })
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == 'file.png'
    assert d['Body'] == base64.b64decode(png_content)
    assert d['MimeType'] == 'custom/mime'

    b = FileField(tmp_png_path)
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert len(d['Name']) > 0
    assert d['Body'] == base64.b64decode(png_content)
    assert d['MimeType'] == 'image/png'

    b = FileField(base64.b64decode(gif_content))
    d = b.to_dict()
    d = b.value
    assert len(d) == 3
    assert d['Name'] == 'Filename'
    assert d['Body'] == base64.b64decode(gif_content)
    assert d['MimeType'] == 'image/gif'
Beispiel #24
0
def Analyzer():
    # Creating tables
    allFuncs = 0
    tables = PrettyTable()
    peStatistics = PrettyTable()
    dllTable = PrettyTable()
    resTable = PrettyTable()
    statistics = PrettyTable()

    # categorizing extracted strings
    for win_api in allStrings:
        for key in regdict:
            if win_api[0] in regdict[key]:
                if win_api[0] != "":
                    dictCateg[key].append(win_api)
                    allFuncs += 1

    # printing categorized strings
    import_indicator = 0
    for key in dictCateg:
        if dictCateg[key] != []:

            # More important categories
            if key == "Keyboard/Keylogging" or key == "Evasion/Bypassing" or key == "System/Persistence" or key == "Cryptography" or key == "Information Gathering":
                print(
                    f"\n{yellow}[{red}!{yellow}]__WARNING__[{red}!{yellow}]{white}"
                )

            # Printing zone
            tables.field_names = [
                f"Functions or Strings about {green}{key}{white}", "Address"
            ]
            for func in dictCateg[key]:
                if func[0] == "":
                    pass
                else:
                    tables.add_row(
                        [f"{red}{func[0]}{white}", f"{red}{func[1]}{white}"])
                    import_indicator += 1

                    # Logging for summary table
                    if key == "Registry":
                        scoreDict[key] += 1
                    elif key == "File":
                        scoreDict[key] += 1
                    elif key == "Networking/Web":
                        scoreDict[key] += 1
                    elif key == "Keyboard/Keylogging":
                        scoreDict[key] += 1
                    elif key == "Process":
                        scoreDict[key] += 1
                    elif key == "Memory Management":
                        scoreDict[key] += 1
                    elif key == "Dll/Resource Handling":
                        scoreDict[key] += 1
                    elif key == "Evasion/Bypassing":
                        scoreDict[key] += 1
                    elif key == "System/Persistence":
                        scoreDict[key] += 1
                    elif key == "COMObject":
                        scoreDict[key] += 1
                    elif key == "Cryptography":
                        scoreDict[key] += 1
                    elif key == "Information Gathering":
                        scoreDict[key] += 1
                    elif key == "Other/Unknown":
                        scoreDict[key] += 1
                    else:
                        pass
            print(tables)
            tables.clear_rows()

    # If there is no function imported in target executable
    if import_indicator == 0:
        print(f"{errorS} There is no function/API imports found.")
        print(
            f"{magenta}>>{white} Try '{green}--packer{white}' or '{green}--lang{white}' to see additional info about target file.\n"
        )

    # gathering extracted dll files
    try:
        dllTable.field_names = [f"Linked {green}DLL{white} Files"]
        for items in binaryfile.DIRECTORY_ENTRY_IMPORT:
            dlStr = str(items.dll.decode())
            dllTable.add_row([f"{red}{dlStr}{white}"])
        print(dllTable)
    except:
        pass

    # Yara rule match
    print(f"\n{infoS} Performing YARA rule matching...")
    WindowsYara(target_file=fileName)

    # Resource scanner zone
    print(f"\n{infoS} Performing magic number analysis...")
    resCounter = 0
    resTable.field_names = [
        f"File Extensions", "Names", "Byte Matches", "Confidence"
    ]
    resourceList = list(pr.magic_file(fileName))
    for res in range(0, len(resourceList)):
        extrExt = str(resourceList[res].extension)
        extrNam = str(resourceList[res].name)
        extrByt = str(resourceList[res].byte_match)
        if resourceList[res].confidence >= 0.4:
            resCounter += 1
            if extrExt == '':
                resTable.add_row([
                    f"{red}No Extension{white}", f"{red}{extrNam}{white}",
                    f"{red}{extrByt}{white}",
                    f"{red}{resourceList[res].confidence}{white}"
                ])
            else:
                resTable.add_row([
                    f"{red}{extrExt}{white}", f"{red}{extrNam}{white}",
                    f"{red}{extrByt}{white}",
                    f"{red}{resourceList[res].confidence}{white}"
                ])
    if len(resourceList) != 0:
        print(resTable)

    # Assembly and pe structure analysis zone
    print(
        f"\n{infoS} Performing PE file structure and assembly code analysis...\n"
    )

    # Gathering information about sections
    peStatistics.field_names = [
        "Section Name", "Virtual Size", "Virtual Address", "Size Of Raw Data",
        "Pointer to Raw Data", "Entropy"
    ]

    pe = pf.PE(fileName)

    # Parsing timedatestamp data
    mydict = pe.dump_dict()
    tempstr = mydict["FILE_HEADER"]["TimeDateStamp"]["Value"][11:].replace(
        "[", "")
    datestamp = tempstr.replace("]", "")

    # Parsing sections
    for sect in pe.sections:
        if sect.get_entropy() >= 7:
            peStatistics.add_row([
                sect.Name.decode().rstrip('\x00'),
                hex(sect.Misc_VirtualSize),
                hex(sect.VirtualAddress),
                hex(sect.SizeOfRawData),
                hex(sect.PointerToRawData),
                f"{red}{sect.get_entropy()}{white} (Possible obfuscation!!)"
            ])
        else:
            peStatistics.add_row([
                sect.Name.decode().rstrip('\x00'),
                hex(sect.Misc_VirtualSize),
                hex(sect.VirtualAddress),
                hex(sect.SizeOfRawData),
                hex(sect.PointerToRawData),
                sect.get_entropy()
            ])
    print(f"{magenta}>>{white} Time Date Stamp: {green}{datestamp}{white}")
    print(peStatistics)

    # Statistics zone
    print(f"\n{green}->{white} Statistics for: {green}{fileName}{white}")

    # printing all function statistics
    statistics.field_names = ["Categories", "Number of Functions or Strings"]
    statistics.add_row(
        [f"{green}All Functions{white}", f"{green}{allFuncs}{white}"])
    for key in scoreDict:
        if scoreDict[key] == 0:
            pass
        else:
            if key == "Keyboard/Keylogging" or key == "Evasion/Bypassing" or key == "System/Persistence" or key == "Cryptography" or key == "Information Gathering":
                statistics.add_row(
                    [f"{yellow}{key}{white}", f"{red}{scoreDict[key]}{white}"])
            else:
                statistics.add_row(
                    [f"{white}{key}", f"{scoreDict[key]}{white}"])
    print(statistics)

    # Warning about obfuscated file
    if allFuncs < 20:
        print(
            f"\n{errorS} This file might be obfuscated or encrypted. Try {green}--packer{white} to scan this file for packers."
        )
        print(
            f"{errorS} You can also use {green}--hashscan{white} to scan this file.\n"
        )
        sys.exit(0)
 def test_magic_file(self):
     """File identification with magic_file          |"""
     self.assertEqual(puremagic.magic_file(TGA_FILE)[1][0][0], ".tga")
Beispiel #26
0
def puremagic_mimetype(url):
    return puremagic.magic_file(url)[0].mime_type