├── requirements.txt ├── requirements_with_ssdeep.txt ├── ext ├── README.md ├── validation.py └── validate_email.py ├── src ├── colors.py ├── check_updates.py ├── mass_analysis.py ├── file_strings.py ├── check_virustotal.py ├── check_strings.py ├── blacklisted_domain_ip.py ├── markdown.py ├── check.py ├── report.py └── check_file.py ├── .travis.yml ├── Dockerfile ├── .gitignore ├── README.md ├── ssma.py └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | pefile 2 | python-magic 3 | yara-python 4 | virustotal-api 5 | gitpython 6 | pyelftools 7 | elasticsearch 8 | uuid 9 | py3dns 10 | -------------------------------------------------------------------------------- /requirements_with_ssdeep.txt: -------------------------------------------------------------------------------- 1 | pefile 2 | python-magic 3 | yara-python 4 | ssdeep 5 | virustotal-api 6 | gitpython 7 | pyelftools 8 | elasticsearch 9 | uuid 10 | py3dns 11 | -------------------------------------------------------------------------------- /ext/README.md: -------------------------------------------------------------------------------- 1 | These files are imported from external libraries. 2 | 1. [Bitcoin Validation](https://github.com/nederhoed/python-bitcoinaddress) 3 | 2. [Email Validation](https://github.com/syrusakbary/validate_email) 4 | -------------------------------------------------------------------------------- /src/colors.py: -------------------------------------------------------------------------------- 1 | RED = "\033[1;31m" 2 | LIGHT_RED = '\033[91m' 3 | BLUE = "\033[1;34m" 4 | LIGHT_BLUE = '\033[94m' 5 | CYAN = "\033[1;36m" 6 | YELLOW = '\033[93m' 7 | GREEN = "\033[0;32m" 8 | RESET = "\033[0;0m" 9 | BOLD = "\033[;1m" 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.3" 4 | - "3.4" 5 | - "3.5" 6 | - "3.6" 7 | - "3.7-dev" # 3.7 development branch 8 | - "nightly" 9 | 10 | install: 11 | - pip install -r requirements.txt 12 | 13 | script: python ssma.py -h 14 | -------------------------------------------------------------------------------- /src/check_updates.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import git 3 | 4 | 5 | def check_internet_connection(): 6 | try: 7 | host = socket.gethostbyname("www.google.com") 8 | s = socket.create_connection((host, 80), 2) 9 | return True 10 | except: 11 | pass 12 | return False 13 | 14 | 15 | def download_yara_rules_git(): 16 | git.Git().clone("https://github.com/Yara-Rules/rules") 17 | 18 | -------------------------------------------------------------------------------- /src/mass_analysis.py: -------------------------------------------------------------------------------- 1 | """ 2 | Mass analysis from a directory 3 | Added by Yang 4 | """ 5 | 6 | import os 7 | 8 | 9 | def start_scan(args): 10 | target_dir = os.path.abspath(args.directory) 11 | for root, _, filenames in os.walk(target_dir): 12 | for filename in filenames: 13 | os.makedirs("analysis_report", exist_ok=True) 14 | file_path = os.path.join(root, filename) 15 | os.system("python3 ssma.py %s -r yes" % file_path) 16 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.5.3 2 | 3 | LABEL maintainer="https://github.com/pielco11" 4 | LABEL malice.plugin.repository = "https://github.com/secrary/SSMA.git" 5 | LABEL malice.plugin.category="av" 6 | LABEL malice.plugin.mime="*" 7 | LABEL malice.plugin.docker.engine="*" 8 | 9 | 10 | RUN git clone https://github.com/pielco11/SSMA.git && cd SSMA && pip3 install -r requirements.txt 11 | RUN chmod +x /SSMA/ssma.py && ln -s /SSMA/ssma.py /bin/ssma 12 | 13 | WORKDIR /malware 14 | 15 | CMD ["ssma", "-h"] 16 | 17 | ENTRYPOINT ["ssma", "-r", "elasticsearch"] 18 | -------------------------------------------------------------------------------- /src/file_strings.py: -------------------------------------------------------------------------------- 1 | from src.check_strings import * 2 | 3 | 4 | class get_strings: 5 | def __init__(self, filename): 6 | self.chars = b"A-Za-z0-9!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ " 7 | self.shortest_run = 4 8 | self.filename = filename 9 | self.regexp = '[{}]{{{},}}'.format(self.chars.decode(), self.shortest_run).encode() 10 | self.pattern = re.compile(self.regexp) 11 | 12 | with open(self.filename, 'rb') as f: 13 | list_bytes = self.process(f) 14 | strings = [] 15 | for n in list_bytes: 16 | strings.append(n.decode()) 17 | self.result = (is_website(strings), is_ip(strings), is_email(strings)) 18 | 19 | def process(self, filename): 20 | data = filename.read() 21 | return self.pattern.findall(data) 22 | 23 | def get_result(self) -> tuple: 24 | return self.result 25 | -------------------------------------------------------------------------------- /src/check_virustotal.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import virus_total_apis 3 | 4 | 5 | def virustotal(filename, api_key): # ("info", result[]) 6 | key = api_key 7 | result = [] 8 | 9 | vt = virus_total_apis.PublicApi(key) 10 | 11 | md5 = hashlib.md5(open(filename, 'rb').read()).hexdigest() 12 | response = vt.get_file_report(md5) 13 | 14 | if response["response_code"] == 204: 15 | pass 16 | 17 | response_code_ = response["results"]["response_code"] 18 | 19 | if response_code_ == 1: 20 | for n in response["results"]["scans"]: 21 | if response["results"]["scans"][n]["detected"]: 22 | result.append("{} ^ {}".format(n, response["results"]["scans"][n]["result"])) 23 | elif response_code_ == -2: 24 | pass 25 | else: 26 | if input("Would you like to upload file to VirusTotal? [Y/n] ") is not "n": 27 | response = vt.scan_file(filename) 28 | result.append(response["results"]["permalink"]) 29 | else: 30 | print() 31 | return ("scan_result", result) if response_code_ is 1 else ("permalink", result) 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | .idea/ 91 | 92 | # SSMA 93 | rules/ 94 | rules_compiled/ 95 | /test.py 96 | /src/test.py 97 | -------------------------------------------------------------------------------- /src/check_strings.py: -------------------------------------------------------------------------------- 1 | import re 2 | from urllib.parse import urlparse 3 | import subprocess 4 | 5 | from ext.validate_email import validate_email 6 | 7 | 8 | def is_ip(list_of_strings): 9 | ipv4_pattern = re.compile( 10 | r'((([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])[ (\[]?(\.|dot)[ )\]]?){3}([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))') 11 | 12 | f = filter(ipv4_pattern.match, list_of_strings) 13 | 14 | return list(f) 15 | 16 | 17 | def is_website(list_of_strings): 18 | list_of_web_addresses = [] 19 | 20 | for n in list_of_strings: 21 | try: 22 | netloc = urlparse(n.split()[0]).netloc 23 | if netloc and "." in netloc and not netloc.startswith(".") and not netloc.endswith("."): 24 | list_of_web_addresses.append(netloc) 25 | except: 26 | pass 27 | 28 | list_of_web_addresses = set(list_of_web_addresses) 29 | 30 | return list_of_web_addresses 31 | 32 | 33 | def is_email(list_of_strings): 34 | email_pattern = re.compile(r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)') 35 | 36 | f = filter(email_pattern.match, list_of_strings) 37 | F = [] 38 | for e in list(f): 39 | if validate_email(e): 40 | F.append(e) 41 | 42 | return F 43 | 44 | 45 | def ascii_strings(filename, enable): 46 | if not enable: 47 | strings_list = "" 48 | else: 49 | output = subprocess.check_output(["strings", "-a", filename]) 50 | strings_list = list(output.decode("utf-8").split('\n')) 51 | return strings_list 52 | 53 | 54 | def unicode_strings(filename, enalble): 55 | if not enalble: 56 | strings_list = "" 57 | else: 58 | output = subprocess.check_output(["strings", "-a", "-el", filename]) 59 | strings_list = list(output.decode("utf-8").split('\n')) 60 | return strings_list 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SSMA 2 | 3 | [![Join the chat at https://gitter.im/simple_static_malware_analyzer/Lobby](https://badges.gitter.im/simple_static_malware_analyzer/Lobby.svg)](https://gitter.im/simple_static_malware_analyzer/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/secrary/SSMA.svg?branch=master)](https://travis-ci.org/secrary/SSMA) 4 | 5 | SSMA is a simple malware analyzer written in Python 3. 6 | 7 | ## Features: 8 | * Analyze PE file's header and sections (number of sections, entropy of sections/PE file, suspicious section names, suspicious flags in the characteristics of the PE file, etc.) 9 | 10 | * Analyze ELF file for Linux malware analysis, it uses various open source tools (ldd, readelf, strings) to display ELF header structure, ASCII/UNICODE strings, shared objects, section header, symbol table, etc. 11 | 12 | * Searches for possible domains, e-mail addresses, IP addresses in the strings of the file. 13 | 14 | * Checks if domains are blacklisted based on abuse.ch's Ransomware Domain Blocklist and malwaredomains.com's blocklist. 15 | 16 | * Looks for Windows functions commonly used by malware. 17 | 18 | * Get results from VirusTotal and/or upload files. 19 | 20 | * Malware detection based on [Yara-rules](https://virustotal.github.io/yara/) 21 | 22 | * Detect well-known software packers. 23 | 24 | * Detect the existence of cryptographic algorithms. 25 | 26 | * Detect anti-debug and anti-virtualization techniques used by malware to evade automated analysis. 27 | 28 | * Find if documents have been crafted to leverage malicious code. 29 | 30 | * Generate json format report. 31 | 32 | * Mass analysis by specifying a folder. 33 | 34 | ## Usage 35 | ``` 36 | git clone https://github.com/secrary/SSMA 37 | 38 | cd SSMA 39 | 40 | sudo pip3 install -r requirements.txt 41 | 42 | python3 ssma.py -h 43 | ``` 44 | 45 | ## Using virtualenv 46 | ``` 47 | git clone https://github.com/secrary/SSMA 48 | cd SSMA 49 | virtualenv -p python3 env 50 | source env/bin/activate 51 | pip3 install -r requirements.txt 52 | python3 ssma.py -h 53 | ``` 54 | 55 | Additional: 56 | ssdeep - [Installation](https://python-ssdeep.readthedocs.io/en/latest/installation.html) 57 | 58 | More: [Simple Static Malware Analyzer](https://secrary.com/SSMA) 59 | 60 | 61 | ## Contributors 62 | * [pielco11](https://github.com/pielco11) 63 | * [firmianay](https://github.com/firmianay) 64 | * [Evan-Sa](https://github.com/Evan-Sa) 65 | -------------------------------------------------------------------------------- /src/blacklisted_domain_ip.py: -------------------------------------------------------------------------------- 1 | import os 2 | import urllib.request 3 | import zipfile 4 | from _socket import timeout 5 | from http.client import IncompleteRead 6 | from io import BytesIO 7 | from urllib.parse import urlparse 8 | import _socket 9 | 10 | _socket.setdefaulttimeout(10) # set timeout 11 | 12 | 13 | def ransomware_and_malware_domain_check(list_of_domains): 14 | while True: 15 | try: 16 | list_of = urllib.request.urlopen( 17 | "https://ransomwaretracker.abuse.ch/downloads/RW_DOMBL.txt").read().decode( 18 | errors='replace').strip().split("\n") 19 | except IncompleteRead: 20 | continue 21 | except timeout: 22 | list_of = "" 23 | break 24 | break 25 | 26 | list_of_mal_domains = [] 27 | 28 | for n in list_of: 29 | if n and not n.startswith("#"): 30 | list_of_mal_domains.append(n.strip()) 31 | 32 | while True: 33 | try: 34 | list_of = urllib.request.urlopen( 35 | "https://ransomwaretracker.abuse.ch/downloads/RW_URLBL.txt").read().decode( 36 | errors='replace').strip().split("\n") 37 | except IncompleteRead: 38 | continue 39 | except timeout: 40 | list_of = "" 41 | break 42 | break 43 | 44 | list_of_mal_urls = [] 45 | 46 | for n in list_of: 47 | if n and not n.startswith("#"): 48 | n = urlparse(n).netloc 49 | if n.startswith("www."): 50 | n = ".".join(n.split(".")[1:]) 51 | list_of_mal_urls.append(n) 52 | 53 | list_of = set(list_of_mal_domains + list_of_mal_urls) 54 | 55 | mal_in_my_domains = [] 56 | for mal_dom in list_of: 57 | for i, my_dom in enumerate(list_of_domains): 58 | if mal_dom in my_dom: 59 | mal_in_my_domains.append(mal_dom) 60 | list_of_domains[i] = mal_dom 61 | 62 | urlfile = urllib.request.urlopen("http://www.malware-domains.com/files/justdomains.zip") 63 | with zipfile.ZipFile(BytesIO(urlfile.read())) as z: 64 | z.extract("justdomains") 65 | my_malware_domains = [] 66 | with open("justdomains", 'r') as malware_domains: 67 | list_of_malware_domains = malware_domains.readlines() 68 | for mal_dom in list_of_malware_domains: 69 | mal_dom = mal_dom.strip() 70 | if mal_dom: 71 | if mal_dom.startswith("www."): 72 | mal_dom = ".".join(mal_dom.split(".")[1:]) 73 | for i, my_domain in enumerate(list_of_domains): 74 | if mal_dom in my_domain: 75 | my_malware_domains.append(mal_dom) 76 | list_of_domains[i] = mal_dom 77 | os.remove("justdomains") 78 | mal_in_my_domains = set(mal_in_my_domains) 79 | my_malware_domains = set(my_malware_domains) 80 | normal_domains = set(list_of_domains) - mal_in_my_domains - my_malware_domains 81 | 82 | return normal_domains, mal_in_my_domains, my_malware_domains 83 | -------------------------------------------------------------------------------- /src/markdown.py: -------------------------------------------------------------------------------- 1 | """ 2 | MARKDOWN TEMPLATE 3 | Added by Pielco11 4 | """ 5 | 6 | class MarkDown: 7 | def __init__(self, args): 8 | [Sections, Functions, Flags, Doms, IPs, Emails] = args 9 | self.max = self.findMax([Sections, Functions, Flags, Doms, IPs, Emails]) 10 | self.nSections = str(len(Sections)) 11 | self.nFunctions = str(len(Functions)) 12 | self.nFlags = str(len(Flags)) 13 | self.nDoms = str(len(Doms.get("normal_domains") + Doms.get("malware_domains"))) 14 | self.lDoms = [] 15 | self.nIPs = str(len(IPs)) 16 | self.nEmails = str(len(Emails)) 17 | self.table = "#### SSMA"+"\n" 18 | self.table += "| Sections | Functions | Flags | Doms | IPs | Emails |\n" 19 | self.table += "|:----------------------:|:-----------------------:|:-------------------:|:------------------:|:-----------------:|:--------------------:|\n" 20 | self.table += "| " + self.nSections + " | " + self.nFunctions + " | " + self.nFlags + " | " + self.nDoms + " | " + self.nIPs + " | " + self.nEmails + " |\n" 21 | self.getlDoms(self.lDoms, [Sections, Functions, Flags, Doms, IPs, Emails]) 22 | self.addRows([Sections, Functions, Flags, Doms, IPs, Emails]) 23 | 24 | def getlDoms(self, lDoms, args): 25 | [Sections, Functions, Flags, Doms, IPs, Emails] = args 26 | for d in range(len(Doms.get("malware_domains"))): 27 | self.lDoms.append(Doms.get("malware_domains")[d]) 28 | for d in range(len(Doms.get("normal_domains"))): 29 | self.lDoms.append(Doms.get("normal_domains")[d]) 30 | 31 | def write(self): 32 | return self.table 33 | 34 | def findMax(self, args): 35 | [Sections, Functions, Flags, Doms, IPs, Emails] = args 36 | max = 0 37 | for arg in [Sections, Functions, Flags, Doms, IPs, Emails]: 38 | if len(arg) > max: 39 | max = len(arg) 40 | return max 41 | 42 | def addRows(self, args): 43 | [Sections, Functions, Flags, Doms, IPs, Emails] = args 44 | for m in range(self.max): 45 | try: 46 | if m < len(Sections): 47 | for s, v in enumerate(Sections): 48 | if s == m: 49 | self.table += "| " + v + " | " 50 | else: 51 | self.table += "| | " 52 | except IndexError: 53 | self.table += "| | " 54 | try: 55 | self.table += Functions[m].split("^")[0][0:len(Functions[m].split("^")[0])-1] + " | " 56 | except IndexError: 57 | self.table += " | " 58 | try: 59 | self.table += Flags[m][0] + " | " 60 | except IndexError: 61 | self.table += " | " 62 | try: 63 | self.table += Doms[m] + " | " 64 | except KeyError: 65 | self.table += " | " 66 | try: 67 | self.table += IPs[m] + " | " 68 | except IndexError: 69 | self.table += " | " 70 | try: 71 | self.table += Emails[m] + " |" 72 | except IndexError: 73 | self.table += " |" 74 | self.table += "\n" 75 | -------------------------------------------------------------------------------- /ext/validation.py: -------------------------------------------------------------------------------- 1 | """Validate bitcoin/altcoin addresses 2 | 3 | Copied from: 4 | http://rosettacode.org/wiki/Bitcoin/address_validation#Python 5 | """ 6 | 7 | import string 8 | from hashlib import sha256 9 | 10 | digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' 11 | 12 | def _bytes_to_long(bytestring, byteorder): 13 | """Convert a bytestring to a long 14 | 15 | For use in python version prior to 3.2 16 | """ 17 | result = [] 18 | if byteorder == 'little': 19 | result = (v << i * 8 for (i, v) in enumerate(bytestring)) 20 | else: 21 | result = (v << i * 8 for (i, v) in enumerate(reversed(bytestring))) 22 | return sum(result) 23 | 24 | def _long_to_bytes(n, length, byteorder): 25 | """Convert a long to a bytestring 26 | 27 | For use in python version prior to 3.2 28 | Source: 29 | http://bugs.python.org/issue16580#msg177208 30 | """ 31 | if byteorder == 'little': 32 | indexes = range(length) 33 | else: 34 | indexes = reversed(range(length)) 35 | return bytearray((n >> i * 8) & 0xff for i in indexes) 36 | 37 | def decode_base58(bitcoin_address, length): 38 | """Decode a base58 encoded address 39 | 40 | This form of base58 decoding is bitcoind specific. Be careful outside of 41 | bitcoind context. 42 | """ 43 | n = 0 44 | for char in bitcoin_address: 45 | try: 46 | n = n * 58 + digits58.index(char) 47 | except: 48 | msg = u"Character not part of Bitcoin's base58: '%s'" 49 | raise ValueError(msg % (char,)) 50 | try: 51 | return n.to_bytes(length, 'big') 52 | except AttributeError: 53 | # Python version < 3.2 54 | return _long_to_bytes(n, length, 'big') 55 | 56 | def encode_base58(bytestring): 57 | """Encode a bytestring to a base58 encoded string 58 | """ 59 | # Count zero's 60 | zeros = 0 61 | for i in range(len(bytestring)): 62 | if bytestring[i] == 0: 63 | zeros += 1 64 | else: 65 | break 66 | try: 67 | n = int.from_bytes(bytestring, 'big') 68 | except AttributeError: 69 | # Python version < 3.2 70 | n = _bytes_to_long(bytestring, 'big') 71 | result = '' 72 | (n, rest) = divmod(n, 58) 73 | while n or rest: 74 | result += digits58[rest] 75 | (n, rest) = divmod(n, 58) 76 | return zeros * '1' + result[::-1] # reverse string 77 | 78 | def validate(bitcoin_address, magicbyte=0): 79 | """Check the integrity of a bitcoin address 80 | 81 | Returns False if the address is invalid. 82 | >>> validate('1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i') 83 | True 84 | >>> validate('') 85 | False 86 | """ 87 | if isinstance(magicbyte, int): 88 | magicbyte = (magicbyte,) 89 | clen = len(bitcoin_address) 90 | if clen < 27 or clen > 35: # XXX or 34? 91 | return False 92 | allowed_first = tuple(string.digits) 93 | try: 94 | bcbytes = decode_base58(bitcoin_address, 25) 95 | except ValueError: 96 | return False 97 | # Check magic byte (for other altcoins, fix by Frederico Reiven) 98 | for mb in magicbyte: 99 | if bcbytes.startswith(chr(int(mb))): 100 | break 101 | else: 102 | return False 103 | # Compare checksum 104 | checksum = sha256(sha256(bcbytes[:-4]).digest()).digest()[:4] 105 | if bcbytes[-4:] != checksum: 106 | return False 107 | # Encoded bytestring should be equal to the original address, 108 | # for example '14oLvT2' has a valid checksum, but is not a valid btc 109 | # address 110 | return bitcoin_address == encode_base58(bcbytes) 111 | -------------------------------------------------------------------------------- /src/check.py: -------------------------------------------------------------------------------- 1 | import os 2 | import yara 3 | 4 | 5 | def is_file_packed(filename): 6 | if not os.path.exists("rules_compiled/packers"): 7 | os.mkdir("rules_compiled/packers") 8 | for n in os.listdir("rules/packers"): 9 | rule = yara.compile("rules/packers/" + n) 10 | rule.save("rules_compiled/packers/" + n) 11 | rule = yara.load("rules_compiled/packers/" + n) 12 | m = rule.match(filename) 13 | if m: 14 | return m 15 | 16 | 17 | def is_malicious_document(filename): 18 | if not os.path.exists("rules_compiled/maldocs"): 19 | os.mkdir("rules_compiled/maldocs") 20 | for n in os.listdir("rules/maldocs"): 21 | rule = yara.compile("rules/maldocs/" + n) 22 | rule.save("rules_compiled/maldocs/" + n) 23 | rule = yara.load("rules_compiled/maldocs/" + n) 24 | m = rule.match(filename) 25 | if m: 26 | return m 27 | 28 | 29 | def is_antidb_antivm(filename): 30 | if not os.path.exists("rules_compiled/antidebug_antivm"): 31 | os.mkdir("rules_compiled/antidebug_antivm") 32 | for n in os.listdir("rules/antidebug_antivm"): 33 | rule = yara.compile("rules/antidebug_antivm/" + n) 34 | rule.save("rules_compiled/antidebug_antivm/" + n) 35 | rule = yara.load("rules_compiled/antidebug_antivm/" + n) 36 | m = rule.match(filename) 37 | if m: 38 | return m 39 | 40 | 41 | def check_crypto(filename): 42 | if not os.path.exists("rules_compiled/crypto"): 43 | os.mkdir("rules_compiled/crypto") 44 | for n in os.listdir("rules/crypto"): 45 | rule = yara.compile("rules/crypto/" + n) 46 | rule.save("rules_compiled/crypto/" + n) 47 | rule = yara.load("rules_compiled/crypto/" + n) 48 | m = rule.match(filename) 49 | if m: 50 | return m 51 | 52 | 53 | def is_malware(filename): 54 | if not os.path.exists("rules_compiled/malware"): 55 | os.mkdir("rules_compiled/malware") 56 | for n in os.listdir("rules/malware/"): 57 | if not os.path.isdir("./" + n): 58 | try: 59 | rule = yara.compile("rules/malware/" + n) 60 | rule.save("rules_compiled/malware/" + n) 61 | rule = yara.load("rules_compiled/malware/" + n) 62 | m = rule.match(filename) 63 | if m: 64 | return m 65 | except: 66 | pass # internal fatal error or warning 67 | else: 68 | pass 69 | 70 | 71 | # Added by Yang 72 | def is_your_target(filename, yara_file): 73 | if not os.path.exists("rules_compiled/your_target"): 74 | os.mkdir("rules_compiled/your_target") 75 | if os.path.isdir(yara_file): 76 | for n in os.listdir(yara_file): 77 | if not os.path.isdir("./" + n): 78 | try: 79 | rule = yara.compile(yara_file + "/" + n) 80 | rule.save("rules_compiled/your_target/" + n) 81 | rule = yara.load("rules_compiled/malware/" + n) 82 | m = rule.match(filename) 83 | if m: 84 | return m 85 | except: 86 | pass 87 | else: 88 | pass 89 | elif os.path.isfile(yara_file): 90 | try: 91 | rule = yara.compile(yara_file) 92 | rule.save("rules_compiled/your_target/" + yara_file) 93 | rule = yara.load("rules_compiled/malware/" + yara_file) 94 | m = rule.match(filename) 95 | if m: 96 | return m 97 | except: 98 | pass 99 | else: 100 | return "[x] Wrong type of input!" 101 | -------------------------------------------------------------------------------- /src/report.py: -------------------------------------------------------------------------------- 1 | """ 2 | Generate a malware analysis report in json format. 3 | Added by Yang 4 | """ 5 | 6 | import os 7 | import json 8 | from src.check_strings import ascii_strings, unicode_strings 9 | 10 | 11 | class pe_report: 12 | def __init__(self, pe, report, strings): 13 | self.filename = pe.filename 14 | self.file_info = pe.file_info(report, True) 15 | self._tsl = pe.checkTSL() 16 | self.check_imports = pe.check_imports() 17 | self.check_date = pe.check_date(True) 18 | self.sections_analysis = pe.sections_analysis(report) 19 | self.check_file_header = pe.check_file_header(report) 20 | self.ascii_strings = ascii_strings(self.filename, strings) 21 | self.unicode_strings = unicode_strings(self.filename, strings) 22 | 23 | def domains(self, domains): 24 | self.domains = domains 25 | 26 | def yara(self, yara): 27 | self.yara = yara 28 | 29 | def write(self): 30 | obj = { 31 | "filename": os.path.basename(self.filename), 32 | "file_info": self.file_info, 33 | "TSL": self._tsl, 34 | "sections": self.sections_analysis, 35 | "file_header": self.check_file_header, 36 | "date": self.check_date, 37 | "imports": self.check_imports, 38 | "yara_results": self.yara, 39 | "malware_domains": self.domains, 40 | "ascii_strings": self.ascii_strings, 41 | "unicode_strings": self.unicode_strings 42 | } 43 | 44 | with open("analysis_report/" + os.path.basename(self.filename) + ".json", "w") as f: 45 | json.dump(obj, f, indent=4) 46 | 47 | def dump(self): 48 | obj = { 49 | "filename": os.path.basename(self.filename), 50 | "file_info": self.file_info, 51 | "TSL": self._tsl, 52 | "sections": self.sections_analysis, 53 | "file_header": self.check_file_header, 54 | "date": self.check_date, 55 | "imports": self.check_imports, 56 | "yara_results": self.yara, 57 | "malware_domains": self.domains, 58 | "ascii_strings": self.ascii_strings, 59 | "unicode_strings": self.unicode_strings 60 | } 61 | return json.dumps(obj, indent=4, sort_keys=False) 62 | 63 | def malice_dump(self, md): 64 | obj = { 65 | "plugins": { 66 | "av": { 67 | "ssma": { 68 | "engine": "1.0", 69 | "infected": True, # setting this as default 70 | "markdown": md, 71 | "result": "scanned", 72 | "updated": "20171104" 73 | } 74 | } 75 | } 76 | } 77 | return json.dumps(obj, indent=4, sort_keys=False) 78 | 79 | class elf_report: 80 | def __init__(self, elf, report, strings): 81 | self.filename = elf.filename 82 | self.file_info = elf.file_info(report) 83 | self.checksec = elf.checksec() 84 | self.dependencies = elf.dependencies().read().decode('utf-8') 85 | self.elf_header = elf.elf_header().read().decode('utf-8') 86 | self.program_header = elf.program_header().read().decode('utf-8') 87 | self.section_header = elf.section_header().read().decode('utf-8') 88 | self.symbols = elf.symbols().read().decode('utf-8') 89 | self.ascii_strings = ascii_strings(self.filename, strings) 90 | self.unicode_strings = unicode_strings(self.filename, strings) 91 | 92 | def domains(self, domains): 93 | self.domains = domains 94 | 95 | def yara(self, yara): 96 | self.yara = yara 97 | 98 | def write(self): 99 | obj = { 100 | "filename": os.path.basename(self.filename), 101 | "file_info": self.file_info, 102 | "checksec": self.checksec, 103 | "dependencies": self.dependencies, 104 | "elf_header": self.elf_header, 105 | "program_header": self.program_header, 106 | "section_header": self.section_header, 107 | "symbols": self.symbols, 108 | "yara_results": self.yara, 109 | "malware_domains": self.domains, 110 | "ascii_strings": self.ascii_strings, 111 | "unicode_strings": self.unicode_strings 112 | } 113 | 114 | with open("analysis_report/" + os.path.basename(self.filename) + ".json", "w") as f: 115 | json.dump(obj, f, indent=4) 116 | 117 | def dump(self): 118 | obj = { 119 | "filename": os.path.basename(self.filename), 120 | "file_info": self.file_info, 121 | "checksec": self.checksec, 122 | "dependencies": self.dependencies, 123 | "elf_header": self.elf_header, 124 | "program_header": self.program_header, 125 | "section_header": self.section_header, 126 | "symbols": self.symbols, 127 | "yara_results": self.yara, 128 | "malware_domains": self.domains, 129 | "ascii_strings": self.ascii_strings, 130 | "unicode_strings": self.unicode_strings 131 | } 132 | 133 | return json.dumps(obj, indent=4, sort_keys=False) 134 | 135 | def malice_dump(self, md): 136 | obj = { 137 | "plugins": { 138 | "av": { 139 | "ssma": { 140 | "engine": "1.0", 141 | "infected": True, # setting this as default 142 | "markdown": md, 143 | "result": "scanned", 144 | "updated": "20171104" 145 | } 146 | } 147 | } 148 | } 149 | return json.dumps(obj, indent=4, sort_keys=False) 150 | 151 | class others_report: 152 | def __init__(self, other, strings): 153 | self.filename = os.path.basename(other[0]) 154 | self.file_info = other 155 | self.ascii_strings = ascii_strings(self.filename, strings) 156 | self.unicode_strings = unicode_strings(self.filename, strings) 157 | 158 | def domains(self, domains): 159 | self.domains = domains 160 | 161 | def yara(self, yara): 162 | self.yara = yara 163 | 164 | def write(self): 165 | obj = { 166 | "filename": self.filename, 167 | "file_info": self.file_info, 168 | "yara_results": self.yara, 169 | "malware_domains": self.domains, 170 | "ascii_strings": self.ascii_strings, 171 | "unicode_strings": self.unicode_strings 172 | } 173 | 174 | with open("analysis_report/" + os.path.basename(self.filename) + ".json", "w") as f: 175 | json.dump(obj, f, indent=4) 176 | 177 | def dump(self): 178 | obj = { 179 | "filename": self.filename, 180 | "file_info": self.file_info, 181 | "yara_results": self.yara, 182 | "malware_domains": self.domains, 183 | "ascii_strings": self.ascii_strings, 184 | "unicode_strings": self.unicode_strings 185 | } 186 | 187 | return json.dumps(obj, indent=4, sort_keys=False) 188 | 189 | def malice_dump(self, md): 190 | obj = { 191 | "plugins": { 192 | "av": { 193 | "ssma": { 194 | "engine": "1.0", 195 | "infected": True, # setting this as default 196 | "markdown": md, 197 | "result": "scanned", 198 | "updated": "20171104" 199 | } 200 | } 201 | } 202 | } 203 | return json.dumps(obj, indent=4, sort_keys=False) 204 | -------------------------------------------------------------------------------- /ext/validate_email.py: -------------------------------------------------------------------------------- 1 | # RFC 2822 - style email validation for Python 2 | # (c) 2012 Syrus Akbary 3 | # Extended from (c) 2011 Noel Bush 4 | # for support of mx and user check 5 | # This code is made available to you under the GNU LGPL v3. 6 | # 7 | # This module provides a single method, valid_email_address(), 8 | # which returns True or False to indicate whether a given address 9 | # is valid according to the 'addr-spec' part of the specification 10 | # given in RFC 2822. Ideally, we would like to find this 11 | # in some other library, already thoroughly tested and well- 12 | # maintained. The standard Python library email.utils 13 | # contains a parse_addr() function, but it is not sufficient 14 | # to detect many malformed addresses. 15 | # 16 | # This implementation aims to be faithful to the RFC, with the 17 | # exception of a circular definition (see comments below), and 18 | # with the omission of the pattern components marked as "obsolete". 19 | 20 | import re 21 | import smtplib 22 | import logging 23 | import socket 24 | 25 | try: 26 | raw_input 27 | except NameError: 28 | def raw_input(prompt=''): 29 | return input(prompt) 30 | 31 | try: 32 | import DNS 33 | ServerError = DNS.ServerError 34 | DNS.DiscoverNameServers() 35 | except (ImportError, AttributeError): 36 | DNS = None 37 | 38 | class ServerError(Exception): 39 | pass 40 | 41 | # All we are really doing is comparing the input string to one 42 | # gigantic regular expression. But building that regexp, and 43 | # ensuring its correctness, is made much easier by assembling it 44 | # from the "tokens" defined by the RFC. Each of these tokens is 45 | # tested in the accompanying unit test file. 46 | # 47 | # The section of RFC 2822 from which each pattern component is 48 | # derived is given in an accompanying comment. 49 | # 50 | # (To make things simple, every string below is given as 'raw', 51 | # even when it's not strictly necessary. This way we don't forget 52 | # when it is necessary.) 53 | # 54 | WSP = r'[\s]' # see 2.2.2. Structured Header Field Bodies 55 | CRLF = r'(?:\r\n)' # see 2.2.3. Long Header Fields 56 | NO_WS_CTL = r'\x01-\x08\x0b\x0c\x0f-\x1f\x7f' # see 3.2.1. Primitive Tokens 57 | QUOTED_PAIR = r'(?:\\.)' # see 3.2.2. Quoted characters 58 | FWS = r'(?:(?:' + WSP + r'*' + CRLF + r')?' + \ 59 | WSP + r'+)' # see 3.2.3. Folding white space and comments 60 | CTEXT = r'[' + NO_WS_CTL + \ 61 | r'\x21-\x27\x2a-\x5b\x5d-\x7e]' # see 3.2.3 62 | CCONTENT = r'(?:' + CTEXT + r'|' + \ 63 | QUOTED_PAIR + r')' # see 3.2.3 (NB: The RFC includes COMMENT here 64 | # as well, but that would be circular.) 65 | COMMENT = r'\((?:' + FWS + r'?' + CCONTENT + \ 66 | r')*' + FWS + r'?\)' # see 3.2.3 67 | CFWS = r'(?:' + FWS + r'?' + COMMENT + ')*(?:' + \ 68 | FWS + '?' + COMMENT + '|' + FWS + ')' # see 3.2.3 69 | ATEXT = r'[\w!#$%&\'\*\+\-/=\?\^`\{\|\}~]' # see 3.2.4. Atom 70 | ATOM = CFWS + r'?' + ATEXT + r'+' + CFWS + r'?' # see 3.2.4 71 | DOT_ATOM_TEXT = ATEXT + r'+(?:\.' + ATEXT + r'+)*' # see 3.2.4 72 | DOT_ATOM = CFWS + r'?' + DOT_ATOM_TEXT + CFWS + r'?' # see 3.2.4 73 | QTEXT = r'[' + NO_WS_CTL + \ 74 | r'\x21\x23-\x5b\x5d-\x7e]' # see 3.2.5. Quoted strings 75 | QCONTENT = r'(?:' + QTEXT + r'|' + \ 76 | QUOTED_PAIR + r')' # see 3.2.5 77 | QUOTED_STRING = CFWS + r'?' + r'"(?:' + FWS + \ 78 | r'?' + QCONTENT + r')*' + FWS + \ 79 | r'?' + r'"' + CFWS + r'?' 80 | LOCAL_PART = r'(?:' + DOT_ATOM + r'|' + \ 81 | QUOTED_STRING + r')' # see 3.4.1. Addr-spec specification 82 | DTEXT = r'[' + NO_WS_CTL + r'\x21-\x5a\x5e-\x7e]' # see 3.4.1 83 | DCONTENT = r'(?:' + DTEXT + r'|' + \ 84 | QUOTED_PAIR + r')' # see 3.4.1 85 | DOMAIN_LITERAL = CFWS + r'?' + r'\[' + \ 86 | r'(?:' + FWS + r'?' + DCONTENT + \ 87 | r')*' + FWS + r'?\]' + CFWS + r'?' # see 3.4.1 88 | DOMAIN = r'(?:' + DOT_ATOM + r'|' + \ 89 | DOMAIN_LITERAL + r')' # see 3.4.1 90 | ADDR_SPEC = LOCAL_PART + r'@' + DOMAIN # see 3.4.1 91 | 92 | # A valid address will match exactly the 3.4.1 addr-spec. 93 | VALID_ADDRESS_REGEXP = '^' + ADDR_SPEC + '$' 94 | 95 | MX_DNS_CACHE = {} 96 | MX_CHECK_CACHE = {} 97 | 98 | 99 | def get_mx_ip(hostname): 100 | if hostname not in MX_DNS_CACHE: 101 | try: 102 | MX_DNS_CACHE[hostname] = DNS.mxlookup(hostname) 103 | except ServerError as e: 104 | if e.rcode == 3 or e.rcode == 2: # NXDOMAIN (Non-Existent Domain) or SERVFAIL 105 | MX_DNS_CACHE[hostname] = None 106 | else: 107 | raise 108 | 109 | return MX_DNS_CACHE[hostname] 110 | 111 | 112 | def validate_email(email, check_mx=False, verify=False, debug=False,\ 113 | sending_email='', smtp_timeout=10): 114 | """Indicate whether the given string is a valid email address 115 | according to the 'addr-spec' portion of RFC 2822 (see section 116 | 3.4.1). Parts of the spec that are marked obsolete are *not* 117 | included in this test, and certain arcane constructions that 118 | depend on circular definitions in the spec may not pass, but in 119 | general this should correctly identify any email address likely 120 | to be in use as of 2011.""" 121 | if debug: 122 | logger = logging.getLogger('validate_email') 123 | logger.setLevel(logging.DEBUG) 124 | else: 125 | logger = None 126 | 127 | try: 128 | assert re.match(VALID_ADDRESS_REGEXP, email) is not None 129 | check_mx |= verify 130 | if check_mx: 131 | if not DNS: 132 | raise Exception('For check the mx records or check if the email exists you must ' 133 | 'have installed pyDNS python package') 134 | hostname = email[email.find('@') + 1:] 135 | mx_hosts = get_mx_ip(hostname) 136 | if mx_hosts is None: 137 | return False 138 | for mx in mx_hosts: 139 | try: 140 | if not verify and mx[1] in MX_CHECK_CACHE: 141 | return MX_CHECK_CACHE[mx[1]] 142 | smtp = smtplib.SMTP(timeout=smtp_timeout) 143 | smtp.connect(mx[1]) 144 | MX_CHECK_CACHE[mx[1]] = True 145 | if not verify: 146 | try: 147 | smtp.quit() 148 | except smtplib.SMTPServerDisconnected: 149 | pass 150 | return True 151 | status, _ = smtp.helo() 152 | if status != 250: 153 | smtp.quit() 154 | if debug: 155 | logger.debug(u'%s answer: %s - %s', mx[1], status, _) 156 | continue 157 | smtp.mail(sending_email) 158 | status, _ = smtp.rcpt(email) 159 | if status == 250: 160 | smtp.quit() 161 | return True 162 | if debug: 163 | logger.debug(u'%s answer: %s - %s', mx[1], status, _) 164 | smtp.quit() 165 | except smtplib.SMTPServerDisconnected: # Server not permits verify user 166 | if debug: 167 | logger.debug(u'%s disconected.', mx[1]) 168 | except smtplib.SMTPConnectError: 169 | if debug: 170 | logger.debug(u'Unable to connect to %s.', mx[1]) 171 | return None 172 | except AssertionError: 173 | return False 174 | except (ServerError, socket.error) as e: 175 | if debug: 176 | logger.debug('ServerError or socket.error exception raised (%s).', e) 177 | return None 178 | return True 179 | 180 | if __name__ == "__main__": 181 | import time 182 | while True: 183 | email = raw_input('Enter email for validation: ') 184 | 185 | mx = raw_input('Validate MX record? [yN] ') 186 | if mx.strip().lower() == 'y': 187 | mx = True 188 | else: 189 | mx = False 190 | 191 | validate = raw_input('Try to contact server for address validation? [yN] ') 192 | if validate.strip().lower() == 'y': 193 | validate = True 194 | else: 195 | validate = False 196 | 197 | logging.basicConfig() 198 | 199 | result = validate_email(email, mx, validate, debug=True, smtp_timeout=1) 200 | if result: 201 | print("Valid!") 202 | elif result is None: 203 | print("I'm not sure.") 204 | else: 205 | print("Invalid!") 206 | 207 | time.sleep(1) 208 | 209 | 210 | # import sys 211 | 212 | # sys.modules[__name__],sys.modules['validate_email_module'] = validate_email,sys.modules[__name__] 213 | # from validate_email_module import * 214 | -------------------------------------------------------------------------------- /ssma.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | @author: Lasha Khasaia 5 | @license: GNU General Public License 3.0 6 | @contact: @_qaz_qaz 7 | @Description: SSMA - Simple Static Malware Analyzer 8 | """ 9 | 10 | import argparse, os, json 11 | import shutil, magic, uuid 12 | import hashlib, contextlib 13 | from elasticsearch import Elasticsearch 14 | 15 | from src import colors 16 | from src.blacklisted_domain_ip import ransomware_and_malware_domain_check 17 | from src.check import is_malware, is_file_packed, check_crypto, is_antidb_antivm, is_malicious_document, is_your_target 18 | from src.check_file import PEScanner, ELFScanner, file_info 19 | from src.check_updates import check_internet_connection, download_yara_rules_git 20 | from src.check_virustotal import virustotal 21 | from src.file_strings import get_strings 22 | from src.mass_analysis import start_scan 23 | from src.report import pe_report, elf_report, others_report 24 | from src import markdown 25 | 26 | ####### NEED THIS FOR ELASTICSEARCH 27 | @contextlib.contextmanager 28 | def nostderr(): 29 | savestderr = sys.stderr 30 | sys.stderr = os.devnull() 31 | try: 32 | yield 33 | finally: 34 | sys.stderr = savestderr 35 | ##################################### 36 | 37 | 38 | if __name__ == '__main__': 39 | parser = argparse.ArgumentParser(description="Simple Static Malware Analyzer") 40 | parser.add_argument("filename", help="/path/to/file") 41 | parser.add_argument("-k", "--api-key", help="Virustotal API key") 42 | parser.add_argument("-d", "--document", help="check document/MS Office file", action="store_true") 43 | parser.add_argument("-u", "--update", help="Update Yara-Rules (yes/no) usage ./ssma.py sample.exe -u yes") 44 | parser.add_argument("-y", "--yara", help="Scan file with your Yara-Rule") 45 | parser.add_argument("-D", "--directory", help="Mass analysis from a dir ./ssma.py (/path/.) period at end of path is necessary") 46 | parser.add_argument("-r", "--report", help="Generate json format report (yes/no/elasticsearch) usage ./ssma.py sample.exe -r yes") 47 | parser.add_argument("-t", "--table", help="Markdown output", action="store_true") 48 | parser.add_argument("-s", "--strings", help="Extract strings", action="store_true") 49 | 50 | args = parser.parse_args() 51 | 52 | if args.report == "elasticsearch": 53 | args.report = "output" 54 | else: 55 | pass 56 | 57 | # Added by Yang 58 | if args.directory: 59 | start_scan(args) 60 | exit() 61 | elif args.directory and args.filename: 62 | print(colors.BOLD + colors.RED + "option error, please select a file or directory, run ssma.py -h") 63 | exit() 64 | 65 | if args.report == "output": 66 | pass 67 | else: 68 | print(colors.CYAN + """ 69 | ███████╗███████╗███╗ ███╗ █████╗ 70 | ██╔════╝██╔════╝████╗ ████║██╔══██╗ Simple 71 | ███████╗███████╗██╔████╔██║███████║ Static 72 | ╚════██║╚════██║██║╚██╔╝██║██╔══██║ Malware 73 | ███████║███████║██║ ╚═╝ ██║██║ ██║ Analyzer 74 | ╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ 75 | """ + colors.RESET) 76 | if args.update == "yes": 77 | if os.path.exists("rules"): 78 | shutil.rmtree("rules") 79 | if os.path.exists("rules_compiled"): 80 | shutil.rmtree("rules_compiled") 81 | os.mkdir("rules_compiled") 82 | print(colors.BOLD + colors.CYAN + "[-] Updating Yara-Rules..." + colors.RESET) 83 | download_yara_rules_git() 84 | print(colors.BOLD + colors.GREEN + "[+] Updated for Yara-Rules!" + colors.RESET) 85 | print() 86 | if not args.filename: 87 | exit() 88 | else: 89 | pass 90 | else: 91 | pass 92 | try: 93 | os.path.realpath(args.filename) 94 | except: 95 | try: 96 | os.path.realpath(args.directory) 97 | except: 98 | print(colors.BOLD + colors.RED + "No option selected, run ssma.py -h" + colors.RESET) 99 | exit() 100 | 101 | internet_connection = check_internet_connection() 102 | 103 | py_file_location = os.path.dirname(__file__) 104 | args.filename = os.path.realpath(args.filename) 105 | if py_file_location: 106 | os.chdir(py_file_location) 107 | filetype = magic.from_file(args.filename, mime=True) 108 | if filetype == 'application/x-dosexec': 109 | pe = PEScanner(filename=args.filename) 110 | if args.report == "output": 111 | pass 112 | else: 113 | print(colors.BOLD + colors.BLUE + "File Details: " + colors.RESET) 114 | for n in pe.file_info(args.report, False): 115 | if args.report == "output": 116 | pass 117 | else: 118 | print('\t', n) 119 | if args.report == "output": 120 | pass 121 | else: 122 | print() 123 | print("================================================================================") 124 | 125 | 126 | if args.report: 127 | if not os.path.exists("analysis_report"): 128 | os.mkdir("analysis_report") 129 | file_report = pe_report(pe, args.report, args.strings) 130 | else: 131 | sections = pe.sections_analysis(args.report) 132 | print("================================================================================") 133 | pe.overlay() 134 | 135 | if args.report == "output": 136 | pass 137 | else: 138 | print("================================================================================") 139 | 140 | 141 | _tls = pe.checkTSL() 142 | if _tls is not None: 143 | if args.report == "output": 144 | pass 145 | else: 146 | print(colors.RED + "The executable contains a .tls section.\n" + colors.RESET + "A TLS callback can be used to execute code before the entry point \ 147 | and therefore execute secretly in a debugger.") 148 | print("================================================================================") 149 | 150 | 151 | check_file_header = pe.check_file_header(args.report) 152 | continue_message = False 153 | if check_file_header["debug"]: 154 | continue_message = True 155 | print( # MAYBE A DUPLICATE WITH "check_file.py" #323 ? 156 | colors.LIGHT_RED + "File contains some debug information, in majority of regular PE files, should not " 157 | "contain debug information" + colors.RESET + "\n") 158 | 159 | if any(tr[1] for tr in check_file_header["flags"]): 160 | continue_message = True 161 | if args.report == "output": 162 | pass 163 | else: 164 | print(colors.LIGHT_RED + "Suspicious flags in the characteristics of the PE file: " + colors.RESET) 165 | for n in check_file_header["flags"]: 166 | if n[1]: 167 | print(colors.RED + n[0] + colors.RESET + " flag is set - {}".format(n[2])) 168 | print() 169 | if args.report == "output": 170 | pass 171 | else: 172 | if continue_message: 173 | print("================================================================================") 174 | 175 | check_date_result = pe.check_date(False) 176 | if check_date_result: 177 | if args.report == "output": 178 | pass 179 | else: 180 | print(check_date_result) 181 | print() 182 | print("================================================================================") 183 | 184 | 185 | check_imports_result = pe.check_imports() 186 | if args.report == "output": 187 | pass 188 | else: 189 | if check_imports_result: 190 | print( 191 | colors.BOLD + colors.BLUE + "This file contains a list of Windows functions commonly used by malware.\nFor more information use the Microsoft documentation.\n" + colors.RESET) 192 | 193 | for n in check_imports_result: 194 | n = n.split("^") 195 | print('\t' + colors.LIGHT_RED + n[0] + colors.RESET + " - " + n[1]) 196 | print() 197 | print("================================================================================") 198 | 199 | 200 | # ELF file -> Linux malware 201 | # Added by Yang 202 | elif filetype == 'application/x-executable': 203 | elf = ELFScanner(filename=args.filename) 204 | 205 | if args.report == "output": 206 | pass 207 | else: 208 | print(colors.BOLD + colors.BLUE + "File Details: " + colors.RESET) 209 | for n in elf.file_info(args.report): 210 | if args.report == "output": 211 | print('\t', n) 212 | else: 213 | print('\t', n) 214 | if args.report == "output": 215 | pass 216 | else: 217 | print() 218 | print("================================================================================") 219 | 220 | 221 | depends = elf.dependencies() 222 | if depends: 223 | if args.report == "output": 224 | pass 225 | else: 226 | print(colors.BOLD + colors.BLUE + "Dependencies: " + colors.RESET) 227 | for line in depends: 228 | line = line.decode('utf-8', 'ignore').replace("\n", "") 229 | print(line) 230 | print() 231 | print("================================================================================") 232 | 233 | 234 | prog_header = elf.program_header() 235 | if prog_header: 236 | if args.report == "output": 237 | pass 238 | else: 239 | print(colors.BOLD + colors.BLUE + "Program Header Information: " + colors.RESET) 240 | for line in prog_header: 241 | line = line.decode('utf-8', 'ignore').replace("\n", "") 242 | print(line) 243 | print() 244 | print("================================================================================") 245 | 246 | 247 | sect_header = elf.section_header() 248 | if sect_header: 249 | if args.report == "output": 250 | pass 251 | else: 252 | print(colors.BOLD + colors.BLUE + "Section Header Information: " + colors.RESET) 253 | for line in sect_header: 254 | line = line.decode('utf-8', 'ignore').replace("\n", "") 255 | print(line) 256 | print() 257 | print("================================================================================") 258 | 259 | 260 | syms = elf.symbols() 261 | if syms: 262 | if args.report == "output": 263 | pass 264 | else: 265 | print(colors.BOLD + colors.BLUE + "Symbol Information: " + colors.RESET) 266 | for line in syms: 267 | line = line.decode('utf-8', 'ignore').replace("\n", "") 268 | print(line) 269 | print() 270 | print("================================================================================") 271 | 272 | 273 | checksec = elf.checksec() 274 | if checksec: 275 | if args.report == "output": 276 | pass 277 | else: 278 | print(colors.BOLD + colors.BLUE + "CheckSec Information: " + colors.RESET) 279 | for key, value in checksec.items(): 280 | print(key + ": " + str(value)) 281 | print() 282 | print("================================================================================") 283 | 284 | 285 | if args.report: 286 | if not os.path.exists("analysis_report"): 287 | os.mkdir("analysis_report") 288 | file_report = (elf, args.report, args.strings) 289 | 290 | else: 291 | print(colors.BOLD + colors.BLUE + "File Details: " + colors.RESET) 292 | for n in file_info(args.filename): 293 | print('\t', n) 294 | print() 295 | print("================================================================================") 296 | 297 | 298 | if args.report: 299 | if not os.path.exists("analysis_report"): 300 | os.mkdir("analysis_report") 301 | file_report = others_report(file_info(args.filename), args.strings) 302 | 303 | if args.api_key and internet_connection: 304 | virus_check = virustotal(args.filename, args.api_key) 305 | if virus_check[0] == "scan_result": 306 | print(colors.BOLD + colors.BLUE + "Virustotal:" + colors.RESET) 307 | for n in virus_check[1]: 308 | n = n.split("^") 309 | print('\t' + colors.CYAN + n[0] + colors.RESET + "-" + colors.LIGHT_RED + n[1] + colors.RESET) 310 | print() 311 | print("================================================================================") 312 | 313 | 314 | elif virus_check[0] == "permalink": 315 | if virus_check[1]: 316 | print(colors.LIGHT_BLUE + "Your file is being analysed." + colors.RESET) 317 | print(colors.BOLD + "VirusTotal link: " + colors.RESET, virus_check[1][0]) 318 | print() 319 | print("================================================================================") 320 | if input("Continue? [Y/n] ") is 'n': 321 | exit() 322 | print() 323 | elif args.api_key and not internet_connection: 324 | print(colors.RED + "No internet connection" + colors.RESET) 325 | print("================================================================================") 326 | 327 | 328 | strings = get_strings(filename=args.filename).get_result() 329 | if strings[0]: 330 | if internet_connection: 331 | mal_domains = ransomware_and_malware_domain_check(list(strings[0])) 332 | if args.report == "output": 333 | pass 334 | else: 335 | print(colors.BOLD + colors.BLUE + "Possible domains in strings of the file: " + colors.RESET) 336 | mal_domains = ransomware_and_malware_domain_check(list(strings[0])) 337 | for n in mal_domains[0]: 338 | print('\t', n) 339 | print() 340 | if mal_domains[1]: 341 | print("\t" + colors.RED + "Abuse.ch's Ransomware Domain Blocklist: " + colors.RESET) 342 | for n in mal_domains[1]: 343 | print('\t', n) 344 | print() 345 | if mal_domains[2]: 346 | print( 347 | "\t" + colors.RED + "A list of domains that are known to be used to propagate malware by http://www.malwaredomains.com/" + colors.RESET) 348 | for n in mal_domains[2]: 349 | print('\t', n) 350 | print() 351 | print() 352 | print("================================================================================") 353 | 354 | 355 | 356 | if strings[1]: 357 | if args.report == "output": 358 | pass 359 | else: 360 | print(colors.BOLD + colors.BLUE + "Possible IP addresses in strings of the file: " + colors.RESET) 361 | for n in strings[1]: 362 | print('\t', n) 363 | print() 364 | print("================================================================================") 365 | 366 | 367 | if strings[2]: 368 | if args.report == "output": 369 | pass 370 | else: 371 | print(colors.BOLD + colors.BLUE + "Possible E-Mail addresses in strings of the file:" + colors.RESET) 372 | for n in strings[2]: 373 | print('\t', n) 374 | print() 375 | print("================================================================================") 376 | 377 | 378 | if args.report: 379 | if internet_connection: 380 | mal_domains = ransomware_and_malware_domain_check(list(strings[0])) 381 | domains = { 382 | "normal_domains": list(mal_domains[0]), 383 | "malware_domains": list(mal_domains[1]) + list(mal_domains[2]) 384 | } 385 | else: 386 | domains = list(strings[0]) 387 | strings_result = { 388 | "Domains": domains, 389 | "IP-addresses": strings[1], 390 | "Email": strings[2] 391 | } 392 | file_report.domains(strings_result) 393 | 394 | if filetype == 'application/x-dosexec' or filetype == 'application/x-executable' or args.document: 395 | if args.report == "output": 396 | pass 397 | else: 398 | print( 399 | colors.BOLD + colors.BLUE + "Scan file using Yara-rules.\nWith Yara rules you can create a \"description\" of malware families to detect new samples.\n" + colors.BOLD + colors.CYAN + "\tFor more information: https://virustotal.github.io/yara/\n" + colors.RESET) 400 | if not os.path.exists("rules"): 401 | os.mkdir("rules") 402 | if not os.path.exists("rules_compiled"): 403 | os.mkdir("rules_compiled") 404 | if not os.listdir("rules"): 405 | if args.report == "output": 406 | pass 407 | else: 408 | print(colors.BOLD + colors.CYAN + "Downloading Yara-rules... \n" + colors.RESET) 409 | print() 410 | download_yara_rules_git() 411 | if filetype == 'application/x-dosexec': 412 | malicious_software = is_malware(filename=args.filename) 413 | if malicious_software: 414 | if args.report == "output": 415 | pass 416 | else: 417 | print( 418 | colors.BOLD + colors.BLUE + "These Yara rules specialised on the identification of well-known malware.\nResult: " + colors.RESET) 419 | for n in malicious_software: 420 | try: 421 | print("\t {} - {}".format(n, n.meta['description'])) 422 | except: 423 | print('\t', n) 424 | print() 425 | print("================================================================================") 426 | 427 | 428 | packed = is_file_packed(filename=args.filename) 429 | if packed: 430 | if args.report == "output": 431 | pass 432 | else: 433 | print( 434 | colors.BOLD + colors.BLUE + "These Yara Rules aimed to detect well-known software packers, that can be used by malware to hide itself.\nResult: " + colors.RESET) 435 | for n in packed: 436 | try: 437 | print("\t {} - {}".format(n, n.meta['description'])) 438 | except: 439 | print('\t', n) 440 | print() 441 | print("================================================================================") 442 | 443 | 444 | crypto = check_crypto(filename=args.filename) 445 | if crypto: 446 | if args.report == "output": 447 | pass 448 | else: 449 | print( 450 | colors.BOLD + colors.BLUE + "These Yara rules aimed to detect the existence of cryptographic algorithms." + colors.RESET) 451 | print(colors.BLUE + "Detected cryptographic algorithms: " + colors.RESET) 452 | for n in crypto: 453 | try: 454 | print("\t {} - {}".format(n, n.meta['description'])) 455 | except: 456 | print('\t', n) 457 | print() 458 | print("================================================================================") 459 | 460 | 461 | anti_vm = is_antidb_antivm(filename=args.filename) 462 | if anti_vm: 463 | if args.report == "output": 464 | pass 465 | else: 466 | print( 467 | colors.BOLD + colors.BLUE + "These Yara Rules aimed to detect anti-debug and anti-virtualization techniques used by malware to evade automated analysis.\nResult: " + colors.RESET) 468 | for n in anti_vm: 469 | try: 470 | print("\t {} - {}".format(n, n.meta['description'])) 471 | except: 472 | print('\t', n) 473 | print() 474 | print("================================================================================") 475 | 476 | 477 | your_target = {} 478 | if args.yara: 479 | yara = str(os.path.realpath(args.yara)) 480 | your_target = is_your_target(args.filename, yara) 481 | if your_target: 482 | if args.report == "output": 483 | pass 484 | else: 485 | print( 486 | colors.BOLD + colors.BLUE + "These Yara Rules are created by yourself and aimed to detecte something you need.\nResult: " + colors.RESET) 487 | for n in your_target: 488 | try: 489 | print("\t {} - {}".format(n, n.meta['description'])) 490 | except: 491 | print('\t', n) 492 | print() 493 | print("================================================================================") 494 | 495 | if args.report: 496 | malicious_software_result = {} 497 | packed_result = {} 498 | crypto_result = {} 499 | anti_vm_result = {} 500 | your_target_result = {} 501 | if malicious_software: 502 | for n in malicious_software: 503 | try: 504 | malicious_software_result[str(n)] = n.meta['description'] 505 | except: 506 | malicious_software_result[str(n)] = None 507 | if packed: 508 | for n in packed: 509 | try: 510 | packed_result[str(n)] = n.meta['description'] 511 | except: 512 | packed_result[str(n)] = None 513 | if crypto: 514 | for n in crypto: 515 | try: 516 | crypto_result[str(n)] = n.meta['description'] 517 | except: 518 | crypto_result[str(n)] = None 519 | if anti_vm: 520 | for n in anti_vm: 521 | try: 522 | anti_vm_result[str(n)] = n.meta['description'] 523 | except: 524 | anti_vm_result[str(n)] = None 525 | if your_target: 526 | for n in your_target: 527 | try: 528 | your_target_result[str(n)] = n.meta['description'] 529 | except: 530 | your_target_result[str(n)] = None 531 | yara_result = { 532 | "malicious_software": malicious_software_result, 533 | "packed": packed_result, 534 | "crypto": crypto_result, 535 | "anti_vm": anti_vm_result, 536 | "your_target": your_target_result 537 | } 538 | file_report.yara(yara_result) 539 | file_report.write() 540 | 541 | if filetype == 'application/x-executable': 542 | your_target = {} 543 | if args.yara: 544 | yara = str(os.path.realpath(args.yara)) 545 | your_target = is_your_target(args.filename, yara) 546 | if your_target: 547 | if args.report == "output": 548 | pass 549 | else: 550 | print( 551 | colors.BOLD + colors.BLUE + "These Yara Rules are created by yourself and aimed to detecte something you need.\nResult: " + colors.RESET) 552 | for n in your_target: 553 | try: 554 | print("\t {} - {}".format(n, n.meta['description'])) 555 | except: 556 | print('\t', n) 557 | print() 558 | print("================================================================================") 559 | 560 | if args.report: 561 | your_target_result = {} 562 | if your_target: 563 | for n in your_target: 564 | try: 565 | your_target_result[str(n)] = n.meta['description'] 566 | except: 567 | your_target_result[str(n)] = None 568 | yara_result = { 569 | "your_target": your_target_result 570 | } 571 | file_report.yara(yara_result) 572 | file_report.write() 573 | 574 | if args.document: 575 | malicious_document = is_malicious_document(filename=args.filename) 576 | if args.report == "output": 577 | pass 578 | else: 579 | print( 580 | colors.BOLD + colors.BLUE + "These Yara Rules to be used with documents to find if they have been crafted to leverage malicious code.\nResult: " + colors.RESET) 581 | if malicious_document: 582 | for n in malicious_document: 583 | try: 584 | print("\t {} - {}".format(n, n.meta['description'])) 585 | except: 586 | print('\t', n) 587 | print("================================================================================") 588 | 589 | 590 | your_target = {} 591 | if args.yara: 592 | yara = str(os.path.realpath(args.yara)) 593 | your_target = is_your_target(args.filename, yara) 594 | if your_target: 595 | if args.report == "output": 596 | pass 597 | else: 598 | print( 599 | colors.BOLD + colors.BLUE + "These Yara Rules are created by yourself and aimed to detecte something you need.\nResult: " + colors.RESET) 600 | for n in your_target: 601 | try: 602 | print("\t {} - {}".format(n, n.meta['description'])) 603 | except: 604 | print('\t', n) 605 | print() 606 | print("================================================================================") 607 | 608 | if args.report: 609 | your_target_result = {} 610 | if your_target: 611 | for n in your_target: 612 | try: 613 | your_target_result[str(n)] = n.meta['description'] 614 | except: 615 | your_target_result[str(n)] = None 616 | 617 | malicious_document_result = {} 618 | if malicious_document: 619 | for n in malicious_document: 620 | try: 621 | malicious_document_result[str(n)] = n['description'] 622 | except: 623 | malicious_document_result[str(n)] = None 624 | yara_result = { 625 | "malicious_document": malicious_document_result, 626 | "your_target": your_target_result 627 | } 628 | file_report.yara(yara_result) 629 | file_report.write() 630 | 631 | else: 632 | print(colors.BOLD + "\tAnalysis Complete" + colors.RESET) 633 | print("================================================================================") 634 | exit() 635 | if args.report == "output": 636 | rDump = file_report.dump() 637 | with open(args.filename, "rb") as ff: 638 | data = ff.read() 639 | hashFile = hashlib.sha256(data).hexdigest() 640 | jd = json.loads(rDump) 641 | Sections = jd.get("sections").get("sections") 642 | Functions = jd.get("imports") 643 | Flags = jd.get("file_header").get("flags") 644 | Doms = jd.get("malware_domains").get("Domains") 645 | IPs = jd.get("malware_domains").get("IP-addresses") 646 | Emails = jd.get("malware_domains").get("Email") 647 | md = markdown.MarkDown([Sections, Functions, Flags, Doms, IPs, Emails]) 648 | mdOut = md.write() 649 | body = file_report.malice_dump(mdOut) 650 | if args.table: 651 | print(mdOut) 652 | try: 653 | with nostderr(): 654 | es = Elasticsearch(["elasticsearch", "127.0.0.1", os.environ.get("MALICE_ELASTICSEARCH")]) 655 | res = es.update(index="malice", doc_type='sample', id=os.environ.get('MALICE_SCANID',hashFile), body=body) 656 | except: 657 | pass 658 | else: 659 | print(rDump) 660 | try: 661 | with nostderr(): 662 | es = Elasticsearch(["elasticsearch", "127.0.0.1", os.environ.get("MALICE_ELASTICSEARCH")]) 663 | res = es.update(index="malice", doc_type='sample', id=os.environ.get('MALICE_SCANID',hashFile), body=body) 664 | except: 665 | pass 666 | else: 667 | print(colors.BLUE + "Ups... " + colors.CYAN + "That's all :)" + colors.RESET + "\n") 668 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /src/check_file.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import numbers 3 | import os 4 | import time 5 | import binascii 6 | import array 7 | import magic 8 | import math 9 | import pefile 10 | from subprocess import Popen, PIPE, STDOUT 11 | from elftools.elf.elffile import ELFFile 12 | 13 | ssdeep_r = True 14 | try: 15 | import ssdeep 16 | except ImportError: 17 | ssdeep_r = False 18 | pass 19 | 20 | from src import colors 21 | 22 | 23 | def old_div(a, b): 24 | """ 25 | Equivalent to ``a / b`` on Python 2 without ``from __future__ import 26 | division``. 27 | 28 | """ 29 | if isinstance(a, numbers.Integral) and isinstance(b, numbers.Integral): 30 | return a // b 31 | else: 32 | return a / b 33 | 34 | 35 | def data_entropy(data): 36 | """Calculate the entropy of a chunk of data.""" 37 | 38 | if len(data) == 0: 39 | return 0.0 40 | 41 | occurences = array.array('L', [0] * 256) 42 | 43 | for x in data: 44 | occurences[x if isinstance(x, int) else ord(x)] += 1 45 | 46 | entropy = 0 47 | for x in occurences: 48 | if x: 49 | p_x = old_div(float(x), len(data)) 50 | entropy -= p_x * math.log(p_x, 2) 51 | 52 | return entropy 53 | 54 | 55 | class PEScanner: 56 | def __init__(self, filename): 57 | self.filename = filename 58 | self.pe = pefile.PE(self.filename) 59 | with open(filename, 'rb') as pe_file: 60 | self.pe_entropy = data_entropy(pe_file.read()) 61 | self.alerts = { # Practical Malware Analysis (2012) - Sikorski M., Honig A. 62 | 'OpenProcess': "Opens a handle to another process running on the system. This handle can be used to read and write to the other process memory or to inject code into the other process.", 63 | 'VirtualAllocEx': "A memory-allocation routine that can allocate memory in a remote process. Malware sometimes uses VirtualAllocEx as part of process injection", 64 | 'WriteProcessMemory': "Used to write data to a remote process. Malware uses WriteProcessMemory as part of process injection.", 65 | 'CreateRemoteThread': "Used to start a thread in a remote process (one other than the calling process). Launchers and stealth malware use CreateRemoteThread to inject code into a different process.", 66 | 'ReadProcessMemory': "Used to read the memory of a remote process.", 67 | 'CreateProcess': "Creates and launches a new process. If malware creates a new process, you will need to analyze the new process as well.", 68 | 'WinExec': "Used to execute another program. If malware creates a new process, you will need to analyze the new process as well.", 69 | 'ShellExecute': "Used to execute another program. If malware creates a new process, you will need to analyze the new process as well.", 70 | 'HttpSendRequest': "Suggest that the PE file uses HTTP", 71 | 'InternetReadFile': "Reads data from a previously opened URL.", 72 | 'InternetWriteFile': "Writes data to a previously opened URL.", 73 | 'InternetConnect': "PE file uses to establish connection", 74 | 'CreateService': "Creates a service that can be started at boot time. Malware uses CreateService for persistence, stealth, or to load kernel drivers.", 75 | 'StartService': "Starting a service", 76 | 'accept': "Used to listen for incoming connections. This function indicates that the program will listen for incoming connections on a socket.", 77 | 'AdjustTokenPrivileges': "Used to enable or disable specific access privileges. Malware that performs process injection often calls this function to gain additional permissions.", 78 | 'VirtualProtectEx': "Changes the protection on a region of memory. Malware may use this function to change a read-only section of memory to an executable.", 79 | 'SetWindowsHookEx': "Sets a hook function to be called whenever a certain event is called. Commonly used with keyloggers and spyware, this function also provides an easy way to load a DLL into all GUI processes on the system. This function is sometimes added by the compiler.", 80 | 'SfcTerminateWatcherThread': "Used to disable Windows file protection and modify files that otherwise would be protected. SfcFileException can also be used in this capacity.", 81 | 'FtpPutFile': "A high-level function for uploading a file to a remote FTP server.", 82 | 'EnumProcesses': "Used to enumerate through running processes on the system. Malware often enumerates through processes to find a process to inject into.", 83 | 'connect': "Used to connect to a remote socket. Malware often uses low-level functionality to connect to a command-and-control server.", 84 | 'GetAdaptersInfo': "Used to obtain information about the network adapters on the system. Backdoors sometimes call GetAdaptersInfo as part of a survey to gather information about infected machines. In some cases, it’s used to gather MAC addresses to check for VMware as part of anti-virtual machine techniques.", 85 | 'GetAsyncKeyState': "Used to determine whether a particular key is being pressed. Malware sometimes uses this function to implement a keylogger.", 86 | 'GetKeyState': "Used by keyloggers to obtain the status of a particular key on the keyboard.", 87 | 'InternetOpen': "Initializes the high-level Internet access functions from WinINet, such as InternetOpenUrl and InternetReadFile . Searching for InternetOpen is a good way to find the start of Internet access functionality. One of the parameters to InternetOpen is the User-Agent, which can sometimes make a good network-based signature.", 88 | 'AttachThreadInput': "Attaches the input processing for one thread to another so that the second thread receives input events such as keyboard and mouse events. Keyloggers and other spyware use this function.", 89 | 'BitBlt': "Used to copy graphic data from one device to another. Spyware sometimes uses this function to capture screenshots. This function is often added by the compiler as part of library code.", 90 | 'CallNextHookEx': "Used within code that is hooking an event set by SetWindowsHookEx. CallNextHookEx calls the next hook in the chain. Analyze the function calling CallNextHookEx to determine the purpose of a hook set by SetWindowsHookEx.", 91 | 'CertOpenSystemStore': "Used to access the certificates stored on the local system.", 92 | 'CheckRemoteDebuggerPresent': "Checks to see if a specific process (including your own) is being debugged. This function is sometimes used as part of an anti-debugging technique.", 93 | 'CoCreateInstance': "Creates a COM object. COM objects provide a wide variety of functionality. The class identifier (CLSID) will tell you which file contains the code that implements the COM object. See Chapter 7 for an in-depth explanation of COM.", 94 | 'ConnectNamedPipe': "Used to create a server pipe for interprocess communication that will wait for a client pipe to connect. Backdoors and reverse shells sometimes use ConnectNamedPipe to simplify connectivity to a command-and-control server.", 95 | 'ControlService': "Used to start, stop, modify, or send a signal to a running service. If malware is using its own malicious service, you’ll need to analyze the code that implements the service in order to determine the purpose of the call.", 96 | 'CreateFile': "Creates a new file or opens an existing file.", 97 | 'CreateFileMapping': "Creates a handle to a file mapping that loads a file into memory and makes it accessible via memory addresses. Launchers, loaders, and injectors use this function to read and modify PE files.", 98 | 'CreateMutex': "Creates a mutual exclusion object that can be used by malware to ensure that only a single instance of the malware is running on a system at any given time. Malware often uses fixed names for mutexes, which can be good host-based indicators to detect additional installations of the malware.", 99 | 'CreateToolhelp32Snapshot': "Used to create a snapshot of processes, heaps, threads, and modules. Malware often uses this function as part of code that iterates through processes or threads.", 100 | 'CryptAcquireContext': "Often the first function used by malware to initialize the use of Windows encryption. There are many other functions associated with encryption, most of which start with Crypt.", 101 | 'DeviceIoControl': "Sends a control message from user space to a device driver. DeviceIoControl is popular with kernel malware because it is an easy, flexible way to pass information between user space and kernel space.", 102 | 'DllCanUnloadNow': "An exported function that indicates that the program implements a COM server.", 103 | 'DllGetClassObject': "An exported function that indicates that the program implements a COM server.", 104 | 'DllInstall': "An exported function that indicates that the program implements a COM server.", 105 | 'DllRegisterServer': "An exported function that indicates that the program implements a COM server.", 106 | 'DllUnregisterServer': "An exported function that indicates that the program implements a COM server.", 107 | 'EnableExecuteProtectionSupport': "An undocumented API function used to modify the Data Execution Protection (DEP) settings of the host, making it more susceptible to attack.", 108 | 'EnumProcessModules': "Used to enumerate the loaded modules (executables and DLLs) for a given process. Malware enumerates through modules when doing injection.", 109 | 'FindFirstFile/FindNextFile': "Used to search through a directory and enumerate the filesystem.", 110 | 'FindResource': "Used to find a resource in an executable or loaded DLL. Malware some- times uses resources to store strings, configuration information, or other malicious files. If you see this function used, check for a .rsrc section in the malware’s PE header.", 111 | 'GetDC': "Returns a handle to a device context for a window or the whole screen. Spyware that takes screen captures often uses this function.", 112 | 'GetForegroundWindow': "Returns a handle to the window currently in the foreground of the desktop. Keyloggers commonly use this function to determine in which window the user is entering his keystrokes.", 113 | 'gethostname': "Retrieves the hostname of the computer. Backdoors sometimes use gethostname as part of a survey of the victim machine.", 114 | 'gethostbyname': "Used to perform a DNS lookup on a particular hostname prior to making an IP connection to a remote host. Hostnames that serve as command- and-control servers often make good network-based signatures.", 115 | 'GetModuleFilename': "Returns the filename of a module that is loaded in the current process. Malware can use this function to modify or copy files in the currently running process.", 116 | 'GetModuleHandle': "Used to obtain a handle to an already loaded module. Malware may use GetModuleHandle to locate and modify code in a loaded module or to search for a good location to inject code.", 117 | 'GetProcAddress': "Retrieves the address of a function in a DLL loaded into memory. Used to import functions from other DLLs in addition to the functions imported in the PE file header.", 118 | 'GetStartupInfo': "Retrieves a structure containing details about how the current process was configured to run, such as where the standard handles are directed.", 119 | 'GetSystemDefaultLangId': "Returns the default language settings for the system. This can be used to customize displays and filenames, as part of a survey of an infected victim, or by “patriotic” malware that affects only systems from certain regions.", 120 | 'GetTempPath': "Returns the temporary file path. If you see malware call this function, check whether it reads or writes any files in the temporary file path.", 121 | 'GetThreadContext': "Returns the context structure of a given thread. The context for a thread stores all the thread information, such as the register values and current state.", 122 | 'GetTickCount': "Retrieves the number of milliseconds since bootup. This function is sometimes used to gather timing information as an anti-debugging technique. GetTickCount is often added by the compiler and is included in many executables, so simply seeing it as an imported function provides little information.", 123 | 'GetVersionEx': "Returns information about which version of Windows is currently running. This can be used as part of a victim survey or to select between different offsets for undocumented structures that have changed between different versions of Windows.", 124 | 'GetWindowsDirectory': "Returns the file path to the Windows directory (usually C:\Windows). Malware sometimes uses this call to determine into which directory to install additional malicious programs.", 125 | 'inet_addr': "Converts an IP address string like 127.0.0.1 so that it can be used by func- tions such as connect . The string specified can sometimes be used as a network-based signature.", 126 | 'InternetOpenUrl': "Opens a specific URL for a connection using FTP, HTTP, or HTTPS. URLs, if fixed, can often be good network-based signatures.", 127 | 'IsDebuggerPresent': "Checks to see if the current process is being debugged, often as part oan anti-debugging technique. This function is often added by the compiler and is included in many executables, so simply seeing it as an imported function provides little information.", 128 | 'IsNTAdmin': "Checks if the user has administrator privileges.", 129 | 'IsWoW64Process': 'Used by a 32-bit process to determine if it is running on a 64-bit operating system.', 130 | 'LdrLoadDll': "Low-level function to load a DLL into a process, just like LoadLibrary . Normal programs use LoadLibrary , and the presence of this import may indicate a program that is attempting to be stealthy.", 131 | 'LoadLibrary': "Loads a DLL into a process that may not have been loaded when the program started. Imported by nearly every Win32 program.", 132 | 'LoadResource': "Loads a resource from a PE file into memory. Malware sometimes uses resources to store strings, configuration information, or other malicious files", 133 | 'LsaEnumerateLogonSessions': "Enumerates through logon sessions on the current system, which can be used as part of a credential stealer.", 134 | 'MapViewOfFile': "Maps a file into memory and makes the contents of the file accessible via memory addresses. Launchers, loaders, and injectors use this function to read and modify PE files. By using MapViewOfFile , the malware can avoid using WriteFile to modify the contents of a file.", 135 | 'MapVirtualKey': "Translates a virtual-key code into a character value. It is often used by keylogging malware.", 136 | 'MmGetSystemRoutineAddress': "Similar to GetProcAddress but used by kernel code. This function retrieves the address of a function from another module, but it can only get addresses from ntoskrnl.exe and hal.dll.", 137 | 'Module32First': "Used to enumerate through modules loaded into a process. Injectors use this function to determine where to inject code.", 138 | 'Module32Next': "Used to enumerate through modules loaded into a process. Injectors use this function to determine where to inject code.", 139 | 'NetScheduleJobAdd': "Submits a request for a program to be run at a specified date and time. Malware can use NetScheduleJobAdd to run a different program. As a malware analyst, you’ll need to locate and analyze the program that will be run in the future.", 140 | 'NetShareEnum': "Used to enumerate network shares.", 141 | 'NtQueryDirectoryFile': "Returns information about files in a directory. Rootkits commonly hook this function in order to hide files.", 142 | 'NtQueryInformationProcess': "Returns various information about a specified process. This function is sometimes used as an anti-debugging technique because it can return the same information as CheckRemoteDebuggerPresent .", 143 | 'NtSetInformationProcess': "Can be used to change the privilege level of a program or to bypass Data Execution Prevention (DEP).", 144 | 'OleInitialize': "Used to initialize the COM library. Programs that use COM objects must call OleInitialize prior to calling any other COM functions.", 145 | 'OpenMutex': "Opens a handle to a mutual exclusion object that can be used by malware to ensure that only a single instance of malware is running on a system at any given time. Malware often uses fixed names for mutexes, which can be good host-based indicators.", 146 | 'OpenSCManager': "Opens a handle to the service control manager. Any program that installs, modifies, or controls a service must call this function before any other service-manipulation function.", 147 | 'OutputDebugString': "Outputs a string to a debugger if one is attached. This can be used as an anti-debugging technique.", 148 | 'PeekNamedPipe': "Used to copy data from a named pipe without removing data from the pipe. This function is popular with reverse shells.", 149 | 'Process32First': "Used to begin enumerating processes from a previous call to CreateToolhelp32Snapshot . Malware often enumerates through processes to find a process to inject into.", 150 | 'Process32Next': "Used to begin enumerating processes from a previous call to CreateToolhelp32Snapshot . Malware often enumerates through processes to find a process to inject into.", 151 | 'QueryPerformanceCounter': "Used to retrieve the value of the hardware-based performance counter. This function is sometimes using to gather timing information as part of an anti-debugging technique. It is often added by the compiler and is included in many executables, so simply seeing it as an imported function provides little information.", 152 | 'QueueUserAPC': "Used to execute code for a different thread. Malware sometimes uses QueueUserAPC to inject code into another process.", 153 | 'recv': "Receives data from a remote machine. Malware often uses this function to receive data from a remote command-and-control server.", 154 | 'RegisterHotKey': "Used to register a handler to be notified anytime a user enters a particular key combination (like CTRL - ALT -J), regardless of which window is active when the user presses the key combination. This function is some- times used by spyware that remains hidden from the user until the key combination is pressed.", 155 | 'RegOpenKey': "Opens a handle to a registry key for reading and editing. Registry keys are sometimes written as a way for software to achieve persistence on a host. The registry also contains a whole host of operating system and application setting information.", 156 | 'ResumeThread': "Resumes a previously suspended thread. ResumeThread is used as part of several injection techniques.", 157 | 'RtlCreateRegistryKey': "Used to create a registry from kernel-mode code.", 158 | 'RtlWriteRegistryValue': "Used to write a value to the registry from kernel-mode code.", 159 | 'SamIConnect': "Connects to the Security Account Manager (SAM) in order to make future calls that access credential information. Hash-dumping programs access the SAM database in order to retrieve the hash of users’ login passwords.", 160 | 'SamIGetPrivateData': "Queries the private information about a specific user from the Security Account Manager (SAM) database. Hash-dumping programs access the SAM database in order to retrieve the hash of users’ login passwords.", 161 | 'SamQueryInformationUse': "Queries information about a specific user in the Security Account Manager (SAM) database. Hash-dumping programs access the SAM database in order to retrieve the hash of users’ login passwords.", 162 | 'send': "Sends data to a remote machine. Malware often uses this function to send data to a remote command-and-control server.", 163 | 'SetFileTime': "Modifies the creation, access, or last modified time of a file. Malware often uses this function to conceal malicious activity.", 164 | 'SetThreadContext': "Used to modify the context of a given thread. Some injection techniques use SetThreadContext.", 165 | 'StartServiceCtrlDispatcher': "Used by a service to connect the main thread of the process to the service control manager. Any process that runs as a service must call this function within 30 seconds of startup. Locating this function in malware tells you that the function should be run as a service.", 166 | 'SuspendThread': "Suspends a thread so that it stops running. Malware will sometimes suspend a thread in order to modify it by performing code injection.", 167 | 'system': "Function to run another program provided by some C runtime libraries. On Windows, this function serves as a wrapper function to CreateProcess.", 168 | 'Thread32First': "Used to iterate through the threads of a process. Injectors use these functions to find an appropriate thread to inject into.", 169 | 'Thread32Next': "Used to iterate through the threads of a process. Injectors use these functions to find an appropriate thread to inject into.", 170 | 'Toolhelp32ReadProcessMemory': "Used to read the memory of a remote process.", 171 | 'URLDownloadToFile': "A high-level call to download a file from a web server and save it to disk. This function is popular with downloaders because it implements all the functionality of a downloader in one function call.", 172 | 'WideCharToMultiByte': "Used to convert a Unicode string into an ASCII string.", 173 | 'Wow64DisableWow64FsRedirection': "Disables file redirection that occurs in 32-bit files loaded on a 64-bit system. If a 32-bit application writes to C:\Windows\System32 after calling this function, then it will write to the real C:\Windows\System32 instead of being redirected to C:\Windows\SysWOW64.", 174 | 'WSAStartup': "Used to initialize low-level network functionality. Finding calls to WSAStartup can often be an easy way to locate the start of network-related functionality." 175 | } 176 | 177 | def get_ssdeep(self): 178 | try: 179 | return ssdeep.hash_from_file(self.filename) 180 | except ImportError: 181 | pass 182 | return '' 183 | 184 | # this requires pefile v1.2.10-139 + 185 | def get_imphash(self): 186 | return self.pe.get_imphash() 187 | 188 | def check_date(self, is_report): 189 | val = self.pe.FILE_HEADER.TimeDateStamp 190 | pe_year = int(time.ctime(val).split()[-1]) 191 | this_year = int(time.gmtime(time.time())[0]) 192 | if pe_year > this_year or pe_year < 2000: 193 | if is_report: 194 | return "[SUSPICIOUS COMPILATION DATE] - {}".format(pe_year) 195 | else: 196 | return colors.RED + " [SUSPICIOUS COMPILATION DATE] - {}".format(pe_year) + colors.RESET 197 | 198 | def file_info(self, report, is_report): 199 | info = [] 200 | low_high_entropy = self.pe_entropy < 1 or self.pe_entropy > 7 201 | with open(self.filename, 'rb') as f: 202 | file = f.read() 203 | if report == "output": 204 | info.append("File: {}".format(self.filename)) 205 | info.append("Size: {} bytes".format(os.path.getsize(self.filename))) 206 | info.append("Type: {}".format(magic.from_file(self.filename, mime=True))) 207 | info.append("MD5: {}".format(hashlib.md5(file).hexdigest())) 208 | info.append("SHA1: {}".format(hashlib.sha1(file).hexdigest())) 209 | info.append("Imphash: {}".format(self.get_imphash())) 210 | if ssdeep_r: 211 | info.append("ssdeep: {}".format(self.get_ssdeep())) 212 | info.append("Date: {}".format(time.ctime(self.pe.FILE_HEADER.TimeDateStamp))) 213 | if is_report: 214 | info.append("PE file entropy: {}".format( 215 | self.pe_entropy 216 | )) 217 | else: 218 | info.append("PE file entropy: {}".format( 219 | self.pe_entropy if not low_high_entropy else colors.LIGHT_RED + str( 220 | self.pe_entropy) + colors.RESET)) 221 | else: 222 | info.append("File: {}".format(self.filename)) 223 | info.append("Size: {} bytes".format(os.path.getsize(self.filename))) 224 | info.append("Type: {}".format(magic.from_file(self.filename, mime=True))) 225 | info.append("MD5: {}".format(hashlib.md5(file).hexdigest())) 226 | info.append("SHA1: {}".format(hashlib.sha1(file).hexdigest())) 227 | info.append("Imphash: {}".format(self.get_imphash())) 228 | if ssdeep_r: 229 | info.append("ssdeep: {}".format(self.get_ssdeep())) 230 | info.append("Date: {}".format(time.ctime(self.pe.FILE_HEADER.TimeDateStamp))) 231 | if is_report: 232 | info.append("PE file entropy: {}".format( 233 | self.pe_entropy 234 | )) 235 | else: 236 | info.append("PE file entropy: {}".format( 237 | self.pe_entropy if not low_high_entropy else colors.LIGHT_RED + str( 238 | self.pe_entropy) + colors.RESET)) 239 | if low_high_entropy and not report == "output": 240 | if is_report: 241 | info.append("Very high or very low entropy means that file is compressed or encrypted since truly random data is not common.") 242 | else: 243 | info.append( 244 | colors.RED + "Very high or very low entropy means that file is compressed or encrypted since truly random data is not common." + colors.RESET) 245 | return info 246 | 247 | def checkTSL(self): 248 | _tls = self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[ 249 | pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_TLS']].VirtualAddress 250 | if _tls: 251 | return _tls 252 | else: 253 | return None 254 | 255 | def check_imports(self): 256 | ret = [] 257 | ret2 = [] 258 | if not hasattr(self.pe, 'DIRECTORY_ENTRY_IMPORT'): 259 | return ret 260 | for lib in self.pe.DIRECTORY_ENTRY_IMPORT: 261 | for imp in lib.imports: 262 | ret.append(imp.name) 263 | for n in ret: 264 | if n: 265 | n = n.decode() 266 | if any(map(n.startswith, self.alerts.keys())): 267 | for a in self.alerts: 268 | if n.startswith(a): 269 | ret2.append("{}^{}".format(n, self.alerts.get(a))) 270 | 271 | return ret2 272 | 273 | def sections_analysis(self, report): 274 | good_sectoins = ['.data', '.text', '.code', '.reloc', '.idata', '.edata', '.rdata', '.bss', '.rsrc'] 275 | number_of_section = self.pe.FILE_HEADER.NumberOfSections 276 | if report == "output": 277 | pass 278 | else: 279 | if number_of_section < 1 or number_of_section > 9: 280 | print(colors.RED + "[SUSPICIOUS NUMBER OF SECTIONS] - {}".format(number_of_section) + colors.RESET) 281 | else: 282 | print("Number of Sections: " + str(number_of_section)) 283 | print() 284 | print("{} {} {} {} {} {}".format(*"Section VirtualAddress VirtualSize SizeofRawData Sections_MD5_Hash Section_Entropy".split())) 285 | h_l_entropy = False 286 | suspicious_size_of_raw_data = False 287 | virtual_size = [] 288 | section_names = [] 289 | sections = {} 290 | for section in self.pe.sections: 291 | sec_name = section.Name.strip(b"\x00").decode(errors='ignore').strip() 292 | section_names.append(sec_name) 293 | entropy = section.get_entropy() 294 | for_section = False 295 | if entropy < 1 or entropy > 7: 296 | h_l_entropy = True 297 | for_section = True 298 | try: 299 | if section.Misc_VirtualSize / section.SizeOfRawData > 10: 300 | virtual_size.append((sec_name, section.Misc_VirtualSize)) 301 | except: 302 | if section.SizeOfRawData == 0 and section.Misc_VirtualSize > 0: 303 | suspicious_size_of_raw_data = True 304 | virtual_size.append((section.Name.decode(errors='ignore').strip(), section.Misc_VirtualSize)) 305 | if report == "output": 306 | pass # TODO 307 | else: 308 | print( 309 | "{:7} {:14} {:11} {:13} {:7} {:14}".format(sec_name, 310 | hex(section.VirtualAddress), 311 | section.Misc_VirtualSize, 312 | section.SizeOfRawData,(section.get_hash_md5()), entropy 313 | if not for_section else colors.LIGHT_RED + str( 314 | entropy) + colors.RESET)) 315 | section_info = { 316 | "Section": sec_name, 317 | "VirtualAddress": hex(section.VirtualAddress), 318 | "VirtualSize": section.Misc_VirtualSize, 319 | "SizeofRawData": section.SizeOfRawData, 320 | "Entropy": entropy 321 | } 322 | sections[sec_name] = section_info 323 | 324 | suspicious = {} 325 | if report == "output": 326 | pass # TODO 327 | else: 328 | print() 329 | if virtual_size: 330 | for n, m in virtual_size: 331 | print(colors.RED + 'SUSPICIOUS size of the section "{}" when stored in memory - {}'.format(n, 332 | m) + colors.RESET) 333 | print() 334 | suspicious["suspicious_size_of_the_section"] = virtual_size 335 | if h_l_entropy: 336 | print( 337 | colors.RED + "Very high or very low entropy means that file/section is compressed or encrypted since truly random data is not common." + colors.RESET) 338 | print() 339 | suspicious[ 340 | "h_l_entropy"] = "Very high or very low entropy means that file/section is compressed or encrypted since truly random data is not common." 341 | if suspicious_size_of_raw_data: 342 | print(colors.RED + "Suspicious size of the raw data - 0\n" + colors.RESET) 343 | suspicious["suspicious_size_of_raw_data"] = "yes" 344 | bad_sections = [bad for bad in section_names if bad not in good_sectoins] 345 | if bad_sections: 346 | print(colors.RED + "SUSPICIOUS section names: " + colors.RESET, end='') 347 | for n in bad_sections: 348 | print(n, end=' ') 349 | print() 350 | suspicious["bad_sections"] = bad_sections 351 | 352 | sections_result = { 353 | "number_of_section": number_of_section, 354 | "sections": sections, 355 | "suspicious": suspicious 356 | } 357 | return sections_result 358 | 359 | def check_file_header(self, report): 360 | continue_message = False 361 | 362 | debug = False 363 | if self.pe.FILE_HEADER.PointerToSymbolTable > 0: 364 | continue_message = True 365 | debug = True 366 | if report == "output": 367 | pass 368 | else: 369 | print( 370 | colors.LIGHT_RED + "File contains some debug information, in majority of regular PE files, should not " 371 | "contain debug information" + colors.RESET + "\n") 372 | 373 | flags = [("BYTES_REVERSED_LO", self.pe.FILE_HEADER.IMAGE_FILE_BYTES_REVERSED_LO, 374 | "Little endian: LSB precedes MSB in memory, deprecated and should be zero."), 375 | ("BYTES_REVERSED_HI", self.pe.FILE_HEADER.IMAGE_FILE_BYTES_REVERSED_HI, 376 | "Big endian: MSB precedes LSB in memory, deprecated and should be zero."), 377 | ("RELOCS_STRIPPED", self.pe.FILE_HEADER.IMAGE_FILE_RELOCS_STRIPPED, 378 | "This indicates that the file does not contain base relocations and must therefore be loaded at its " 379 | "preferred base address.\nFlag has the effect of disabling Address Space Layout Randomization(ASLR) " 380 | "for the process.")] 381 | return { 382 | "debug": debug, 383 | "flags": flags 384 | } 385 | # CIC: Call If Callable needed for def overlay 386 | def CIC(self, expression): 387 | if callable(expression): 388 | return expression() 389 | else: 390 | return expression 391 | 392 | # IFF: IF Function needed for def overlay 393 | def IFF(self, expression, valueTrue, valueFalse): 394 | if expression: 395 | return self.CIC(valueTrue) 396 | else: 397 | return self.CIC(valueFalse) 398 | #Both functions NumberfBytesHumanRepresentation & Overlay calculate information if overlay is present in a PE file 399 | def NumberOfBytesHumanRepresentation(self, value): 400 | if value <= 1024: 401 | return '%s bytes' % value 402 | elif value < 1024 * 1024: 403 | return '%.1f KB' % (float(value) / 1024.0) 404 | elif value < 1024 * 1024 * 1024: 405 | return '%.1f MB' % (float(value) / 1024.0 / 1024.0) 406 | else: 407 | return '%.1f GB' % (float(value) / 1024.0 / 1024.0 / 1024.0) 408 | 409 | def overlay(self): 410 | overlayOffset = self.pe.get_overlay_data_start_offset() 411 | raw= self.pe.write() 412 | if overlayOffset == None: 413 | print (' No overlay Data Present') 414 | else: 415 | print ('Overlay Data is present which is often associated with malware') 416 | print(' Start offset: 0x%08x' % overlayOffset) 417 | overlaySize = len(raw[overlayOffset:]) 418 | print(' Size: 0x%08x %s %.2f%%' % (overlaySize, self.NumberOfBytesHumanRepresentation(overlaySize), float(overlaySize) / float(len(raw)) * 100.0)) 419 | print(' MD5: %s' % hashlib.md5(raw[overlayOffset:]).hexdigest()) 420 | print(' SHA-256: %s' % hashlib.sha256(raw[overlayOffset:]).hexdigest()) 421 | overlayMagic = raw[overlayOffset:][:4] 422 | if type(overlayMagic[0]) == int: 423 | overlayMagic = ''.join([chr(b) for b in overlayMagic]) 424 | print(' MAGIC: %s %s' % (binascii.b2a_hex(overlayMagic.encode('utf-8')), ''.join([self.IFF(ord(b) >= 32, b, '.') for b in overlayMagic]))) 425 | print(' PE file without overlay:') 426 | print(' MD5: %s' % hashlib.md5(raw[:overlayOffset]).hexdigest()) 427 | print(' SHA-256: %s' % hashlib.sha256(raw[:overlayOffset]).hexdigest()) 428 | 429 | # Added by Yang 430 | class ELFScanner: 431 | def __init__(self, filename): 432 | self.filename = filename 433 | with open(self.filename, 'rb') as f: 434 | self.elffile = ELFFile(f) 435 | 436 | def get_ssdeep(self): 437 | try: 438 | return ssdeep.hash_from_file(self.filename) 439 | except ImportError: 440 | pass 441 | return '' 442 | 443 | def file_info(self, report): 444 | info = [] 445 | with open(self.filename, 'rb') as f: 446 | file = f.read() 447 | if report == "output": 448 | return "" 449 | else: 450 | info.append("File: {}".format(self.filename)) 451 | info.append("Size: {} bytes".format(os.path.getsize(self.filename))) 452 | info.append("Type: {}".format(magic.from_file(self.filename, mime=True))) 453 | info.append("MD5: {}".format(hashlib.md5(file).hexdigest())) 454 | info.append("SHA1: {}".format(hashlib.sha1(file).hexdigest())) 455 | if ssdeep_r: 456 | info.append("ssdeep: {}".format(self.get_ssdeep())) 457 | return info 458 | 459 | def dependencies(self): 460 | try: 461 | output = Popen(['ldd', self.filename], 462 | stdout=PIPE, stdin=PIPE, stderr=STDOUT, bufsize=1) 463 | return output.stdout 464 | except: 465 | pass 466 | 467 | def elf_header(self): 468 | try: 469 | output = Popen(['readelf', '-h', self.filename], 470 | stdout=PIPE, stdin=PIPE, stderr=STDOUT, bufsize=1) 471 | return output.stdout 472 | except: 473 | pass 474 | 475 | def program_header(self): 476 | try: 477 | output = Popen(['readelf', '-l', self.filename], 478 | stdout=PIPE, stdin=PIPE, stderr=STDOUT, bufsize=1) 479 | return output.stdout 480 | except: 481 | pass 482 | 483 | def section_header(self): 484 | try: 485 | output = Popen(['readelf', '-S', self.filename], 486 | stdout=PIPE, stdin=PIPE, stderr=STDOUT, bufsize=1) 487 | return output.stdout 488 | except: 489 | pass 490 | 491 | def symbols(self): 492 | try: 493 | output = Popen(['readelf', '-s', self.filename], 494 | stdout=PIPE, stdin=PIPE, stderr=STDOUT, bufsize=1) 495 | return output.stdout 496 | except: 497 | pass 498 | 499 | def checksec(self): 500 | result = {} 501 | result["RELRO"] = 0 502 | result["CANARY"] = 0 503 | result["NX"] = 1 504 | result["PIE"] = 0 505 | result["FORTIFY"] = 0 506 | try: 507 | output = Popen(['readelf', '-W', '-a', self.filename], 508 | stdout=PIPE, stdin=PIPE, stderr=STDOUT, bufsize=1) 509 | 510 | for line in output.stdout: 511 | line = line.decode('utf-8', 'ignore').replace("\n", "") 512 | if "GNU_RELRO" in line: 513 | result["RELRO"] |= 2 514 | if "BIND_NOW" in line: 515 | result["RELRO"] |= 1 516 | if "__stack_chk_fail" in line: 517 | result["CANARY"] = 1 518 | if "GNU_STACK" in line and "RWE" in line: 519 | result["NX"] = 0 520 | if "Type:" in line and "DYN (" in line: 521 | result["PIE"] = 4 522 | if "(DEBUG)" in line and result["PIE"] == 4: 523 | result["PIE"] = 1 524 | if "_chk@" in line: 525 | result["FORTIFY"] = 1 526 | 527 | if result["RELRO"] == 1: 528 | result["RELRO"] = 0 529 | return result 530 | except: 531 | pass 532 | 533 | 534 | def file_info(filename): 535 | info = [] 536 | with open(filename, 'rb') as f: 537 | file = f.read() 538 | info.append("File: {}".format(filename)) 539 | info.append("Size: {} bytes".format(os.path.getsize(filename))) 540 | info.append("Type: {}".format(magic.from_file(filename, mime=True))) 541 | info.append("MD5: {}".format(hashlib.md5(file).hexdigest())) 542 | info.append("SHA1: {}".format(hashlib.sha1(file).hexdigest())) 543 | if ssdeep_r: 544 | info.append("ssdeep: {}".format(ssdeep.hash_from_file(filename))) 545 | return info 546 | --------------------------------------------------------------------------------