├── .gitmodules ├── lib ├── __init__.py ├── levenshtein.py ├── vuln_checker.py ├── pesieve.py ├── helpers.py ├── lokilogger.py └── doublepulsar.py ├── test ├── unicode-test │ ├── dotfile │ │ └── .txt │ └── Иixdrin │ │ └── webshell_tiny_Файл.asp └── yara │ └── JFolder.jsp ├── loki.ico ├── lokiicon.jpg ├── screens ├── lokicmd.png ├── lokiconf1.png ├── lokiconf2.png ├── lokiinit.png ├── lokilog1.png ├── lokiscan1.png ├── lokiscan2.png ├── lokiscan3.png ├── lokititle.png └── scanner-comparison.png ├── prepare_push.sh ├── tools ├── pe-sieve32.exe ├── pe-sieve64.exe ├── vt-checker.py └── vt-checker-hosts.py ├── requirements.txt ├── .gitignore ├── Pipfile ├── loki.spec ├── loki-upgrader.spec ├── .travis.yml ├── config └── excludes.cfg ├── .github └── workflows │ └── lint_python.yml ├── docs ├── LICENSE-PE-Sieve └── LICENSE-doublepulsarcheck ├── plugins └── loki-plugin-wmi.py ├── loki-upgrader.py ├── README.md └── LICENSE /.gitmodules: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lib/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/unicode-test/dotfile/.txt: -------------------------------------------------------------------------------- 1 | Testweisew -------------------------------------------------------------------------------- /loki.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/loki.ico -------------------------------------------------------------------------------- /lokiicon.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/lokiicon.jpg -------------------------------------------------------------------------------- /test/unicode-test/Иixdrin/webshell_tiny_Файл.asp: -------------------------------------------------------------------------------- 1 | <%execute request(chr(42))%> -------------------------------------------------------------------------------- /screens/lokicmd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/screens/lokicmd.png -------------------------------------------------------------------------------- /prepare_push.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | git submodule foreach git pull origin master 4 | 5 | -------------------------------------------------------------------------------- /screens/lokiconf1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/screens/lokiconf1.png -------------------------------------------------------------------------------- /screens/lokiconf2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/screens/lokiconf2.png -------------------------------------------------------------------------------- /screens/lokiinit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/screens/lokiinit.png -------------------------------------------------------------------------------- /screens/lokilog1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/screens/lokilog1.png -------------------------------------------------------------------------------- /screens/lokiscan1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/screens/lokiscan1.png -------------------------------------------------------------------------------- /screens/lokiscan2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/screens/lokiscan2.png -------------------------------------------------------------------------------- /screens/lokiscan3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/screens/lokiscan3.png -------------------------------------------------------------------------------- /screens/lokititle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/screens/lokititle.png -------------------------------------------------------------------------------- /test/yara/JFolder.jsp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/test/yara/JFolder.jsp -------------------------------------------------------------------------------- /tools/pe-sieve32.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/tools/pe-sieve32.exe -------------------------------------------------------------------------------- /tools/pe-sieve64.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/tools/pe-sieve64.exe -------------------------------------------------------------------------------- /screens/scanner-comparison.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/product/Loki/master/screens/scanner-comparison.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | colorama 2 | future 3 | netaddr 4 | psutil 5 | rfc5424-logging-handler 6 | wmi ; sys_platform == 'win32' 7 | pywin32 ; sys_platform == 'win32' 8 | yara-python 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.csv 3 | 4 | *.pkl 5 | 6 | tools/vt-checker_flo\.py 7 | 8 | *.log 9 | 10 | backup/base64-stats.py 11 | 12 | backup/loki copy.py 13 | 14 | loki.zip 15 | dist 16 | run_loki.bat 17 | loki 18 | dummy 19 | tools/*.txt 20 | tools/*.db 21 | tools/*_flo.py 22 | *.xlsx 23 | 24 | \.idea/ 25 | 26 | loki\.log 27 | 28 | *.pyc 29 | signature-base 30 | tools/old-results 31 | build 32 | private-signatures 33 | rules 34 | rules.key 35 | *.htm 36 | loki.exe 37 | -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | url = "https://pypi.python.org/simple" 3 | verify_ssl = true 4 | name = "pypi" 5 | 6 | [scripts] 7 | loki = "python loki.py" 8 | 9 | [packages] 10 | wheel = "*" 11 | colorama = "*" 12 | future = "*" 13 | netaddr = "*" 14 | psutil = "*" 15 | rfc5424-logging-handler = "*" 16 | pywin32 = { version="*", sys_platform="== 'win32'" } 17 | yara-python = "*" 18 | WMI = {version="*",sys_platform="== 'win32'" } 19 | 20 | [dev-packages] 21 | 22 | [requires] 23 | python_version = "3" 24 | -------------------------------------------------------------------------------- /loki.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | 3 | a = Analysis(['loki.py'], 4 | pathex=['.'], 5 | hiddenimports=[], 6 | hookspath=None, 7 | runtime_hooks=None) 8 | pyz = PYZ(a.pure) 9 | 10 | a.datas = list({tuple(map(str.upper, t)) for t in a.datas}) 11 | 12 | exe = EXE(pyz, 13 | a.scripts, 14 | a.binaries, 15 | a.zipfiles, 16 | a.datas, 17 | name='loki.exe', 18 | debug=False, 19 | strip=None, 20 | upx=False, 21 | console=True , icon='loki.ico') 22 | -------------------------------------------------------------------------------- /loki-upgrader.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | 3 | a = Analysis(['loki-upgrader.py'], 4 | pathex=['.'], 5 | hiddenimports=[], 6 | hookspath=None, 7 | runtime_hooks=None) 8 | pyz = PYZ(a.pure) 9 | 10 | a.datas = list({tuple(map(str.upper, t)) for t in a.datas}) 11 | 12 | exe = EXE(pyz, 13 | a.scripts, 14 | a.binaries, 15 | a.zipfiles, 16 | a.datas, 17 | name='loki-upgrader.exe', 18 | debug=False, 19 | strip=None, 20 | upx=False, 21 | console=True , icon='loki.ico') 22 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - 3.8 4 | cache: pip 5 | install: 6 | - pip install colorama flake8 future netaddr psutil rfc5424-logging-handler yara-python 7 | 8 | script: 9 | - flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 10 | - python ./loki.py --noprocs --noindicator --dontwait --debug -p ./test 11 | - python ./loki.py --noprocs --noindicator --dontwait --debug --intense -p ./test 12 | - python ./loki.py --noprocs --noindicator --dontwait --debug --csv -p ./test 13 | 14 | notifications: 15 | email: 16 | recipients: 17 | - venom14@gmail.com 18 | on_success: never 19 | on_failure: always 20 | -------------------------------------------------------------------------------- /config/excludes.cfg: -------------------------------------------------------------------------------- 1 | # Excluded directories 2 | # 3 | # - add directories you want to exclude from the scan 4 | # - double escape back slashes 5 | # - values are case-insensitive 6 | # - remember to use back slashes on Windows and slashes on Linux / Unix / OSX 7 | # - each line contains a regex that matches somewhere in the full path (case insensitive) 8 | # e.g.: 9 | # Regex: \\System32\\ 10 | # Matches C:\Windows\System32\cmd.exe 11 | # 12 | # Regex: /var/log/[^/]+\.log 13 | # Matches: /var/log/test.log 14 | # Not Matches: /var/log/test.gz 15 | # 16 | 17 | # Useful examples (google "antivirus exclusion recommendations" to find more) 18 | \\Ntfrs\\ 19 | \\Ntds\\ 20 | \\EDB[^\.]+\.log 21 | Sysvol\\Staging\\Nntfrs_cmp 22 | \\System Volume Information\\DFSR -------------------------------------------------------------------------------- /.github/workflows/lint_python.yml: -------------------------------------------------------------------------------- 1 | name: lint_python 2 | on: [pull_request, push] 3 | jobs: 4 | lint_python: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v2 8 | - uses: actions/setup-python@v2 9 | - run: pip install black codespell flake8 isort mypy pytest pyupgrade safety 10 | - run: black --check . || true 11 | - run: codespell --ignore-words-list="datas" 12 | - run: flake8 . --count --exit-zero --select=E9,F63,F7,F82 --show-source --statistics 13 | - run: flake8 . --count --exit-zero --max-complexity=10 --max-line-length=88 --show-source --statistics 14 | - run: isort --check-only --profile black . || true 15 | - run: pip install -r requirements.txt 16 | - run: mypy --install-types --non-interactive . || true 17 | - run: pytest . || true 18 | - run: pytest --doctest-modules . || true 19 | - run: python ./loki.py --noprocs --noindicator --dontwait --debug -p ./test 20 | - run: python ./loki.py --noprocs --noindicator --dontwait --debug --intense -p ./test 21 | - run: python ./loki.py --noprocs --noindicator --dontwait --debug --csv -p ./test 22 | - run: shopt -s globstar && pyupgrade --py36-plus **/*.py || true 23 | - run: safety check 24 | -------------------------------------------------------------------------------- /lib/levenshtein.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: iso-8859-1 -*- 3 | # -*- coding: utf-8 -*- 4 | # 5 | # Levenshtein related functions 6 | 7 | CHECK_FILES = ['svchost.exe', 'explorer.exe', 'iexplore.exe', 'lsass.exe', 'chrome.exe', 'csrss.exe', 'firefox.exe', 8 | 'winlogon.exe'] 9 | 10 | class LevCheck(): 11 | 12 | def __init__(self): 13 | pass 14 | 15 | def check(self, fileName): 16 | """ 17 | Check if file name is very similar to a file in the check list 18 | :param fileName: 19 | :return: 20 | """ 21 | for checkFile in CHECK_FILES: 22 | if levenshtein(checkFile, fileName) == 1: 23 | return checkFile 24 | return None 25 | 26 | def levenshtein(s, t): 27 | if s == t: return 0 28 | elif len(s) == 0: return len(t) 29 | elif len(t) == 0: return len(s) 30 | v0 = [None] * (len(t) + 1) 31 | v1 = [None] * (len(t) + 1) 32 | for i in range(len(v0)): 33 | v0[i] = i 34 | for i in range(len(s)): 35 | v1[0] = i + 1 36 | for j in range(len(t)): 37 | cost = 0 if s[i] == t[j] else 1 38 | v1[j + 1] = min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost) 39 | for j in range(len(v0)): 40 | v0[j] = v1[j] 41 | 42 | return v1[len(t)] 43 | 44 | -------------------------------------------------------------------------------- /docs/LICENSE-PE-Sieve: -------------------------------------------------------------------------------- 1 | BSD 2-Clause License 2 | 3 | Copyright (c) 2017, @hasherezade 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 20 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 23 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /docs/LICENSE-doublepulsarcheck: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017, Countercept (https://countercept.com) 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | 7 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | 9 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 10 | 11 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /lib/vuln_checker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: iso-8859-1 -*- 3 | # -*- coding: utf-8 -*- 4 | # 5 | # Different vulnerability checks 6 | 7 | import subprocess 8 | import traceback 9 | 10 | class VulnChecker(): 11 | 12 | def __init__(self, logger): 13 | # Logger 14 | self.logger = logger 15 | pass 16 | 17 | def run(self): 18 | self.logger.log("INFO", "VulnChecker", "Starting vulnerability checks ...") 19 | self.check_sam_readable() 20 | 21 | def check_sam_readable(self): 22 | """ 23 | Check if the local SAM is readable by everyone 24 | https://twitter.com/wdormann/status/1417447179149533185 25 | :return: 26 | """ 27 | output = b'' 28 | try: 29 | output += subprocess.check_output([r'icacls.exe', r'C:\Windows\System32\config\sam'], stderr=subprocess.STDOUT) 30 | except subprocess.CalledProcessError as e: 31 | pass 32 | try: 33 | output += subprocess.check_output([r'icacls.exe', r'C:\Windows\SysNative\config\sam'], stderr=subprocess.STDOUT) 34 | except subprocess.CalledProcessError as e: 35 | pass 36 | # Check the output 37 | try: 38 | if r'BUILTIN\Users:(I)(RX)' in output.decode('latin1', errors='ignore'): 39 | self.logger.log("WARNING", "VulnChecker", 40 | "The Security Account Manager (SAM) database file C:\\Windows\\System32\\config\\SAM is " 41 | "readable by every user. This is caused by the Hive Permission Bug, which is problematic " 42 | "on systems that have System Protection configured for drive C: (see " 43 | "https://doublepulsar.com/hivenightmare-aka-serioussam-anybody-can-read-the-registry-in-" 44 | "windows-10-7a871c465fa5)") 45 | return True 46 | else: 47 | self.logger.log("DEBUG", "VulnChecker", "SAM Database isn't readable by every user.") 48 | except UnicodeDecodeError as e: 49 | self.logger.log("ERROR", "VulnChecker", "Unicode decode error in SAM check") 50 | return False 51 | -------------------------------------------------------------------------------- /lib/pesieve.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # PE-Sieve Integration by @hasherezade 4 | 5 | import os 6 | import sys 7 | import json 8 | import traceback 9 | 10 | from lib.lokilogger import * 11 | from lib.helpers import runProcess 12 | 13 | class PESieve(object): 14 | """ 15 | PESieve class makes use of hasherezade's PE-Sieve tool to scans a given process, 16 | searching for the modules containing in-memory code modifications 17 | """ 18 | active = False 19 | 20 | def __init__(self, workingDir, is64bit, logger): 21 | 22 | # Logger 23 | self.logger = logger 24 | # PE-Sieve tools 25 | self.peSieve = os.path.join(workingDir, 'tools/pe-sieve32.exe'.replace("/", os.sep)) 26 | if is64bit: 27 | self.peSieve = os.path.join(workingDir, 'tools/pe-sieve64.exe'.replace("/", os.sep)) 28 | 29 | if self.isAvailable(): 30 | self.active = True 31 | self.logger.log("NOTICE", "PESieve", "PE-Sieve successfully initialized BINARY: {0} " 32 | "SOURCE: https://github.com/hasherezade/pe-sieve".format(self.peSieve)) 33 | else: 34 | self.logger.log("NOTICE", "PESieve", "Cannot find PE-Sieve in expected location {0} " 35 | "SOURCE: https://github.com/hasherezade/pe-sieve".format(self.peSieve)) 36 | 37 | def isAvailable(self): 38 | """ 39 | Checks if the PE-Sieve tools are available in a "./tools" sub folder 40 | :return: 41 | """ 42 | if not os.path.exists(self.peSieve): 43 | self.logger.log("DEBUG", "PESieve", "PE-Sieve not found in location '{0}' - " 44 | "feature will not be active".format(self.peSieve)) 45 | return False 46 | return True 47 | 48 | def scan(self, pid, pesieveshellc = False): 49 | """ 50 | Performs a scan on a given process ID 51 | :param pid: process id of the process to check 52 | :return hooked, replaces, suspicious: number of findings per type 53 | """ 54 | # Presets 55 | results = {"patched": 0, "replaced": 0, "unreachable_file": 0, "implanted_pe": 0, "implanted_shc": 0} 56 | # Compose command 57 | command = [self.peSieve, '/pid', str(pid), '/ofilter', '2', '/quiet', '/json'] + (['/shellc'] if pesieveshellc else []) 58 | # Run PE-Sieve on given process 59 | (output, returnCode) = runProcess(command) 60 | # Debug output 61 | if self.logger.debug: 62 | print("PE-Sieve JSON output: %s" % output) 63 | if output == '' or not output: 64 | return results 65 | try: 66 | results_raw = json.loads(output) 67 | results = results_raw["scanned"]["modified"] 68 | except ValueError as v: 69 | traceback.print_exc() 70 | self.logger.log("DEBUG", "PESieve", "Couldn't parse the JSON output.") 71 | except Exception as e: 72 | traceback.print_exc() 73 | self.logger.log("ERROR", "PESieve", "Something went wrong during PE-Sieve scan.") 74 | return results 75 | -------------------------------------------------------------------------------- /plugins/loki-plugin-wmi.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Loki WMI Scanner plugin 5 | 2018/04/20 6 | 2018/04/21 7 | Author: @DidierStevens 8 | """ 9 | 10 | import hashlib 11 | import sys 12 | 13 | def ScanWMI(): 14 | global logger # logger is defined in loki.py.__main__ 15 | 16 | if sys.platform in ("win32", "cygwin"): 17 | try: 18 | import wmi 19 | except ImportError as e: 20 | wmi = None 21 | logger.log("CRITICAL", "WMIScan", "Unable to import wmi") 22 | print("Unable to import wmi") 23 | oWMI = wmi.WMI(namespace=r'root\subscription') 24 | 25 | knownHashes = ['159e2bcde798cf5fbb290f90a7ccc1a6', '20d385446e60cf9134792d5b145c54bb', '65c80cb7a9094b32c3f9982887b9862a', '6ddb270d17551138747ad7c1bc3db9b3', 'de5b1c4f59c4463f8e9b70cbe1156976'] 26 | 27 | leventFilter = [] 28 | lFilterToConsumerBinding = [] 29 | lCommandLineEventConsumer = [] 30 | lActiveScriptEventConsumer = [] 31 | try: 32 | leventFilter = oWMI.__eventFilter() 33 | except: 34 | logger.log("WARNING", "WMIScan", 'Error retrieving __eventFilter') 35 | try: 36 | lFilterToConsumerBinding = oWMI.__FilterToConsumerBinding() 37 | except: 38 | logger.log("WARNING", "WMIScan", 'Error retrieving __FilterToConsumerBinding') 39 | try: 40 | lCommandLineEventConsumer = oWMI.CommandLineEventConsumer() 41 | except: 42 | logger.log("WARNING", "WMIScan", 'Error retrieving CommandLineEventConsumer') 43 | try: 44 | lActiveScriptEventConsumer = oWMI.ActiveScriptEventConsumer() 45 | except: 46 | logger.log("WARNING", "WMIScan", 'Error retrieving ActiveScriptEventConsumer') 47 | 48 | for eventFilter in leventFilter: 49 | try: 50 | hashEntry = hashlib.md5(str(eventFilter)).hexdigest() 51 | if not hashEntry in knownHashes: 52 | logger.log("WARNING", "WMIScan", 'CLASS: __eventFilter MD5: %s NAME: %s QUERY: %s' % (hashEntry, eventFilter.wmi_property('Name').value, eventFilter.wmi_property('Query').value)) 53 | except: 54 | logger.log("INFO", "WMIScan", repr(str(eventFilter))) 55 | for FilterToConsumerBinding in lFilterToConsumerBinding: 56 | try: 57 | hashEntry = hashlib.md5(str(FilterToConsumerBinding)).hexdigest() 58 | if not hashEntry in knownHashes: 59 | logger.log("WARNING", "WMIScan", 'CLASS: __FilterToConsumerBinding MD5: %s CONSUMER: %s FILTER: %s' % (hashEntry, FilterToConsumerBinding.wmi_property('Consumer').value, FilterToConsumerBinding.wmi_property('Filter').value)) 60 | except: 61 | logger.log("INFO", "WMIScan", repr(str(FilterToConsumerBinding))) 62 | for CommandLineEventConsumer in lCommandLineEventConsumer: 63 | try: 64 | hashEntry = hashlib.md5(str(CommandLineEventConsumer)).hexdigest() 65 | if not hashEntry in knownHashes: 66 | logger.log("WARNING", "WMIScan", 'CLASS: CommandLineEventConsumer MD5: %s NAME: %s COMMANDLINETEMPLATE: %s' % (hashEntry, CommandLineEventConsumer.wmi_property('Name').value, CommandLineEventConsumer.wmi_property('CommandLineTemplate').value)) 67 | except: 68 | logger.log("INFO", "WMIScan", repr(str(CommandLineEventConsumer))) 69 | for ActiveScriptEventConsumer in lActiveScriptEventConsumer: 70 | logger.log("INFO", "WMIScan", repr(str(ActiveScriptEventConsumer))) 71 | 72 | 73 | LokiRegisterPlugin("PluginWMI", ScanWMI, 1) # noqa: F821 undefined name 'LokiRegisterPlugin' 74 | -------------------------------------------------------------------------------- /lib/helpers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: iso-8859-1 -*- 3 | # -*- coding: utf-8 -*- 4 | # 5 | # Loki 6 | # Simple IOC Scanner 7 | 8 | import sys 9 | import hashlib 10 | import string 11 | import struct 12 | import traceback 13 | import os 14 | import re 15 | import psutil 16 | try: 17 | from StringIO import StringIO 18 | except ImportError: 19 | from io import StringIO 20 | import netaddr 21 | import platform 22 | import time 23 | import threading 24 | import subprocess 25 | import signal 26 | 27 | # Helper Functions ------------------------------------------------------------- 28 | 29 | def is_ip(string): 30 | try: 31 | if netaddr.valid_ipv4(string): 32 | return True 33 | if netaddr.valid_ipv6(string): 34 | return True 35 | return False 36 | except: 37 | traceback.print_exc() 38 | return False 39 | 40 | 41 | def is_cidr(string): 42 | try: 43 | if netaddr.IPNetwork(string) and "/" in string: 44 | return True 45 | return False 46 | except: 47 | return False 48 | 49 | 50 | def ip_in_net(ip, network): 51 | try: 52 | # print "Checking if ip %s is in network %s" % (ip, network) 53 | if netaddr.IPAddress(ip) in netaddr.IPNetwork(network): 54 | return True 55 | return False 56 | except: 57 | return False 58 | 59 | 60 | def generateHashes(filedata): 61 | try: 62 | md5 = hashlib.md5() 63 | sha1 = hashlib.sha1() 64 | sha256 = hashlib.sha256() 65 | md5.update(filedata) 66 | sha1.update(filedata) 67 | sha256.update(filedata) 68 | return md5.hexdigest(), sha1.hexdigest(), sha256.hexdigest() 69 | except Exception as e: 70 | traceback.print_exc() 71 | return 0, 0, 0 72 | 73 | 74 | def getPlatformFull(): 75 | type_info = "" 76 | try: 77 | type_info = "%s PROC: %s ARCH: %s" % ( " ".join(platform.win32_ver()), platform.processor(), " ".join(platform.architecture())) 78 | except Exception as e: 79 | type_info = " ".join(platform.win32_ver()) 80 | return type_info 81 | 82 | 83 | def setNice(logger): 84 | try: 85 | pid = os.getpid() 86 | p = psutil.Process(pid) 87 | logger.log("INFO", "Init", "Setting LOKI process with PID: %s to priority IDLE" % pid) 88 | p.nice(psutil.IDLE_PRIORITY_CLASS) 89 | return 1 90 | except Exception as e: 91 | if logger.debug: 92 | traceback.print_exc() 93 | logger.log("ERROR", "Init", "Error setting nice value of THOR process") 94 | return 0 95 | 96 | 97 | def getExcludedMountpoints(): 98 | excludes = [] 99 | try: 100 | mtab = open("/etc/mtab", "r") 101 | for mpoint in mtab: 102 | options = mpoint.split(" ") 103 | if not options[0].startswith("/dev/"): 104 | if not options[1] == "/": 105 | excludes.append(options[1]) 106 | except Exception as e: 107 | print ("Error while reading /etc/mtab") 108 | finally: 109 | mtab.close() 110 | return excludes 111 | 112 | 113 | def removeBinaryZero(string): 114 | return re.sub(r'\x00','',string) 115 | 116 | 117 | def printProgress(i): 118 | if (i%4) == 0: 119 | sys.stdout.write('\b/') 120 | elif (i%4) == 1: 121 | sys.stdout.write('\b-') 122 | elif (i%4) == 2: 123 | sys.stdout.write('\b\\') 124 | elif (i%4) == 3: 125 | sys.stdout.write('\b|') 126 | sys.stdout.flush() 127 | 128 | 129 | def transformOS(regex, platform): 130 | # Replace '\' with '/' on Linux/Unix/OSX 131 | if platform != "windows": 132 | regex = regex.replace(r'\\', r'/') 133 | regex = regex.replace(r'C:', '') 134 | return regex 135 | 136 | 137 | def replaceEnvVars(path): 138 | 139 | # Setting new path to old path for default 140 | new_path = path 141 | 142 | # ENV VARS ---------------------------------------------------------------- 143 | # Now check if an environment env is included in the path string 144 | res = re.search(r"([@]?%[A-Za-z_]+%)", path) 145 | if res: 146 | env_var_full = res.group(1) 147 | env_var = env_var_full.replace("%", "").replace("@", "") 148 | 149 | # Check environment variables if there is a matching var 150 | if env_var in os.environ: 151 | if os.environ[env_var]: 152 | new_path = path.replace(env_var_full, re.escape(os.environ[env_var])) 153 | 154 | # TYPICAL REPLACEMENTS ---------------------------------------------------- 155 | if path[:11].lower() == "\\systemroot": 156 | new_path = path.replace("\\SystemRoot", os.environ["SystemRoot"]) 157 | 158 | if path[:8].lower() == "system32": 159 | new_path = path.replace("system32", "%s\\System32" % os.environ["SystemRoot"]) 160 | 161 | #if path != new_path: 162 | # print "OLD: %s NEW: %s" % (path, new_path) 163 | return new_path 164 | 165 | 166 | def get_file_type(filePath, filetype_sigs, max_filetype_magics, logger): 167 | try: 168 | # Reading bytes from file 169 | res_full = open(filePath, 'rb', os.O_RDONLY).read(max_filetype_magics) 170 | # Checking sigs 171 | for sig in filetype_sigs: 172 | bytes_to_read = int(len(str(sig)) / 2) 173 | res = res_full[:bytes_to_read] 174 | if res == bytes.fromhex(sig): 175 | return filetype_sigs[sig] 176 | return "UNKNOWN" 177 | except Exception as e: 178 | if logger.debug: 179 | traceback.print_exc() 180 | return "UNKNOWN" 181 | 182 | 183 | def removeNonAscii(s, stripit=False): 184 | nonascii = "error" 185 | try: 186 | try: 187 | printable = set(string.printable) 188 | filtered_string = filter(lambda x: x in printable, s.decode('utf-8')) 189 | nonascii = ''.join(filtered_string) 190 | except Exception as e: 191 | traceback.print_exc() 192 | nonascii = s.hex() 193 | except Exception as e: 194 | traceback.print_exc() 195 | pass 196 | 197 | return nonascii 198 | 199 | 200 | def removeNonAsciiDrop(s): 201 | nonascii = "error" 202 | try: 203 | # Generate a new string without disturbing characters 204 | printable = set(string.printable) 205 | nonascii = filter(lambda x: x in printable, s) 206 | except Exception as e: 207 | traceback.print_exc() 208 | pass 209 | return nonascii 210 | 211 | 212 | def getAge(filePath): 213 | try: 214 | stats=os.stat(filePath) 215 | 216 | # Created 217 | ctime=stats.st_ctime 218 | # Modified 219 | mtime=stats.st_mtime 220 | # Accessed 221 | atime=stats.st_atime 222 | 223 | except Exception as e: 224 | # traceback.print_exc() 225 | return (0, 0, 0) 226 | 227 | # print "%s %s %s" % ( ctime, mtime, atime ) 228 | return (ctime, mtime, atime) 229 | 230 | def getAgeString(filePath): 231 | ( ctime, mtime, atime ) = getAge(filePath) 232 | timestring = "" 233 | try: 234 | timestring = "CREATED: %s MODIFIED: %s ACCESSED: %s" % ( time.ctime(ctime), time.ctime(mtime), time.ctime(atime) ) 235 | except Exception as e: 236 | timestring = "CREATED: not_available MODIFIED: not_available ACCESSED: not_available" 237 | return timestring 238 | 239 | 240 | def runProcess(command, timeout=10): 241 | """ 242 | Run a process and check it's output 243 | :param command: 244 | :return output: 245 | """ 246 | output = "" 247 | returnCode = 0 248 | 249 | # Kill check 250 | try: 251 | kill_check = threading.Event() 252 | def _kill_process_after_a_timeout(pid): 253 | os.kill(pid, signal.SIGTERM) 254 | kill_check.set() # tell the main routine that we had to kill 255 | print("timeout hit - killing pid {0}".format(pid)) 256 | # use SIGKILL if hard to kill... 257 | return "", 1 258 | try: 259 | p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 260 | except subprocess.CalledProcessError as e: 261 | returnCode = e.returncode 262 | traceback.print_exc() 263 | #print p.communicate()[0] 264 | pid = p.pid 265 | watchdog = threading.Timer(timeout, _kill_process_after_a_timeout, args=(pid, )) 266 | watchdog.start() 267 | (stdout, stderr) = p.communicate() 268 | output = "{0}{1}".format(stdout.decode('utf-8'), stderr.decode('utf-8')) 269 | watchdog.cancel() # if it's still waiting to run 270 | success = not kill_check.isSet() 271 | kill_check.clear() 272 | except Exception as e: 273 | traceback.print_exc() 274 | 275 | return output, returnCode 276 | 277 | def getHostname(os_platform): 278 | """ 279 | Generate and return a hostname 280 | :return: 281 | """ 282 | # Computername 283 | if os_platform == "linux" or os_platform == "macos": 284 | return os.uname()[1] 285 | else: 286 | return os.environ['COMPUTERNAME'] 287 | -------------------------------------------------------------------------------- /lib/lokilogger.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # LOKI Logger 4 | 5 | import sys 6 | import re 7 | from colorama import Fore, Back, Style 8 | from colorama import init 9 | import codecs 10 | import datetime 11 | import traceback 12 | import rfc5424logging 13 | import logging 14 | from logging import handlers 15 | import socket 16 | from .helpers import removeNonAsciiDrop 17 | 18 | __version__ = '0.44.2' 19 | 20 | 21 | # Logger Class ----------------------------------------------------------------- 22 | class LokiLogger: 23 | 24 | STDOUT_CSV = 0 25 | STDOUT_LINE = 1 26 | FILE_CSV = 2 27 | FILE_LINE = 3 28 | SYSLOG_LINE = 4 29 | 30 | no_log_file = False 31 | log_file = "loki.log" 32 | csv = False 33 | hostname = "NOTSET" 34 | alerts = 0 35 | warnings = 0 36 | notices = 0 37 | messagecount = 0 38 | only_relevant = False 39 | remote_logging = False 40 | debug = False 41 | linesep = "\n" 42 | 43 | def __init__(self, no_log_file, log_file, hostname, remote_host, remote_port, syslog_tcp, csv, only_relevant, debug, platform, caller, customformatter=None): 44 | self.version = __version__ 45 | self.no_log_file = no_log_file 46 | self.log_file = log_file 47 | self.hostname = hostname 48 | self.csv = csv 49 | self.only_relevant = only_relevant 50 | self.debug = debug 51 | self.caller = caller 52 | self.CustomFormatter = customformatter 53 | if "windows" in platform.lower(): 54 | self.linesep = "\r\n" 55 | 56 | # Colorization ---------------------------------------------------- 57 | init() 58 | 59 | # Welcome 60 | if not self.csv: 61 | self.print_welcome() 62 | 63 | # Syslog server target 64 | if remote_host: 65 | try: 66 | # Create remote logger 67 | self.remote_logger = logging.getLogger('LOKI') 68 | self.remote_logger.setLevel(logging.DEBUG) 69 | socket_type = socket.SOCK_STREAM if syslog_tcp else socket.SOCK_DGRAM 70 | remote_syslog_handler = rfc5424logging.Rfc5424SysLogHandler(address=(remote_host, remote_port), 71 | facility=handlers.SysLogHandler.LOG_LOCAL3, 72 | socktype=socket_type) 73 | self.remote_logger.addHandler(remote_syslog_handler) 74 | self.remote_logging = True 75 | except Exception as e: 76 | print('Failed to create remote logger: ' + str(e)) 77 | sys.exit(1) 78 | 79 | def log(self, mes_type, module, message): 80 | 81 | if not self.debug and mes_type == "DEBUG": 82 | return 83 | 84 | # Counter 85 | if mes_type == "ALERT": 86 | self.alerts += 1 87 | if mes_type == "WARNING": 88 | self.warnings += 1 89 | if mes_type == "NOTICE": 90 | self.notices += 1 91 | self.messagecount += 1 92 | 93 | if self.only_relevant: 94 | if mes_type not in ('ALERT', 'WARNING'): 95 | return 96 | 97 | # to file 98 | if not self.no_log_file: 99 | self.log_to_file(message, mes_type, module) 100 | 101 | # to stdout 102 | try: 103 | self.log_to_stdout(message, mes_type) 104 | except Exception as e: 105 | print ("Cannot print certain characters to command line - see log file for full unicode encoded log line") 106 | self.log_to_stdout(message, mes_type) 107 | 108 | # to syslog server 109 | if self.remote_logging: 110 | self.log_to_remotesys(message, mes_type, module) 111 | 112 | def Format(self, type, message, *args): 113 | if not self.CustomFormatter: 114 | return message.format(*args) 115 | else: 116 | return self.CustomFormatter(type, message, args) 117 | 118 | def log_to_stdout(self, message, mes_type): 119 | 120 | if self.csv: 121 | print(self.Format(self.STDOUT_CSV, '{0},{1},{2},{3}', getSyslogTimestamp(), self.hostname, mes_type, message)) 122 | 123 | else: 124 | try: 125 | reset_all = Style.NORMAL+Fore.RESET 126 | key_color = Fore.WHITE 127 | base_color = Back.BLACK+Fore.WHITE 128 | high_color = Fore.WHITE+Back.BLACK 129 | 130 | if mes_type == "NOTICE": 131 | base_color = Fore.CYAN+''+Back.BLACK 132 | high_color = Fore.BLACK+''+Back.CYAN 133 | elif mes_type == "INFO": 134 | base_color = Fore.GREEN+''+Back.BLACK 135 | high_color = Fore.BLACK+''+Back.GREEN 136 | elif mes_type == "WARNING": 137 | base_color = Fore.YELLOW+''+Back.BLACK 138 | high_color = Fore.BLACK+''+Back.YELLOW 139 | elif mes_type == "ALERT": 140 | base_color = Fore.RED+''+Back.BLACK 141 | high_color = Fore.BLACK+''+Back.RED 142 | elif mes_type == "DEBUG": 143 | base_color = Fore.WHITE+''+Back.BLACK 144 | high_color = Fore.BLACK+''+Back.WHITE 145 | elif mes_type == "ERROR": 146 | base_color = Fore.MAGENTA+''+Back.BLACK 147 | high_color = Fore.WHITE+''+Back.MAGENTA 148 | elif mes_type == "RESULT": 149 | if "clean" in message.lower(): 150 | high_color = Fore.BLACK+Back.GREEN 151 | base_color = Fore.GREEN+Back.BLACK 152 | elif "suspicious" in message.lower(): 153 | high_color = Fore.BLACK+Back.YELLOW 154 | base_color = Fore.YELLOW+Back.BLACK 155 | else: 156 | high_color = Fore.BLACK+Back.RED 157 | base_color = Fore.RED+Back.BLACK 158 | 159 | # Colorize Type Word at the beginning of the line 160 | type_colorer = re.compile(r'([A-Z]{3,})', re.VERBOSE) 161 | mes_type = type_colorer.sub(high_color+r'[\1]'+base_color, mes_type) 162 | # Break Line before REASONS 163 | linebreaker = re.compile('(MD5:|SHA1:|SHA256:|MATCHES:|FILE:|FIRST_BYTES:|DESCRIPTION:|REASON_[0-9]+)', re.VERBOSE) 164 | message = linebreaker.sub(r'\n\1', message) 165 | # Colorize Key Words 166 | colorer = re.compile('([A-Z_0-9]{2,}:)\s', re.VERBOSE) 167 | message = colorer.sub(key_color+Style.BRIGHT+r'\1 '+base_color+Style.NORMAL, message) 168 | 169 | # Print to console 170 | if mes_type == "RESULT": 171 | res_message = "\b\b%s %s" % (mes_type, message) 172 | print(base_color+' '+res_message+' '+Back.BLACK) 173 | print(Fore.WHITE+' '+Style.NORMAL) 174 | else: 175 | sys.stdout.write("%s%s\b\b%s %s%s%s%s\n" % (reset_all, base_color, mes_type, message, Back.BLACK,Fore.WHITE,Style.NORMAL)) 176 | 177 | except Exception as e: 178 | if self.debug: 179 | traceback.print_exc() 180 | sys.exit(1) 181 | print("Cannot print to cmd line - formatting error") 182 | 183 | def log_to_file(self, message, mes_type, module): 184 | try: 185 | # Write to file 186 | with codecs.open(self.log_file, "a", encoding='utf-8') as logfile: 187 | if self.csv: 188 | logfile.write(self.Format(self.FILE_CSV, u"{0},{1},{2},{3},{4}{5}", getSyslogTimestamp(), self.hostname, mes_type, module, message, self.linesep)) 189 | else: 190 | logfile.write(self.Format(self.FILE_LINE, u"{0} {1} LOKI: {2}: MODULE: {3} MESSAGE: {4}{5}", getSyslogTimestamp(), self.hostname, mes_type.title(), module, message, self.linesep)) 191 | except Exception as e: 192 | if self.debug: 193 | traceback.print_exc() 194 | sys.exit(1) 195 | print("Cannot print line to log file {0}".format(self.log_file)) 196 | 197 | def log_to_remotesys(self, message, mes_type, module): 198 | # Preparing the message 199 | syslog_message = self.Format(self.SYSLOG_LINE, "LOKI: {0}: MODULE: {1} MESSAGE: {2}", mes_type.title(), module, message) 200 | try: 201 | # Mapping LOKI's levels to the syslog levels 202 | if mes_type == "NOTICE": 203 | self.remote_logger.info(syslog_message, extra={'msgid': str(self.messagecount)}) 204 | elif mes_type == "INFO": 205 | self.remote_logger.info(syslog_message, extra={'msgid': str(self.messagecount)}) 206 | elif mes_type == "WARNING": 207 | self.remote_logger.warning(syslog_message, extra={'msgid': str(self.messagecount)}) 208 | elif mes_type == "ALERT": 209 | self.remote_logger.critical(syslog_message, extra={'msgid': str(self.messagecount)}) 210 | elif mes_type == "DEBUG": 211 | self.remote_logger.debug(syslog_message, extra={'msgid': str(self.messagecount)}) 212 | elif mes_type == "ERROR": 213 | self.remote_logger.error(syslog_message, extra={'msgid': str(self.messagecount)}) 214 | except Exception as e: 215 | if self.debug: 216 | traceback.print_exc() 217 | sys.exit(1) 218 | print("Error while logging to remote syslog server ERROR: %s" % str(e)) 219 | 220 | def print_welcome(self): 221 | 222 | if self.caller == 'main': 223 | print(str(Back.WHITE)) 224 | print(" ".ljust(79) + Back.BLACK + Style.BRIGHT) 225 | 226 | print(" __ ____ __ ______ ") 227 | print(" / / / __ \\/ //_/ _/ ") 228 | print(" / /__/ /_/ / ,< _/ / ") 229 | print(" /____/\\____/_/|_/___/ ") 230 | print(" YARA and IOC Scanner ") 231 | print(" ") 232 | print(" by Florian Roth, GNU General Public License") 233 | print(" version %s (Python 3 release)" % __version__) 234 | print(" ") 235 | print(" DISCLAIMER - USE AT YOUR OWN RISK") 236 | print(str(Back.WHITE)) 237 | print(" ".ljust(79) + Back.BLACK + Fore.GREEN) 238 | print(Fore.WHITE+''+Back.BLACK) 239 | 240 | else: 241 | print(" ") 242 | print(Back.GREEN + " ".ljust(79) + Back.BLACK + Fore.GREEN) 243 | 244 | print(" ") 245 | print(" LOKI UPGRADER ") 246 | 247 | print(" ") 248 | print(Back.GREEN + " ".ljust(79) + Back.BLACK) 249 | print(Fore.WHITE + '' + Back.BLACK) 250 | 251 | 252 | def getSyslogTimestamp(): 253 | date_obj = datetime.datetime.utcnow() 254 | date_str = date_obj.strftime("%Y%m%dT%H:%M:%SZ") 255 | return date_str 256 | -------------------------------------------------------------------------------- /lib/doublepulsar.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # Double Pulsar Checks 4 | # https://github.com/countercept/doublepulsar-detection-script/blob/master/detect_doublepulsar_rdp.py 5 | # Author: Luke Jennings (luke.jennings@countercept.com - @jukelennings) 6 | # XOR Key calculation provided by https://github.com/FireFart 7 | # 8 | # Modified version that allows to be used as library 9 | # 10 | # Copyright (c) 2017, Countercept (https://countercept.com) 11 | # 12 | # Redistribution and use in source and binary forms, with or without 13 | # modification, are permitted provided that the following conditions are 14 | # met: 15 | # 16 | # 1. Redistributions of source code must retain the above copyright 17 | # notice, this list of conditions and the following disclaimer. 18 | # 19 | # 2. Redistributions in binary form must reproduce the above copyright 20 | # notice, this list of conditions and the following disclaimer in the 21 | # documentation and/or other materials provided with the distribution. 22 | # 23 | # 3. Neither the name of the copyright holder nor the names of its 24 | # contributors may be used to endorse or promote products derived from 25 | # this software without specific prior written permission. 26 | # 27 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 28 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 29 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 30 | # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 31 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 32 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 33 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 34 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 35 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 36 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 37 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 38 | 39 | import binascii 40 | import socket 41 | import ssl 42 | import struct 43 | 44 | class DoublePulsar(object): 45 | 46 | def __init__(self, ip="127.0.0.1", timeout=None, verbose=False): 47 | self.ip = ip 48 | self.timeout = timeout 49 | self.verbose = verbose 50 | 51 | # RDP 52 | # Packets 53 | self.ssl_negotiation_request = binascii.unhexlify("030000130ee000000000000100080001000000") 54 | self.non_ssl_negotiation_request = binascii.unhexlify("030000130ee000000000000100080000000000") 55 | self.non_ssl_client_data = binascii.unhexlify( 56 | "030001ac02f0807f658201a00401010401010101ff30190201220201020201000201010201000201010202ffff020102301902010102010102010102010102010002010102020420020102301c0202ffff0202fc170202ffff0201010201000201010202ffff0201020482013f000500147c00018136000800100001c00044756361812801c0d800040008000005000401ca03aa09080000b01d0000000000000000000000000000000000000000000000000000000000000000000007000000000000000c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001ca01000000000018000f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000004c00c00110000000000000002c00c001b0000000000000003c0380004000000726470647200000000008080726470736e640000000000c0647264796e766300000080c0636c6970726472000000a0c0") 57 | self.ssl_client_data = binascii.unhexlify( 58 | "030001ac02f0807f658201a00401010401010101ff30190201220201020201000201010201000201010202ffff020102301902010102010102010102010102010002010102020420020102301c0202ffff0202fc170202ffff0201010201000201010202ffff0201020482013f000500147c00018136000800100001c00044756361812801c0d800040008000005000401ca03aa09080000b01d0000000000000000000000000000000000000000000000000000000000000000000007000000000000000c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001ca01000000000018000f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000100000004c00c00110000000000000002c00c001b0000000000000003c0380004000000726470647200000000008080726470736e640000000000c0647264796e766300000080c0636c6970726472000000a0c0") 59 | self.ping_packet = binascii.unhexlify("0300000e02f0803c443728190200") 60 | 61 | # SMB 62 | # Packets 63 | self.negotiate_protocol_request = binascii.unhexlify( 64 | "00000085ff534d4272000000001853c00000000000000000000000000000fffe00004000006200025043204e4554574f524b2050524f4752414d20312e3000024c414e4d414e312e30000257696e646f777320666f7220576f726b67726f75707320332e316100024c4d312e325830303200024c414e4d414e322e3100024e54204c4d20302e313200") 65 | self.session_setup_request = binascii.unhexlify( 66 | "00000088ff534d4273000000001807c00000000000000000000000000000fffe000040000dff00880004110a000000000000000100000000000000d40000004b000000000000570069006e0064006f007700730020003200300030003000200032003100390035000000570069006e0064006f007700730020003200300030003000200035002e0030000000") 67 | self.tree_connect_request = binascii.unhexlify( 68 | "00000060ff534d4275000000001807c00000000000000000000000000000fffe0008400004ff006000080001003500005c005c003100390032002e003100360038002e003100370035002e003100320038005c00490050004300240000003f3f3f3f3f00") 69 | self.trans2_session_setup = binascii.unhexlify( 70 | "0000004eff534d4232000000001807c00000000000000000000000000008fffe000841000f0c0000000100000000000000a6d9a40000000c00420000004e0001000e000d0000000000000000000000000000") 71 | 72 | def check_ip_smb(self): 73 | 74 | # Connect to socket 75 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 76 | s.settimeout(float(self.timeout) if self.timeout else None) 77 | host = self.ip 78 | port = 445 79 | s.connect((host, port)) 80 | 81 | # Send/receive negotiate protocol request 82 | if self.verbose: 83 | print("Sending negotiation protocol request") 84 | s.send(self.negotiate_protocol_request) 85 | s.recv(1024) 86 | 87 | # Send/receive session setup request 88 | if self.verbose: 89 | print("Sending session setup request") 90 | s.send(self.session_setup_request) 91 | session_setup_response = s.recv(1024) 92 | 93 | # Extract user ID from session setup response 94 | user_id = session_setup_response[32:34] 95 | if self.verbose: 96 | print("User ID = %s" % struct.unpack("= 19 and negotiation_response[11] == "\x02" and negotiation_response[15] == "\x01": 157 | if self.verbose: 158 | print("Server chose to use SSL - negotiating SSL connection") 159 | sock = ssl.wrap_socket(s) 160 | s = sock 161 | 162 | # Send/receive ssl client data 163 | if self.verbose: 164 | print("Sending SSL client data") 165 | s.send(self.ssl_client_data) 166 | s.recv(1024) 167 | 168 | # Server explicitly refused SSL 169 | elif len(negotiation_response) >= 19 and negotiation_response[11] == "\x03" and negotiation_response[15] == "\x02": 170 | if self.verbose: 171 | print("Server explicitly refused SSL, reconnecting") 172 | 173 | # Re-connect 174 | s.close() 175 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 176 | s.settimeout(float(self.timeout) if self.timeout else None) 177 | s.connect((host, port)) 178 | 179 | # Send/receive non-ssl negotiation request 180 | if self.verbose: 181 | print("Sending non-ssl negotiation request") 182 | s.send(self.non_ssl_negotiation_request) 183 | s.recv(1024) 184 | 185 | # Server requires NLA which implant does not support 186 | elif len(negotiation_response) >= 19 and negotiation_response[11] == "\x03" and negotiation_response[15] == "\x05": 187 | s.close() 188 | return False, "Server requires NLA, which DOUBLEPULSAR does not support" 189 | 190 | # Carry on non-ssl 191 | else: 192 | # Send/receive non-ssl client data 193 | if self.verbose: 194 | print("Sending client data") 195 | s.send(self.non_ssl_client_data) 196 | s.recv(1024) 197 | 198 | # Send/receive ping 199 | if self.verbose: 200 | print("Sending ping packet") 201 | s.send(self.ping_packet) 202 | 203 | # Non-infected machines terminate connection, infected send a response 204 | try: 205 | ping_response = s.recv(1024) 206 | 207 | if len(ping_response) == 288: 208 | return True, "DoublePulsar SMB implant detected" 209 | else: 210 | return False, "Status Unknown - Response received but length was %d not 288" % (len(ping_response)) 211 | 212 | s.close() 213 | except socket.error as e: 214 | return False, "No presence of DOUBLEPULSAR RDP implant" 215 | 216 | 217 | def calculate_doublepulsar_xor_key(s): 218 | x = (2 * s ^ (((s & 0xff00 | (s << 16)) << 8) | (((s >> 16) | s & 0xff0000) >> 8))) 219 | x = x & 0xffffffff # this line was added just to truncate to 32 bits 220 | return x -------------------------------------------------------------------------------- /loki-upgrader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: iso-8859-1 -*- 3 | # -*- coding: utf-8 -*- 4 | # 5 | # LOKI Upgrader 6 | try: 7 | from urllib2 import urlopen 8 | except ImportError: 9 | from urllib.request import urlopen #For python 3.5 10 | import json 11 | import zipfile 12 | import shutil 13 | import io 14 | import os 15 | import argparse 16 | import traceback 17 | from sys import platform as _platform 18 | 19 | # Win32 Imports 20 | if _platform == "win32": 21 | try: 22 | import wmi 23 | import win32api 24 | from win32com.shell import shell 25 | except Exception as e: 26 | platform = "linux" # crazy guess 27 | 28 | 29 | from lib.lokilogger import * 30 | 31 | # Platform 32 | platform = "" 33 | if _platform == "linux" or _platform == "linux2": 34 | platform = "linux" 35 | elif _platform == "darwin": 36 | platform = "macos" 37 | elif _platform == "win32": 38 | platform = "windows" 39 | 40 | 41 | class LOKIUpdater(object): 42 | 43 | # Incompatible signatures 44 | INCOMPATIBLE_RULES = [] 45 | 46 | UPDATE_URL_SIGS = [ 47 | "https://github.com/Neo23x0/signature-base/archive/master.zip", 48 | "https://github.com/reversinglabs/reversinglabs-yara-rules/archive/develop.zip" 49 | ] 50 | 51 | UPDATE_URL_LOKI = "https://api.github.com/repos/Neo23x0/Loki/releases/latest" 52 | 53 | def __init__(self, debug, logger, application_path): 54 | self.debug = debug 55 | self.logger = logger 56 | self.application_path = application_path 57 | 58 | def update_signatures(self, clean=False): 59 | try: 60 | for sig_url in self.UPDATE_URL_SIGS: 61 | # Downloading current repository 62 | try: 63 | self.logger.log("INFO", "Upgrader", "Downloading %s ..." % sig_url) 64 | response = urlopen(sig_url) 65 | except Exception as e: 66 | if self.debug: 67 | traceback.print_exc() 68 | self.logger.log("ERROR", "Upgrader", "Error downloading the signature database - " 69 | "check your Internet connection") 70 | sys.exit(1) 71 | 72 | # Preparations 73 | try: 74 | sigDir = os.path.join(self.application_path, os.path.abspath('signature-base/')) 75 | if clean: 76 | self.logger.log("INFO", "Upgrader", "Cleaning directory '%s'" % sigDir) 77 | shutil.rmtree(sigDir) 78 | for outDir in ['', 'iocs', 'yara', 'misc']: 79 | fullOutDir = os.path.join(sigDir, outDir) 80 | if not os.path.exists(fullOutDir): 81 | os.makedirs(fullOutDir) 82 | except Exception as e: 83 | if self.debug: 84 | traceback.print_exc() 85 | self.logger.log("ERROR", "Upgrader", "Error while creating the signature-base directories") 86 | sys.exit(1) 87 | 88 | # Read ZIP file 89 | try: 90 | zipUpdate = zipfile.ZipFile(io.BytesIO(response.read())) 91 | for zipFilePath in zipUpdate.namelist(): 92 | sigName = os.path.basename(zipFilePath) 93 | if zipFilePath.endswith("/"): 94 | continue 95 | # Skip incompatible rules 96 | skip = False 97 | for incompatible_rule in self.INCOMPATIBLE_RULES: 98 | if sigName.endswith(incompatible_rule): 99 | self.logger.log("NOTICE", "Upgrader", "Skipping incompatible rule %s" % sigName) 100 | skip = True 101 | if skip: 102 | continue 103 | # Extract the rules 104 | self.logger.log("DEBUG", "Upgrader", "Extracting %s ..." % zipFilePath) 105 | if "/iocs/" in zipFilePath and zipFilePath.endswith(".txt"): 106 | targetFile = os.path.join(sigDir, "iocs", sigName) 107 | elif "/yara/" in zipFilePath and zipFilePath.endswith(".yar"): 108 | targetFile = os.path.join(sigDir, "yara", sigName) 109 | elif "/misc/" in zipFilePath and zipFilePath.endswith(".txt"): 110 | targetFile = os.path.join(sigDir, "misc", sigName) 111 | elif zipFilePath.endswith(".yara"): 112 | targetFile = os.path.join(sigDir, "yara", sigName) 113 | else: 114 | continue 115 | 116 | # New file 117 | if not os.path.exists(targetFile): 118 | self.logger.log("INFO", "Upgrader", "New signature file: %s" % sigName) 119 | 120 | # Extract file 121 | source = zipUpdate.open(zipFilePath) 122 | target = open(targetFile, "wb") 123 | with source, target: 124 | shutil.copyfileobj(source, target) 125 | target.close() 126 | source.close() 127 | 128 | except Exception as e: 129 | if self.debug: 130 | traceback.print_exc() 131 | self.logger.log("ERROR", "Upgrader", "Error while extracting the signature files from the download " 132 | "package") 133 | sys.exit(1) 134 | 135 | except Exception as e: 136 | if self.debug: 137 | traceback.print_exc() 138 | return False 139 | return True 140 | 141 | 142 | def update_loki(self): 143 | try: 144 | 145 | # Downloading the info for latest release 146 | try: 147 | self.logger.log("INFO", "Upgrader", "Checking location of latest release %s ..." % self.UPDATE_URL_LOKI) 148 | response_info = urlopen(self.UPDATE_URL_LOKI) 149 | data = json.load(response_info) 150 | # Get download URL 151 | zip_url = data['assets'][0]['browser_download_url'] 152 | self.logger.log("INFO", "Upgrader", "Downloading latest release %s ..." % zip_url) 153 | response_zip = urlopen(zip_url) 154 | except Exception as e: 155 | if self.debug: 156 | traceback.print_exc() 157 | self.logger.log("ERROR", "Upgrader", "Error downloading the loki update - check your Internet connection") 158 | sys.exit(1) 159 | 160 | # Read ZIP file 161 | try: 162 | zipUpdate = zipfile.ZipFile(io.BytesIO(response_zip.read())) 163 | for zipFilePath in zipUpdate.namelist(): 164 | if zipFilePath.endswith("/") or "/config/" in zipFilePath or "/loki-upgrader.exe" in zipFilePath: 165 | continue 166 | 167 | source = zipUpdate.open(zipFilePath) 168 | targetFile = "/".join(zipFilePath.split("/")[1:]) 169 | 170 | self.logger.log("INFO", "Upgrader", "Extracting %s ..." %targetFile) 171 | 172 | try: 173 | # Create file if not present 174 | if not os.path.exists(os.path.dirname(targetFile)): 175 | if os.path.dirname(targetFile) != '': 176 | os.makedirs(os.path.dirname(targetFile)) 177 | except Exception as e: 178 | if self.debug: 179 | self.logger.log("DEBUG", "Upgrader", "Cannot create dir name '%s'" % os.path.dirname(targetFile)) 180 | traceback.print_exc() 181 | 182 | try: 183 | # Create target file 184 | target = open(targetFile, "wb") 185 | with source, target: 186 | shutil.copyfileobj(source, target) 187 | if self.debug: 188 | self.logger.log("DEBUG", "Upgrader", "Successfully extracted '%s'" % targetFile) 189 | target.close() 190 | except Exception as e: 191 | self.logger.log("ERROR", "Upgrader", "Cannot extract '%s'" % targetFile) 192 | if self.debug: 193 | traceback.print_exc() 194 | 195 | except Exception as e: 196 | if self.debug: 197 | traceback.print_exc() 198 | self.logger.log("ERROR", "Upgrader", 199 | "Error while extracting the signature files from the download package") 200 | sys.exit(1) 201 | 202 | except Exception as e: 203 | if self.debug: 204 | traceback.print_exc() 205 | return False 206 | return True 207 | 208 | 209 | def get_application_path(): 210 | try: 211 | if getattr(sys, 'frozen', False): 212 | application_path = os.path.dirname(os.path.realpath(sys.executable)) 213 | else: 214 | application_path = os.path.dirname(os.path.realpath(__file__)) 215 | if "~" in application_path and platform == "windows": 216 | # print "Trying to translate" 217 | # print application_path 218 | application_path = win32api.GetLongPathName(application_path) 219 | #if args.debug: 220 | # logger.log("DEBUG", "Init", "Application Path: %s" % application_path) 221 | return application_path 222 | except Exception as e: 223 | print("Error while evaluation of application path") 224 | traceback.print_exc() 225 | 226 | 227 | if __name__ == '__main__': 228 | 229 | # Parse Arguments 230 | parser = argparse.ArgumentParser(description='Loki - Upgrader') 231 | parser.add_argument('-l', help='Log file', metavar='log-file', default='loki-upgrade.log') 232 | parser.add_argument('--sigsonly', action='store_true', help='Update the signatures only', default=False) 233 | parser.add_argument('--progonly', action='store_true', help='Update the program files only', default=False) 234 | parser.add_argument('--nolog', action='store_true', help='Don\'t write a local log file', default=False) 235 | parser.add_argument('--debug', action='store_true', default=False, help='Debug output') 236 | parser.add_argument('--clean', action='store_true', default=False, help='Clean up the signature directory and get ' 237 | 'a fresh set') 238 | parser.add_argument('--detached', action='store_true', default=False, help=argparse.SUPPRESS) 239 | 240 | args = parser.parse_args() 241 | 242 | # Computername 243 | if platform == "windows": 244 | t_hostname = os.environ['COMPUTERNAME'] 245 | else: 246 | t_hostname = os.uname()[1] 247 | 248 | # Logger 249 | logger = LokiLogger(args.nolog, args.l, t_hostname, '', '', False, False, False, args.debug, platform=platform, caller='upgrader') 250 | 251 | # Update LOKI 252 | updater = LOKIUpdater(args.debug, logger, get_application_path()) 253 | 254 | if not args.sigsonly: 255 | logger.log("INFO", "Upgrader", "Updating LOKI ...") 256 | updater.update_loki() 257 | if not args.progonly: 258 | logger.log("INFO", "Upgrader", "Updating Signatures ...") 259 | updater.update_signatures(args.clean) 260 | 261 | logger.log("INFO", "Upgrader", "Update complete") 262 | 263 | if args.detached: 264 | logger.log("INFO", "Upgrader", "Press any key to return ...") 265 | 266 | sys.exit(0) 267 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Actively Maintained](https://img.shields.io/badge/Maintenance%20Level-Actively%20Maintained-green.svg)](https://gist.github.com/cheerfulstoic/d107229326a01ff0f333a1d3476e068d) 2 | 3 | ![Logo](/lokiicon.jpg) 4 | # Loki - Simple IOC and YARA Scanner 5 | 6 | Scanner for Simple Indicators of Compromise 7 | 8 | Detection is based on four detection methods: 9 | 10 | 1. File Name IOC 11 | Regex match on full file path/name 12 | 13 | 2. Yara Rule Check 14 | Yara signature match on file data and process memory 15 | 16 | 3. Hash Check 17 | Compares known malicious hashes (MD5, SHA1, SHA256) with scanned files 18 | 19 | 4. C2 Back Connect Check 20 | Compares process connection endpoints with C2 IOCs (new since version v.10) 21 | 22 | Additional Checks: 23 | 24 | 1. Regin filesystem check (via --reginfs) 25 | 2. Process anomaly check (based on [Sysforensics](http://goo.gl/P99QZQ) 26 | 3. SWF decompressed scan (new since version v0.8) 27 | 4. SAM dump check 28 | 29 | The Windows binary is compiled with PyInstaller and should run as x86 application on both x86 and x64 based systems. 30 | 31 | ## How-To Run LOKI and Analyse the Reports 32 | 33 | ### Run 34 | 35 | - Download the newest version of LOKI from the [releases](https://github.com/Neo23x0/Loki/releases) section 36 | - Extract the program package 37 | - Run loki-upgrader.exe on system with Internet access to retrieve the newest signatures 38 | - Bring the program folder to a target system that should be scanned: removable media, network share, folder on target system 39 | - Open a command line "cmd.exe" as Administrator and run it from there (you can also run LOKI without administrative privileges but some checks will be disabled and relevant objects on disk will not be accessible) 40 | 41 | ### Reports 42 | 43 | - The resulting report will show a GREEN, YELLOW or RED result line. 44 | - Please analyse the findings yourself by: 45 | 1. uploading non-confidential samples to Virustotal.com 46 | 2. Search the web for the filename 47 | 3. Search the web for keywords from the rule name (e.g. EQUATIONGroupMalware_1 > search for "Equation Group") 48 | 4. Search the web for the MD5 hash of the sample 49 | - Please report back false positives via the "Issues" section, which is accessible via the right sidebar (mention the false positive indicator like a hash and/or filename and the rule name that triggered) 50 | 51 | ## Requirements 52 | 53 | No requirements if you use the compiled EXE. 54 | 55 | If you want to build it yourself: 56 | 57 | - [yara](https://github.com/VirusTotal/yara-python/releases) : It's recommended to use the most recent version of the compiled packages for Windows (x86) - Download it from here: https://github.com/VirusTotal/yara-python/releases 58 | - [colorama](https://pypi.python.org/pypi/colorama) : to color it up 59 | - [psutil](https://pypi.python.org/pypi/psutil) : process checks 60 | - [pywin32](http://sourceforge.net/projects/pywin32/) : path conversions (PyInstaller [issue](https://github.com/pyinstaller/pyinstaller/issues/1282); Windows only) 61 | 62 | # Usage 63 | 64 | usage: loki.py [-h] [-p path] [-s kilobyte] [-l log-file] [-r remote-loghost] 65 | [-t remote-syslog-port] [-a alert-level] [-w warning-level] 66 | [-n notice-level] [--allhds] [--alldrives] [--printall] 67 | [--allreasons] [--noprocscan] [--nofilescan] [--vulnchecks] 68 | [--nolevcheck] [--scriptanalysis] [--rootkit] [--noindicator] 69 | [--dontwait] [--intense] [--csv] [--onlyrelevant] [--nolog] 70 | [--update] [--debug] [--maxworkingset MAXWORKINGSET] 71 | [--syslogtcp] [--logfolder log-folder] [--nopesieve] 72 | [--pesieveshellc] [--nolisten] 73 | [--excludeprocess EXCLUDEPROCESS] [--force] 74 | 75 | Loki - Simple IOC Scanner 76 | 77 | optional arguments: 78 | -h, --help show this help message and exit 79 | -p path Path to scan 80 | -s kilobyte Maximum file size to check in KB (default 5000 KB) 81 | -l log-file Log file 82 | -r remote-loghost Remote syslog system 83 | -t remote-syslog-port 84 | Remote syslog port 85 | -a alert-level Alert score 86 | -w warning-level Warning score 87 | -n notice-level Notice score 88 | --allhds Scan all local hard drives (Windows only) 89 | --alldrives Scan all drives (including network drives and 90 | removable media) 91 | --printall Print all files that are scanned 92 | --allreasons Print all reasons that caused the score 93 | --noprocscan Skip the process scan 94 | --nofilescan Skip the file scan 95 | --vulnchecks Run the vulnerability checks 96 | --nolevcheck Skip the Levenshtein distance check 97 | --scriptanalysis Statistical analysis for scripts to detect obfuscated 98 | code (beta) 99 | --rootkit Skip the rootkit check 100 | --noindicator Do not show a progress indicator 101 | --dontwait Do not wait on exit 102 | --intense Intense scan mode (also scan unknown file types and 103 | all extensions) 104 | --csv Write CSV log format to STDOUT (machine processing) 105 | --onlyrelevant Only print warnings or alerts 106 | --nolog Don't write a local log file 107 | --update Update the signatures from the "signature-base" sub 108 | repository 109 | --debug Debug output 110 | --maxworkingset MAXWORKINGSET 111 | Maximum working set size of processes to scan (in MB, 112 | default 100 MB) 113 | --syslogtcp Use TCP instead of UDP for syslog logging 114 | --logfolder log-folder 115 | Folder to use for logging when log file is not 116 | specified 117 | --nopesieve Do not perform pe-sieve scans 118 | --pesieveshellc Perform pe-sieve shellcode scan 119 | --nolisten Dot not show listening connections 120 | --excludeprocess EXCLUDEPROCESS 121 | Specify an executable name to exclude from scans, can 122 | be used multiple times 123 | --force Force the scan on a certain folder (even if excluded 124 | with hard exclude in LOKI's code 125 | 126 | 127 | ## Signature and IOCs 128 | 129 | Since version 0.15 the Yara signatures reside in the sub-repository [signature-base](https://github.com/Neo23x0/signature-base). You will not get the sub-repository by downloading the LOKI as ZIP file. It will be included when you clone the repository. 130 | 131 | The IOC files for hashes and filenames are stored in the './signature-base/iocs' folder. All '.yar' files placed in the './signature-base/yara' folder will be initialized together with the rule set that is already included. Use the 'score' value to define the level of the message upon a signature match. 132 | 133 | You can add hash, c2 and filename IOCs by adding files to the './signature-base/iocs' subfolder. All hash IOCs and filename IOC files must be in the format used by LOKI (see the default files). The files must have the strings "hash", "filename" or "c2" in their name to get pulled during initialization. 134 | 135 | For Hash IOCs (divided by newline; hash type is detected automatically) 136 | ``` 137 | Hash;Description [Reference] 138 | ``` 139 | 140 | For Filename IOCs (divided by newline) 141 | ``` 142 | # (optional) Description [Reference] 143 | Filename as Regex[;Score as integer[;False-positive as Regex]] 144 | ``` 145 | 146 | # User-Defined Scan Excludes 147 | 148 | Since version v0.16.2 LOKI supports the definition of user-defined excludes via "excludes.cfg" in the new "./config" folder. Each line represents a regular expression that gets applied to the full file path during the directory walk. This way you can exclude certain directories regardless of their drive name, file extensions in certain folders and all files and directories that belong to a product that is sensitive to antivirus scanning. 149 | 150 | The '''exclude.cfg''' looks like this: 151 | 152 | # Excluded directories 153 | # 154 | # - add directories you want to exclude from the scan 155 | # - double escape back slashes 156 | # - values are case-insensitive 157 | # - remember to use back slashes on Windows and slashes on Linux / Unix / OSX 158 | # - each line contains a regex that matches somewhere in the full path (case insensitive) 159 | # e.g.: 160 | # Regex: \\System32\\ 161 | # Matches C:\Windows\System32\cmd.exe 162 | # 163 | # Regex: /var/log/[^/]+\.log 164 | # Matches: /var/log/test.log 165 | # Not Matches: /var/log/test.gz 166 | # 167 | 168 | # Useful examples 169 | \\Ntfrs\\ 170 | \\Ntds\\ 171 | \\EDB[^\.]+\.log 172 | Sysvol\\Staging\\Nntfrs_cmp 173 | \\System Volume Information\\DFSR 174 | 175 | # Screenshots 176 | 177 | Loki Scan 178 | 179 | ![Screen](/screens/lokiscan2.png) 180 | 181 | Regin Matches 182 | 183 | ![Screen](/screens/lokiscan1.png) 184 | 185 | Regin False Positives 186 | 187 | ![Screen](/screens/lokiscan3.png) 188 | 189 | Hash based IOCs 190 | 191 | ![Screen](/screens/lokiconf1.png) 192 | 193 | File Name based IOCs 194 | 195 | ![Screen](/screens/lokiconf2.png) 196 | 197 | Generated log file 198 | 199 | ![Screen](/screens/lokilog1.png) 200 | 201 | # Contact 202 | 203 | LOKI scanner on our company homepage 204 | [https://www.nextron-systems.com/loki/](https://www.nextron-systems.com/loki/) 205 | 206 | Twitter 207 | [@cyb3rOps](https://twitter.com/Cyb3rOps) 208 | [@thor_scanner](https://twitter.com/thor_scanner) 209 | 210 | If you are interested in a corporate solution for APT scanning, check out Loki's big brother [THOR](https://www.nextron-systems.com/thor/). 211 | 212 | # Compile the Scanner 213 | 214 | Download [PyInstaller](https://github.com/pyinstaller/pyinstaller/releases/), switch to the pyinstaller program directory and execute: 215 | 216 | python ./pyinstaller.py -F C:\path\to\loki.py 217 | 218 | This will create a `loki.exe` in the subfolder `./loki/dist`. 219 | 220 | ## Pro Tip (optional) 221 | 222 | To include the msvcr100.dll to improve the target os compatibility change the line in the file `./loki/loki.spec` that contains `a.binaries,` to the following: 223 | 224 | a.binaries + [('msvcr100.dll', 'C:\Windows\System32\msvcr100.dll', 'BINARY')], 225 | 226 | # Use LOKI on Mac OS X 227 | 228 | - Download Yara sources from [here](https://github.com/VirusTotal/yara/releases) 229 | - Change to folder ```yara-python``` 230 | - Run ```python setup.py install``` 231 | - Also install the requirement mentioned above by ```sudo pip install colorama``` 232 | 233 | # Antivirus - False Positives 234 | 235 | The compiled scanner may be detected by antivirus engines. This is caused by the fact that the scanner is a compiled python script that implement some file system and process scanning features that are also used in compiled malware code. 236 | 237 | If you don't trust the compiled executable, please compile it yourself. 238 | 239 | # License 240 | 241 | Loki - Simple IOC Scanner 242 | Copyright (c) 2015 Florian Roth 243 | 244 | This program is free software: you can redistribute it and/or modify 245 | it under the terms of the GNU General Public License as published by 246 | the Free Software Foundation, either version 3 of the License, or 247 | (at your option) any later version. 248 | 249 | This program is distributed in the hope that it will be useful, 250 | but WITHOUT ANY WARRANTY; without even the implied warranty of 251 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 252 | GNU General Public License for more details. 253 | 254 | You should have received a copy of the GNU General Public License 255 | along with this program. If not, see [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/) 256 | -------------------------------------------------------------------------------- /tools/vt-checker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | """Checks Hashes read from an input file on Virustotal""" 3 | from __future__ import print_function 4 | 5 | __AUTHOR__ = 'Florian Roth' 6 | __VERSION__ = "0.10 September 2017" 7 | 8 | """ 9 | Modified by Hannah Ward: clean up, removal of simplejson, urllib2 with requests 10 | 11 | Install dependencies with: 12 | pip install requests bs4 colorama 13 | """ 14 | 15 | import requests 16 | import time 17 | import re 18 | import os 19 | import signal 20 | import sys 21 | import pickle 22 | from bs4 import BeautifulSoup 23 | import traceback 24 | import argparse 25 | from colorama import init, Fore, Back, Style 26 | 27 | URL = r'https://www.virustotal.com/vtapi/v2/file/report' 28 | VENDORS = ['Microsoft', 'Kaspersky', 'McAfee', 'CrowdStrike', 'TrendMicro', 29 | 'ESET-NOD32', 'Symantec', 'F-Secure', 'Sophos', 'GData'] 30 | API_KEY = '-' 31 | WAIT_TIME = 15 # Public API allows 4 request per minute, so we wait 15 secs by default 32 | 33 | 34 | def fetch_hash(line): 35 | pattern = r'(? 0: 38 | hash = hash_search[-1] 39 | rest = ' '.join(re.sub('({0}|;|,|:)'.format(hash), ' ', line).strip().split()) 40 | 41 | return hash, rest 42 | return '', '' 43 | 44 | 45 | def print_highlighted(line, hl_color=Back.WHITE): 46 | """ 47 | Print a highlighted line 48 | """ 49 | # Tags 50 | colorer = re.compile('(HARMLESS|SIGNED|MS_SOFTWARE_CATALOGUE)', re.VERBOSE) 51 | line = colorer.sub(Fore.BLACK + Back.GREEN + r'\1' + Style.RESET_ALL + ' ', line) 52 | colorer = re.compile('(SIG_REVOKED)', re.VERBOSE) 53 | line = colorer.sub(Fore.BLACK + Back.RED + r'\1' + Style.RESET_ALL + ' ', line) 54 | colorer = re.compile('(SIG_EXPIRED)', re.VERBOSE) 55 | line = colorer.sub(Fore.BLACK + Back.YELLOW + r'\1' + Style.RESET_ALL + ' ', line) 56 | # Extras 57 | colorer = re.compile('(\[!\])', re.VERBOSE) 58 | line = colorer.sub(Fore.BLACK + Back.CYAN + r'\1' + Style.RESET_ALL + ' ', line) 59 | # Standard 60 | colorer = re.compile('([A-Z_]{2,}:)\s', re.VERBOSE) 61 | line = colorer.sub(Fore.BLACK + hl_color + r'\1' + Style.RESET_ALL + ' ', line) 62 | print(line) 63 | 64 | 65 | def process_permalink(url, debug=False): 66 | """ 67 | Requests the HTML page for the sample and extracts other useful data 68 | that is not included in the public API 69 | """ 70 | headers = {'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', 71 | 'Referrer': 'https://www.virustotal.com/en/'} 72 | info = {'filenames': ['-'], 'firstsubmission': '-', 'harmless': False, 'signed': False, 'revoked': False, 73 | 'expired': False, 'mssoft': False, 'imphash': '-', 'filetype': '-'} 74 | try: 75 | source_code = requests.get(url, headers=headers) 76 | # Extract info from source code 77 | soup = BeautifulSoup(source_code.text, 'html.parser') 78 | # Get file names 79 | elements = soup.find_all('td') 80 | for i, row in enumerate(elements): 81 | text = row.text.strip() 82 | if text == "File names": 83 | file_names = elements[i + 1].text.strip().split("\n") 84 | info['filenames'] = filter(None, map(lambda file: file.strip(), file_names)) 85 | # Get file names 86 | elements = soup.find_all('div') 87 | for i, row in enumerate(elements): 88 | text = row.text.strip() 89 | if text.startswith('File type'): 90 | info['filetype'] = elements[i].text[10:].strip() 91 | # Get additional information 92 | elements = soup.findAll("div", {"class": "enum"}) 93 | for i, row in enumerate(elements): 94 | text = row.text.strip() 95 | if 'First submission' in text: 96 | first_submission_raw = elements[i].text.strip().split("\n") 97 | info['firstsubmission'] = first_submission_raw[1].strip() 98 | if 'imphash' in text: 99 | info['imphash'] = elements[i].text.strip().split("\n")[-1].strip() 100 | # Harmless 101 | if "Probably harmless!" in source_code: 102 | info['harmless'] = True 103 | # Signed 104 | if "Signed file, verified signature" in source_code: 105 | info['signed'] = True 106 | # Revoked 107 | if "revoked by its issuer" in source_code: 108 | info['revoked'] = True 109 | # Expired 110 | if "Expired certificate" in source_code: 111 | info['expired'] = True 112 | # Microsoft Software 113 | if "This file belongs to the Microsoft Corporation software catalogue." in source_code: 114 | info['mssoft'] = True 115 | except Exception as e: 116 | if debug: 117 | traceback.print_exc() 118 | finally: 119 | # Return the info dictionary 120 | return info 121 | 122 | 123 | def saveCache(cache, fileName): 124 | """ 125 | Saves the cache database as pickle dump to a file 126 | :param cache: 127 | :param fileName: 128 | :return: 129 | """ 130 | with open(fileName, 'wb') as fh: 131 | pickle.dump(cache, fh, pickle.HIGHEST_PROTOCOL) 132 | 133 | 134 | def loadCache(fileName): 135 | """ 136 | Load cache database as pickle dump from file 137 | :param fileName: 138 | :return: 139 | """ 140 | try: 141 | with open(fileName, 'rb') as fh: 142 | return pickle.load(fh), True 143 | except Exception as e: 144 | # traceback.print_exc() 145 | return {}, False 146 | 147 | 148 | def removeNonAsciiDrop(string): 149 | nonascii = "error" 150 | # print "CON: ", string 151 | try: 152 | # Generate a new string without disturbing characters and allow new lines 153 | nonascii = "".join(i for i in string if (ord(i) < 127 and ord(i) > 31) or ord(i) == 10 or ord(i) == 13) 154 | except Exception as e: 155 | traceback.print_exc() 156 | pass 157 | return nonascii 158 | 159 | 160 | def signal_handler(signal, frame): 161 | print("\n[+] Saving {0} cache entries to file {1}".format(len(cache), args.c)) 162 | saveCache(cache, args.c) 163 | sys.exit(0) 164 | 165 | 166 | def process_lines(lines, result_file, nocsv=False, dups=False, debug=False): 167 | """ 168 | Process the input file line by line 169 | """ 170 | 171 | # Some statistics that could help find similarities 172 | imphashes = {} 173 | 174 | for line in lines: 175 | 176 | # Skip comments 177 | if line.startswith("#"): 178 | continue 179 | 180 | # Remove line break 181 | line.rstrip("\n\r") 182 | 183 | # Get all hashes in line 184 | # ... and the rest of the line as comment 185 | hashVal, comment = fetch_hash(line) 186 | 187 | # If no hash found 188 | if hashVal == '': 189 | continue 190 | 191 | # Cache 192 | if hashVal in cache: 193 | if dups: 194 | # Colorized head of each hash check 195 | print_highlighted("\nHASH: {0} COMMENT: {1}".format(hashVal, comment)) 196 | print_highlighted("RESULT: %s (from cache)" % cache[hashVal]) 197 | continue 198 | else: 199 | # Colorized head of each hash check 200 | print_highlighted("\nHASH: {0} COMMENT: {1}".format(hashVal, comment)) 201 | 202 | # Prepare VT API request 203 | parameters = {"resource": hashVal, "apikey": API_KEY} 204 | success = False 205 | while not success: 206 | try: 207 | response_dict = requests.get(URL, params=parameters).json() 208 | success = True 209 | except Exception as e: 210 | if debug: 211 | traceback.print_exc() 212 | # print "Error requesting VT results" 213 | pass 214 | 215 | # Process results 216 | result = "- / -" 217 | virus = "-" 218 | last_submitted = "-" 219 | first_submitted = "-" 220 | filenames = "-" 221 | filetype = "-" 222 | rating = "unknown" 223 | positives = 0 224 | res_color = Back.CYAN 225 | md5 = "-" 226 | sha1 = "-" 227 | sha256 = "-" 228 | imphash = "-" 229 | harmless = "" 230 | signed = "" 231 | revoked = "" 232 | expired = "" 233 | mssoft = "" 234 | vendor_result_string = "-" 235 | 236 | if response_dict.get("response_code") > 0: 237 | # Hashes 238 | md5 = response_dict.get("md5") 239 | sha1 = response_dict.get("sha1") 240 | sha256 = response_dict.get("sha256") 241 | # AV matches 242 | positives = response_dict.get("positives") 243 | total = response_dict.get("total") 244 | last_submitted = response_dict.get("scan_date") 245 | # Virus Name 246 | scans = response_dict.get("scans") 247 | virus_names = [] 248 | vendor_results = [] 249 | for vendor in VENDORS: 250 | if vendor in scans: 251 | if scans[vendor]["result"]: 252 | virus_names.append("{0}: {1}".format(vendor, scans[vendor]["result"])) 253 | vendor_results.append(scans[vendor]["result"]) 254 | else: 255 | vendor_results.append("-") 256 | else: 257 | vendor_results.append("-") 258 | vendor_result_string = ";".join(vendor_results) 259 | if len(virus_names) > 0: 260 | virus = " / ".join(virus_names) 261 | # Type 262 | rating = "clean" 263 | res_color = Back.GREEN 264 | if positives > 0: 265 | rating = "suspicious" 266 | res_color = Back.YELLOW 267 | if positives > 10: 268 | rating = "malicious" 269 | res_color = Back.RED 270 | # Get more information with permalink 271 | if debug: 272 | print("[D] Processing permalink {0}".format(response_dict.get("permalink"))) 273 | info = process_permalink(response_dict.get("permalink"), debug) 274 | # File Names 275 | filenames = removeNonAsciiDrop(", ".join(info['filenames'][:5]).replace(';', '_')) 276 | first_submitted = info['firstsubmission'] 277 | # Other info 278 | filetype = info['filetype'] 279 | imphash = info['imphash'] 280 | if imphash != "-": 281 | if imphash in imphashes: 282 | print_highlighted("[!] Imphash seen in %d samples " 283 | "https://totalhash.cymru.com/search/?hash:%s" % 284 | (imphashes[imphash], imphash), hl_color=res_color) 285 | imphashes[imphash] += 1 286 | else: 287 | imphashes[imphash] = 1 288 | # Result 289 | result = "%s / %s" % (response_dict.get("positives"), response_dict.get("total")) 290 | print_highlighted("VIRUS: {0}".format(virus)) 291 | print_highlighted("FILENAMES: {0}".format(filenames)) 292 | print_highlighted("FILE_TYPE: {2} FIRST_SUBMITTED: {0} LAST_SUBMITTED: {1}".format( 293 | first_submitted, last_submitted, filetype)) 294 | 295 | # Permalink analysis results 296 | if info['harmless']: 297 | harmless = " HARMLESS" 298 | if info['signed']: 299 | signed = " SIGNED" 300 | if info['revoked']: 301 | revoked = " SIG_REVOKED" 302 | if info['expired']: 303 | expired = " SIG_EXPIRED" 304 | if info["mssoft"]: 305 | mssoft = "MS_SOFTWARE_CATALOGUE" 306 | 307 | # Print the highlighted result line 308 | print_highlighted("RESULT: %s %s%s%s%s%s" % (result, harmless, signed, revoked, expired, mssoft), 309 | hl_color=res_color) 310 | 311 | # Add to log file 312 | if not nocsv: 313 | result_line = "{0};{1};{2};{3};{4};{5};{6};{7};" \ 314 | "{8};{9};{10};{11};{12};{13};{14};{15};{16};{17}\n".format(hashVal, rating, comment, 315 | positives, 316 | virus, filenames, 317 | first_submitted, 318 | last_submitted, 319 | filetype, 320 | md5, sha1, sha256, imphash, 321 | harmless.lstrip(' '), 322 | signed.lstrip(' '), 323 | revoked.lstrip(' '), 324 | expired.lstrip(' '), 325 | vendor_result_string) 326 | with open(result_file, "a") as fh_results: 327 | fh_results.write(result_line) 328 | 329 | # Add to hash cache 330 | cache[hashVal] = result 331 | 332 | # Wait some time for the next request 333 | time.sleep(WAIT_TIME) 334 | 335 | 336 | if __name__ == '__main__': 337 | 338 | signal.signal(signal.SIGINT, signal_handler) 339 | init(autoreset=False) 340 | 341 | print(Style.RESET_ALL) 342 | print(Fore.WHITE + Back.BLUE) 343 | print(" ".ljust(80)) 344 | print(" _ ________ _______ __ ".ljust(80)) 345 | print(" | | / /_ __/ / ___/ / ___ ____/ /_____ ____ ".ljust(80)) 346 | print(" | |/ / / / / /__/ _ \/ -_) __/ '_/ -_) __/ ".ljust(80)) 347 | print(" |___/ /_/ \___/_//_/\\__/\__/_/\_\\__/_/ ".ljust(80)) 348 | print(" ".ljust(80)) 349 | print((" " + __AUTHOR__ + " - " + __VERSION__ + "").ljust(80)) 350 | print(" ".ljust(80) + Style.RESET_ALL) 351 | print(Style.RESET_ALL + " ") 352 | 353 | parser = argparse.ArgumentParser(description='Virustotal Online Checker') 354 | parser.add_argument('-f', help='File to process (hash line by line OR csv with hash in each line - auto-detects ' 355 | 'position and comment)', metavar='path', default='') 356 | parser.add_argument('-c', help='Name of the cache database file (default: vt-hash-db.pkl)', metavar='cache-db', 357 | default='vt-hash-db.pkl') 358 | parser.add_argument('--nocache', action='store_true', help='Do not use cache database file', default=False) 359 | parser.add_argument('--nocsv', action='store_true', help='Do not write a CSV with the results', default=False) 360 | parser.add_argument('--dups', action='store_true', help='Do not skip duplicate hashes', default=False) 361 | parser.add_argument('--debug', action='store_true', default=False, help='Debug output') 362 | 363 | args = parser.parse_args() 364 | 365 | # Check API Key 366 | if API_KEY == '': 367 | print("[E] No API Key set") 368 | print(" Include your API key in the header section of the script (API_KEY)\n") 369 | print(" More info:") 370 | print(" https://www.virustotal.com/en/faq/#virustotal-api\n") 371 | sys.exit(1) 372 | 373 | # Check input file 374 | if args.f == '': 375 | print("[E] Please provide an input file with '-f inputfile'\n") 376 | parser.print_help() 377 | sys.exit(1) 378 | if not os.path.exists(args.f): 379 | print("[E] Cannot find input file {0}".format(args.f)) 380 | sys.exit(1) 381 | 382 | # Caches 383 | cache = {} 384 | # Trying to load cache from pickle dump 385 | if not args.nocache: 386 | cache, success = loadCache(args.c) 387 | if success: 388 | print("[+] {0} cache entries read from cache database: {1}".format(len(cache), args.c)) 389 | else: 390 | print("[-] No cache database found") 391 | print("[+] Analyzed hashes will be written to cache database: {0}".format(args.c)) 392 | print("[+] You can always interrupt the scan by pressing CTRL+C without losing the scan state") 393 | 394 | # Open input file 395 | try: 396 | with open(args.f, 'rU') as fh: 397 | lines = fh.readlines() 398 | except Exception as e: 399 | print("[E] Cannot read input file ") 400 | sys.exit(1) 401 | 402 | # Result file 403 | # Result file 404 | if not args.nocsv: 405 | result_file = "check-results_{0}.csv".format(os.path.splitext(os.path.basename(args.f))[0]) 406 | if os.path.exists(result_file): 407 | print("[+] Found results CSV from previous run: {0}".format(result_file)) 408 | print("[+] Appending results to file: {0}".format(result_file)) 409 | else: 410 | print("[+] Writing results to new file: {0}".format(result_file)) 411 | try: 412 | with open(result_file, 'w') as fh_results: 413 | fh_results.write("Lookup Hash;Rating;Comment;Positives;Virus;File Names;First Submitted;" 414 | "Last Submitted;MD5;SHA1;SHA256;ImpHash;Harmless;Signed;Revoked;Expired;" 415 | "{0}\n".format(";".join(VENDORS))) 416 | except Exception as e: 417 | print("[E] Cannot write export file {0}".format(result_file)) 418 | 419 | # Process the input lines 420 | process_lines(lines, result_file, args.nocsv, args.dups, args.debug) 421 | 422 | # Write Cache 423 | print("\n[+] Saving {0} cache entries to file {1}".format(len(cache), args.c)) 424 | saveCache(cache, args.c) 425 | 426 | print(Style.RESET_ALL) 427 | -------------------------------------------------------------------------------- /tools/vt-checker-hosts.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | """Checks IPs and Hosts read from an input file on Virustotal""" 3 | from __future__ import print_function 4 | 5 | __AUTHOR__ = 'Florian Roth' 6 | __VERSION__ = "0.2 July 2017" 7 | 8 | """ 9 | Install dependencies with: 10 | pip install simplejson colorama IPy pickle pycurl 11 | """ 12 | 13 | import simplejson, json 14 | import signal 15 | import urllib 16 | import urllib2 17 | import pycurl 18 | import StringIO 19 | import urlparse 20 | import platform 21 | import time 22 | import re 23 | import os 24 | import sys 25 | import traceback 26 | import subprocess 27 | import argparse 28 | import socket 29 | import pickle 30 | from IPy import IP 31 | from colorama import init, Fore, Back, Style 32 | 33 | URLS = {'ip': r'https://www.virustotal.com/vtapi/v2/ip-address/report', 34 | 'domain': r'https://www.virustotal.com/vtapi/v2/domain/report'} 35 | API_KEY = '-' 36 | WAIT_TIME = 15 # Public API allows 4 request per minute, so we wait 15 secs by default 37 | IP_WHITE_LIST = ['1.0.0.127', '127.0.0.1'] 38 | OWNER_WHITE_LIST = ['Google Inc.', 'Facebook, Inc.', 'CloudFlare, Inc.', 'Microsoft Corporation', 39 | 'Akamai Technologies, Inc.'] # not yet used 40 | DOMAIN_WHITE_LIST = ['sourceforge.net'] 41 | RES_TARGETS = {'ip': 'hostname', 'domain': 'ip_address'} 42 | 43 | 44 | def fetch_ip_and_domains(line): 45 | """ 46 | Extracts IPs and Domains from a log line 47 | """ 48 | domains = [] 49 | # Modify line to easily extract IPs and Domains from reports 50 | # get 183.200.23[.]213 51 | mod_line = line.replace("[", "").replace("]", "") 52 | ip_pattern = r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b' 53 | ips = re.findall(ip_pattern, mod_line) 54 | domain_pattern = r'\b(?=.{4,253}$)(((?!-)[a-zA-Z0-9-]{1,63}(? 0: 293 | 294 | # Predefine Rating 295 | rating = "clean" 296 | 297 | # Other Info 298 | owner = response_dict.get("as_owner") 299 | country = response_dict.get("country") 300 | 301 | # WHITE LIST CHECKS 302 | if owner: 303 | for owl in OWNER_WHITE_LIST: 304 | if owl in owner: 305 | print_highlighted("Owner white-listed - skipping this host OWNER: %s" % owner) 306 | 307 | # Resolutions 308 | if 'resolutions' in response_dict: 309 | resolution_list = response_dict['resolutions'] 310 | for i, res in enumerate(resolution_list): 311 | resolutions.append({'target': res[RES_TARGETS[cat]], 'last_resolved': res['last_resolved']}) 312 | if i < max_items: 313 | print_highlighted("HOST: {0} LAST_RESOLVED: {1}".format(res[RES_TARGETS[cat]], 314 | res['last_resolved'])) 315 | else: 316 | if "hosts" not in shown_messages: 317 | sys.stdout.write("Others found: ") 318 | shown_messages["hosts"] = True 319 | sys.stdout.write(".") 320 | # Add the IP to the elements 321 | if args.recursive: 322 | new_value = res[RES_TARGETS[cat]] 323 | if is_ip(new_value): 324 | elements.append({'value': new_value, 'type': 'ip'}) 325 | else: 326 | elements.append({'value': new_value, 'type': 'domain'}) 327 | if "hosts" in shown_messages: 328 | sys.stdout.write("\n") 329 | 330 | # URL matches 331 | if 'detected_urls' in response_dict: 332 | detected_urls = response_dict['detected_urls'] 333 | for i, url in enumerate(detected_urls): 334 | positives_url = url['positives'] 335 | total_url = url['total'] 336 | urls.append({'url': url['url'], 'positives': positives_url, 'total': total_url}) 337 | if i < max_items and args.download: 338 | print_highlighted("URL: {0} POSITIVES: {1} TOTAL: {2}".format(url['url'], 339 | positives_url, 340 | total_url)) 341 | else: 342 | if "urls" not in shown_messages: 343 | sys.stdout.write("Others found: ") 344 | shown_messages["urls"] = True 345 | sys.stdout.write(".") 346 | positives += positives_url 347 | total += total_url 348 | # Download URL 349 | if args.download: 350 | download_url(value, url['url']) 351 | if "urls" in shown_messages: 352 | sys.stdout.write("\n") 353 | 354 | # Samples 355 | if 'detected_communicating_samples' in response_dict: 356 | samples_list = response_dict['detected_communicating_samples'] 357 | for i, sample in enumerate(samples_list): 358 | positives_sample = sample['positives'] 359 | total_sample = sample['total'] 360 | date = sample['date'] 361 | sha256 = sample['sha256'] 362 | samples.append({'sample': sha256, 'positives': positives_sample, 'total': total_sample, 363 | 'date': date}) 364 | if i < max_items: 365 | print_highlighted("SAMPLE: {0} POSITIVES: {1} TOTAL: {2} " 366 | "DATE: {3}".format(sha256, positives_sample, total_sample, date)) 367 | else: 368 | if "samples" not in shown_messages: 369 | sys.stdout.write("Others found: ") 370 | shown_messages["samples"] = True 371 | sys.stdout.write(".") 372 | sample_positives += positives_sample 373 | sample_total += total_sample 374 | if "samples" in shown_messages: 375 | sys.stdout.write("\n") 376 | 377 | # Calculations ------------------------------------------------------------------------------------- 378 | # Rating 379 | # Calculate ratio 380 | if positives > 0 and total > 0: 381 | ratio = (float(positives) / float(total)) * 100 382 | # Set rating 383 | if ratio > 3 and rating == "clean": 384 | rating = "suspicious" 385 | if ratio > 10 and (rating == "clean" or rating == "suspicious"): 386 | rating = "malicious" 387 | 388 | # Type 389 | res_color = Back.GREEN 390 | if rating == "suspicious": 391 | res_color = Back.YELLOW 392 | if rating == "malicious": 393 | res_color = Back.RED 394 | 395 | # Result ------------------------------------------------------------------------------------------- 396 | result = "%s / %s" % (positives, total) 397 | print_highlighted("COUNTRY: {0} OWNER: {1}".format(country, owner)) 398 | print_highlighted("POSITIVES: %s RATING: %s" % (result, rating), hl_color=res_color) 399 | 400 | else: 401 | # Print the highlighted result line 402 | print_highlighted("POSITIVES: %s RATING: %s" % (result, rating), hl_color=res_color) 403 | 404 | # CSV OUTPUT ------------------------------------------------------------------------------------------- 405 | # Add to log file 406 | if not nocsv: 407 | # Hosts string 408 | targets = [] 409 | for r in resolutions: 410 | targets.append(r['target']) 411 | targets_value = ', '.join(targets) 412 | # Malicious samples 413 | mal_samples = [] 414 | for s in samples: 415 | if s['positives'] > 3: 416 | mal_samples.append(s['sample']) 417 | samples_value = ', '.join(mal_samples) 418 | # urls = ', '.join("%s=%r" % (key,val) for (key,val) in urls.iteritems()) 419 | # samples = ', '.join("%s=%r" % (key,val) for (key,val) in samples.iteritems()) 420 | result_line = "{0};{1};{2};{3};{4};{5};{6};{7}\n".format(value, rating, owner, country, 421 | positives, total, 422 | samples_value, targets_value) 423 | with open(result_file, "a") as fh_results: 424 | fh_results.write(result_line) 425 | 426 | # Add to cache ----------------------------------------------------------------------------------------- 427 | cache[value] = result 428 | 429 | # Wait ------------------------------------------------------------------------------------------------- 430 | # Wait some time for the next request 431 | time.sleep(WAIT_TIME) 432 | 433 | 434 | def download_url(host_id, url): 435 | """ 436 | Downloads an URL and stores the response to a directory with named as the host/IP 437 | :param host_id: 438 | :param url: 439 | :return: 440 | """ 441 | output = StringIO.StringIO() 442 | header = StringIO.StringIO() 443 | 444 | print("[>] Trying to download URL: %s" % url) 445 | # Download file 446 | try: 447 | # 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)') 448 | c = pycurl.Curl() 449 | c.setopt(c.URL, url) 450 | c.setopt(pycurl.CONNECTTIMEOUT, 10) 451 | c.setopt(pycurl.TIMEOUT, 180) 452 | c.setopt(pycurl.FOLLOWLOCATION, 1) 453 | c.setopt(pycurl.USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)') 454 | c.setopt(c.WRITEFUNCTION, output.write) 455 | c.setopt(c.HEADERFUNCTION, header.write) 456 | c.perform() 457 | # Header parsing 458 | header_info = header_function(header.getvalue()) 459 | except Exception as e: 460 | if args.debug: 461 | traceback.print_exc() 462 | print_highlighted("[-] Error MESSAGE: %s" % str(e)) 463 | 464 | # Write File 465 | if c.getinfo(c.RESPONSE_CODE) == 200: 466 | # Check folder 467 | out_path = os.path.join(os.path.abspath(args.o), host_id) 468 | if not os.path.exists(out_path): 469 | os.makedirs(out_path) 470 | # Output file name 471 | r = urlparse.urlparse(url) 472 | filename = r.path.split("/")[-1] 473 | if filename == "": 474 | if r.path != "/": 475 | out_path = os.path.join(out_path, r.path.lstrip("/")) 476 | filename = "index.dat" 477 | out_filename = os.path.join(os.path.abspath(out_path), filename) 478 | # Write file 479 | try: 480 | with open(out_filename, 'wb') as f: 481 | f.write(output.getvalue()) 482 | print_highlighted("[+] Successfully saved to FILE: %s" % out_filename) 483 | except Exception as e: 484 | if args.debug: 485 | traceback.print_exc() 486 | print("[-] Failed to write file %s (use --debug for more info)" % out_filename) 487 | else: 488 | try: 489 | print_highlighted("[i] Response CODE: %s MIME_TYPE: %s SIZE: %s" % ( 490 | str(c.getinfo(c.RESPONSE_CODE)), 491 | header_info['content-type'], 492 | header_info['content-length']) 493 | ) 494 | except Exception as e: 495 | print_highlighted("[-] Response CODE: %s" % str(c.getinfo(c.RESPONSE_CODE))) 496 | 497 | output.close() 498 | 499 | 500 | def header_function(header_raw): 501 | """ 502 | Process header info 503 | Example from pycurl quick start guide http://pycurl.io/docs/latest/quickstart.html 504 | :param header_line: 505 | :return: 506 | """ 507 | headers = {} 508 | header_lines = header_raw.splitlines() 509 | 510 | for header_line in header_lines: 511 | 512 | # HTTP standard specifies that headers are encoded in iso-8859-1. 513 | # On Python 2, decoding step can be skipped. 514 | # On Python 3, decoding step is required. 515 | header_line = header_line.decode('iso-8859-1') 516 | 517 | # Header lines include the first status line (HTTP/1.x ...). 518 | # We are going to ignore all lines that don't have a colon in them. 519 | # This will botch headers that are split on multiple lines... 520 | if ':' not in header_line: 521 | continue 522 | 523 | # Break the header line into header name and value. 524 | name, value = header_line.split(':', 1) 525 | 526 | # Remove whitespace that may be present. 527 | # Header lines include the trailing newline, and there may be whitespace 528 | # around the colon. 529 | name = name.strip() 530 | value = value.strip() 531 | 532 | # Header names are case insensitive. 533 | # Lowercase name here. 534 | name = name.lower() 535 | 536 | # Now we can actually record the header name and value. 537 | headers[name] = value 538 | 539 | return headers 540 | 541 | 542 | def signal_handler(signal, frame): 543 | print("\n[+] Saving {0} cache entries to file {1}".format(len(cache), args.c)) 544 | saveCache(cache, args.c) 545 | sys.exit(0) 546 | 547 | 548 | if __name__ == '__main__': 549 | 550 | signal.signal(signal.SIGINT, signal_handler) 551 | init(autoreset=False) 552 | 553 | print(Style.RESET_ALL + Fore.WHITE + Back.BLUE) 554 | print(" ".ljust(80)) 555 | print(" _ ________ _______ __ ".ljust(80)) 556 | print(" | | / /_ __/ / ___/ / ___ ____/ /_____ ____ ".ljust(80)) 557 | print(" | |/ / / / / /__/ _ \/ -_) __/ '_/ -_) __/ ".ljust(80)) 558 | print(" |___/ /_/ \___/_//_/\\__/\__/_/\_\\__/_/ ".ljust(80)) 559 | print(" ".ljust(80)) 560 | print(" IP and Domain Version ".ljust(80)) 561 | print((" " + __AUTHOR__ + " - " + __VERSION__ + "").ljust(80)) 562 | print(" ".ljust(80) + Style.RESET_ALL) 563 | print(Style.RESET_ALL + " ") 564 | 565 | parser = argparse.ArgumentParser(description='Virustotal Online Checker (IP/Domain)') 566 | parser.add_argument('-f', help='File to process (hash line by line OR csv with hash in each line - auto-detects ' 567 | 'position and comment)', metavar='path', default='') 568 | parser.add_argument('-m', help='Maximum number of items (urls, hosts, samples) to show', metavar='max-items', 569 | default=10) 570 | parser.add_argument('-c', help='Name of the cache database file (default: vt-check-db.pkl)', metavar='cache-db', 571 | default='vt-check-db.pkl') 572 | parser.add_argument('--nocache', action='store_true', help='Do not use the load the cache db (vt-check-cache.pkl)', 573 | default=False) 574 | parser.add_argument('--nocsv', action='store_true', help='Do not write a CSV with the results', default=False) 575 | parser.add_argument('--recursive', action='store_true', help='Process the resolved IPs as well', default=False) 576 | parser.add_argument('--download', action='store_true', 577 | help='Try to download the URLs (directories with host/ip names)', default=False) 578 | parser.add_argument('-o', help='Store the downloads to the given directory', metavar='output-folder', 579 | default='./') 580 | parser.add_argument('--dups', action='store_true', help='Do not skip duplicate hashes', default=False) 581 | parser.add_argument('--noresolve', action='store_true', help='Do not perform DNS resolve test on found domain ' 582 | 'names', default=False) 583 | parser.add_argument('--ping', action='store_true', help='Perform ping check on IPs (speeds up process if many ' 584 | 'public but internally routed IPs appear in text file)', 585 | default=False) 586 | parser.add_argument('--debug', action='store_true', default=False, help='Debug output') 587 | 588 | args = parser.parse_args() 589 | 590 | # Check API Key 591 | if API_KEY == '': 592 | print("[E] No API Key set") 593 | print(" Include your API key in the header section of the script (API_KEY)\n") 594 | print(" More info:") 595 | print(" https://www.virustotal.com/en/faq/#virustotal-api\n") 596 | sys.exit(1) 597 | 598 | # Check input file 599 | if args.f == '': 600 | print("[E] Please provide an input file with '-f inputfile'\n") 601 | parser.print_help() 602 | sys.exit(1) 603 | if not os.path.exists(args.f): 604 | print("[E] Cannot find input file {0}".format(args.f)) 605 | sys.exit(1) 606 | 607 | # Caches 608 | cache = {} 609 | # Trying to load cache from pickle dump 610 | if not args.nocache: 611 | cache, success = loadCache(args.c) 612 | if success: 613 | print("[+] {0} cache entries read from cache database: {1}".format(len(cache), args.c)) 614 | else: 615 | print("[-] No cache database found") 616 | print("[+] Analyzed IPs/domains will be written to cache database: {0}".format(args.c)) 617 | print("[+] You can always interrupt the scan by pressing CTRL+C without losing the scan state") 618 | 619 | # Open input file 620 | try: 621 | with open(args.f, 'r') as fh_input: 622 | lines = fh_input.readlines() 623 | except Exception as e: 624 | print("[E] Cannot read input file") 625 | sys.exit(1) 626 | 627 | # Result file 628 | if not args.nocsv: 629 | result_file = "check-results_{0}.csv".format(os.path.splitext(os.path.basename(args.f))[0]) 630 | if os.path.exists(result_file): 631 | print("[+] Found results CSV from previous run: {0}".format(result_file)) 632 | print("[+] Appending results to file: {0}".format(result_file)) 633 | else: 634 | print("[+] Writing results to new file: {0}".format(result_file)) 635 | try: 636 | with open(result_file, 'w') as fh_results: 637 | fh_results.write( 638 | "IP;Rating;Owner;Country Code;Log Line No;Positives;Total;Malicious Samples;Hosts\n") 639 | except Exception as e: 640 | print("[E] Cannot write CSV export file: {0}".format(result_file)) 641 | 642 | # Process the input lines 643 | elements = process_lines(lines, args.debug) 644 | 645 | # Process elements 646 | process_elements(elements, result_file, int(args.m), args.nocsv, args.dups, args.noresolve, args.ping, 647 | args.debug) 648 | 649 | # Write Cache 650 | print("\n[+] Saving {0} cache entries to file {1}".format(len(cache), args.c)) 651 | saveCache(cache, args.c) 652 | 653 | print(Style.RESET_ALL) 654 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------