├── .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 ├── lokiinit.png ├── lokilog1.png ├── lokiconf1.png ├── lokiconf2.png ├── lokiscan1.png ├── lokiscan2.png ├── lokiscan3.png ├── lokititle.png └── scanner-comparison.png ├── tools ├── pe-sieve32.exe └── pe-sieve64.exe ├── prepare_push.sh ├── requirements.txt ├── .gitignore ├── Pipfile ├── loki.spec ├── loki-upgrader.spec ├── .github ├── dependabot.yml └── workflows │ ├── pyinstaller.yml │ └── lint_python.yml ├── .travis.yml ├── config └── excludes.cfg ├── 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/Neo23x0/Loki/HEAD/loki.ico -------------------------------------------------------------------------------- /lokiicon.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/lokiicon.jpg -------------------------------------------------------------------------------- /test/unicode-test/Иixdrin/webshell_tiny_Файл.asp: -------------------------------------------------------------------------------- 1 | <%execute request(chr(42))%> -------------------------------------------------------------------------------- /screens/lokicmd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/screens/lokicmd.png -------------------------------------------------------------------------------- /screens/lokiinit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/screens/lokiinit.png -------------------------------------------------------------------------------- /screens/lokilog1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/screens/lokilog1.png -------------------------------------------------------------------------------- /tools/pe-sieve32.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/tools/pe-sieve32.exe -------------------------------------------------------------------------------- /tools/pe-sieve64.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/tools/pe-sieve64.exe -------------------------------------------------------------------------------- /prepare_push.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | git submodule foreach git pull origin master 4 | 5 | -------------------------------------------------------------------------------- /screens/lokiconf1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/screens/lokiconf1.png -------------------------------------------------------------------------------- /screens/lokiconf2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/screens/lokiconf2.png -------------------------------------------------------------------------------- /screens/lokiscan1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/screens/lokiscan1.png -------------------------------------------------------------------------------- /screens/lokiscan2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/screens/lokiscan2.png -------------------------------------------------------------------------------- /screens/lokiscan3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/screens/lokiscan3.png -------------------------------------------------------------------------------- /screens/lokititle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/screens/lokititle.png -------------------------------------------------------------------------------- /screens/scanner-comparison.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Neo23x0/Loki/HEAD/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 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Keep GitHub Actions up to date with GitHub's Dependabot... 2 | # https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot 3 | # https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem 4 | version: 2 5 | updates: 6 | - package-ecosystem: github-actions 7 | directory: / 8 | groups: 9 | github-actions: 10 | patterns: 11 | - "*" # Group all Actions updates into a single larger pull request 12 | schedule: 13 | interval: weekly 14 | -------------------------------------------------------------------------------- /.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/pyinstaller.yml: -------------------------------------------------------------------------------- 1 | name: binary_creation 2 | on: [pull_request, push] 3 | jobs: 4 | build: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v4 8 | - name: generate loki.exe 9 | uses: JackMcKew/pyinstaller-action-windows@main 10 | with: 11 | spec: loki.spec 12 | path: . 13 | - name: generate loki-uprader.exe 14 | uses: JackMcKew/pyinstaller-action-windows@main 15 | with: 16 | spec: loki-upgrader.spec 17 | path: . 18 | - name: create subdir 19 | run: mkdir dist/windows/tools 20 | - name: copy additional files 21 | run: cp tools/pe-sieve*.exe dist/windows/tools 22 | - name: zip files 23 | uses: edgarrc/action-7z@v1 24 | with: 25 | args: 7z a -tzip -mm=Deflate -mmt=off -mx5 -mfb=32 -mpass=1 -sccUTF-8 -mem=AES256 build.7z dist/windows 26 | - name: upload files 27 | uses: actions/upload-artifact@v4 28 | with: 29 | name: loki-binaries 30 | path: dist/windows -------------------------------------------------------------------------------- /.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@v4 8 | - uses: actions/setup-python@v5 9 | - run: pip install --upgrade pip setuptools wheel 10 | - run: pip install codespell mypy pytest ruff safety 11 | - run: ruff check --output-format=github --ignore=E501,E701,E713,E722,F401,F403,F405,F841 --line-length=263 . 12 | - run: ruff format || true 13 | - run: codespell --ignore-words-list="datas" --skip="./.git/*" 14 | - run: pip install -r requirements.txt 15 | - run: mypy --install-types --non-interactive . || true 16 | - run: pytest . || true 17 | - run: pytest --doctest-modules . || true 18 | - run: python ./loki.py --noprocs --noindicator --dontwait --debug -p ./test 19 | - run: python ./loki.py --noprocs --noindicator --dontwait --debug --intense -p ./test 20 | - run: python ./loki.py --noprocs --noindicator --dontwait --debug --csv -p ./test 21 | # - run: safety check 22 | -------------------------------------------------------------------------------- /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 | 9 | class VulnChecker(): 10 | 11 | def __init__(self, logger): 12 | # Logger 13 | self.logger = logger 14 | pass 15 | 16 | def run(self): 17 | self.logger.log("INFO", "VulnChecker", "Starting vulnerability checks ...") 18 | self.check_sam_readable() 19 | 20 | def check_sam_readable(self): 21 | """ 22 | Check if the local SAM is readable by everyone 23 | https://twitter.com/wdormann/status/1417447179149533185 24 | :return: 25 | """ 26 | output = b'' 27 | try: 28 | output += subprocess.check_output([r'icacls.exe', r'C:\Windows\System32\config\sam'], stderr=subprocess.STDOUT) 29 | except subprocess.CalledProcessError: 30 | pass 31 | try: 32 | output += subprocess.check_output([r'icacls.exe', r'C:\Windows\SysNative\config\sam'], stderr=subprocess.STDOUT) 33 | except subprocess.CalledProcessError: 34 | pass 35 | # Check the output 36 | try: 37 | if r'BUILTIN\Users:(I)(RX)' in output.decode('latin1', errors='ignore'): 38 | self.logger.log("WARNING", "VulnChecker", 39 | "The Security Account Manager (SAM) database file C:\\Windows\\System32\\config\\SAM is " 40 | "readable by every user. This is caused by the Hive Permission Bug, which is problematic " 41 | "on systems that have System Protection configured for drive C: (see " 42 | "https://doublepulsar.com/hivenightmare-aka-serioussam-anybody-can-read-the-registry-in-" 43 | "windows-10-7a871c465fa5)") 44 | return True 45 | else: 46 | self.logger.log("DEBUG", "VulnChecker", "SAM Database isn't readable by every user.") 47 | except UnicodeDecodeError: 48 | self.logger.log("ERROR", "VulnChecker", "Unicode decode error in SAM check") 49 | return False 50 | -------------------------------------------------------------------------------- /lib/pesieve.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # PE-Sieve Integration by @hasherezade 4 | 5 | import os 6 | import json 7 | import traceback 8 | 9 | from lib.lokilogger import * 10 | from lib.helpers import runProcess 11 | 12 | class PESieve(object): 13 | """ 14 | PESieve class makes use of hasherezade's PE-Sieve tool to scans a given process, 15 | searching for the modules containing in-memory code modifications 16 | """ 17 | active = False 18 | 19 | def __init__(self, workingDir, is64bit, logger): 20 | 21 | # Logger 22 | self.logger = logger 23 | # PE-Sieve tools 24 | self.peSieve = os.path.join(workingDir, 'tools/pe-sieve32.exe'.replace("/", os.sep)) 25 | if is64bit: 26 | self.peSieve = os.path.join(workingDir, 'tools/pe-sieve64.exe'.replace("/", os.sep)) 27 | 28 | if self.isAvailable(): 29 | self.active = True 30 | self.logger.log("NOTICE", "PESieve", "PE-Sieve successfully initialized BINARY: {0} " 31 | "SOURCE: https://github.com/hasherezade/pe-sieve".format(self.peSieve)) 32 | else: 33 | self.logger.log("NOTICE", "PESieve", "Cannot find PE-Sieve in expected location {0} " 34 | "SOURCE: https://github.com/hasherezade/pe-sieve".format(self.peSieve)) 35 | 36 | def isAvailable(self): 37 | """ 38 | Checks if the PE-Sieve tools are available in a "./tools" sub folder 39 | :return: 40 | """ 41 | if not os.path.exists(self.peSieve): 42 | self.logger.log("DEBUG", "PESieve", "PE-Sieve not found in location '{0}' - " 43 | "feature will not be active".format(self.peSieve)) 44 | return False 45 | return True 46 | 47 | def scan(self, pid, pesieveshellc = False): 48 | """ 49 | Performs a scan on a given process ID 50 | :param pid: process id of the process to check 51 | :return hooked, replaces, suspicious: number of findings per type 52 | """ 53 | # Presets 54 | results = {"patched": 0, "replaced": 0, "unreachable_file": 0, "implanted_pe": 0, "implanted_shc": 0} 55 | # Compose command 56 | command = [self.peSieve, '/pid', str(pid), '/ofilter', '2', '/quiet', '/json'] + (['/shellc'] if pesieveshellc else []) 57 | # Run PE-Sieve on given process 58 | (output, returnCode) = runProcess(command) 59 | # Debug output 60 | if self.logger.debug: 61 | print("PE-Sieve JSON output: %s" % output) 62 | if output == '' or not output: 63 | return results 64 | try: 65 | results_raw = json.loads(output) 66 | #results = results_raw["scan_report"]["scanned"]["modified"] 67 | results = results_raw["scanned"]["modified"] 68 | except ValueError: 69 | traceback.print_exc() 70 | self.logger.log("DEBUG", "PESieve", "Couldn't parse the JSON output.") 71 | except Exception: 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: 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 hashEntry not 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 hashEntry not 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 hashEntry not 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 traceback 12 | import os 13 | import re 14 | import psutil 15 | try: 16 | from StringIO import StringIO 17 | except ImportError: 18 | pass 19 | import netaddr 20 | import platform 21 | import time 22 | import threading 23 | import subprocess 24 | import signal 25 | 26 | # Helper Functions ------------------------------------------------------------- 27 | 28 | def is_ip(string): 29 | try: 30 | if netaddr.valid_ipv4(string): 31 | return True 32 | if netaddr.valid_ipv6(string): 33 | return True 34 | return False 35 | except: 36 | traceback.print_exc() 37 | return False 38 | 39 | 40 | def is_cidr(string): 41 | try: 42 | if netaddr.IPNetwork(string) and "/" in string: 43 | return True 44 | return False 45 | except: 46 | return False 47 | 48 | 49 | def ip_in_net(ip, network): 50 | try: 51 | # print "Checking if ip %s is in network %s" % (ip, network) 52 | if netaddr.IPAddress(ip) in netaddr.IPNetwork(network): 53 | return True 54 | return False 55 | except: 56 | return False 57 | 58 | 59 | def generateHashes(filedata): 60 | try: 61 | md5 = hashlib.md5() 62 | sha1 = hashlib.sha1() 63 | sha256 = hashlib.sha256() 64 | md5.update(filedata) 65 | sha1.update(filedata) 66 | sha256.update(filedata) 67 | return md5.hexdigest(), sha1.hexdigest(), sha256.hexdigest() 68 | except Exception: 69 | traceback.print_exc() 70 | return 0, 0, 0 71 | 72 | 73 | def getPlatformFull(): 74 | type_info = "" 75 | try: 76 | type_info = "%s PROC: %s ARCH: %s" % ( " ".join(platform.win32_ver()), platform.processor(), " ".join(platform.architecture())) 77 | except Exception: 78 | type_info = " ".join(platform.win32_ver()) 79 | return type_info 80 | 81 | 82 | def setNice(logger): 83 | try: 84 | pid = os.getpid() 85 | p = psutil.Process(pid) 86 | logger.log("INFO", "Init", "Setting LOKI process with PID: %s to priority IDLE" % pid) 87 | p.nice(psutil.IDLE_PRIORITY_CLASS) 88 | return 1 89 | except Exception: 90 | if logger.debug: 91 | traceback.print_exc() 92 | logger.log("ERROR", "Init", "Error setting nice value of THOR process") 93 | return 0 94 | 95 | 96 | def getExcludedMountpoints(): 97 | excludes = [] 98 | try: 99 | mtab = open("/etc/mtab", "r") 100 | for mpoint in mtab: 101 | options = mpoint.split(" ") 102 | if not options[0].startswith("/dev/"): 103 | if not options[1] == "/": 104 | excludes.append(options[1]) 105 | except Exception: 106 | print ("Error while reading /etc/mtab") 107 | finally: 108 | mtab.close() 109 | return excludes 110 | 111 | 112 | def removeBinaryZero(string): 113 | return re.sub(r'\x00','',string) 114 | 115 | 116 | def printProgress(i): 117 | if (i%4) == 0: 118 | sys.stdout.write('\b/') 119 | elif (i%4) == 1: 120 | sys.stdout.write('\b-') 121 | elif (i%4) == 2: 122 | sys.stdout.write('\b\\') 123 | elif (i%4) == 3: 124 | sys.stdout.write('\b|') 125 | sys.stdout.flush() 126 | 127 | 128 | def transformOS(regex, platform): 129 | # Replace '\' with '/' on Linux/Unix/OSX 130 | if platform != "windows": 131 | regex = regex.replace(r'\\', r'/') 132 | regex = regex.replace(r'C:', '') 133 | return regex 134 | 135 | 136 | def replaceEnvVars(path): 137 | 138 | # Setting new path to old path for default 139 | new_path = path 140 | 141 | # ENV VARS ---------------------------------------------------------------- 142 | # Now check if an environment env is included in the path string 143 | res = re.search(r"([@]?%[A-Za-z_]+%)", path) 144 | if res: 145 | env_var_full = res.group(1) 146 | env_var = env_var_full.replace("%", "").replace("@", "") 147 | 148 | # Check environment variables if there is a matching var 149 | if env_var in os.environ: 150 | if os.environ[env_var]: 151 | new_path = path.replace(env_var_full, re.escape(os.environ[env_var])) 152 | 153 | # TYPICAL REPLACEMENTS ---------------------------------------------------- 154 | if path[:11].lower() == "\\systemroot": 155 | new_path = path.replace("\\SystemRoot", os.environ["SystemRoot"]) 156 | 157 | if path[:8].lower() == "system32": 158 | new_path = path.replace("system32", "%s\\System32" % os.environ["SystemRoot"]) 159 | 160 | #if path != new_path: 161 | # print "OLD: %s NEW: %s" % (path, new_path) 162 | return new_path 163 | 164 | 165 | def get_file_type(filePath, filetype_sigs, max_filetype_magics, logger): 166 | try: 167 | # Reading bytes from file 168 | res_full = open(filePath, 'rb', os.O_RDONLY).read(max_filetype_magics) 169 | # Checking sigs 170 | for sig in filetype_sigs: 171 | bytes_to_read = int(len(str(sig)) / 2) 172 | res = res_full[:bytes_to_read] 173 | if res == bytes.fromhex(sig): 174 | return filetype_sigs[sig] 175 | return "UNKNOWN" 176 | except Exception: 177 | if logger.debug: 178 | traceback.print_exc() 179 | return "UNKNOWN" 180 | 181 | 182 | def removeNonAscii(s, stripit=False): 183 | nonascii = "error" 184 | try: 185 | try: 186 | printable = set(string.printable) 187 | filtered_string = filter(lambda x: x in printable, s.decode('utf-8')) 188 | nonascii = ''.join(filtered_string) 189 | except Exception: 190 | traceback.print_exc() 191 | nonascii = s.hex() 192 | except Exception: 193 | traceback.print_exc() 194 | pass 195 | 196 | return nonascii 197 | 198 | 199 | def removeNonAsciiDrop(s): 200 | nonascii = "error" 201 | try: 202 | # Generate a new string without disturbing characters 203 | printable = set(string.printable) 204 | nonascii = filter(lambda x: x in printable, s) 205 | except Exception: 206 | traceback.print_exc() 207 | pass 208 | return nonascii 209 | 210 | 211 | def getAge(filePath): 212 | try: 213 | stats=os.stat(filePath) 214 | 215 | # Created 216 | ctime=stats.st_ctime 217 | # Modified 218 | mtime=stats.st_mtime 219 | # Accessed 220 | atime=stats.st_atime 221 | 222 | except Exception: 223 | # traceback.print_exc() 224 | return (0, 0, 0) 225 | 226 | # print "%s %s %s" % ( ctime, mtime, atime ) 227 | return (ctime, mtime, atime) 228 | 229 | def getAgeString(filePath): 230 | ( ctime, mtime, atime ) = getAge(filePath) 231 | timestring = "" 232 | try: 233 | timestring = "CREATED: %s MODIFIED: %s ACCESSED: %s" % ( time.ctime(ctime), time.ctime(mtime), time.ctime(atime) ) 234 | except Exception: 235 | timestring = "CREATED: not_available MODIFIED: not_available ACCESSED: not_available" 236 | return timestring 237 | 238 | 239 | def runProcess(command, timeout=10): 240 | """ 241 | Run a process and check it's output 242 | :param command: 243 | :return output: 244 | """ 245 | output = "" 246 | returnCode = 0 247 | 248 | # Kill check 249 | try: 250 | kill_check = threading.Event() 251 | def _kill_process_after_a_timeout(pid): 252 | os.kill(pid, signal.SIGTERM) 253 | kill_check.set() # tell the main routine that we had to kill 254 | print("timeout hit - killing pid {0}".format(pid)) 255 | # use SIGKILL if hard to kill... 256 | return "", 1 257 | try: 258 | p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 259 | except subprocess.CalledProcessError as e: 260 | returnCode = e.returncode 261 | traceback.print_exc() 262 | #print p.communicate()[0] 263 | pid = p.pid 264 | watchdog = threading.Timer(timeout, _kill_process_after_a_timeout, args=(pid, )) 265 | watchdog.start() 266 | (stdout, stderr) = p.communicate() 267 | output = "{0}{1}".format(stdout.decode('utf-8'), stderr.decode('utf-8')) 268 | watchdog.cancel() # if it's still waiting to run 269 | success = not kill_check.isSet() 270 | kill_check.clear() 271 | except Exception: 272 | traceback.print_exc() 273 | 274 | return output, returnCode 275 | 276 | def getHostname(os_platform): 277 | """ 278 | Generate and return a hostname 279 | :return: 280 | """ 281 | # Computername 282 | if os_platform == "linux" or os_platform == "macos": 283 | return os.uname()[1] 284 | else: 285 | return os.environ['COMPUTERNAME'] 286 | -------------------------------------------------------------------------------- /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 | 17 | __version__ = '0.51.1' 18 | 19 | 20 | # Logger Class ----------------------------------------------------------------- 21 | class LokiLogger: 22 | 23 | STDOUT_CSV = 0 24 | STDOUT_LINE = 1 25 | FILE_CSV = 2 26 | FILE_LINE = 3 27 | SYSLOG_LINE = 4 28 | 29 | no_log_file = False 30 | log_file = "loki.log" 31 | csv = False 32 | hostname = "NOTSET" 33 | alerts = 0 34 | warnings = 0 35 | notices = 0 36 | messagecount = 0 37 | only_relevant = False 38 | remote_logging = False 39 | debug = False 40 | linesep = "\n" 41 | 42 | def __init__(self, no_log_file, log_file, hostname, remote_host, remote_port, syslog_tcp, csv, only_relevant, debug, platform, caller, customformatter=None): 43 | self.version = __version__ 44 | self.no_log_file = no_log_file 45 | self.log_file = log_file 46 | self.hostname = hostname 47 | self.csv = csv 48 | self.only_relevant = only_relevant 49 | self.debug = debug 50 | self.caller = caller 51 | self.CustomFormatter = customformatter 52 | if "windows" in platform.lower(): 53 | self.linesep = "\r\n" 54 | 55 | # Colorization ---------------------------------------------------- 56 | init() 57 | 58 | # Welcome 59 | if not self.csv: 60 | self.print_welcome() 61 | 62 | # Syslog server target 63 | if remote_host: 64 | try: 65 | # Create remote logger 66 | self.remote_logger = logging.getLogger('LOKI') 67 | self.remote_logger.setLevel(logging.DEBUG) 68 | socket_type = socket.SOCK_STREAM if syslog_tcp else socket.SOCK_DGRAM 69 | remote_syslog_handler = rfc5424logging.Rfc5424SysLogHandler(address=(remote_host, remote_port), 70 | facility=handlers.SysLogHandler.LOG_LOCAL3, 71 | socktype=socket_type) 72 | self.remote_logger.addHandler(remote_syslog_handler) 73 | self.remote_logging = True 74 | except Exception as e: 75 | print('Failed to create remote logger: ' + str(e)) 76 | sys.exit(1) 77 | 78 | def log(self, mes_type, module, message): 79 | 80 | if not self.debug and mes_type == "DEBUG": 81 | return 82 | 83 | # Counter 84 | if mes_type == "ALERT": 85 | self.alerts += 1 86 | if mes_type == "WARNING": 87 | self.warnings += 1 88 | if mes_type == "NOTICE": 89 | self.notices += 1 90 | self.messagecount += 1 91 | 92 | if self.only_relevant: 93 | if mes_type not in ('ALERT', 'WARNING'): 94 | return 95 | 96 | # to file 97 | if not self.no_log_file: 98 | self.log_to_file(message, mes_type, module) 99 | 100 | # to stdout 101 | try: 102 | self.log_to_stdout(message, mes_type) 103 | except Exception: 104 | print ("Cannot print certain characters to command line - see log file for full unicode encoded log line") 105 | self.log_to_stdout(message, mes_type) 106 | 107 | # to syslog server 108 | if self.remote_logging: 109 | self.log_to_remotesys(message, mes_type, module) 110 | 111 | def Format(self, type, message, *args): 112 | if not self.CustomFormatter: 113 | return message.format(*args) 114 | else: 115 | return self.CustomFormatter(type, message, args) 116 | 117 | def log_to_stdout(self, message, mes_type): 118 | 119 | if self.csv: 120 | print(self.Format(self.STDOUT_CSV, '{0},{1},{2},{3}', getSyslogTimestamp(), self.hostname, mes_type, message)) 121 | 122 | else: 123 | try: 124 | reset_all = Style.NORMAL+Fore.RESET 125 | key_color = Fore.WHITE 126 | base_color = Back.BLACK+Fore.WHITE 127 | high_color = Fore.WHITE+Back.BLACK 128 | 129 | if mes_type == "NOTICE": 130 | base_color = Fore.CYAN+''+Back.BLACK 131 | high_color = Fore.BLACK+''+Back.CYAN 132 | elif mes_type == "INFO": 133 | base_color = Fore.GREEN+''+Back.BLACK 134 | high_color = Fore.BLACK+''+Back.GREEN 135 | elif mes_type == "WARNING": 136 | base_color = Fore.YELLOW+''+Back.BLACK 137 | high_color = Fore.BLACK+''+Back.YELLOW 138 | elif mes_type == "ALERT": 139 | base_color = Fore.RED+''+Back.BLACK 140 | high_color = Fore.BLACK+''+Back.RED 141 | elif mes_type == "DEBUG": 142 | base_color = Fore.WHITE+''+Back.BLACK 143 | high_color = Fore.BLACK+''+Back.WHITE 144 | elif mes_type == "ERROR": 145 | base_color = Fore.MAGENTA+''+Back.BLACK 146 | high_color = Fore.WHITE+''+Back.MAGENTA 147 | elif mes_type == "RESULT": 148 | if "clean" in message.lower(): 149 | high_color = Fore.BLACK+Back.GREEN 150 | base_color = Fore.GREEN+Back.BLACK 151 | elif "suspicious" in message.lower(): 152 | high_color = Fore.BLACK+Back.YELLOW 153 | base_color = Fore.YELLOW+Back.BLACK 154 | else: 155 | high_color = Fore.BLACK+Back.RED 156 | base_color = Fore.RED+Back.BLACK 157 | 158 | # Colorize Type Word at the beginning of the line 159 | type_colorer = re.compile(r'([A-Z]{3,})', re.VERBOSE) 160 | mes_type = type_colorer.sub(high_color+r'[\1]'+base_color, mes_type) 161 | # Break Line before REASONS 162 | linebreaker = re.compile('(MD5:|SHA1:|SHA256:|MATCHES:|FILE:|FIRST_BYTES:|DESCRIPTION:|REASON_[0-9]+)', re.VERBOSE) 163 | message = linebreaker.sub(r'\n\1', message) 164 | # Colorize Key Words 165 | colorer = re.compile('([A-Z_0-9]{2,}:)\s', re.VERBOSE) 166 | message = colorer.sub(key_color+Style.BRIGHT+r'\1 '+base_color+Style.NORMAL, message) 167 | 168 | # Print to console 169 | if mes_type == "RESULT": 170 | res_message = "\b\b%s %s" % (mes_type, message) 171 | print(base_color+' '+res_message+' '+Back.BLACK) 172 | print(Fore.WHITE+' '+Style.NORMAL) 173 | else: 174 | 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)) 175 | 176 | except Exception: 177 | if self.debug: 178 | traceback.print_exc() 179 | sys.exit(1) 180 | print("Cannot print to cmd line - formatting error") 181 | 182 | def log_to_file(self, message, mes_type, module): 183 | try: 184 | # Write to file 185 | with codecs.open(self.log_file, "a", encoding='utf-8') as logfile: 186 | if self.csv: 187 | logfile.write(self.Format(self.FILE_CSV, u"{0},{1},{2},{3},{4}{5}", getSyslogTimestamp(), self.hostname, mes_type, module, message, self.linesep)) 188 | else: 189 | 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)) 190 | except Exception: 191 | if self.debug: 192 | traceback.print_exc() 193 | sys.exit(1) 194 | print("Cannot print line to log file {0}".format(self.log_file)) 195 | 196 | def log_to_remotesys(self, message, mes_type, module): 197 | # Preparing the message 198 | syslog_message = self.Format(self.SYSLOG_LINE, "LOKI: {0}: MODULE: {1} MESSAGE: {2}", mes_type.title(), module, message) 199 | try: 200 | # Mapping LOKI's levels to the syslog levels 201 | if mes_type == "NOTICE": 202 | self.remote_logger.info(syslog_message, extra={'msgid': str(self.messagecount)}) 203 | elif mes_type == "INFO": 204 | self.remote_logger.info(syslog_message, extra={'msgid': str(self.messagecount)}) 205 | elif mes_type == "WARNING": 206 | self.remote_logger.warning(syslog_message, extra={'msgid': str(self.messagecount)}) 207 | elif mes_type == "ALERT": 208 | self.remote_logger.critical(syslog_message, extra={'msgid': str(self.messagecount)}) 209 | elif mes_type == "DEBUG": 210 | self.remote_logger.debug(syslog_message, extra={'msgid': str(self.messagecount)}) 211 | elif mes_type == "ERROR": 212 | self.remote_logger.error(syslog_message, extra={'msgid': str(self.messagecount)}) 213 | except Exception as e: 214 | if self.debug: 215 | traceback.print_exc() 216 | sys.exit(1) 217 | print("Error while logging to remote syslog server ERROR: %s" % str(e)) 218 | 219 | def print_welcome(self): 220 | 221 | if self.caller == 'main': 222 | print(str(Back.WHITE)) 223 | print(" ".ljust(79) + Back.BLACK + Style.BRIGHT) 224 | 225 | print(" __ ____ __ ______ ") 226 | print(" / / / __ \\/ //_/ _/ ") 227 | print(" / /__/ /_/ / ,< _/ / ") 228 | print(" /____/\\____/_/|_/___/ ") 229 | print(" YARA and IOC Scanner ") 230 | print(" ") 231 | print(" by Florian Roth, GNU General Public License") 232 | print(" version %s (Python 3 release)" % __version__) 233 | print(" ") 234 | print(" DISCLAIMER - USE AT YOUR OWN RISK") 235 | print(str(Back.WHITE)) 236 | print(" ".ljust(79) + Back.BLACK + Fore.GREEN) 237 | print(Fore.WHITE+''+Back.BLACK) 238 | 239 | else: 240 | print(" ") 241 | print(Back.GREEN + " ".ljust(79) + Back.BLACK + Fore.GREEN) 242 | 243 | print(" ") 244 | print(" LOKI UPGRADER ") 245 | 246 | print(" ") 247 | print(Back.GREEN + " ".ljust(79) + Back.BLACK) 248 | print(Fore.WHITE + '' + Back.BLACK) 249 | 250 | 251 | def getSyslogTimestamp(): 252 | date_obj = datetime.datetime.utcnow() 253 | date_str = date_obj.strftime("%Y%m%dT%H:%M:%SZ") 254 | return date_str 255 | -------------------------------------------------------------------------------- /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: 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 | try: 19 | from urlparse import urlparse 20 | except ImportError: 21 | from urllib.parse import urlparse 22 | from os.path import exists 23 | 24 | # Win32 Imports 25 | if _platform == "win32": 26 | try: 27 | import win32api 28 | except Exception: 29 | platform = "linux" # crazy guess 30 | 31 | 32 | from lib.lokilogger import * 33 | 34 | # Platform 35 | platform = "" 36 | if _platform == "linux" or _platform == "linux2": 37 | platform = "linux" 38 | elif _platform == "darwin": 39 | platform = "macos" 40 | elif _platform == "win32": 41 | platform = "windows" 42 | 43 | def needs_update(sig_url): 44 | try: 45 | o=urlparse(sig_url) 46 | path=o.path.split('/') 47 | branch=path[4].split('.')[0] 48 | path.pop(len(path)-1) 49 | path.pop(len(path)-1) 50 | url = o.scheme+'://api.'+o.netloc+'/repos'+'/'.join(path)+'/commits/'+branch 51 | response_info = urlopen(url) 52 | j = json.load(response_info) 53 | sha=j['sha'] 54 | cache='_'.join(path)+'.cache' 55 | changed=False 56 | if exists(cache): 57 | with open(cache, "r") as file: 58 | old_sha = file.read().rstrip() 59 | if sha != old_sha: 60 | changed=True 61 | else: 62 | with open(cache, "w") as file: 63 | file.write(sha) 64 | changed=True 65 | return changed 66 | except Exception: 67 | return True 68 | 69 | 70 | class LOKIUpdater(object): 71 | 72 | # Incompatible signatures 73 | INCOMPATIBLE_RULES = [] 74 | 75 | UPDATE_URL_SIGS = [ 76 | "https://github.com/Neo23x0/signature-base/archive/master.zip", 77 | "https://github.com/reversinglabs/reversinglabs-yara-rules/archive/develop.zip" 78 | ] 79 | 80 | UPDATE_URL_LOKI = "https://api.github.com/repos/Neo23x0/Loki/releases/latest" 81 | 82 | def __init__(self, debug, logger, application_path): 83 | self.debug = debug 84 | self.logger = logger 85 | self.application_path = application_path 86 | 87 | def update_signatures(self, clean=False): 88 | try: 89 | for sig_url in self.UPDATE_URL_SIGS: 90 | if needs_update(sig_url): 91 | # Downloading current repository 92 | try: 93 | self.logger.log("INFO", "Upgrader", "Downloading %s ..." % sig_url) 94 | response = urlopen(sig_url) 95 | except Exception: 96 | if self.debug: 97 | traceback.print_exc() 98 | self.logger.log("ERROR", "Upgrader", "Error downloading the signature database - " 99 | "check your Internet connection") 100 | sys.exit(1) 101 | 102 | # Preparations 103 | try: 104 | sigDir = os.path.join(self.application_path, os.path.abspath('signature-base/')) 105 | if clean: 106 | self.logger.log("INFO", "Upgrader", "Cleaning directory '%s'" % sigDir) 107 | shutil.rmtree(sigDir) 108 | for outDir in ['', 'iocs', 'yara', 'misc']: 109 | fullOutDir = os.path.join(sigDir, outDir) 110 | if not os.path.exists(fullOutDir): 111 | os.makedirs(fullOutDir) 112 | except Exception: 113 | if self.debug: 114 | traceback.print_exc() 115 | self.logger.log("ERROR", "Upgrader", "Error while creating the signature-base directories") 116 | sys.exit(1) 117 | 118 | # Read ZIP file 119 | try: 120 | zipUpdate = zipfile.ZipFile(io.BytesIO(response.read())) 121 | for zipFilePath in zipUpdate.namelist(): 122 | sigName = os.path.basename(zipFilePath) 123 | if zipFilePath.endswith("/"): 124 | continue 125 | # Skip incompatible rules 126 | skip = False 127 | for incompatible_rule in self.INCOMPATIBLE_RULES: 128 | if sigName.endswith(incompatible_rule): 129 | self.logger.log("NOTICE", "Upgrader", "Skipping incompatible rule %s" % sigName) 130 | skip = True 131 | if skip: 132 | continue 133 | # Extract the rules 134 | self.logger.log("DEBUG", "Upgrader", "Extracting %s ..." % zipFilePath) 135 | if "/iocs/" in zipFilePath and zipFilePath.endswith(".txt"): 136 | targetFile = os.path.join(sigDir, "iocs", sigName) 137 | elif "/yara/" in zipFilePath and zipFilePath.endswith(".yar"): 138 | targetFile = os.path.join(sigDir, "yara", sigName) 139 | elif "/misc/" in zipFilePath and zipFilePath.endswith(".txt"): 140 | targetFile = os.path.join(sigDir, "misc", sigName) 141 | elif zipFilePath.endswith(".yara"): 142 | targetFile = os.path.join(sigDir, "yara", sigName) 143 | else: 144 | continue 145 | 146 | # New file 147 | if not os.path.exists(targetFile): 148 | self.logger.log("INFO", "Upgrader", "New signature file: %s" % sigName) 149 | 150 | # Extract file 151 | source = zipUpdate.open(zipFilePath) 152 | target = open(targetFile, "wb") 153 | with source, target: 154 | shutil.copyfileobj(source, target) 155 | target.close() 156 | source.close() 157 | 158 | except Exception: 159 | if self.debug: 160 | traceback.print_exc() 161 | self.logger.log("ERROR", "Upgrader", "Error while extracting the signature files from the download " 162 | "package") 163 | sys.exit(1) 164 | else: 165 | self.logger.log("INFO", "Upgrader", "%s is up to date." % sig_url) 166 | 167 | except Exception: 168 | if self.debug: 169 | traceback.print_exc() 170 | return False 171 | return True 172 | 173 | 174 | def update_loki(self): 175 | try: 176 | 177 | # Downloading the info for latest release 178 | try: 179 | self.logger.log("INFO", "Upgrader", "Checking location of latest release %s ..." % self.UPDATE_URL_LOKI) 180 | response_info = urlopen(self.UPDATE_URL_LOKI) 181 | data = json.load(response_info) 182 | # Get download URL 183 | zip_url = data['assets'][0]['browser_download_url'] 184 | self.logger.log("INFO", "Upgrader", "Downloading latest release %s ..." % zip_url) 185 | response_zip = urlopen(zip_url) 186 | except Exception: 187 | if self.debug: 188 | traceback.print_exc() 189 | self.logger.log("ERROR", "Upgrader", "Error downloading the loki update - check your Internet connection") 190 | sys.exit(1) 191 | 192 | # Read ZIP file 193 | try: 194 | zipUpdate = zipfile.ZipFile(io.BytesIO(response_zip.read())) 195 | for zipFilePath in zipUpdate.namelist(): 196 | if zipFilePath.endswith("/") or "/config/" in zipFilePath or "/loki-upgrader.exe" in zipFilePath: 197 | continue 198 | 199 | source = zipUpdate.open(zipFilePath) 200 | targetFile = "/".join(zipFilePath.split("/")[1:]) 201 | 202 | self.logger.log("INFO", "Upgrader", "Extracting %s ..." %targetFile) 203 | 204 | try: 205 | # Create file if not present 206 | if not os.path.exists(os.path.dirname(targetFile)): 207 | if os.path.dirname(targetFile) != '': 208 | os.makedirs(os.path.dirname(targetFile)) 209 | except Exception: 210 | if self.debug: 211 | self.logger.log("DEBUG", "Upgrader", "Cannot create dir name '%s'" % os.path.dirname(targetFile)) 212 | traceback.print_exc() 213 | 214 | try: 215 | # Create target file 216 | target = open(targetFile, "wb") 217 | with source, target: 218 | shutil.copyfileobj(source, target) 219 | if self.debug: 220 | self.logger.log("DEBUG", "Upgrader", "Successfully extracted '%s'" % targetFile) 221 | target.close() 222 | except Exception: 223 | self.logger.log("ERROR", "Upgrader", "Cannot extract '%s'" % targetFile) 224 | if self.debug: 225 | traceback.print_exc() 226 | 227 | except Exception: 228 | if self.debug: 229 | traceback.print_exc() 230 | self.logger.log("ERROR", "Upgrader", 231 | "Error while extracting the signature files from the download package") 232 | sys.exit(1) 233 | 234 | except Exception: 235 | if self.debug: 236 | traceback.print_exc() 237 | return False 238 | return True 239 | 240 | 241 | def get_application_path(): 242 | try: 243 | if getattr(sys, 'frozen', False): 244 | application_path = os.path.dirname(os.path.realpath(sys.executable)) 245 | else: 246 | application_path = os.path.dirname(os.path.realpath(__file__)) 247 | if "~" in application_path and platform == "windows": 248 | # print "Trying to translate" 249 | # print application_path 250 | application_path = win32api.GetLongPathName(application_path) 251 | #if args.debug: 252 | # logger.log("DEBUG", "Init", "Application Path: %s" % application_path) 253 | return application_path 254 | except Exception: 255 | print("Error while evaluation of application path") 256 | traceback.print_exc() 257 | 258 | 259 | if __name__ == '__main__': 260 | 261 | # Parse Arguments 262 | parser = argparse.ArgumentParser(description='Loki - Upgrader') 263 | parser.add_argument('-l', help='Log file', metavar='log-file', default='loki-upgrade.log') 264 | parser.add_argument('--sigsonly', action='store_true', help='Update the signatures only', default=False) 265 | parser.add_argument('--progonly', action='store_true', help='Update the program files only', default=False) 266 | parser.add_argument('--nolog', action='store_true', help='Don\'t write a local log file', default=False) 267 | parser.add_argument('--debug', action='store_true', default=False, help='Debug output') 268 | parser.add_argument('--clean', action='store_true', default=False, help='Clean up the signature directory and get ' 269 | 'a fresh set') 270 | parser.add_argument('--detached', action='store_true', default=False, help=argparse.SUPPRESS) 271 | 272 | args = parser.parse_args() 273 | 274 | # Computername 275 | if platform == "windows": 276 | t_hostname = os.environ['COMPUTERNAME'] 277 | else: 278 | t_hostname = os.uname()[1] 279 | 280 | # Logger 281 | logger = LokiLogger(args.nolog, args.l, t_hostname, '', '', False, False, False, args.debug, platform=platform, caller='upgrader') 282 | 283 | # Update LOKI 284 | updater = LOKIUpdater(args.debug, logger, get_application_path()) 285 | 286 | if not args.sigsonly: 287 | logger.log("INFO", "Upgrader", "Updating LOKI ...") 288 | updater.update_loki() 289 | if not args.progonly: 290 | logger.log("INFO", "Upgrader", "Updating Signatures ...") 291 | updater.update_signatures(args.clean) 292 | 293 | logger.log("INFO", "Upgrader", "Update complete") 294 | 295 | if args.detached: 296 | logger.log("INFO", "Upgrader", "Press any key to return ...") 297 | 298 | sys.exit(0) 299 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Inactively Maintained](https://img.shields.io/badge/Maintenance%20Level-Inactively%20Maintained-yellowgreen.svg)](https://gist.github.com/cheerfulstoic/d107229326a01ff0f333a1d3476e068d) 2 | 3 | ## Important Note 4 | 5 | This project is now in inactive maintenance mode. This means that while I merge pull requests for bug fixes and straightforward issues, I currently lack the time to add new features or expand existing ones. For years, my focus has been on developing a more advanced scanner, THOR, which offers a range of improvements over this project. A free version, [THOR Lite](https://www.nextron-systems.com/thor-lite/), is available; it's faster, more stable, and rigorously tested in our CI environments—simply a better solution. You can find a comparison of the open-source, free, and commercial scanners [here](https://www.nextron-systems.com/thor-lite/). 6 | 7 | I've also begun work on a Rust-based version of LOKI called [LOKI 2](https://github.com/Neo23x0/Loki2). However, I’m unsure when it will reach feature parity with the current LOKI release. Additionally, I created a [flow chart](https://twitter.com/cyb3rops/status/1361980419223207936) to help you decide which scanner best meets your needs. 8 | 9 | ![Logo](/lokiicon.jpg) 10 | # Loki - Simple IOC and YARA Scanner 11 | 12 | Scanner for Simple Indicators of Compromise 13 | 14 | Detection is based on four detection methods: 15 | 16 | 1. File Name IOC 17 | Regex match on full file path/name 18 | 19 | 2. Yara Rule Check 20 | Yara signature match on file data and process memory 21 | 22 | 3. Hash Check 23 | Compares known malicious hashes (MD5, SHA1, SHA256) with scanned files 24 | 25 | 4. C2 Back Connect Check 26 | Compares process connection endpoints with C2 IOCs (new since version v.10) 27 | 28 | Additional Checks: 29 | 30 | 1. Regin filesystem check (via --reginfs) 31 | 2. Process anomaly check (based on [Sysforensics](http://goo.gl/P99QZQ) 32 | 3. SWF decompressed scan (new since version v0.8) 33 | 4. SAM dump check 34 | 35 | The Windows binary is compiled with PyInstaller and should run as x86 application on both x86 and x64 based systems. 36 | 37 | ## How-To Run LOKI and Analyse the Reports 38 | 39 | ### Run 40 | 41 | - Download the newest version of LOKI from the [releases](https://github.com/Neo23x0/Loki/releases) section 42 | - Extract the program package 43 | - Run loki-upgrader.exe on system with Internet access to retrieve the newest signatures 44 | - Bring the program folder to a target system that should be scanned: removable media, network share, folder on target system 45 | - 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) 46 | 47 | ### Reports 48 | 49 | - The resulting report will show a GREEN, YELLOW or RED result line. 50 | - Please analyse the findings yourself by: 51 | 1. uploading non-confidential samples to Virustotal.com 52 | 2. Search the web for the filename 53 | 3. Search the web for keywords from the rule name (e.g. EQUATIONGroupMalware_1 > search for "Equation Group") 54 | 4. Search the web for the MD5 hash of the sample 55 | - 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) 56 | 57 | ## Requirements 58 | 59 | No requirements if you use the compiled EXE. 60 | 61 | If you want to build it yourself: 62 | 63 | - [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 64 | - [colorama](https://pypi.python.org/pypi/colorama) : to color it up 65 | - [psutil](https://pypi.python.org/pypi/psutil) : process checks 66 | - [pywin32](http://sourceforge.net/projects/pywin32/) : path conversions (PyInstaller [issue](https://github.com/pyinstaller/pyinstaller/issues/1282); Windows only) 67 | 68 | # Usage 69 | 70 | usage: loki.py [-h] [-p path] [-s kilobyte] [-l log-file] [-r remote-loghost] 71 | [-t remote-syslog-port] [-a alert-level] [-w warning-level] 72 | [-n notice-level] [--allhds] [--alldrives] [--printall] 73 | [--allreasons] [--noprocscan] [--nofilescan] [--vulnchecks] 74 | [--nolevcheck] [--scriptanalysis] [--rootkit] [--noindicator] 75 | [--dontwait] [--intense] [--csv] [--onlyrelevant] [--nolog] 76 | [--update] [--debug] [--maxworkingset MAXWORKINGSET] 77 | [--syslogtcp] [--logfolder log-folder] [--nopesieve] 78 | [--pesieveshellc] [--nolisten] 79 | [--excludeprocess EXCLUDEPROCESS] [--force] 80 | 81 | Loki - Simple IOC Scanner 82 | 83 | optional arguments: 84 | -h, --help show this help message and exit 85 | -p path Path to scan 86 | -s kilobyte Maximum file size to check in KB (default 5000 KB) 87 | -l log-file Log file 88 | -r remote-loghost Remote syslog system 89 | -t remote-syslog-port 90 | Remote syslog port 91 | -a alert-level Alert score 92 | -w warning-level Warning score 93 | -n notice-level Notice score 94 | --allhds Scan all local hard drives (Windows only) 95 | --alldrives Scan all drives (including network drives and 96 | removable media) 97 | --printall Print all files that are scanned 98 | --allreasons Print all reasons that caused the score 99 | --noprocscan Skip the process scan 100 | --nofilescan Skip the file scan 101 | --vulnchecks Run the vulnerability checks 102 | --nolevcheck Skip the Levenshtein distance check 103 | --scriptanalysis Statistical analysis for scripts to detect obfuscated 104 | code (beta) 105 | --rootkit Skip the rootkit check 106 | --noindicator Do not show a progress indicator 107 | --dontwait Do not wait on exit 108 | --intense Intense scan mode (also scan unknown file types and 109 | all extensions) 110 | --csv Write CSV log format to STDOUT (machine processing) 111 | --onlyrelevant Only print warnings or alerts 112 | --nolog Don't write a local log file 113 | --update Update the signatures from the "signature-base" sub 114 | repository 115 | --debug Debug output 116 | --maxworkingset MAXWORKINGSET 117 | Maximum working set size of processes to scan (in MB, 118 | default 100 MB) 119 | --syslogtcp Use TCP instead of UDP for syslog logging 120 | --logfolder log-folder 121 | Folder to use for logging when log file is not 122 | specified 123 | --nopesieve Do not perform pe-sieve scans 124 | --pesieveshellc Perform pe-sieve shellcode scan 125 | --nolisten Dot not show listening connections 126 | --excludeprocess EXCLUDEPROCESS 127 | Specify an executable name to exclude from scans, can 128 | be used multiple times 129 | --force Force the scan on a certain folder (even if excluded 130 | with hard exclude in LOKI's code 131 | 132 | 133 | ## Signature and IOCs 134 | 135 | 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. 136 | 137 | 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. 138 | 139 | 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. 140 | 141 | For Hash IOCs (divided by newline; hash type is detected automatically) 142 | ``` 143 | Hash;Description [Reference] 144 | ``` 145 | 146 | For Filename IOCs (divided by newline) 147 | ``` 148 | # (optional) Description [Reference] 149 | Filename as Regex[;Score as integer[;False-positive as Regex]] 150 | ``` 151 | 152 | # User-Defined Scan Excludes 153 | 154 | 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. 155 | 156 | The '''exclude.cfg''' looks like this: 157 | 158 | # Excluded directories 159 | # 160 | # - add directories you want to exclude from the scan 161 | # - double escape back slashes 162 | # - values are case-insensitive 163 | # - remember to use back slashes on Windows and slashes on Linux / Unix / OSX 164 | # - each line contains a regex that matches somewhere in the full path (case insensitive) 165 | # e.g.: 166 | # Regex: \\System32\\ 167 | # Matches C:\Windows\System32\cmd.exe 168 | # 169 | # Regex: /var/log/[^/]+\.log 170 | # Matches: /var/log/test.log 171 | # Not Matches: /var/log/test.gz 172 | # 173 | 174 | # Useful examples 175 | \\Ntfrs\\ 176 | \\Ntds\\ 177 | \\EDB[^\.]+\.log 178 | Sysvol\\Staging\\Nntfrs_cmp 179 | \\System Volume Information\\DFSR 180 | 181 | # Screenshots 182 | 183 | Loki Scan 184 | 185 | ![Screen](/screens/lokiscan2.png) 186 | 187 | Regin Matches 188 | 189 | ![Screen](/screens/lokiscan1.png) 190 | 191 | Regin False Positives 192 | 193 | ![Screen](/screens/lokiscan3.png) 194 | 195 | Hash based IOCs 196 | 197 | ![Screen](/screens/lokiconf1.png) 198 | 199 | File Name based IOCs 200 | 201 | ![Screen](/screens/lokiconf2.png) 202 | 203 | Generated log file 204 | 205 | ![Screen](/screens/lokilog1.png) 206 | 207 | # Contact 208 | 209 | LOKI scanner on our company homepage 210 | [https://www.nextron-systems.com/loki/](https://www.nextron-systems.com/loki/) 211 | 212 | Twitter 213 | [@cyb3rOps](https://twitter.com/Cyb3rOps) 214 | [@thor_scanner](https://twitter.com/thor_scanner) 215 | 216 | If you are interested in a corporate solution for APT scanning, check out Loki's big brother [THOR](https://www.nextron-systems.com/thor/). 217 | 218 | # Compile the Scanner 219 | 220 | Download [PyInstaller](https://github.com/pyinstaller/pyinstaller/releases/), switch to the pyinstaller program directory and execute: 221 | 222 | python ./pyinstaller.py -F C:\path\to\loki.py 223 | 224 | This will create a `loki.exe` in the subfolder `./loki/dist`. 225 | 226 | ## Pro Tip (optional) 227 | 228 | 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: 229 | 230 | a.binaries + [('msvcr100.dll', 'C:\Windows\System32\msvcr100.dll', 'BINARY')], 231 | 232 | # Use LOKI on Mac OS X (Or later) or Linux 233 | 234 | 235 | - Initialize a Python virtual environment for loki. To do this you have to make sure you have the Python module `venv` then run `python -m venv path/to/venv` where `path/to/venv` is the path to your virtual environment. Test your virtual environment by running `path/to/venv/bin/python --version`. 236 | Upgrade your virtual environment modules for `pip`, `setuptools`, and `wheel` by running `path/to/venv/bin/python -m pip install --upgrade pip setuptools wheel`. 237 | - Install libraries ```path/to/venv/bin/python -m pip install colorama yara-python psutil rfc5424-logging-handler netaddr``` 238 | - Run loki-upgrader.py ```path/to/venv/bin/python path/to/loki/loki-upgrader.py``` where `path/to/loki` is the path of the Loki repository. 239 | - Run loki ```sudo path/to/venv/bin/python loki.py``` 240 | 241 | # Yara sources 242 | 243 | Download Yara sources from [here](https://github.com/VirusTotal/yara/releases) 244 | 245 | 246 | # Antivirus - False Positives 247 | 248 | 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. 249 | 250 | If you don't trust the compiled executable, please compile it yourself. 251 | 252 | # License 253 | 254 | Loki - Simple IOC Scanner 255 | Copyright (c) 2015 Florian Roth 256 | 257 | This program is free software: you can redistribute it and/or modify 258 | it under the terms of the GNU General Public License as published by 259 | the Free Software Foundation, either version 3 of the License, or 260 | (at your option) any later version. 261 | 262 | This program is distributed in the hope that it will be useful, 263 | but WITHOUT ANY WARRANTY; without even the implied warranty of 264 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 265 | GNU General Public License for more details. 266 | 267 | You should have received a copy of the GNU General Public License 268 | along with this program. If not, see [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/) 269 | -------------------------------------------------------------------------------- /test/yara/JFolder.jsp: -------------------------------------------------------------------------------- 1 | <% 2 | /** 3 | JFileMan V1.0 windows platform 4 | @Filename�� JFolder.jsp 5 | @Description�� һ���򵥵�ϵͳ�ļ�Ŀ¼��ʾ������������Դ���������ṩ�������ļ��������������������ˡ� 6 | @Author�� Steven Cee 7 | @Email �� cqq1978@Gmail.com 8 | @Bugs : ����ʱ�������ļ����޷�������ʾ��Unix����ϵͳ�ϴ� 9 | */ 10 | %> 11 | <%@page errorPage="/"%> 12 | <%@page contentType="text/html;charset=gb2312"%> 13 | <%@page import="java.io.*,java.util.*,java.net.*" %> 14 | <%! 15 | private final static int languageNo=1; //Language,0 : Chinese; 1:English 16 | String strThisFile="JFileMan.jsp"; 17 | String strSeparator = File.separator; 18 | String[] authorInfo={" д�IJ��ã��������ð� - - by ����ǿ http://www.topronet.com "," Thanks for your support - - by Steven Cee http://www.topronet.com "}; 19 | String[] strFileManage = {"�� �� �� ��","File Management"}; 20 | String[] strCommand = {"CMD �� ��","Command Window"}; 21 | String[] strSysProperty = {"ϵ ͳ �� ��","System Property"}; 22 | String[] strHelp = {"�� ��","Help"}; 23 | String[] strParentFolder = {"�ϼ�Ŀ¼","Parent Folder"}; 24 | String[] strCurrentFolder= {"��ǰĿ¼","Current Folder"}; 25 | String[] strDrivers = {"������","Drivers"}; 26 | String[] strFileName = {"�ļ�����","File Name"}; 27 | String[] strFileSize = {"�ļ���С","File Size"}; 28 | String[] strLastModified = {"����޸�","Last Modified"}; 29 | String[] strFileOperation= {"�ļ�����","Operations"}; 30 | String[] strFileEdit = {"�޸�","Edit"}; 31 | String[] strFileDown = {"����","Download"}; 32 | String[] strFileCopy = {"����","Move"}; 33 | String[] strFileDel = {"ɾ��","Delete"}; 34 | String[] strExecute = {"ִ��","Execute"}; 35 | String[] strBack = {"����","Back"}; 36 | String[] strFileSave = {"����","Save"}; 37 | 38 | public class FileHandler 39 | { 40 | private String strAction=""; 41 | private String strFile=""; 42 | void FileHandler(String action,String f) 43 | { 44 | 45 | } 46 | } 47 | 48 | public static class UploadMonitor { 49 | 50 | static Hashtable uploadTable = new Hashtable(); 51 | 52 | static void set(String fName, UplInfo info) { 53 | uploadTable.put(fName, info); 54 | } 55 | 56 | static void remove(String fName) { 57 | uploadTable.remove(fName); 58 | } 59 | 60 | static UplInfo getInfo(String fName) { 61 | UplInfo info = (UplInfo) uploadTable.get(fName); 62 | return info; 63 | } 64 | } 65 | 66 | public class UplInfo { 67 | 68 | public long totalSize; 69 | public long currSize; 70 | public long starttime; 71 | public boolean aborted; 72 | 73 | public UplInfo() { 74 | totalSize = 0l; 75 | currSize = 0l; 76 | starttime = System.currentTimeMillis(); 77 | aborted = false; 78 | } 79 | 80 | public UplInfo(int size) { 81 | totalSize = size; 82 | currSize = 0; 83 | starttime = System.currentTimeMillis(); 84 | aborted = false; 85 | } 86 | 87 | public String getUprate() { 88 | long time = System.currentTimeMillis() - starttime; 89 | if (time != 0) { 90 | long uprate = currSize * 1000 / time; 91 | return convertFileSize(uprate) + "/s"; 92 | } 93 | else return "n/a"; 94 | } 95 | 96 | public int getPercent() { 97 | if (totalSize == 0) return 0; 98 | else return (int) (currSize * 100 / totalSize); 99 | } 100 | 101 | public String getTimeElapsed() { 102 | long time = (System.currentTimeMillis() - starttime) / 1000l; 103 | if (time - 60l >= 0){ 104 | if (time % 60 >=10) return time / 60 + ":" + (time % 60) + "m"; 105 | else return time / 60 + ":0" + (time % 60) + "m"; 106 | } 107 | else return time<10 ? "0" + time + "s": time + "s"; 108 | } 109 | 110 | public String getTimeEstimated() { 111 | if (currSize == 0) return "n/a"; 112 | long time = System.currentTimeMillis() - starttime; 113 | time = totalSize * time / currSize; 114 | time /= 1000l; 115 | if (time - 60l >= 0){ 116 | if (time % 60 >=10) return time / 60 + ":" + (time % 60) + "m"; 117 | else return time / 60 + ":0" + (time % 60) + "m"; 118 | } 119 | else return time<10 ? "0" + time + "s": time + "s"; 120 | } 121 | 122 | } 123 | 124 | public class FileInfo { 125 | 126 | public String name = null, clientFileName = null, fileContentType = null; 127 | private byte[] fileContents = null; 128 | public File file = null; 129 | public StringBuffer sb = new StringBuffer(100); 130 | 131 | public void setFileContents(byte[] aByteArray) { 132 | fileContents = new byte[aByteArray.length]; 133 | System.arraycopy(aByteArray, 0, fileContents, 0, aByteArray.length); 134 | } 135 | } 136 | 137 | // A Class with methods used to process a ServletInputStream 138 | public class HttpMultiPartParser { 139 | 140 | private final String lineSeparator = System.getProperty("line.separator", "\n"); 141 | private final int ONE_MB = 1024 * 1; 142 | 143 | public Hashtable processData(ServletInputStream is, String boundary, String saveInDir, 144 | int clength) throws IllegalArgumentException, IOException { 145 | if (is == null) throw new IllegalArgumentException("InputStream"); 146 | if (boundary == null || boundary.trim().length() < 1) throw new IllegalArgumentException( 147 | "\"" + boundary + "\" is an illegal boundary indicator"); 148 | boundary = "--" + boundary; 149 | StringTokenizer stLine = null, stFields = null; 150 | FileInfo fileInfo = null; 151 | Hashtable dataTable = new Hashtable(5); 152 | String line = null, field = null, paramName = null; 153 | boolean saveFiles = (saveInDir != null && saveInDir.trim().length() > 0); 154 | boolean isFile = false; 155 | if (saveFiles) { // Create the required directory (including parent dirs) 156 | File f = new File(saveInDir); 157 | f.mkdirs(); 158 | } 159 | line = getLine(is); 160 | if (line == null || !line.startsWith(boundary)) throw new IOException( 161 | "Boundary not found; boundary = " + boundary + ", line = " + line); 162 | while (line != null) { 163 | if (line == null || !line.startsWith(boundary)) return dataTable; 164 | line = getLine(is); 165 | if (line == null) return dataTable; 166 | stLine = new StringTokenizer(line, ";\r\n"); 167 | if (stLine.countTokens() < 2) throw new IllegalArgumentException( 168 | "Bad data in second line"); 169 | line = stLine.nextToken().toLowerCase(); 170 | if (line.indexOf("form-data") < 0) throw new IllegalArgumentException( 171 | "Bad data in second line"); 172 | stFields = new StringTokenizer(stLine.nextToken(), "=\""); 173 | if (stFields.countTokens() < 2) throw new IllegalArgumentException( 174 | "Bad data in second line"); 175 | fileInfo = new FileInfo(); 176 | stFields.nextToken(); 177 | paramName = stFields.nextToken(); 178 | isFile = false; 179 | if (stLine.hasMoreTokens()) { 180 | field = stLine.nextToken(); 181 | stFields = new StringTokenizer(field, "=\""); 182 | if (stFields.countTokens() > 1) { 183 | if (stFields.nextToken().trim().equalsIgnoreCase("filename")) { 184 | fileInfo.name = paramName; 185 | String value = stFields.nextToken(); 186 | if (value != null && value.trim().length() > 0) { 187 | fileInfo.clientFileName = value; 188 | isFile = true; 189 | } 190 | else { 191 | line = getLine(is); // Skip "Content-Type:" line 192 | line = getLine(is); // Skip blank line 193 | line = getLine(is); // Skip blank line 194 | line = getLine(is); // Position to boundary line 195 | continue; 196 | } 197 | } 198 | } 199 | else if (field.toLowerCase().indexOf("filename") >= 0) { 200 | line = getLine(is); // Skip "Content-Type:" line 201 | line = getLine(is); // Skip blank line 202 | line = getLine(is); // Skip blank line 203 | line = getLine(is); // Position to boundary line 204 | continue; 205 | } 206 | } 207 | boolean skipBlankLine = true; 208 | if (isFile) { 209 | line = getLine(is); 210 | if (line == null) return dataTable; 211 | if (line.trim().length() < 1) skipBlankLine = false; 212 | else { 213 | stLine = new StringTokenizer(line, ": "); 214 | if (stLine.countTokens() < 2) throw new IllegalArgumentException( 215 | "Bad data in third line"); 216 | stLine.nextToken(); // Content-Type 217 | fileInfo.fileContentType = stLine.nextToken(); 218 | } 219 | } 220 | if (skipBlankLine) { 221 | line = getLine(is); 222 | if (line == null) return dataTable; 223 | } 224 | if (!isFile) { 225 | line = getLine(is); 226 | if (line == null) return dataTable; 227 | dataTable.put(paramName, line); 228 | // If parameter is dir, change saveInDir to dir 229 | if (paramName.equals("dir")) saveInDir = line; 230 | line = getLine(is); 231 | continue; 232 | } 233 | try { 234 | UplInfo uplInfo = new UplInfo(clength); 235 | UploadMonitor.set(fileInfo.clientFileName, uplInfo); 236 | OutputStream os = null; 237 | String path = null; 238 | if (saveFiles) os = new FileOutputStream(path = getFileName(saveInDir, 239 | fileInfo.clientFileName)); 240 | else os = new ByteArrayOutputStream(ONE_MB); 241 | boolean readingContent = true; 242 | byte previousLine[] = new byte[2 * ONE_MB]; 243 | byte temp[] = null; 244 | byte currentLine[] = new byte[2 * ONE_MB]; 245 | int read, read3; 246 | if ((read = is.readLine(previousLine, 0, previousLine.length)) == -1) { 247 | line = null; 248 | break; 249 | } 250 | while (readingContent) { 251 | if ((read3 = is.readLine(currentLine, 0, currentLine.length)) == -1) { 252 | line = null; 253 | uplInfo.aborted = true; 254 | break; 255 | } 256 | if (compareBoundary(boundary, currentLine)) { 257 | os.write(previousLine, 0, read - 2); 258 | line = new String(currentLine, 0, read3); 259 | break; 260 | } 261 | else { 262 | os.write(previousLine, 0, read); 263 | uplInfo.currSize += read; 264 | temp = currentLine; 265 | currentLine = previousLine; 266 | previousLine = temp; 267 | read = read3; 268 | }//end else 269 | }//end while 270 | os.flush(); 271 | os.close(); 272 | if (!saveFiles) { 273 | ByteArrayOutputStream baos = (ByteArrayOutputStream) os; 274 | fileInfo.setFileContents(baos.toByteArray()); 275 | } 276 | else fileInfo.file = new File(path); 277 | dataTable.put(paramName, fileInfo); 278 | uplInfo.currSize = uplInfo.totalSize; 279 | }//end try 280 | catch (IOException e) { 281 | throw e; 282 | } 283 | } 284 | return dataTable; 285 | } 286 | 287 | /** 288 | * Compares boundary string to byte array 289 | */ 290 | private boolean compareBoundary(String boundary, byte ba[]) { 291 | byte b; 292 | if (boundary == null || ba == null) return false; 293 | for (int i = 0; i < boundary.length(); i++) 294 | if ((byte) boundary.charAt(i) != ba[i]) return false; 295 | return true; 296 | } 297 | 298 | /** Convenience method to read HTTP header lines */ 299 | private synchronized String getLine(ServletInputStream sis) throws IOException { 300 | byte b[] = new byte[1024]; 301 | int read = sis.readLine(b, 0, b.length), index; 302 | String line = null; 303 | if (read != -1) { 304 | line = new String(b, 0, read); 305 | if ((index = line.indexOf('\n')) >= 0) line = line.substring(0, index - 1); 306 | } 307 | return line; 308 | } 309 | 310 | public String getFileName(String dir, String fileName) throws IllegalArgumentException { 311 | String path = null; 312 | if (dir == null || fileName == null) throw new IllegalArgumentException( 313 | "dir or fileName is null"); 314 | int index = fileName.lastIndexOf('/'); 315 | String name = null; 316 | if (index >= 0) name = fileName.substring(index + 1); 317 | else name = fileName; 318 | index = name.lastIndexOf('\\'); 319 | if (index >= 0) fileName = name.substring(index + 1); 320 | path = dir + File.separator + fileName; 321 | if (File.separatorChar == '/') return path.replace('\\', File.separatorChar); 322 | else return path.replace('/', File.separatorChar); 323 | } 324 | } //End of class HttpMultiPartParser 325 | 326 | String formatPath(String p) 327 | { 328 | StringBuffer sb=new StringBuffer(); 329 | for (int i = 0; i < p.length(); i++) 330 | { 331 | if(p.charAt(i)=='\\') 332 | { 333 | sb.append("\\\\"); 334 | } 335 | else 336 | { 337 | sb.append(p.charAt(i)); 338 | } 339 | } 340 | return sb.toString(); 341 | } 342 | 343 | /** 344 | * Converts some important chars (int) to the corresponding html string 345 | */ 346 | static String conv2Html(int i) { 347 | if (i == '&') return "&"; 348 | else if (i == '<') return "<"; 349 | else if (i == '>') return ">"; 350 | else if (i == '"') return """; 351 | else return "" + (char) i; 352 | } 353 | 354 | /** 355 | * Converts a normal string to a html conform string 356 | */ 357 | static String htmlEncode(String st) { 358 | StringBuffer buf = new StringBuffer(); 359 | for (int i = 0; i < st.length(); i++) { 360 | buf.append(conv2Html(st.charAt(i))); 361 | } 362 | return buf.toString(); 363 | } 364 | String getDrivers() 365 | /** 366 | Windowsϵͳ��ȡ�ÿ��õ������߼��� 367 | */ 368 | { 369 | StringBuffer sb=new StringBuffer(strDrivers[languageNo] + " : "); 370 | File roots[]=File.listRoots(); 371 | for(int i=0;i"); 374 | sb.append(roots[i]+" "); 375 | } 376 | return sb.toString(); 377 | } 378 | static String convertFileSize(long filesize) 379 | { 380 | //bug 5.09M ��ʾ5.9M 381 | String strUnit="Bytes"; 382 | String strAfterComma=""; 383 | int intDivisor=1; 384 | if(filesize>=1024*1024) 385 | { 386 | strUnit = "MB"; 387 | intDivisor=1024*1024; 388 | } 389 | else if(filesize>=1024) 390 | { 391 | strUnit = "KB"; 392 | intDivisor=1024; 393 | } 394 | if(intDivisor==1) return filesize + " " + strUnit; 395 | strAfterComma = "" + 100 * (filesize % intDivisor) / intDivisor ; 396 | if(strAfterComma=="") strAfterComma=".0"; 397 | return filesize / intDivisor + "." + strAfterComma + " " + strUnit; 398 | } 399 | %> 400 | <% 401 | request.setCharacterEncoding("gb2312"); 402 | String tabID = request.getParameter("tabID"); 403 | String strDir = request.getParameter("path"); 404 | String strAction = request.getParameter("action"); 405 | String strFile = request.getParameter("file"); 406 | String strPath = strDir + strSeparator + strFile; 407 | String strCmd = request.getParameter("cmd"); 408 | StringBuffer sbEdit=new StringBuffer(""); 409 | StringBuffer sbDown=new StringBuffer(""); 410 | StringBuffer sbCopy=new StringBuffer(""); 411 | StringBuffer sbSaveCopy=new StringBuffer(""); 412 | StringBuffer sbNewFile=new StringBuffer(""); 413 | String strOS = System.getProperty("os.name").toLowerCase(); 414 | //out.print(strPath); 415 | if((tabID==null) || tabID.equals("")) 416 | { 417 | tabID = "1"; 418 | } 419 | 420 | if(strDir==null||strDir.length()<1) 421 | { 422 | strDir = request.getRealPath("."); 423 | } 424 | 425 | 426 | if(strAction!=null && strAction.equals("down")) 427 | { 428 | File f=new File(strPath); 429 | if(f.length()==0) 430 | { 431 | sbDown.append("�ļ���СΪ 0 �ֽڣ��Ͳ������˰�"); 432 | } 433 | else 434 | { 435 | response.setHeader("content-type","text/html; charset=ISO-8859-1"); 436 | response.setContentType("APPLICATION/OCTET-STREAM"); 437 | response.setHeader("Content-Disposition","attachment; filename=\""+f.getName()+"\""); 438 | FileInputStream fileInputStream =new FileInputStream(f.getAbsolutePath()); 439 | out.clearBuffer(); 440 | int i; 441 | while ((i=fileInputStream.read()) != -1) 442 | { 443 | out.write(i); 444 | } 445 | fileInputStream.close(); 446 | out.close(); 447 | } 448 | } 449 | 450 | if(strAction!=null && strAction.equals("del")) 451 | { 452 | File f=new File(strPath); 453 | f.delete(); 454 | } 455 | 456 | if(strAction!=null && strAction.equals("edit")) 457 | { 458 | File f=new File(strPath); 459 | BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(f))); 460 | sbEdit.append("
\r\n"); 461 | sbEdit.append("\r\n"); 462 | sbEdit.append("\r\n"); 463 | sbEdit.append("\r\n"); 464 | sbEdit.append(" "); 465 | sbEdit.append("  "+strPath+"\r\n"); 466 | sbEdit.append("
"); 473 | sbEdit.append(""); 474 | sbEdit.append("
"); 475 | } 476 | 477 | if(strAction!=null && strAction.equals("save")) 478 | { 479 | File f=new File(strPath); 480 | BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f))); 481 | String strContent=request.getParameter("content"); 482 | bw.write(strContent); 483 | bw.close(); 484 | } 485 | if(strAction!=null && strAction.equals("copy")) 486 | { 487 | File f=new File(strPath); 488 | sbCopy.append("
\r\n"); 489 | sbCopy.append("\r\n"); 490 | sbCopy.append("\r\n"); 491 | sbCopy.append("\r\n"); 492 | sbCopy.append("ԭʼ�ļ��� "+strPath+"

"); 493 | sbCopy.append("Ŀ���ļ���

"); 494 | sbCopy.append(" "); 495 | sbCopy.append("

 \r\n"); 496 | sbCopy.append("

"); 497 | } 498 | if(strAction!=null && strAction.equals("savecopy")) 499 | { 500 | File f=new File(strPath); 501 | String strDesFile=request.getParameter("file2"); 502 | if(strDesFile==null || strDesFile.equals("")) 503 | { 504 | sbSaveCopy.append("

Ŀ���ļ�����"); 505 | } 506 | else 507 | { 508 | File f_des=new File(strDesFile); 509 | if(f_des.isFile()) 510 | { 511 | sbSaveCopy.append("

Ŀ���ļ��Ѵ���,���ܸ��ơ�"); 512 | } 513 | else 514 | { 515 | String strTmpFile=strDesFile; 516 | if(f_des.isDirectory()) 517 | { 518 | if(!strDesFile.endsWith(strSeparator)) 519 | { 520 | strDesFile=strDesFile+strSeparator; 521 | } 522 | strTmpFile=strDesFile+"cqq_"+strFile; 523 | } 524 | 525 | File f_des_copy=new File(strTmpFile); 526 | FileInputStream in1=new FileInputStream(f); 527 | FileOutputStream out1=new FileOutputStream(f_des_copy); 528 | byte[] buffer=new byte[1024]; 529 | int c; 530 | while((c=in1.read(buffer))!=-1) 531 | { 532 | out1.write(buffer,0,c); 533 | } 534 | in1.close(); 535 | out1.close(); 536 | 537 | sbSaveCopy.append("ԭʼ�ļ� ��"+strPath+"

"); 538 | sbSaveCopy.append("Ŀ���ļ� ��"+strTmpFile+"

"); 539 | sbSaveCopy.append("���Ƴɹ���"); 540 | } 541 | } 542 | sbSaveCopy.append("

"); 543 | } 544 | if(strAction!=null && strAction.equals("newFile")) 545 | { 546 | String strF=request.getParameter("fileName"); 547 | String strType1=request.getParameter("btnNewFile"); 548 | String strType2=request.getParameter("btnNewDir"); 549 | String strType=""; 550 | if(strType1==null) 551 | { 552 | strType="Dir"; 553 | } 554 | else if(strType2==null) 555 | { 556 | strType="File"; 557 | } 558 | if(!strType.equals("") && !(strF==null || strF.equals(""))) 559 | { 560 | File f_new=new File(strF); 561 | if(strType.equals("File") && !f_new.createNewFile()) 562 | sbNewFile.append(strF+" �ļ�����ʧ��"); 563 | if(strType.equals("Dir") && !f_new.mkdirs()) 564 | sbNewFile.append(strF+" Ŀ¼����ʧ��"); 565 | } 566 | else 567 | { 568 | sbNewFile.append("

�����ļ���Ŀ¼������"); 569 | } 570 | } 571 | 572 | if((request.getContentType()!= null) && (request.getContentType().toLowerCase().startsWith("multipart"))) 573 | { 574 | String tempdir="."; 575 | boolean error=false; 576 | response.setContentType("text/html"); 577 | HttpMultiPartParser parser = new HttpMultiPartParser(); 578 | 579 | int bstart = request.getContentType().lastIndexOf("oundary="); 580 | String bound = request.getContentType().substring(bstart + 8); 581 | int clength = request.getContentLength(); 582 | Hashtable ht = parser.processData(request.getInputStream(), bound, tempdir, clength); 583 | if (ht.get("cqqUploadFile") != null) 584 | { 585 | 586 | FileInfo fi = (FileInfo) ht.get("cqqUploadFile"); 587 | File f1 = fi.file; 588 | UplInfo info = UploadMonitor.getInfo(fi.clientFileName); 589 | if (info != null && info.aborted) 590 | { 591 | f1.delete(); 592 | request.setAttribute("error", "Upload aborted"); 593 | } 594 | else 595 | { 596 | String path = (String) ht.get("path"); 597 | 598 | if(path!=null && !path.endsWith(strSeparator)) 599 | path = path + strSeparator; 600 | strDir = path; 601 | //out.println(path + f1.getName()); 602 | if (!f1.renameTo(new File(path + f1.getName()))) 603 | { 604 | request.setAttribute("error", "Cannot upload file."); 605 | out.println("error,upload "); 606 | error = true; 607 | f1.delete(); 608 | } 609 | } 610 | } 611 | } 612 | %> 613 | 614 | 615 | 659 | 660 | 723 | 744 | 745 | JFoler 1.0 ---A jsp based web folder management tool by Steven Cee 746 | 747 | 748 | 749 | 750 | 751 |

752 | 753 | 754 | 755 | 756 | 757 | 758 |
759 | 760 | 761 | 768 | 769 | 770 | 771 | <% 772 | StringBuffer sbFolder=new StringBuffer(""); 773 | StringBuffer sbFile=new StringBuffer(""); 774 | try 775 | { 776 | File objFile = new File(strDir); 777 | File list[] = objFile.listFiles(); 778 | if(objFile.getAbsolutePath().length()>3) 779 | { 780 | sbFolder.append(" "); 781 | sbFolder.append(strParentFolder[languageNo]+"
- - - - - - - - - - - \r\n "); 782 | 783 | 784 | } 785 | for(int i=0;i "); 790 | sbFolder.append(" "); 791 | sbFolder.append(list[i].getName()+"
"); 792 | } 793 | else 794 | { 795 | String strLen=""; 796 | String strDT=""; 797 | long lFile=0; 798 | lFile=list[i].length(); 799 | strLen = convertFileSize(lFile); 800 | Date dt=new Date(list[i].lastModified()); 801 | strDT=dt.toLocaleString(); 802 | sbFile.append(""); 803 | sbFile.append(""+list[i].getName()); 804 | sbFile.append(""); 805 | sbFile.append(""+strLen); 806 | sbFile.append(""); 807 | sbFile.append(""+strDT); 808 | sbFile.append(""); 809 | 810 | sbFile.append("  "); 811 | sbFile.append(strFileEdit[languageNo]+" "); 812 | 813 | sbFile.append("  "); 814 | sbFile.append(strFileDel[languageNo]+" "); 815 | 816 | sbFile.append("  "); 817 | sbFile.append(strFileDown[languageNo]+" "); 818 | 819 | sbFile.append("  "); 820 | sbFile.append(strFileCopy[languageNo]+" "); 821 | } 822 | 823 | } 824 | } 825 | catch(Exception e) 826 | { 827 | out.println("����ʧ�ܣ� "+e.toString()+""); 828 | } 829 | %> 830 | 831 |
832 | 833 | 834 | 845 | 846 | 865 | 866 | 867 | 957 | 1019 |
1020 |

1021 |
www.topronet.com ,All Rights Reserved. 1022 |
Any question, please email me cqq1978@Gmail.com -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------