Upload cryptomining_detection dataset
Browse filesFiles changed (46)
- cryptomining_detection/MalConfScan-master/.github/workflows/.yara-ci.ymlAdded+3
- cryptomining_detection/MalConfScan-master/.gitignoreAdded+3
- cryptomining_detection/MalConfScan-master/LICENSE.txtAdded+20
- cryptomining_detection/MalConfScan-master/README.mdAdded+78
- cryptomining_detection/MalConfScan-master/images/logo.svgAdded
- cryptomining_detection/MalConfScan-master/images/sample1.pngAdded
- cryptomining_detection/MalConfScan-master/images/sample2.pngAdded
- cryptomining_detection/MalConfScan-master/images/sample3.pngAdded
- cryptomining_detection/MalConfScan-master/images/sample4.pngAdded
- cryptomining_detection/MalConfScan-master/images/title.svgAdded
- cryptomining_detection/MalConfScan-master/malconfscan.pyAdded+380
- cryptomining_detection/MalConfScan-master/requirements.txtAdded+6
- cryptomining_detection/MalConfScan-master/utils/__init__.pyAdded
- cryptomining_detection/MalConfScan-master/utils/agentteslascan.pyAdded+169
- cryptomining_detection/MalConfScan-master/utils/aplib.pyAdded+384
- cryptomining_detection/MalConfScan-master/utils/asyncratscan.pyAdded+211
- cryptomining_detection/MalConfScan-master/utils/azorultscan.pyAdded+116
- cryptomining_detection/MalConfScan-master/utils/beblohscan.pyAdded+199
- cryptomining_detection/MalConfScan-master/utils/cobaltstrikescan.pyAdded+184
- cryptomining_detection/MalConfScan-master/utils/datperscan.pyAdded+288
- cryptomining_detection/MalConfScan-master/utils/elf_pleadscan.pyAdded+167
- cryptomining_detection/MalConfScan-master/utils/elf_wellmess.pyAdded+131
- cryptomining_detection/MalConfScan-master/utils/emotetscan.pyAdded+141
- cryptomining_detection/MalConfScan-master/utils/formbook_decryption.pyAdded+315
- cryptomining_detection/MalConfScan-master/utils/formbookscan.pyAdded+201
- cryptomining_detection/MalConfScan-master/utils/hawkeyescan.pyAdded+205
- cryptomining_detection/MalConfScan-master/utils/lokibotscan.pyAdded+168
- cryptomining_detection/MalConfScan-master/utils/nanocorescan.pyAdded+150
- cryptomining_detection/MalConfScan-master/utils/netwirescan.pyAdded+170
- cryptomining_detection/MalConfScan-master/utils/njratscan.pyAdded+140
- cryptomining_detection/MalConfScan-master/utils/noderatscan.pyAdded+109
- cryptomining_detection/MalConfScan-master/utils/plugxscan.pyAdded+708
- cryptomining_detection/MalConfScan-master/utils/poisonivyscan.pyAdded+164
- cryptomining_detection/MalConfScan-master/utils/quasarscan.pyAdded+215
- cryptomining_detection/MalConfScan-master/utils/ramnitscan.pyAdded+173
- cryptomining_detection/MalConfScan-master/utils/redleavesscan.pyAdded+207
- cryptomining_detection/MalConfScan-master/utils/remcosscan.pyAdded+245
- cryptomining_detection/MalConfScan-master/utils/smokeloaderscan.pyAdded+176
- cryptomining_detection/MalConfScan-master/utils/trickbotscan.pyAdded+129
- cryptomining_detection/MalConfScan-master/utils/tscookiescan.pyAdded+220
- cryptomining_detection/MalConfScan-master/utils/ursnifscan.pyAdded+347
- cryptomining_detection/MalConfScan-master/utils/wellmessscan.pyAdded+145
- cryptomining_detection/MalConfScan-master/utils/xxmmscan.pyAdded+183
- cryptomining_detection/MalConfScan-master/yara/rule.yaraAdded+584
- cryptomining_detection/cryptomining_detection_processed.csvAdded
- cryptomining_detection/metadata.jsonAdded+14
123files: accept: - "yara/rule.yara"123*.pyc*~*.bak1234567891011121314151617181920The 3-Clause BSD License
SPDX short identifier: BSD-3-Clause Note: This license has also been called the "New BSD License" or "Modified BSD License". See also the 2-clause BSD License.
---
Copyright 2023 JPCERT Coordination Center
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
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.
3. Neither JPCERT Coordination Center nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778<div align="center"><img src="images/title.svg" width="800"></div>
[](http://www.toolswatch.org/2019/05/amazing-black-hat-arsenal-usa-2019-lineup-announced/)
## Concept **MalConfScan** is a [Volatility](https://github.com/volatilityfoundation/volatility) plugin extracts configuration data of known malware. Volatility is an open-source memory forensics framework for incident response and malware analysis. This tool searches for malware in memory images and dumps configuration data. In addition, this tool has a function to list strings to which malicious code refers.

## Supported Malware Families MalConfScan can dump the following malware configuration data, decoded strings or DGA domains:
- [x] Ursnif - [x] Emotet - [x] Smoke Loader - [x] PoisonIvy - [x] CobaltStrike - [x] NetWire - [x] PlugX - [x] RedLeaves / Himawari / Lavender / Armadill / zark20rk - [x] TSCookie - [x] TSC_Loader - [x] xxmm - [x] Datper - [x] Ramnit - [x] HawkEye - [x] Lokibot - [x] Bebloh (Shiotob/URLZone) - [x] AZORult - [x] NanoCore RAT - [x] AgentTesla - [x] FormBook - [x] NodeRAT (https://blogs.jpcert.or.jp/ja/2019/02/tick-activity.html) - [x] njRAT - [x] TrickBot - [x] Remcos - [x] QuasarRAT - [x] AsyncRAT - [x] WellMess (Windows/Linux) - [x] ELF_PLEAD - [ ] Pony
## Additional Analysis MalConfScan has a function to list strings to which malicious code refers. Configuration data is usually encoded by malware. Malware writes decoded configuration data to memory, it may be in memory. This feature may list decoded configuration data.
## How to Install If you want to know more details, please check [the MalConfScan wiki](https://github.com/JPCERTCC/MalConfScan/wiki).
## How to Use MalConfScan has two functions **malconfscan**, **linux_malconfscan** and **malstrscan**.
### Export known malware configuration```$ python vol.py malconfscan -f images.mem --profile=Win7SP1x64```
### Export known malware configuration for Linux```$ python vol.py linux_malconfscan -f images.mem --profile=LinuxDebianx64```
### List the referenced strings```$ python vol.py malstrscan -f images.mem --profile=Win7SP1x64```
## Overview & Demonstration
Following [YouTube video](https://youtu.be/n36WAzgHldY) shows the overview of MalConfScan.
[](https://youtu.be/n36WAzgHldY)
And, following [YouTube video](https://youtu.be/kPsOvoRHK3k) is the demonstration of MalConfScan.
[](https://youtu.be/kPsOvoRHK3k)
## MalConfScan with Cuckoo Malware configuration data can be dumped automatically by adding MalConfScan to Cuckoo Sandbox. If you need more details on Cuckoo and MalConfScan integration, please check [MalConfScan with Cuckoo](https://github.com/JPCERTCC/MalConfScan-with-Cuckoo).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380# MalConfScan: Detecting Malware Configuration for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/#
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.obj as objimport volatility.plugins.vadinfo as vadinfoimport volatility.plugins.procdump as procdumpimport volatility.plugins.malware.malfind as malfindimport volatility.plugins.linux.pslist as linux_pslistimport volatility.plugins.linux.linux_yarascan as linux_yarascanimport reimport osimport pefilefrom struct import unpack_fromfrom collections import OrderedDictfrom importlib import import_module
PATTERNS = ["PUSH", "MOV", "CMP", "LEA"]
try: import yara has_yara = Trueexcept ImportError: has_yara = False
try: import distorm3 has_distorm3 = Trueexcept ImportError: has_distorm3 = False
class malconfScan(taskmods.DllList): """Detect infected processes and parse malware configuration"""
@staticmethod def is_valid_profile(profile): return profile.metadata.get('os', 'unknown'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
osversion, memory_model = self.is_valid_profile(addr_space.profile) base = os.path.dirname(os.path.abspath(__file__)) rules = yara.compile(base + "/yara/rule.yara") if osversion == "windows":
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address)
malname = str(hit).lower() if str(hit) in ["Himawari", "Lavender", "Armadill", "zark20rk"]: malname = "redleaves" if str(hit) in "TSC_Loader": malname = "tscookie" if "Agenttesla" in str(hit): malname = "agenttesla"
try: module = import_module("volatility.plugins.malware.utils.{name}scan".format(name=malname)) module_cls = getattr(module, malname + "Config") instance = module_cls(self._config) except: debug.error("Can't loading module volatility.plugins.malware.utils.{name}scan".format(name=malname))
for task, vad_base_addr, end, hit, memory_model, config_data in instance.calculate(): yield task, vad_base_addr, end, hit, memory_model, config_data break elif osversion == "linux": debug.error("Please use linux_malconfscan.") else: debug.error("This command does not support the selected profile.")
def render_text(self, outfd, data):
delim = '-' * 70
outfd.write("[+] Searching memory by Yara rules.\n")
for task, start, end, malname, memory_model, config_data in data: outfd.write("[+] Detect malware by Yara rules.\n") outfd.write("[+] Process Name : {0}\n".format(task.ImageFileName)) outfd.write("[+] Process ID : {0}\n".format(task.UniqueProcessId)) outfd.write("[+] Malware name : {0}\n".format(malname)) outfd.write("[+] Base Address(VAD) : 0x{0:X}\n".format(start)) outfd.write("[+] Size : 0x{0:X}\n".format(end - start + 1))
outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<22}: {1}\n".format(id, param))
class linux_malconfScan(linux_pslist.linux_pslist): """Detect infected processes and parse malware configuration for Linux"""
@staticmethod def is_valid_profile(profile): return profile.metadata.get('os', 'unknown'), profile.metadata.get('memory_model', '32bit')
def get_vma_base(self, task, address): for vma in task.get_proc_maps(): if address >= vma.vm_start and address < vma.vm_end: return vma.vm_start, vma.vm_end
return None
def filter_tasks(self): tasks = linux_pslist.linux_pslist(self._config).calculate()
if self._config.PID is not None: try: pidlist = [int(p) for p in self._config.PID.split(',')] except ValueError: debug.error("Invalid PID {0}".format(self._config.PID))
pids = [t for t in tasks if t.pid in pidlist] if len(pids) == 0: debug.error("Cannot find PID {0}. If its terminated or unlinked, use psscan and then supply --offset=OFFSET".format(self._config.PID)) return pids
return tasks
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
osversion, memory_model = self.is_valid_profile(addr_space.profile) base = os.path.dirname(os.path.abspath(__file__)) rules = yara.compile(base + "/yara/rule.yara")
if osversion == "linux": tasks = self.filter_tasks() for task in tasks: scanner = linux_yarascan.VmaYaraScanner(task = task, rules = rules) for hit, address in scanner.scan():
start, end = self.get_vma_base(task, address)
malname = str(hit).lower()
try: module = import_module("volatility.plugins.malware.utils.{name}scan".format(name=malname)) module_cls = getattr(module, malname + "Config") instance = module_cls(self._config) except: debug.error("Can't loading module volatility.plugins.malware.utils.{name}scan".format(name=malname))
for task, start, end, hit, memory_model, config_data in instance.calculate(): yield task, start, end, hit, memory_model, config_data break elif osversion == "windows": debug.error("Please use malconfscan.") else: debug.error("This command does not support the selected profile.")
def render_text(self, outfd, data):
delim = '-' * 70
outfd.write("[+] Searching memory by Yara rules.\n")
for task, start, end, malname, memory_model, config_data in data: outfd.write("[+] Detect malware by Yara rules.\n") outfd.write("[+] Process Name : {0}\n".format(task.comm)) outfd.write("[+] Process ID : {0}\n".format(task.pid)) outfd.write("[+] Malware name : {0}\n".format(malname)) outfd.write("[+] Address : 0x{0:X}\n".format(start)) outfd.write("[+] Size : 0x{0:X}\n".format(end - start))
outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.comm, task.pid))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<22}: {1}\n".format(id, param))
class malstrScan(procdump.ProcDump, malfind.Malfind, vadinfo.VADDump): """Search strings with malicious space"""
def __init__(self, config, *args, **kwargs): procdump.ProcDump.__init__(self, config, *args, **kwargs) config.add_option("FULLSCAN", short_option="a", default=False, action="store_true", help="Search with parent memory spaces.")
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def Disassemble(self, data, start, pe, bits='32bit', stoponret=False): if not has_distorm3: raise StopIteration
if bits == "32bit": mode = distorm3.Decode32Bits else: mode = distorm3.Decode64Bits
for address, _, code, hex_data in distorm3.DecodeGenerator(start, data, mode): if stoponret and i.startswith("RET"): raise StopIteration yield address, code, len(hex_data)/2
def detect_injection_proc(self, proc, space): detects = [] for vad, address_space in proc.get_vads(vad_filter=proc._injection_filter): data = address_space.zread(vad.Start, vad.End + 1) vad_protection = vadinfo.PROTECT_FLAGS.get(vad.VadFlags.Protection.v()) if self._is_vad_empty(vad, address_space): continue if obj.Object("_IMAGE_DOS_HEADER", offset=vad.Start, vm=address_space).e_magic != 0x5A4D: nt_magic = unpack_from("<H", data, 0x3c)[0] if nt_magic > 1 and nt_magic <= 0x100 and self._config.FULLSCAN: data = "\x4d\x5a" + data[2:] data = data[:nt_magic] + "\x50\x45" + data[nt_magic + 2:] else: continue detects.append([vad.Start, vad.End, data, vad_protection])
return detects
def get_strings(self, data, n=5): # ascii for match in re.finditer(('([\x20-\x7e]{%s}[\x20-\x7e]*)' % n).encode(), data): yield match.start(), match.group(0)
# unicode for match in re.finditer(('(([\x20-\x7e]\x00){%s}([\x20-\x7e]\x00)*)' % n).encode(), data): yield match.start(), match.group(0)
def ascii_check(self, code): if (code >= "\x20" and code <= "\x7e") or code == "\x00" or code == "\x0a" or code == "\x0d": return False else: return True
def search_strings(self, offset, data): string_data = [] while 1: if self.ascii_check(data[offset]) or self.ascii_check(data[offset + 1]): string_data = [] break
string_data.append(data[offset]) if data[offset + 1] != "\x00" or data[offset + 2] != "\x00": if data[offset - 1] != "\x00" or data[offset + 1] != "\x00": string_data.append(data[offset + 1]) if data[offset + 2] == "\x00": break if data[offset - 1] != "\x00" and data[offset + 1] == "\x00": break offset += 2 else: break
return string_data
def calculate(self):
if not has_distorm3: debug.error("Distorm3 must be installed for this plugin")
addr_space = utils.load_as(self._config)
osversion, memory_model = self.is_valid_profile(addr_space.profile) data = self.filter_tasks(tasks.pslist(addr_space))
for proc in data: space = proc.get_process_address_space() if space == None: continue
for start, end, memdata, protection in self.detect_injection_proc(proc, space): strings = {}
pe = pefile.PE(data=memdata) if pe.FILE_HEADER.Machine in (pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_IA64'], pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']): mode = "64bit" else: mode = "32bit"
for curent_address, i, code_len in self.Disassemble(memdata, start, pe, bits=mode): code = i.split(" ") if code[0] in PATTERNS: for ope in code: if "0x" in ope: string_addr = int(re.sub("[\],]", "", ope.split("0x")[1]), 16) if mode == "32bit": string_rva = string_addr - start else: string_rva = string_addr + curent_address + code_len - start if string_rva > 0x1000 and string_rva < (end - start): if mode == "32bit": offset = unpack_from("<H", memdata, string_rva)[0] else: offset = unpack_from("<Q", memdata, string_rva)[0]
if offset > start and offset < end: string_data = self.search_strings(offset - start, memdata) string = str("".join(string_data)).replace("\n", " ").replace("\r", " ") if len(string) > 1 and string != "\x00\x00": strings[offset] = string # print("0x{0:0>8X} -> 0x{1:0>8X}: {2}".format(string_addr, offset, string)) else: string_data = self.search_strings(string_rva, memdata) string = str("".join(string_data)).replace("\n", " ").replace("\r", " ") if len(string) > 1 and string != "\x00\x00": strings[string_rva + start] = string # print("0x{0:0>8X}: {1}".format(string_addr, string))
levels = {} if self._config.FULLSCAN: for vad in proc.VadRoot.traverse(): if vad: if vad.Start == start: level = levels.get(vad.Parent.obj_offset, -1) + 1 levels[vad.obj_offset] = level elif vad.Parent.obj_offset in levels: level = levels.get(vad.Parent.obj_offset, -1) + 1 levels[vad.obj_offset] = level if vad.Start > 0x70000000 and mode == "32bit": break data = space.zread(vad.Start, vad.End - vad.Start) for addr, word in self.get_strings(data): strings[vad.Start + addr] = word
yield proc, start, end, memdata, protection, strings
def render_text(self, outfd, data):
delim = '-' * 70
if self._config.FULLSCAN: outfd.write("[+] Searching for malicious memory space and parent memory spaces.\n") else: outfd.write("[+] Searching for malicious memory space.\n")
for task, start, end, data, protection, strings in data: outfd.write("[+] Detect Process Hollowing space.\n") outfd.write("[+] Process Name : {0}\n".format(task.ImageFileName)) outfd.write("[+] Process ID : {0}\n".format(task.UniqueProcessId)) outfd.write("[+] Base Address(VAD) : 0x{0:X}\n".format(start)) outfd.write("[+] Size : 0x{0:X}\n".format(end - start + 1)) outfd.write("[+] Vad Protection : {0}\n".format(protection))
outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
sort_strings = OrderedDict(sorted(strings.items())) for address, str_data in sort_strings.items(): outfd.write("0x{0:0>8X}: {1}\n".format(address, str_data))
outfd.write("\n")123456distorm3pycryptoyara-pythonpefilepbkdf2distorm3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169# Detecting AgentTesla Keylogger for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv agentteslascan.py volatility/plugins/malware# 3. python vol.py agentteslaconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom base64 import b64decodefrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
try: from Crypto.Cipher import AES has_crypto = Trueexcept ImportError: has_crypto = False
agenttesla_sig = { 'namespace1' : 'rule Agenttesla_type1 { \ strings: \ $type1ie = "C:\\\\Users\\\\Admin\\\\Desktop\\\\IELibrary\\\\IELibrary\\\\obj\\\\Debug\\\\IELibrary.pdb" \ $type1at = "C:\\\\Users\\\\Admin\\\\Desktop\\\\ConsoleApp1\\\\ConsoleApp1\\\\obj\\\\Debug\\\\ConsoleApp1.pdb" \ $type1sql = "Not a valid SQLite 3 Database File" wide \ condition: all of them}', 'namespace2' : 'rule Agenttesla_type2 { \ strings: \ $type2db1 = "1.85 (Hash, version 2, native byte-order)" wide \ $type2db2 = "Unknow database format" wide \ $type2db3 = "SQLite format 3" wide \ $type2db4 = "Berkelet DB" wide \ condition: (uint16(0) == 0x5A4D) and 3 of them}'}
# IVIV = "@1B2c3D4e5F6g7H8"
# AES KeyKEY = "\x34\x88\x6D\x5B\x09\x7A\x94\x19\x78\xD0\xE3\x8b\x1b\x5c\xa3\x29\x60\x74\x6a\x5e\x5d\x64\x87\x11\xb1\x2c\x67\xaa\x5b\x3a\x8e\xbf"
class agentteslaConfig(taskmods.DllList): """Parse the Agenttesla configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def base64strings(self, data, n=18): for match in re.finditer(("(([0-9a-z-A-Z\+/]\x00){%s}([0-9a-z-A-Z\+/]\x00)*(=\x00){0,2})" % n).encode(), data): yield match.group(0)
def remove_unascii(self, b): cleaned = "" for i in b: if ord(i) >= 0x20 and ord(i) < 0x7f: cleaned += i return cleaned
def stringdecrypt_type1(self, a): string = b64decode(a) cleartext = AES.new(KEY[0:32], AES.MODE_CBC, IV).decrypt(string) return cleartext
def stringdecrypt_type2(self, data): encdata = data[0x2050:]
dlist = OrderedDict() offset = 0 num = 0 i = 16 while True: key = encdata[offset:offset + 32] iv = encdata[offset + 32:offset + 48] enc_data =encdata[offset + 48:offset + 48 + i]
if b"\x00\x00" in key and b"\x00\x00" in iv: break
try: cleartext = AES.new(key, AES.MODE_CBC, iv).decrypt(enc_data) if len(cleartext) and (ord(cleartext[-1]) <= 0x10 or self.remove_unascii(cleartext) % 16 == 0) and not (ord(cleartext[-2]) == 0x0d and ord(cleartext[-1]) == 0x0a): dlist["Encoded string " + str(num)] = self.remove_unascii(cleartext).rstrip() offset = offset + 48 + i num += 1 i = 0 else: i += 16 except: i += 16
return dlist
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
if not has_crypto: debug.error("pycrypto must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=agenttesla_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = [] dlist = OrderedDict() if "type1" in str(hit): for word in self.base64strings(data): try: dec = self.stringdecrypt_type1(word) dec = self.remove_unascii(dec).rstrip() dlist[word.strip().replace('\0', '')] = dec except: pass
if "type2" in str(hit): dlist = self.stringdecrypt_type2(data)
config_data.append(dlist)
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<25}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384# this is a standalone single-file merge of aplib compression and decompression# taken from my own library Kabopan http://code.google.com/p/kabopan/# (no other clean-up or improvement)
# Ange Albertini, BSD Licence, 2007-2011
# from kbp\comp\_lz77.py ##################################################def find_longest_match(s, sub): """returns the number of byte to look backward and the length of byte to copy)""" if sub == "": return 0, 0 limit = len(s) dic = s[:] l = 0 offset = 0 length = 0 first = 0 word = ""
word += sub[l] pos = dic.rfind(word, 0, limit + 1) if pos == -1: return offset, length
offset = limit - pos length = len(word) dic += sub[l]
while l < len(sub) - 1: l += 1 word += sub[l]
pos = dic.rfind(word, 0, limit + 1) if pos == -1: return offset, length offset = limit - pos length = len(word) dic += sub[l] return offset, length
# from _misc.py ###############################
def int2lebin(value, size): """ouputs value in binary, as little-endian""" result = "" for i in xrange(size): result = result + chr((value >> (8 * i)) & 0xFF ) return result
def modifystring(s, sub, offset): """overwrites 'sub' at 'offset' of 's'""" return s[:offset] + sub + s[offset + len(sub):]
def getbinlen(value): """return the bit length of an integer""" result = 0 if value == 0: return 1 while value != 0: value >>= 1 result += 1 return result
# from kbp\_bits.py #################################class _bits_compress(): """bit machine for variable-sized auto-reloading tag compression""" def __init__(self, tagsize): """tagsize is the number of bytes that takes the tag""" self.out = ""
self.__tagsize = tagsize self.__tag = 0 self.__tagoffset = -1 self.__maxbit = (self.__tagsize * 8) - 1 self.__curbit = 0 self.__isfirsttag = True
def getdata(self): """builds an output string of what's currently compressed: currently output bit + current tag content""" tagstr = int2lebin(self.__tag, self.__tagsize) return modifystring(self.out, tagstr, self.__tagoffset)
def write_bit(self, value): """writes a bit, make space for the tag if necessary""" if self.__curbit != 0: self.__curbit -= 1 else: if self.__isfirsttag: self.__isfirsttag = False else: self.out = self.getdata() self.__tagoffset = len(self.out) self.out += "".join(["\x00"] * self.__tagsize) self.__curbit = self.__maxbit self.__tag = 0
if value: self.__tag |= (1 << self.__curbit) return
def write_bitstring(self, s): """write a string of bits""" for c in s: self.write_bit(0 if c == "0" else 1) return
def write_byte(self, b): """writes a char or a number""" assert len(b) == 1 if isinstance(b, str) else 0 <= b <= 255 self.out += b[0:1] if isinstance(b, str) else chr(b) return
def write_fixednumber(self, value, nbbit): """write a value on a fixed range of bits""" for i in xrange(nbbit - 1, -1, -1): self.write_bit( (value >> i) & 1) return
def write_variablenumber(self, value): assert value >= 2
length = getbinlen(value) - 2 # the highest bit is 1 self.write_bit(value & (1 << length)) for i in xrange(length - 1, -1, -1): self.write_bit(1) self.write_bit(value & (1 << i)) self.write_bit(0) return
class _bits_decompress(): """bit machine for variable-sized auto-reloading tag decompression""" def __init__(self, data, tagsize): self.__curbit = 0 self.__offset = 0 self.__tag = None self.__tagsize = tagsize self.__in = data self.out = ""
def getoffset(self): """return the current byte offset""" return self.__offset
# def getdata(self):# return self.__lzdata
def read_bit(self): """read next bit from the stream, reloads the tag if necessary""" if self.__curbit != 0: self.__curbit -= 1 else: self.__curbit = (self.__tagsize * 8) - 1 self.__tag = ord(self.read_byte()) for i in xrange(self.__tagsize - 1): self.__tag += ord(self.read_byte()) << (8 * (i + 1))
bit = (self.__tag >> ((self.__tagsize * 8) - 1)) & 0x01 self.__tag <<= 1 return bit
def is_end(self): return self.__offset == len(self.__in) and self.__curbit == 1
def read_byte(self): """read next byte from the stream""" if type(self.__in) == str: result = self.__in[self.__offset] elif type(self.__in) == file: result = self.__in.read(1) self.__offset += 1 return result
def read_fixednumber(self, nbbit, init=0): """reads a fixed bit-length number""" result = init for i in xrange(nbbit): result = (result << 1) + self.read_bit() return result
def read_variablenumber(self): """return a variable bit-length number x, x >= 2
reads a bit until the next bit in the pair is not set""" result = 1 result = (result << 1) + self.read_bit() while self.read_bit(): result = (result << 1) + self.read_bit() return result
def read_setbits(self, max_, set_=1): """read bits as long as their set or a maximum is reached""" result = 0 while result < max_ and self.read_bit() == set_: result += 1 return result
def back_copy(self, offset, length=1): for i in xrange(length): self.out += self.out[-offset] return
def read_literal(self, value=None): if value is None: self.out += self.read_byte() else: self.out += value return False
# from kbp\comp\aplib.py ###################################################"""aPLib, LZSS based lossless compression algorithm
Jorgen Ibsen U{http://www.ibsensoftware.com}"""
def lengthdelta(offset): if offset < 0x80 or 0x7D00 <= offset: return 2 elif 0x500 <= offset: return 1 return 0
class compress(_bits_compress): """ aplib compression is based on lz77 """ def __init__(self, data, length=None): _bits_compress.__init__(self, 1) self.__in = data self.__length = length if length is not None else len(data) self.__offset = 0 self.__lastoffset = 0 self.__pair = True return
def __literal(self, marker=True): if marker: self.write_bit(0) self.write_byte(self.__in[self.__offset]) self.__offset += 1 self.__pair = True return
def __block(self, offset, length): assert offset >= 2 self.write_bitstring("10")
# if the last operations were literal or single byte # and the offset is unchanged since the last block copy # we can just store a 'null' offset and the length if self.__pair and self.__lastoffset == offset: self.write_variablenumber(2) # 2- self.write_variablenumber(length) else: high = (offset >> 8) + 2 if self.__pair: high += 1 self.write_variablenumber(high) low = offset & 0xFF self.write_byte(low) self.write_variablenumber(length - lengthdelta(offset)) self.__offset += length self.__lastoffset = offset self.__pair = False return
def __shortblock(self, offset, length): assert 2 <= length <= 3 assert 0 < offset <= 127 self.write_bitstring("110") b = (offset << 1 ) + (length - 2) self.write_byte(b) self.__offset += length self.__lastoffset = offset self.__pair = False return
def __singlebyte(self, offset): assert 0 <= offset < 16 self.write_bitstring("111") self.write_fixednumber(offset, 4) self.__offset += 1 self.__pair = True return
def __end(self): self.write_bitstring("110") self.write_byte(chr(0)) return
def do(self): self.__literal(False) while self.__offset < self.__length: offset, length = find_longest_match(self.__in[:self.__offset], self.__in[self.__offset:]) if length == 0: c = self.__in[self.__offset] if c == "\x00": self.__singlebyte(0) else: self.__literal() elif length == 1 and 0 <= offset < 16: self.__singlebyte(offset) elif 2 <= length <= 3 and 0 < offset <= 127: self.__shortblock(offset, length) elif 3 <= length and 2 <= offset: self.__block(offset, length) else: self.__literal() #raise ValueError("no parsing found", offset, length) self.__end() return self.getdata()
class decompress(_bits_decompress): def __init__(self, data): _bits_decompress.__init__(self, data, tagsize=1) self.__pair = True # paired sequence self.__lastoffset = 0 self.__functions = [ self.__literal, self.__block, self.__shortblock, self.__singlebyte] return
def __literal(self): self.read_literal() self.__pair = True return False
def __block(self): b = self.read_variablenumber() # 2- if b == 2 and self.__pair : # reuse the same offset offset = self.__lastoffset length = self.read_variablenumber() # 2- else: high = b - 2 # 0- if self.__pair: high -= 1 offset = (high << 8) + ord(self.read_byte()) length = self.read_variablenumber() # 2- length += lengthdelta(offset) self.__lastoffset = offset self.back_copy(offset, length) self.__pair = False return False
def __shortblock(self): b = ord(self.read_byte()) if b <= 1: # likely 0 return True length = 2 + (b & 0x01) # 2-3 offset = b >> 1 # 1-127 self.back_copy(offset, length) self.__lastoffset = offset self.__pair = False return False
def __singlebyte(self): offset = self.read_fixednumber(4) # 0-15 if offset: self.back_copy(offset) else: self.read_literal('\x00') self.__pair = True return False
def do(self): """returns decompressed buffer and consumed bytes counter""" self.read_literal() while True: if self.__functions[self.read_setbits(3)](): break return self.out, self.getoffset()
if __name__ == "__main__":# from kbp\test\aplib_test.py ###################################################################### assert decompress(compress("a").do()).do() == ("a", 3) assert decompress(compress("ababababababab").do()).do() == ('ababababababab', 9) assert decompress(compress("aaaaaaaaaaaaaacaaaaaa").do()).do() == ('aaaaaaaaaaaaaacaaaaaa', 11)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindfrom struct import unpack, packfrom base64 import b64decodefrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
try: from Crypto.Cipher import AES from Crypto.Protocol.KDF import PBKDF2 has_crypto = Trueexcept ImportError: has_crypto = False
asyncrat_sig = { 'namespace1': 'rule asyncrat { \ strings: \ $salt = {BF EB 1E 56 FB CD 97 3B B2 19 02 24 30 A5 78 43 00 3D 56 44 D2 1E 62 B9 D4 F1 80 E7 E6 C3 39 41}\ $b1 = {00 00 00 0D 53 00 48 00 41 00 32 00 35 00 36 00 00}\ $b2 = {09 50 00 6F 00 6E 00 67 00 00}\ $s1 = "pastebin" ascii wide nocase \ $s2 = "pong" wide\ $s3 = "Stub.exe" ascii wide\ condition: ($salt and (2 of ($s*) or 1 of ($b*))) or (all of ($b*) and 2 of ($s*)) }'}
CONFIG_PATTERNS = [ b"\x00\x00\x00\x0D\x53\x00\x48\x00\x41\x00\x32\x00\x35\x00\x36\x00\x00"]
## format "index" : ("position_in_storage_stream","field_name","encryption_method")config_index = { 1: (2,"Server", "aes"), 2: (1,"Ports", "aes"), 3: (3,"Version", "aes"), 4: (4,"Autorun", "aes"), 5: (5,"Install_Folder", ""), 6: (6,"Install_File", "aes"), 7: (7,"AES_key", "base64"), 8: (8,"Mutex", "aes"), 9: (11,"AntiDetection", "aes"), 10: (12,"External_config_on_Pastebin", "aes"), 11: (13,"BDOS", "aes"), 12: (14,"HWID", ""), 13: (15,"Startup_Delay", ""), 14: (9,"Certificate", "aes"), 15: (10,"ServerSignature", "aes")}
class asyncratConfig(taskmods.DllList): """Parse the asyncrat configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def printable(self, data): if len(data) < 1: return data cleaned = ""
for d in data: if 0x20 <= ord(d) and ord(d) <= 0x7F: cleaned += d
return cleaned
def storage_stream_us_parser(self, data): """ parse storage_stream for unicode strings in .NET assembly. unicode_strings chunk patterns pat1: [size of unicode strings(1byte)][unicode strings][terminate code(0x00 or 0x01)] pat2: [size of unicode strings(2byte)][unicode strings][terminate code(0x00 or 0x01)] """ if len(data) < 2: return list() unicode_strings = list()
while True: # first byte must be the size of unicode strings chunk. initial_byte = ord(data[0]) if initial_byte == 0x00: break elif initial_byte < 0x80: size = initial_byte p = 1 elif initial_byte >= 0x80: size = unpack(">H",pack("B",initial_byte-0x80)+data[1])[0] # size = int.from_bytes(bytes([data[0]-0x80, data[1]]), "big") p = 2
if size < 0 or 0x7FFF < size or size > len(data)-3: debug.info("Invalid string size found in stroage stream.") break try: unicode_strings.append( data[p:size + p - 1].decode().replace("\x00", "")) except UnicodeDecodeError: debug.info("Invalid unicode byte(s) found in storage stream.") pass # check the termination code. termination_byte = ord(data[size + p - 1]) if termination_byte == 0x00 or termination_byte == 0x01: # goto next block data = data[size + p:] continue else: debug.info("Invalid termination code: {}".format(termination_byte)) break
return unicode_strings
def parse_config(self, unicode_strings):
if len(unicode_strings) < 7: debug.info("unicode strings list is too short.") return OrderedDict()
config = OrderedDict()
key = b64decode(unicode_strings[7]) salt = "BFEB1E56FBCD973BB219022430A57843003D5644D21E62B9D4F180E7E6C33941".decode("hex") aes_key = PBKDF2(key, salt, 32, 50000)
for _ , params in config_index.items(): pos, field, enc_type = params if enc_type == "aes" and len(unicode_strings[pos]) > 48: enc_data = b64decode(unicode_strings[pos]) # hmac = enc_data[:32] aes_iv = enc_data[32:48] cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) value = self.printable(cipher.decrypt(enc_data[48:])) elif enc_type == "base64": value = self.printable(b64decode(unicode_strings[pos])) else: value = unicode_strings[pos] config[field] = value return config
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
if not has_crypto: debug.error("pycrypto must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=asyncrat_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan(): vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread( vad_base_addr, end - vad_base_addr)
config_data = [] dlist = OrderedDict()
for pattern in CONFIG_PATTERNS: m = data.find(pattern) if m > 0: unicode_strings = self.storage_stream_us_parser( data[m + 3:]) dlist = self.parse_config(unicode_strings) break else: debug.info( "Asyncrat configuration signature not found.")
config_data.append(dlist)
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format( task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<25}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116# Detecting Azorult for Volatilitv## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv azorultconfigallocate.py volatility/plugins/malware# 3. python vol.py azorultconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom struct import unpack, unpack_from
try: import yara has_yara = Trueexcept ImportError: has_yara = False
azorult_sig = { 'namespace1' : 'rule Azorult { \ strings: \ $v1 = "Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1)" \ $v2 = "http://ip-api.com/json" \ $v3 = { c6 07 1e c6 47 01 15 c6 47 02 34 } \ condition: all of them}'}
# Config patternCONFIG_PATTERNS = [re.compile("[-+]{10}\x0D\x0A", re.DOTALL)]
class azorultConfig(taskmods.DllList): "Parse the Azorult configuration"
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End return None
def calculate(self):
if not has_yara: debug.error('Yara must be installed for this plugin.')
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error('This command does not support the selected profile.')
rules = yara.compile(sources=azorult_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules) for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() memdata = proc_addr_space.get_available_addresses()
config_data = []
for m in memdata: if m[1] < 0x100000: continue p_data = {}
data = proc_addr_space.zread(m[0], m[1])
for pattern in CONFIG_PATTERNS: m = re.search(pattern, data)
if m: offset = m.start() - 0x1c else: continue
i = 0 while(True): _, _, param_len = unpack_from("<III", data, offset) if param_len > 0x100: break offset = offset + 0xc param_data = data[offset:offset + param_len] p_data[i] = param_data rest_len = 4 - (param_len % 4) offset += param_len + rest_len i += 1
config_data.append(p_data) yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Download Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<4}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199# Detecting Bebloh(Shiotob, URLZone) for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv beblohscan.py volatility/plugins/malware# 3. python vol.py beblohconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom struct import unpack, unpack_fromfrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
bebloh_sig = { 'namespace1' : 'rule Bebloh { \ strings: \ $crc32f = { b8 EE 56 0b ca } \ $dga = "qwertyuiopasdfghjklzxcvbnm123945678" \ $post1 = "&vcmd=" \ $post2 = "?tver=" \ condition: all of them}'}
# RSA key headerRSA_HEADER = b"\x06\x02\x00\x00\x00\xa4\x00\x00\x52\x53\x41\x31\x00\x04\x00\x00"
# Config patternCONFIG_PATTERNS = [re.compile("\x83\x45\x08\x02\xe8(....)", re.DOTALL)]
class beblohConfig(taskmods.DllList): """Parse the Bebloh configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def crc32(self, buf, value): table = []
for i in range(256): v = i for j in range(8): v = (0xEDB88320 ^ (v >> 1)) if(v & 1) == 1 else (v >> 1) table.append(v)
for c in buf:
value = value ^ ord(c) value = table[value & 0xFF] ^ (value >> 8)
return value
def sum_of_characters(self, domain): return sum([ord(d) for d in domain[:-3]])
def get_next_domain(self, domain, xor): qwerty = "qwertyuiopasdfghjklzxcvbnm123945678"
sof = self.sum_of_characters(domain) ^ xor ascii_codes = [ord(d) for d in domain] + 100 * [0] old_hostname_length = len(domain) - 4 for i in range(0, 66): for j in range(0, 66): edi = j + i if edi < 65: p = (old_hostname_length * ascii_codes[j]) cl = p ^ ascii_codes[edi] ^ sof ascii_codes[edi] = cl & 0xFF
""" calculate the new hostname length max: 255/16 = 15 min: 10 """ cx = ((ascii_codes[2] * old_hostname_length) ^ ascii_codes[0]) & 0xFF hostname_length = int(cx / 16) # at most 15 if hostname_length < 10: hostname_length = old_hostname_length
""" generate hostname """ for i in range(hostname_length): index = int(ascii_codes[i] / 8) # max 31 --> last 3 chars of qwerty unreachable bl = ord(qwerty[index]) ascii_codes[i] = bl
hostname = ''.join([chr(a) for a in ascii_codes[:hostname_length]])
""" append .net or .com (alternating) """ tld = '.com' if domain.endswith('.net') else '.net' domain = hostname + tld
return domain
def parse_config(self, data, base, rsa_key, dga_key): p_data = OrderedDict() p_data["RSA key"] = rsa_key.encode("hex") p_data["Sleep count"] = unpack_from("<I", data, base + 5)[0] p_data["Seed URL"] = data[base + 9:base + 0x29].replace("\0", "") p_data["Sleep time"] = unpack_from("<I", data, base + 0xf9)[0] p_data["Botid"] = data[base + 0xfd:base + 0x10f].replace("\0", "") p_data["Registry subkey"] = data[base + 0x136:base + 0x160].replace("\0", "")
site_check_flag = unpack_from("<I", data, base + 0xf9)[0] if site_check_flag != 0: site_check = "Enable" else: site_check = "Disable"
p_data["Network Chack"] = site_check p_data["Botnet"] = data[base + 0x178:base + 0x188].replace("\0", "") p_data["Registry key"] = data[base + 0x188:base + 0x194].replace("\0", "")
domain = data[base + 9:base + 0x29].split("/")[0]
for i in range(51): p_data["DGA " + str(i)] = domain domain = self.get_next_domain(domain, dga_key)
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=bebloh_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
rsa_key_index = data.find(RSA_HEADER) rsa_key = data[rsa_key_index:rsa_key_index + 0x94]
dga_key = self.crc32(rsa_key, 0xCA0B56EE)
for pattern in CONFIG_PATTERNS: offset = re.search(pattern, data).start()
while not (data[offset] == "\xBA" or data[offset] == "\xB8"): offset += 1
(config_addr, ) = unpack("=I", data[offset + 1:offset + 5]) config_addr -= vad_base_addr
config_data.append(self.parse_config(data, config_addr, rsa_key, dga_key))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<16}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184# Detecting CobaltStrike for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. locate "cobaltstrikescan.py" in [Volatility_Plugins_Directory]# ex) mv cobaltstrikescan.py /usr/lib/python2.7/dist-packages/volatility/plugins/malware# 2. python vol.py cobaltstrikeconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom struct import unpack, unpack_fromfrom socket import inet_ntoafrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
cobaltstrike_sig = { 'namespace1' : 'rule CobaltStrike { \ strings: \ $v1 = { 73 70 72 6E 67 00} \ $v2 = { 69 69 69 69 69 69 69 69} \ condition: $v1 and $v2}'}
CONF_PATTERNS = [{ 'pattern': '\x69\x68\x69\x68\x69', 'cfg_size': 0x1000, 'cfg_info': [['\x00\x01\x00\x01\x00\x02', 'BeaconType', 0x2], ['\x00\x02\x00\x01\x00\x02', 'Port', 0x2], ['\x00\x03\x00\x02\x00\x04', 'Polling(ms)', 0x4], ['\x00\x04\x00\x02\x00\x04', 'Unknown1', 0x4], ['\x00\x05\x00\x01\x00\x02', 'Jitter', 0x2], ['\x00\x06\x00\x01\x00\x02', 'Maxdns', 0x2], ['\x00\x07\x00\x03\x01\x00', 'Unknown2', 0x100], ['\x00\x08\x00\x03\x01\x00', 'C2Server', 0x100], ['\x00\x09\x00\x03\x00\x80', 'UserAgent', 0x80], ['\x00\x0a\x00\x03\x00\x40', 'HTTP_Method2_Path', 0x40], ['\x00\x0b\x00\x03\x01\x00', 'Unknown3', 0x100], ['\x00\x0c\x00\x03\x01\x00', 'Header1', 0x100], ['\x00\x0d\x00\x03\x01\x00', 'Header2', 0x100], ['\x00\x0e\x00\x03\x00\x40', 'Injection_Process', 0x40], ['\x00\x0f\x00\x03\x00\x80', 'PipeName', 0x80], ['\x00\x10\x00\x01\x00\x02', 'Year', 0x2], ['\x00\x11\x00\x01\x00\x02', 'Month', 0x2], ['\x00\x12\x00\x01\x00\x02', 'Day', 0x2], ['\x00\x13\x00\x02\x00\x04', 'DNS_idle', 0x4], ['\x00\x14\x00\x02\x00\x04', 'DNS_sleep(ms)', 0x2], ['\x00\x1a\x00\x03\x00\x10', 'Method1', 0x10], ['\x00\x1b\x00\x03\x00\x10', 'Method2', 0x10], ['\x00\x1c\x00\x02\x00\x04', 'Unknown4', 0x4], ['\x00\x1d\x00\x03\x00\x40', 'Spawnto_x86', 0x40], ['\x00\x1e\x00\x03\x00\x40', 'Spawnto_x64', 0x40], ['\x00\x1f\x00\x01\x00\x02', 'Unknown5', 0x2], ['\x00\x20\x00\x03\x00\x80', 'Proxy_HostName', 0x80], ['\x00\x21\x00\x03\x00\x40', 'Proxy_UserName', 0x40], ['\x00\x22\x00\x03\x00\x40', 'Proxy_Password', 0x40], ['\x00\x23\x00\x01\x00\x02', 'Proxy_AccessType', 0x2], ['\x00\x24\x00\x01\x00\x02', 'create_remote_thread', 0x2]]}]
BEACONTYPE = {0x0: "0 (HTTP)", 0x1: "1 (Hybrid HTTP and DNS)", 0x8: "8 (HTTPS)"}ACCESSTYPE = {0x0: "0 (not use)", 0x1: "1 (use direct connection)", 0x2: "2 (use IE settings)", 0x4: "4 (use proxy server)"}
class cobaltstrikeConfig(taskmods.DllList):
"""Detect processes infected with CobaltStrike malware"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def decode_config(self, cfg_blob): return "".join(chr(ord(cfg_offset) ^ 0x69) for cfg_offset in cfg_blob)
def parse_config(self, cfg_blob, nw):
p_data = OrderedDict()
for pattern, name, size in nw['cfg_info']: if name.count('Port'): port = unpack_from('>H', cfg_blob, 0xE)[0] p_data[name] = port continue
offset = cfg_blob.find(pattern) if offset == -1: p_data[name] = "" continue
config_data = cfg_blob[offset + 6:offset + 6 + size] if name.count('Unknown'): p_data[name] = repr(config_data) continue
if size == 2: if name.count('BeaconType'): p_data[name] = BEACONTYPE[unpack('>H', config_data)[0]] elif name.count('AccessType'): p_data[name] = ACCESSTYPE[unpack('>H', config_data)[0]] elif name.count('create_remote_thread'): if unpack('>H', config_data)[0] != 0: p_data[name] = "Enable" else: p_data[name] = "Disable" else: p_data[name] = unpack('>H', config_data)[0] elif size == 4: if name.count('DNS_idle'): p_data[name] = inet_ntoa(config_data) else: p_data[name] = unpack('>I', config_data)[0] else: if name.count('Header'): cfg_offset = 3 flag = 0 while 1: if cfg_offset > 255: break else: if config_data[cfg_offset] != '\x00': if config_data[cfg_offset + 1] != '\x00': if flag: name = name + "+" p_data[name] = config_data[(cfg_offset + 1):].split('\x00')[0] cfg_offset = config_data[cfg_offset:].find('\x00\x00\x00') + cfg_offset - 1 flag += 1 else: cfg_offset += 4 continue else: cfg_offset += 4 continue else: p_data[name] = config_data
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=cobaltstrike_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
for nw in CONF_PATTERNS: cfg_addr = data.find(nw['pattern']) if cfg_addr != -1: break else: continue
cfg_blob = data[cfg_addr:cfg_addr + nw['cfg_size']] config_data.append(self.parse_config(self.decode_config(cfg_blob), nw))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<22}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288# Detecting Datper for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv datperscan.py volatility/plugins/malware# 3. python vol.py datperconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport pefilefrom struct import unpack, unpack_fromfrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
datper_sig = { 'namespace1' : 'rule Datper { \ strings: \ $a1 = { E8 03 00 00 } \ $b1 = "|||" \ $c1 = "Content-Type: application/x-www-form-urlencoded" \ $delphi = "Borland\\Delphi" ascii wide \ $push7530h64 = { C7 C1 30 75 00 00 } \ $push7530h = { 68 30 75 00 00 } \ condition: $a1 and $b1 and $c1 and $delphi and ($push7530h64 or $push7530h)}'}
CONFIG_PATTERNS = [ re.compile("\xB8(....)(\xBA\xE8\x03\x00\x00)", re.DOTALL), # mov eax, qword ptr config_offset;mov edx 0x3e8 re.compile("\xB8(....)(\x75\x00\xBA\xE8\x03\x00\x00)", re.DOTALL), # mov eax, qword ptr config_offset;jnz short $+2;mov edx 0x3e8 re.compile("\x48\x8D\x0D(....)(\xC7\xC2\xE8\x03\x00\x00)", re.DOTALL) # lea rax, qword ptr config_offset;mov edx 0x3e8]
RC4KEY = ["d4n[6h}8o<09,d(21i`t4n$]hx%.h,hd", "B3uT16@qs\l,!GdSevH=Y(;7Ady$jl\e", "V7oT1@@qr\\t,!GOSKvb=p(;3Akb$rl\\a" ]
idx_list = { 0: "ID", 1: "URL", 2: "Sleep time(s)", 3: "Mutex", 4: "Proxy server", 5: "Proxy port", 6: "Unknown", 7: "Unknown", 8: "Startup time(h)", 9: "End time(h)", 10: "Unknown", 11: "User-Agent", 12: "RSA key(e + modules)"}
CONFSIZE = 0x3F8config_delimiter = ["|||", "[|-]"]
class datperConfig(taskmods.DllList): """Parse the Datper configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
# Custom RC4 use sbox seed def custom_rc4(self, data, key, box_seed): x = 0 box = range(256) if box_seed != 0: for i in range(256): box[i] = (i + box_seed) & 0xFF
for i in range(256): x = (x + box[i] + ord(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x = 0 y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 box[x], box[y] = box[y], box[x] out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256]))
return ''.join(out)
def get_config_data_64(self, data, pe): for pattern in CONFIG_PATTERNS: m = re.search(pattern, data) if m: #print("found pattern") rva_offset_config = pe.get_rva_from_offset(m.start(2)) + unpack("<L", data[m.start(1):m.start(1) + 4])[0] config = pe.get_memory_mapped_image()[rva_offset_config:rva_offset_config + CONFSIZE] return config return None
def get_config_data_32(self, data, pe, start): for pattern in CONFIG_PATTERNS: m = re.search(pattern, data) if m: #print("found pattern") rva_offset_config = unpack("<L", data[m.start(1):m.start(1) + 4])[0] rva_config = rva_offset_config - start config = data[rva_config:rva_config + CONFSIZE] return config return None
def decompress(self, data): if ord(data[0]) == 0x80: return data[1:] length = unpack("<H", data[:2])[0] if length > len(data[2:]): print("[!] invalid length") return "" data = data[2:2 + length] tmp = "" for i, c in enumerate(data): val = (((i >> 5) + (i << 7) + length + ~i) & 0xFF) tmp += chr(ord(c) ^ (((i >> 5) + (i << 7) + length + ~i) & 0xFF))
tmp = map(ord, list(tmp))[1:] i = 0 block_len = 16 dec = "" try: while i < len(tmp): if block_len == 16: block_flag = (tmp[i] << 8) + tmp[i + 1] block_len = 0 i += 2
if block_flag & (0x8000 >> block_len) != 0: char_flag = (tmp[i + 1] >> 4) + (16 * tmp[i]) if char_flag != 0: loop_count = (tmp[i + 1] & 0xF) + 3 for n in range(loop_count): dec += dec[-char_flag] i += 2 else: loop_count = (tmp[i + 1] << 8) + tmp[i + 2] + 16 for n in range(loop_count): #data += chr(tmp[i + 3]) pass i += 4 else: dec += chr(tmp[i]) i += 1
block_len += 1 except: raise return "" return dec
def decrypt(self, dec): decrypted_len = len(dec) decomp = [] processed_len = 0 while (decrypted_len > processed_len): enc_compressed_len = unpack("<H", dec[processed_len:processed_len + 2])[0] enc_compressed = dec[processed_len + 2:processed_len + 2 + enc_compressed_len] if enc_compressed_len > len(enc_compressed): break processed_len += enc_compressed_len + 2 tmp = [] for i in range(enc_compressed_len): xor_key = (i >> 5) & 0xff xor_key += (i << 7) & 0xff xor_key += enc_compressed_len xor_key += ~i xor_key = xor_key & 0xff tmp.append(chr(ord(enc_compressed[i]) ^ xor_key)) compressed = "".join(tmp) decompressed = self.decompress(compressed) decomp.append(decompressed) return "".join(decomp)
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=datper_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
try: pe = pefile.PE(data=data) except: # print("[!] could not parse as a PE file") break
config_size = CONFSIZE
if pe.FILE_HEADER.Machine in (pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_IA64'], pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']): enc = self.get_config_data_64(data, pe) else: enc = self.get_config_data_32(data, pe, vad_base_addr)
dec = "" for key in RC4KEY: for rc4key_seed in range(0xFF): dec = self.custom_rc4(enc, key, rc4key_seed) dec = self.decrypt(dec) for dline in config_delimiter: if dline in dec: break else: continue break else: continue break
if dec == "": dec = self.decrypt(enc) for dline in config_delimiter: if dline in dec: key = "NULL" rc4key_seed = "NULL" break
p_data = OrderedDict() if dec != "": p_data["RC4 key"] = key p_data["RC4 Sbox seed"] = rc4key_seed p_data["Config delimiter"] = dline idx = 0 for e in (dec.split(dline)): try: p_data[idx_list[idx]] = e except: p_data["Unknown " + str(idx)] = e idx += 1 else: outfd.write("[!] failed to decrypt\n")
config_data.append(p_data)
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<16}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167# Detecting ELF_PLEAD for Volatilitv## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv elf_pleadconfig.py volatility/plugins/malware# 3. python vol.py elf_pleadconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport volatility.plugins.linux.pslist as linux_pslistimport volatility.plugins.linux.linux_yarascan as linux_yarascanimport reimport iofrom struct import unpack, unpack_fromfrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
elf_plead_sig = { 'namespace1' : 'rule elf_plead { \ strings: \ $ioctl = "ioctl TIOCSWINSZ error" \ $class1 = "CPortForwardManager" \ $class2 = "CRemoteShell" \ $class3 = "CFileManager" \ $lzo = { 81 ?? FF 07 00 00 81 ?? 1F 20 00 00 } \ condition: 3 of them}'}
# Config patternCONFIG_PATTERNS = [re.compile("\xBA(...)\x00\xB9\xAA\x01\x00\x00\xBE\x20\x00\x00\x00\xBF(...)\x00", re.DOTALL)]
CONFIG_SIZE = 0x1AAKEY_SIZE = 0x20
class elf_pleadConfig(linux_pslist.linux_pslist): "Parse the ELF_PLEAD configuration"
@staticmethod def is_valid_profile(profile): return profile.metadata.get('os', 'unknown'), profile.metadata.get('memory_model', '32bit')
def get_vma_base(self, task, address): for vma in task.get_proc_maps(): if address >= vma.vm_start and address < vma.vm_end: return vma.vm_start, vma.vm_end
return None
def filter_tasks(self): tasks = linux_pslist.linux_pslist(self._config).calculate()
if self._config.PID is not None: try: pidlist = [int(p) for p in self._config.PID.split(',')] except ValueError: debug.error("Invalid PID {0}".format(self._config.PID))
pids = [t for t in tasks if t.pid in pidlist] if len(pids) == 0: debug.error("Cannot find PID {0}. If its terminated or unlinked, use psscan and then supply --offset=OFFSET".format(self._config.PID)) return pids
return tasks
def rc4(self, data, key): x = 0 box = range(256) for i in range(256): x = (x + box[i] + ord(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x = 0 y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 box[x], box[y] = box[y], box[x] out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256]))
return ''.join(out)
def parse_config(self, data, start, memory_model):
p_data = OrderedDict()
for pattern in CONFIG_PATTERNS: if "64" in memory_model: data_base_address = unpack("=Q", data[0x90:0x98])[0] - unpack("=Q", data[0x80:0x88])[0] else: data_base_address = unpack("=I", data[0x60:0x64])[0] - unpack("=I", data[0x58:0x5C])[0]
mc = re.search(pattern, data) if mc: config_offset = mc.start(1) config_address = unpack("=I", data[config_offset:config_offset + 4])[0] - data_base_address enc_config = data[config_address:config_address + CONFIG_SIZE]
key_offset = mc.start(2) key_address = unpack("=I", data[key_offset:key_offset + 4])[0] - data_base_address key = data[key_address:key_address + KEY_SIZE]
if enc_config[0] == "\x00": print("[!] Config area is brank.") else: config = self.rc4(enc_config, key)
p_data["ID"] = unpack_from("<8s", config, 0)[0].replace("\0", "") p_data["Unknown1"] = u"0x{0:X}".format(unpack_from("=Q", config, 0x8)[0]) p_data["Unknown2"] = u"0x{0:X}".format(unpack_from("=Q", config, 0x10)[0]) p_data["Unknown3"] = u"0x{0:X}".format(unpack_from("=Q", config, 0x18)[0]) p_data["Port1"] = unpack_from("<H", config, 0x20)[0] p_data["Port2"] = unpack_from("<H", config, 0x22)[0] p_data["Server"] = unpack_from("<384s", config, 0x26)[0].replace("\0", "") p_data["Key"] = u"0x{0:X}".format(unpack_from(">I", config, 0x1A6)[0])
return p_data
def calculate(self):
if not has_yara: debug.error('Yara must be installed for this plugin.')
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error('This command does not support the selected profile.')
rules = yara.compile(sources=elf_plead_sig)
for task in self.filter_tasks(): scanner = linux_yarascan.VmaYaraScanner(task = task, rules = rules) for hit, address in scanner.scan():
start, end = self.get_vma_base(task, address) data = scanner.address_space.zread(start, (end - start) * 2) #data = scanner.address_space.zread(address - self._config.REVERSE, self._config.SIZE)
config_data = [] config_data.append(self.parse_config(data, start, memory_model))
yield task, start, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.comm, task.pid))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<20}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# Detecting ELF_Wellmess for Volatilitv## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv elf_wellmessconfig.py volatility/plugins/malware# 3. python vol.py elf_wellmessconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport volatility.plugins.linux.pslist as linux_pslistimport volatility.plugins.linux.linux_yarascan as linux_yarascanimport reimport iofrom struct import unpack, unpack_fromfrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
elf_wellmess_sig = { 'namespace1' : 'rule elf_wellmess { \ strings: \ $botlib1 = "botlib.wellMess" ascii\ $botlib2 = "botlib.Command" ascii\ $botlib3 = "botlib.Download" ascii\ $botlib4 = "botlib.AES_Encrypt" ascii\ condition: (uint32(0) == 0x464C457F) and all of ($botlib*)}'}
# Config patternCONFIG_PATTERNS = [re.compile("\x00(.)\x00\x00\x00\x8B\x05...\x00\x85\xC0\x0F\x85..\x00\x00\x8D\x05(....)\x89\x05...\x00\xC7\x05", re.DOTALL), re.compile("\x00(.)\x00\x00\x00\x8B\x05...\x00\x85\xC0\x0F\x85..\x00\x00\x48\x8D\x05(....)\x48\x89\x05...\x00\x48\xC7\x05", re.DOTALL)]
class elf_wellmessConfig(linux_pslist.linux_pslist): "Parse the ELF_Wellmess configuration"
@staticmethod def is_valid_profile(profile): return profile.metadata.get('os', 'unknown'), profile.metadata.get('memory_model', '32bit')
def get_vma_base(self, task, address): for vma in task.get_proc_maps(): if address >= vma.vm_start and address < vma.vm_end: return vma.vm_start, vma.vm_end
return None
def filter_tasks(self): tasks = linux_pslist.linux_pslist(self._config).calculate()
if self._config.PID is not None: try: pidlist = [int(p) for p in self._config.PID.split(',')] except ValueError: debug.error("Invalid PID {0}".format(self._config.PID))
pids = [t for t in tasks if t.pid in pidlist] if len(pids) == 0: debug.error("Cannot find PID {0}. If its terminated or unlinked, use psscan and then supply --offset=OFFSET".format(self._config.PID)) return pids
return tasks
def parse_config(self, config): p_data = OrderedDict() for i, d in enumerate(config): p_data["conf " + str(i)] = d
return p_data
def calculate(self):
if not has_yara: debug.error('Yara must be installed for this plugin.')
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error('This command does not support the selected profile.')
rules = yara.compile(sources=elf_wellmess_sig)
for task in self.filter_tasks(): scanner = linux_yarascan.VmaYaraScanner(task = task, rules = rules) for hit, address in scanner.scan():
start, end = self.get_vma_base(task, address) data = scanner.address_space.zread(start, (end - start) * 2) #data = scanner.address_space.zread(address - self._config.REVERSE, self._config.SIZE)
config_data = [] configs = [] for pattern in CONFIG_PATTERNS: mc = list(re.finditer(pattern, data)) if mc: for m in mc: hit_adderss = m.span() config_rva = unpack("=I", m.groups()[1])[0]
if ord(data[0x4]) == 0x2: # for 64bit config_offset = config_rva + hit_adderss[0] + 26 else: # for 32bit config_offset = config_rva - 0x40000 configs.append(data[config_offset:config_offset + ord(m.groups()[0])])
yield task, start, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.comm, task.pid))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<20}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141# Detecting Emotet for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv emotetscan.py volatility/plugins/malware# 3. python vol.py emotetconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom struct import unpack, packfrom collections import OrderedDictfrom socket import inet_ntoa
try: from Crypto.Util import asn1 from Crypto.PublicKey import RSA has_crypto = Trueexcept ImportError: has_crypto = False
try: import yara has_yara = Trueexcept ImportError: has_yara = False
emotet_sig = { 'namespace1' : 'rule Emotet { \ strings: \ $v4a = { BB 00 C3 4C 84 } \ $v4b = { B8 00 C3 CC 84 } \ $v5a = { 6D 4E C6 41 33 D2 81 C1 39 30 00 00 } \ $v6a = { C7 40 20 ?? ?? ?? 00 C7 40 10 ?? ?? ?? 00 C7 40 0C 00 00 00 00 83 3C CD ?? ?? ?? ?? 00 74 0E 41 89 48 ?? 83 3C CD ?? ?? ?? ?? 00 75 F2 } \ $v7a = { 6A 06 33 D2 ?? F7 ?? 8B DA 43 74 } \ $v7b = { 83 E6 0F 8B CF 83 C6 04 50 8B D6 E8 ?? ?? ?? ?? 59 6A 2F 8D 3C 77 58 66 89 07 83 C7 02 4B 75 } \ condition: all of ($v4*) or $v5a or $v6a or all of ($v7*)}'}
# MZ HeaderMZ_HEADER = b"\x4D\x5A\x90\x00"
# Config patternCONFIG_PATTERNS = [re.compile("(........)(\x9A\x1F|\x90\x1F|\xBB\x01|\x50\x00|\xA8\x1B|\x2F\x10|\x50\xC3|\xDE\x03|\x2F\x10|\xE3\x03|\x14\x00|\x16\x00)(......)(\x9A\x1F|\x90\x1F|\xBB\x01|\x50\x00|\xA8\x1B|\x2F\x10|\x50\xC3|\xDE\x03|\x2F\x10|\xE3\x03|\x14\x00|\x16\x00)", re.DOTALL), re.compile("\x00\x00\x00\x00(....)(\x9A\x1F|\x90\x1F|\xBB\x01|\x50\x00|\xA8\x1B|\x2F\x10|\x50\xC3|\xDE\x03|\x2F\x10|\xE3\x03|\x14\x00|\x16\x00)(......)(\x9A\x1F|\x90\x1F|\xBB\x01|\x50\x00|\xA8\x1B|\x2F\x10|\x50\xC3|\xDE\x03|\x2F\x10|\xE3\x03|\x14\x00|\x16\x00)", re.DOTALL)]
class emotetConfig(taskmods.DllList): """Parse the Emotet configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def extract_rsakey(self, data): pubkey = "" pemkey_match = re.findall('''\x30[\x00-\xFF]{100}\x02\x03\x01\x00\x01\x00\x00''',data)
if pemkey_match: pemkey = pemkey_match[0][0:106] seq = asn1.DerSequence() seq.decode(pemkey) pemkey = RSA.construct((seq[0],seq[1])) pubkey = pemkey.exportKey()
return pubkey
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=emotet_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
p_data = OrderedDict() for pattern in CONFIG_PATTERNS: mc = re.search(pattern, data) if mc: try: d = 4 i = 0 while 1: ip = data[mc.start() + d + 3] + data[mc.start() + d + 2] + data[mc.start() + d + 1] + data[mc.start() + d] port = unpack("=H", data[mc.start() + d + 4:mc.start() + d + 6])[0] d += 8 if ip == "\x00\x00\x00\x00" and port == 0: break else: p_data["IP " + str(i)] = str(inet_ntoa(ip)) + ":" + str(port) i += 1 except: outfd.write("[!] Not found config data.\n")
config_data.append({"RSA Public Key" : self.extract_rsakey(data)}) config_data.append(p_data)
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Static IP Address list]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0}:{1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315# https://github.com/tildedennis/malware/blob/master/formbook/formbook_decryption.py
from Crypto.Cipher import ARC4
class FormBookDecryption:
def decrypt_func1(self, encbuf, plainbuf_len): plainbuf = []
ebl = [ord(b) for b in encbuf]
if ebl[0] != 0x55 or ebl[1] != 0x8b: print "doesn't start with a function prologue" return
ebl = ebl[3:] ei = 0
while len(plainbuf) < plainbuf_len: if ((ebl[ei] - 64) & 0xff) > 31: if ((ebl[ei] - 112) & 0xff) > 15: plainbuf, ei = self.decrypt_func1_transform(plainbuf, ebl, ei) else: ei += 2 else: plainbuf, ei = self.offset0_byte_1byte(plainbuf, ebl, ei)
return "".join([chr(b & 0xff) for b in plainbuf])
def decrypt_func1_transform(self, plainbuf, ebl, ei): if ebl[ei] <= 3: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 4: return self.offset1_byte_2bytes(plainbuf, ebl, ei)
if ebl[ei] == 5: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ((ebl[ei] - 8) & 0xff) <= 3: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 12: return self.offset1_byte_2bytes(plainbuf, ebl, ei)
if ebl[ei] == 13: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ebl[ei] == 15: ei += 6 return plainbuf, ei
if ((ebl[ei] - 16) & 0xff) <= 3: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 20: return self.offset1_byte_2bytes(plainbuf, ebl, ei)
if ebl[ei] == 21: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ((ebl[ei] - 24) & 0xff) <= 3: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 28: return self.offset1_byte_2bytes(plainbuf, ebl, ei)
if ebl[ei] == 29: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ((ebl[ei] - 32) & 0xff) <= 3: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 36: return self.offset1_byte_2bytes(plainbuf, ebl, ei)
if ebl[ei] == 37: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ((ebl[ei] - 40) & 0xff) <= 3: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 44: return self.offset1_byte_2bytes(plainbuf, ebl, ei)
if ebl[ei] == 45: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ((ebl[ei] - 48) & 0xff) <= 3: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 52: return self.offset1_byte_2bytes(plainbuf, ebl, ei)
if ebl[ei] == 53: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ((ebl[ei] - 56) & 0xff) <= 3: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 60: return self.offset1_byte_2bytes(plainbuf, ebl, ei)
if ebl[ei] == 61: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ebl[ei] == 102: if ebl[ei+1] == 106: plainbuf += ebl[ei+1:ei+1+2] ei += 3 if ebl[ei+1] == 104 or ebl[ei+1] == 184: plainbuf, ei = self.offset2_short_4bytes(plainbuf, ebl, ei) else: ei += 1
return plainbuf, ei
if ebl[ei] == 104: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ebl[ei] == 105: plainbuf += ebl[ei+2:ei+2+4] plainbuf += ebl[ei+6:ei+6+2] ei += 10 return plainbuf, ei
if ebl[ei] == 106: offset = ebl[ei+1] if (offset & 0x80) != 0: offset |= 0xffffff00 plainbuf += ebl[offset:offset+4] ei += 2 return plainbuf, ei
if ebl[ei] == 107: plainbuf += ebl[ei+2:ei+2+4] plainbuf += ebl[ei+6:ei+6+2] ei += 7 return plainbuf, ei
if ebl[ei] == 128: if ebl[ei+1] == 5: plainbuf += ebl[ei+2:ei+2+4] ei += 7 else: plainbuf += ebl[ei+2:ei+2+1] ei += 3 return plainbuf, ei
if ebl[ei] == 129: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 131: offset = ebl[ei+2] if (offset & 0x80) != 0: offset |= 0xffffff00 plainbuf += ebl[offset:offset+4] ei += 3
if ((ebl[ei] + 124) & 0xff) <= 7: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 141: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 143: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 144: return self.offset0_byte_1byte(plainbuf, ebl, ei)
if ((ebl[ei] + 96) & 0xff) <= 3: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ((ebl[ei] + 92) & 0xff) <= 3: return self.offset0_byte_1byte(plainbuf, ebl, ei)
if ebl[ei] == 168: return self.offset1_byte_2bytes(plainbuf, ebl, ei)
if ebl[ei] == 169: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ((ebl[ei] + 86) & 0xff) <= 5: return self.offset0_byte_1byte(plainbuf, ebl, ei)
if ((ebl[ei] + 80) & 0xff) <= 7: return self.offset1_byte_2bytes(plainbuf, ebl, ei)
if ((ebl[ei] + 72) & 0xff) <= 7: return self.offset1_dword_5bytes(plainbuf, ebl, ei)
if ebl[ei] == 192: return self.offset2_dword_7bytes(plainbuf, ebl, ei)
if ebl[ei] == 193: return self.offset2_dword_7bytes(plainbuf, ebl, ei)
if ebl[ei] == 194: return self.offset1_short_3bytes(plainbuf, ebl, ei)
if ebl[ei] == 195: return self.offset0_byte_1byte(plainbuf, ebl, ei)
if ebl[ei] == 208: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 209: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 232 or ebl[ei] == 233: ei += 5 return plainbuf, ei
if ebl[ei] == 235: ei += 2 return plainbuf, ei
if ebl[ei] == 242: return self.offset0_byte_1byte(plainbuf, ebl, ei)
if ebl[ei] == 246: return self.offset2_byte_3bytes(plainbuf, ebl, ei)
if ebl[ei] == 247: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
if ebl[ei] == 255: if ebl[ei + 1] == 53: return self.offset2_dword_6bytes(plainbuf, ebl, ei)
return plainbuf, ei
def offset0_byte_1byte(self, plainbuf, ebl, ei): plainbuf += [ebl[ei]] ei += 1 return plainbuf, ei
def offset1_byte_2bytes(self, plainbuf, ebl, ei): plainbuf += ebl[ei+1:ei+1+1] ei += 2 return plainbuf, ei
def offset1_short_3bytes(self, plainbuf, ebl, ei): plainbuf += ebl[ei+1:ei+1+2] ei += 3 return plainbuf, ei
def offset2_byte_3bytes(self, plainbuf, ebl, ei): plainbuf += ebl[ei+2:ei+2+1] ei += 3 return plainbuf, ei
def offset2_short_4bytes(self, plainbuf, ebl, ei): plainbuf += ebl[ei+2:ei+2+2] ei += 4 return plainbuf, ei
def offset1_dword_5bytes(self, plainbuf, ebl, ei): plainbuf += ebl[ei+1:ei+1+4] ei += 5 return plainbuf, ei
def offset2_dword_6bytes(self, plainbuf, ebl, ei): plainbuf += ebl[ei+2:ei+2+4] ei += 6 return plainbuf, ei
def offset2_dword_7bytes(self, plainbuf, ebl, ei): plainbuf += ebl[ei+2:ei+2+4] ei += 7 return plainbuf, ei
def decrypt_func2(self, encbuf, key): ebl = [ord(b) for b in encbuf]
# transform 1 for i in range(len(encbuf) - 1, 0, -1): ebl[i-1] -= ebl[i]
# transform 2 for i in range(0, len(encbuf) -1): ebl[i] -= ebl[i+1]
# rc4 round2 = "".join([chr(b & 0xff) for b in ebl]) arc4 = ARC4.new(key) round3 = arc4.decrypt(round2)
round3l = [ord(b) for b in round3]
# transform 3 for i in range(len(encbuf) - 1, 0, -1): round3l[i-1] -= round3l[i]
# transform 4 for i in range(0, len(encbuf) -1): round3l[i] -= round3l[i+1]
plainbuf = "".join([chr(b & 0xff) for b in round3l])
return plainbuf123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201# Detecting Formbook for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv formbookscan.py volatility/plugins/malware# 3. python vol.py formbookconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport pefilefrom Crypto.Hash import SHAfrom struct import unpack, unpack_from, packfrom collections import OrderedDictfrom formbook_decryption import FormBookDecryption
try: import yara has_yara = Trueexcept ImportError: has_yara = False
formbook_sig = { 'namespace1' : 'rule Formbook { \ strings: \ $sqlite3step = { 68 34 1c 7b e1 } \ $sqlite3text = { 68 38 2a 90 c5 } \ $sqlite3blob = { 68 53 d8 7f 8c } \ condition: all of them}'}
# Config patternCONFIG_PATTERNS = [re.compile("\x83\xc4\x0c\x6a\x14\xe8(....)\x83\xc0\x02\x50\x8d(..)\x51\xe8(....)\x83\xc4\x0c\x6a\x14\xe8(....)\x83\xc0\x02\x50\x8d(..)\x52", re.DOTALL)]
# Hashs patternHASHS_PATTERNS = [re.compile("\x68(.)(\x02|\x03)\x00\x00\x8d(...)\x00\x00\xe8", re.DOTALL)]
# Strings patternSTRINGS_PATTERNS = [re.compile("\x6a\x00\x50\xc6\x85(....)\x00\xe8(....)\x83\xc4\x0c\x68(..)\x00\x00\xe8", re.DOTALL)]
class formbookConfig(taskmods.DllList): """Parse the Formbook configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def sha1_revert(self, digest): tuples = unpack("<IIIII", digest) output_hash = "" for item in tuples: output_hash += pack(">I", item) return output_hash
def formbook_compute_sha1(self, input_buffer): sha1 = SHA.new() sha1.update(input_buffer) return self.sha1_revert(sha1.digest())
def formbook_decrypt_strings(self, fb_decrypt, p_data, key, encrypted_strings): offset = 0 i = 0 while offset < len(encrypted_strings): str_len = ord(encrypted_strings[offset]) offset += 1 dec_str = fb_decrypt.decrypt_func2(encrypted_strings[offset:offset + str_len], key) dec_str = dec_str[:-1] # remove '\0' character p_data["Encoded string " + str(i)] = dec_str offset += str_len i += 1
return p_data
def formbook_decrypt(self, key1, key2, config, config_size, strings_data, strings_size, url_size, hashs_data, hashs_size): fb_decrypt = FormBookDecryption() p_data = OrderedDict()
rc4_key_one = fb_decrypt.decrypt_func1(key1, 0x14) rc4_key_two = fb_decrypt.decrypt_func1(key2, 0x14) encbuf2_s1 = fb_decrypt.decrypt_func1(hashs_data, hashs_size) encbuf8_s1 = fb_decrypt.decrypt_func1(config, config_size) encbuf9_s1 = fb_decrypt.decrypt_func1(strings_data, strings_size)
rc4_key_1 = self.formbook_compute_sha1(encbuf8_s1) rc4_key_2 = self.formbook_compute_sha1(encbuf9_s1) rc4_key_3 = self.formbook_compute_sha1(rc4_key_two) encbuf2_s2 = fb_decrypt.decrypt_func2(encbuf2_s1, rc4_key_1) encbuf8_s2 = fb_decrypt.decrypt_func2(encbuf8_s1, rc4_key_2)
n = 1 for i in xrange(config_size): encrypted_c2c_uri = encbuf8_s2[i:i + url_size] encrypted_c2c_uri = fb_decrypt.decrypt_func2(encrypted_c2c_uri, rc4_key_two) c2c_uri = fb_decrypt.decrypt_func2(encrypted_c2c_uri, rc4_key_one) if "www." in c2c_uri: p_data["C&C URI " + str(n)] = c2c_uri n += 1
encrypted_hashes_array = fb_decrypt.decrypt_func2(encbuf2_s2, rc4_key_3) rc4_key_pre_final = self.formbook_compute_sha1(encrypted_hashes_array) rc4_key_final = fb_decrypt.decrypt_func2(rc4_key_two, rc4_key_pre_final)
p_data = self.formbook_decrypt_strings(fb_decrypt, p_data, rc4_key_final, encbuf9_s1)
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=formbook_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = [] try: pe = pefile.PE(data=data) except: continue
for pattern in CONFIG_PATTERNS: offset = re.search(pattern, data).start()
offset += 6 key1_offset = unpack("=I", data[offset:offset + 4])[0] + offset + 11 key1 = data[key1_offset:key1_offset + (0x14 * 2)] offset += 23 key2_offset = unpack("=I", data[offset:offset + 4])[0] + offset + 11 key2 = data[key2_offset:key2_offset + (0x14 * 2)] offset += 21 config_size = unpack("=I", data[offset:offset + 4])[0] offset += 5 config_offset = unpack("=I", data[offset:offset + 4])[0] + offset + 11 config = data[config_offset:config_offset + (config_size * 2)] offset += 33 url_size = unpack("b", data[offset])[0]
for pattern in STRINGS_PATTERNS: offset = re.search(pattern, data).start()
offset += 19 strings_size = unpack("=I", data[offset:offset + 4])[0] offset += 5 strings_offset = unpack("=I", data[offset:offset + 4])[0] + offset + 11 strings_data = data[strings_offset:strings_offset + (strings_size * 2)]
for pattern in HASHS_PATTERNS: offset = re.search(pattern, data).start()
offset += 1 hashs_size = unpack("=I", data[offset:offset + 4])[0] offset += 11 hashs_offset = unpack("=I", data[offset:offset + 4])[0] + offset + 11 hashs_data = data[hashs_offset:hashs_offset + (hashs_size * 2)]
config_data.append(self.formbook_decrypt(key1, key2, config, config_size, strings_data, strings_size, url_size, hashs_data, hashs_size))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<16}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205# Detecting HawkEye Keylogger for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv hawkeyescan.py volatility/plugins/malware# 3. python vol.py hawkeyeconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom base64 import b64decodefrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
try: from Crypto.Cipher import AES has_crypto = Trueexcept ImportError: has_crypto = False
try: from pbkdf2 import PBKDF2 has_pbkdf2 = Trueexcept ImportError: has_pbkdf2 = False
hawkeye_sig = { 'namespace1' : 'rule Hawkeye { \ strings: \ $hawkstr1 = "HawkEye Keylogger" wide \ $hawkstr2 = "Dear HawkEye Customers!" wide \ $hawkstr3 = "HawkEye Logger Details:" wide \ condition: all of them}'}
# Config patternCONFIG_PATTERNS = [re.compile("\x57\x00\x69\x00\x6E\x00\x46\x00\x6F\x00\x72\x00\x6D\x00\x73\x00\x5F\x00\x53\x00\x65\x00\x65\x00\x49\x00\x6E\x00\x6E\x00\x65\x00\x72\x00\x45\x00\x78\x00\x63\x00\x65\x00\x70\x00\x74\x00\x69\x00\x6F\x00\x6E\x00\x00\x80", re.DOTALL)]
idx_list = { 0: "encryptedemailstring", 1: "encryptedpassstring", 2: "encryptedsmtpstring", 3: "portstring", 4: "timerstring", 5: "fakemgrstring", 6: "encryptedftphost", 7: "encryptedftpuser", 8: "encryptedftppass", 9: "encryptedphplink", 10: "useemail", 11: "useftp", 12: "usephp", 13: "delaytime", 14: "clearie", 15: "clearff", 16: "binder", 17: "downloader", 18: "websitevisitor", 19: "websiteblocker", 20: "notify", 21: "DisableSSL", 22: "fakerror", 23: "startup", 24: "screeny", 25: "clip", 26: "TaskManager", 27: "logger", 28: "stealers", 29: "melt", 30: "reg", 31: "cmd", 32: "misconfig", 33: "spreaders", 34: "steam", 35: "meltLocation",}
class hawkeyeConfig(taskmods.DllList): """Parse the Hawkeye configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def string_print(self, line): try: return "".join((char for char in line if 32 < ord(char) < 127)) except: return line
def decrypt_string(self, key, salt, coded): generator = PBKDF2(key, salt) aes_iv = generator.read(16) aes_key = generator.read(32)
mode = AES.MODE_CBC cipher = AES.new(aes_key, mode, IV=aes_iv) value = cipher.decrypt(b64decode(coded)).replace('\x00', '') return self.string_print(value)
def parse_config(self, configs): i = 0 p_data = OrderedDict() key, salt = 'HawkEyeKeylogger', '3000390039007500370038003700390037003800370038003600'.decode('hex') for config in configs: if i in [0, 1, 2, 6, 7, 8, 9]: config = self.decrypt_string(key, salt, config) p_data[idx_list[i]] = config i += 1
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
if not has_crypto: debug.error("pycrypto must be installed for this plugin")
if not has_pbkdf2: debug.error("pbkdf2 must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=hawkeye_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
offset = 0 for pattern in CONFIG_PATTERNS: mc = re.search(pattern, data) if mc: offset = mc.end()
configs = [] if offset > 0: while 1: strings = [] string_len = ord(data[offset]) if data[offset] == "\x80": string_len = ord(data[offset + 1]) offset += 1 offset += 1 for i in range(string_len): if data[offset + i] != "\x00": strings.append(data[offset + i]) configs.append("".join(strings)) offset = offset + string_len if len(configs) > 35: break
if not configs[13].isdigit(): configs.insert(13, 0) configs.pop(-1)
config_data.append(self.parse_config(configs))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<21}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168# Detecting LokiBot for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv lokibotscan.py volatility/plugins/malware# 3. python vol.py lokibotconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom base64 import b64decodefrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
try: from Crypto.Cipher import DES3 has_crypto = Trueexcept ImportError: has_crypto = False
lokibot_sig = { 'namespace1' : 'rule Lokibot { \ strings: \ $des3 = { 68 03 66 00 00 } \ $param = "MAC=%02X%02X%02XINSTALL=%08X%08X" \ $string = { 2d 00 75 00 00 00 46 75 63 6b 61 76 2e 72 75 00 00} \ condition: all of them}'}
# Config patternCONF_PATTERNS = [re.compile("(..)\x0F\x84(......)\xe9(....)\x90\x90\x90\x90\x90\x90", re.DOTALL)]
class lokibotConfig(taskmods.DllList): """Parse the Lokibot configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def string_print(self, line): try: return "".join((char for char in line if 32 < ord(char) < 127)) except: return line
def config_decode(self, name, data, config_index, enc_data_count): enc_data = [] key_data = [] enc_set = [] p_data = OrderedDict() x = 0 for i in range(enc_data_count): while 1: if data[config_index + x] != "\0": enc_set.append(data[config_index + x]) x += 1 else: enc_data.append("".join(enc_set)) enc_set = [] x += 4 break
config_index = config_index + x iv = data[config_index:config_index + 12].replace("\0", "")
config_index = config_index + 12 for i in range(3)[::-1]: key_data.append(data[config_index + (12 * i):config_index + (12 * (i + 1))].replace("\0", ""))
key = "".join(key_data) i = 0 for data in enc_data: des = DES3.new(key, IV=iv, mode=DES3.MODE_CBC) data_dec = des.decrypt(data) p_data[name + " " + str(i)] = self.string_print(data_dec) i += 1
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
if not has_crypto: debug.error("pycrypto must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=lokibot_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
config_index = data.find("ckav.ru") + 12 config_data.append(self.config_decode("Original URL", data, config_index, 4)) config_index = data.find("INSTALL=%08X%08X") + 16 config_data.append(self.config_decode("Registry key", data, config_index, 1))
for pattern in CONF_PATTERNS: mk = re.search(pattern, data)
enc_set = [] x = 0 if mk: if "h" in data[mk.start() + 0x30]: key = 0x0 else: key = 0xFF
while 1: if data[mk.start() + 0x30 + x] != "\0": enc_set.append(chr(ord(data[mk.start() + 0x30 + x]) ^ key)) x += 1 else: enc_data = "".join(enc_set) break
p_data = {} p_data["Setting URL"] = self.string_print(enc_data) config_data.append(p_data)
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<16}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150# Detecting Nanocore RAT for Volatilitv## Based on the script below:# https://github.com/kevthehermit/RATDecoders/blob/master/decoders/NanoCore.py## How to use:# 1. cd "Volatility Folder"# 2. mv nanocoreconfigallocate.py volatility/plugins/malware# 3. python vol.py nanocoreconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom struct import unpack, unpack_fromfrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
nanocore_sig = { 'namespace1' : 'rule Nanocore { \ strings: \ $v1 = "NanoCore Client" \ $v2 = "PluginCommand" \ $v3 = "CommandType" \ condition: all of them}'}
# Config patternCONFIG_PATTERNS = [re.compile("Version.\x07(.*?)\x0cMutex", re.DOTALL)]
MODE = {0x0: "Disable", 0x01: "Enable"}
class nanocoreConfig(taskmods.DllList): "Parse the Nanocore configuration"
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End return None
def parse_config(self, data):
p_data = OrderedDict()
p_data['Version'] = re.search('Version..(.*?)\x0c', data).group()[8:16] p_data['Mutex'] = re.search('Mutex(.*?)\x0c', data).group()[6:-1].encode('hex') p_data['Group'] = re.search('DefaultGroup\x0c(.*?)\x0c', data).group()[14:-1] p_data['Domain1'] = re.search('PrimaryConnectionHost\x0c(.*?)Back', data, re.DOTALL).group()[23:-6] p_data['Domain2'] = re.search('BackupConnectionHost\x0c(.*?)\x0c', data).group()[22:-1] p_data['Port'] = unpack("<H", re.search('ConnectionPort...', data, re.DOTALL).group()[15:])[0] try: p_data['KeyboardLogging'] = MODE[ord(re.search('KeyboardLogging(.*?)\x0c', data).group()[16:-1])] except: pass p_data['RunOnStartup'] = MODE[ord(re.search('RunOnStartup(.*?)\x0c', data).group()[13:-1])] p_data['RequestElevation'] = MODE[ord(re.search('RequestElevation(.*?)\x0c', data).group()[17:-1])] p_data['BypassUAC'] = MODE[ord(re.search('BypassUserAccountControl(.*?)\x0c', data).group()[25:-1])] p_data['ClearZoneIdentifier'] = MODE[ord(re.search('ClearZoneIdentifier(.*?)\x0c', data).group()[20:-1])] p_data['ClearAccessControl'] = MODE[ord(re.search('ClearAccessControl(.*?)\x0c', data).group()[19:-1])] p_data['SetCriticalProcess'] = MODE[ord(re.search('SetCriticalProcess(.*?)\x0c', data).group()[19:-1])] p_data['PreventSystemSleep'] = MODE[ord(re.search('PreventSystemSleep(.*?)\x0c', data).group()[19:-1])] p_data['ActivateAwayMode'] = MODE[ord(re.search('ActivateAwayMode(.*?)\x0c', data).group()[17:-1])] p_data['EnableDebugMode'] = MODE[ord(re.search('EnableDebugMode(.*?)\x0c', data).group()[16:-1])] p_data['RunDelay'] = unpack("<i", re.search('RunDelay(.*?)\x0c', data).group()[9:-1])[0] p_data['ConnectDelay'] = unpack("<i", re.search('ConnectDelay(.*?)\x0c', data).group()[13:-1])[0] p_data['RestartDelay'] = unpack("<i", re.search('RestartDelay(.*?)\x0c', data).group()[13:-1])[0] p_data['TimeoutInterval'] = unpack("<i", re.search('TimeoutInterval(.*?)\x0c', data).group()[16:-1])[0] p_data['KeepAliveTimeout'] = unpack("<i", re.search('KeepAliveTimeout(.*?)\x0c', data).group()[17:-1])[0] p_data['MutexTimeout'] = unpack("<i", re.search('MutexTimeout(.*?)\x0c', data).group()[13:-1])[0] p_data['LanTimeout'] = unpack("<i", re.search('LanTimeout(.*?)\x0c', data).group()[11:-1])[0] p_data['WanTimeout'] = unpack("<i", re.search('WanTimeout(.*?)\x0c', data).group()[11:-1])[0] p_data['BufferSize'] = re.search('BufferSize(.*?)\x0c', data).group()[11:-1].encode('hex') p_data['MaxPacketSize'] = re.search('MaxPacketSize(.*?)\x0c', data).group()[14:-1].encode('hex') p_data['GCThreshold'] = re.search('GCThreshold(.*?)\x0c', data).group()[12:-1].encode('hex') try: p_data['UseCustomDNS'] = MODE[ord(re.search('UseCustomDnsServer(.*?)\x0c', data).group()[19:-1])] p_data['PrimaryDNSServer']= re.search('PrimaryDnsServer\x0c(.*?)\x0c', data).group()[18:-1] p_data['BackupDNSServer'] = re.search('BackupDnsServer\x0c(.*?)(\x04|\x0c)', data).group()[16:-1] except: pass
return p_data
def calculate(self):
if not has_yara: debug.error('Yara must be installed for this plugin.')
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error('This command does not support the selected profile.')
rules = yara.compile(sources=nanocore_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules) for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() memdata = proc_addr_space.get_available_addresses()
config_data = []
for m in memdata: if m[1] < 0x100000: continue
data = proc_addr_space.zread(m[0], m[1])
for pattern in CONFIG_PATTERNS: m = re.search(pattern, data)
if m: offset = m.start() else: continue
config_data.append(self.parse_config(data[offset: offset + 0x1000]))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<20}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170# NetWire config dumper for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## Created by You Nakatsuru (@you0708)## How to use:# 1. cd "Volatility Folder"# 2. mkdir contrib/plugins/malware# 3. mv netwirescan.py contrib/plugins/malware# 4. python vol.py --plugins=contrib/plugins/malware netwireconfig -f images.mem --profile=WinXPSP3x86
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindfrom struct import unpackimport refrom collections import OrderedDict
NETWIRE_INFO = [{ 'version': '1.5b', 'pattern': re.compile("\xE8\x8B(.)\x00\x00\xC7\x44(.)\x08\x03\x00\x00\x00", re.DOTALL), 'cfg_offset': 17, 'cfg_size': 0x3A4, 'cfg_info': [['Unknown0', 0], ['Unknown1', 0x4], ['KeyLog Dir', 0x8], ['Active Setup', 0x8C], ['Run Key', 0xB4], ['Startup', 0xC8], ['Mutex', 0x14C], ['UUID', 0x158], ['Password', 0x180], ['Unknown2', 0x1A4], ['Host', 0x2A4]]}, { 'version': '1.5d', 'pattern': re.compile("\xE8(..)\x00\x00\x89\x1C(.)\xC7\x44\x24\x08", re.DOTALL), 'cfg_offset': 20, 'cfg_size': 0x3A8, 'cfg_info': [['Unknown0', 0], ['Unknown1', 0x4], ['Unknown2', 0x8], ['KeyLog Dir', 0xC], ['Active Setup', 0x90], ['Run Key', 0xB8], ['Startup', 0xCC], ['Mutex', 0x150], ['UUID', 0x15C], ['Password', 0x184], ['Unknown3', 0x1A8], ['Host', 0x2A8]]}, { 'version': '1.6a Final?', 'pattern': re.compile("\xE8\x87(.)\x00\x00\x89\x1C(.)\xC7\x44\x24\x08\x03", re.DOTALL), 'cfg_offset': 20, 'cfg_size': 0x3A8, 'cfg_info': [['Unknown0', 0], ['Unknown1', 0x4], ['Unknown2', 0x8], ['KeyLog Dir', 0xC], ['Active Setup', 0x90], ['Run Key', 0xB8], ['Startup', 0xCC], ['Mutex', 0x150], ['UUID', 0x15C], ['Password', 0x184], ['Unknown3', 0x1A8], ['Host', 0x2A8]]}, { 'version': '1.6a', 'pattern': re.compile("\xE8\x9F(.)\x00\x00\x89\x1C(.)\xC7\x44\x24\x08\x03", re.DOTALL), 'cfg_offset': 20, 'cfg_size': 0x3A8, 'cfg_info': [['Unknown0', 0], ['Unknown1', 0x4], ['Unknown2', 0x8], ['KeyLog Dir', 0xC], ['Active Setup', 0x90], ['Run Key', 0xB8], ['Startup', 0xCC], ['Mutex', 0x150], ['UUID', 0x15C], ['Password', 0x184], ['Unknown3', 0x1A8], ['Host', 0x2A8]]}, { 'version': '1.7a', 'pattern': re.compile("\xE8(..)\x00\x00\xC7\x44(.)\x08\xFF\x00\x00\x00", re.DOTALL), 'cfg_offset': 17, 'cfg_size': 0x3D0, 'cfg_info': [['C2', 0], ['Unknown0', 0x100], ['AES Key', 0x200], ['Host ID', 0x238], ['Mutex', 0x24C], ['Install Path', 0x260], ['Startup', 0x2E4], ['UUID', 0x300], ['KeyLog Dir', 0x340], ['Unknown1', 0x3C4], ['Unknown2', 0x3C8], ['Unknown3', 0x3CC]]}, { 'version': 'Unknown', 'pattern': re.compile("\xE8\x53(.)\x00\x00\xC7\x44(.)\x10\xFF\x00\x00\x00", re.DOTALL), 'cfg_offset': 17, 'cfg_size': 0x468, 'cfg_info': [['C2', 0], ['Unknown0', 0x100], ['AES Key', 0x200], ['Host ID', 0x238], ['Group', 0x24C], ['Mutex', 0x260], ['Install Path', 0x280], ['Startup', 0x320], ['UUID', 0x360], ['KeyLog Dir', 0x3A0], ['Unknown1', 0x424], ['Unknown2', 0x440], ['Unknown3', 0x464]]}]
try: import yara has_yara = Trueexcept ImportError: has_yara = False
signatures = { 'namespace1' : 'rule netwire { \ strings: \ $v1 = "HostId-%Rand%" \ $v2 = "mozsqlite3" \ $v3 = "[Scroll Lock]" \ $v4 = "GetRawInputData" \ $ping = "ping 192.0.2.2" \ $log = "[Log Started] - [%.2d/%.2d/%d %.2d:%.2d:%.2d]" \ condition: ($v1) or ($v2 and $v3 and $v4) or ($ping and $log)}'}
class netwireConfig(taskmods.DllList): """Parse the NetWire configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): """ Get the VAD starting address """
for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
# This should never really happen return None
def parse_config(self, cfg_blob, nw): p_data = OrderedDict() p_data["Version"] = nw["version"]
for name, offset in nw["cfg_info"]: data = cfg_blob[offset:].split("\x00")[0] p_data[name] = data
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=signatures)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
if len(data) < 0x10000 or len(data) > 0x200000: continue
for nw in NETWIRE_INFO: m = re.search(nw["pattern"], data) if m: offset = m.start() break else: continue
cfg_addr = unpack("=I", data[offset + nw["cfg_offset"]:offset + nw["cfg_offset"] + 4])[0] if cfg_addr < vad_base_addr: continue
cfg_addr -= vad_base_addr cfg_blob = data[cfg_addr:cfg_addr + nw["cfg_size"]] config_data.append(self.parse_config(cfg_blob, nw))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<16}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140# Detecting njRAT Keylogger for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv njratscan.py volatility/plugins/malware# 3. python vol.py njratconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom base64 import b64decodefrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
njrat_sig = { 'namespace1' : 'rule Njrat { \ strings: \ $reg = "SEE_MASK_NOZONECHECKS" wide \ $msg = "Execute ERROR" wide \ $ping = "cmd.exe /c ping 0 -n 2 & del" wide \ condition: all of them}'}
# Config patternCONFIG_PATTERNS = [re.compile("\x46\x69\x78\x00\x6b\x00\x57\x52\x4B\x00\x6D\x61\x69\x6E\x00\x00\x00", re.DOTALL)]
idx_list = { 0: "ID", 1: "Version", 2: "Name of Executable", 3: "Copy Direcroty", 4: "Registry Name", 5: "Server", 6: "Port", 7: "Split", 8: "Registry Key",}
class njratConfig(taskmods.DllList): """Parse the njRAT configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def parse_config(self, configs): i = 0 p_data = OrderedDict() for config in configs: if i == 0: p_data[idx_list[i]] = b64decode(config) else: p_data[idx_list[i]] = config i += 1
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=njrat_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
offset = 0 for pattern in CONFIG_PATTERNS: mc = re.search(pattern, data) if mc: offset = mc.end()
configs = [] if offset > 0: while 1: strings = [] while data[offset] == "\x01" or data[offset] == "\x00": offset += 1 string_len = ord(data[offset]) offset += 1 for i in range(string_len): if data[offset + i] != "\x00": strings.append(data[offset + i]) if "False" not in "".join(strings) and "True" not in "".join(strings): configs.append("".join(strings)) offset = offset + string_len if len(configs) > 8: break
config_data.append(self.parse_config(configs))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<21}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109# Detecting NodeRat for Volatilitv## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv noderatconfigallocate.py volatility/plugins/malware# 3. python vol.py noderatconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport jsonfrom struct import unpack, unpack_from
try: import yara has_yara = Trueexcept ImportError: has_yara = False
noderat_sig = { 'namespace1' : 'rule Noderat { \ strings: \ $config = "/config/app.json" \ $key = "/config/.regeditKey.rc" \ $message = "uninstall error when readFileSync: " \ condition: all of them}'}
# Config patternCONFIG_PATTERNS = [re.compile("\x7B\x0D\x0A\x20\x20\x22\x6E\x61\x6D\x65\x22\x3A\x20(.*)\x65\x0d\x0a\x7d", re.DOTALL)]
class noderatConfig(taskmods.DllList): "Parse the Noderat configuration"
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End return None
def calculate(self):
if not has_yara: debug.error('Yara must be installed for this plugin.')
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error('This command does not support the selected profile.')
rules = yara.compile(sources=noderat_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules) for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() memdata = proc_addr_space.get_available_addresses()
config_data = []
for m in memdata: if m[1] < 0x100000: continue p_data = {}
data = proc_addr_space.zread(m[0], m[1])
for pattern in CONFIG_PATTERNS: m = re.search(pattern, data)
if m: offset = m.start() else: continue
json_data = data[offset:m.end()] d = json.loads(json_data)
config_data.append(d) break yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<10}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708# Detecting PlugX for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv plugxscan.py volatility/plugins/malware# 3. python vol.py [ plugxscan | plugxconfig ] -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindfrom struct import unpack, unpack_fromfrom socket import inet_ntoafrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
plugx_sig = { 'namespace1' : 'rule plugx { \ strings: \ $v1 = { 47 55 4c 50 00 00 00 00 } \ $v2a = { 68 40 25 00 00 } \ $v2c = { 68 58 2D 00 00 } \ $v2b = { 68 a0 02 00 00 } \ $v2d = { 68 a4 36 00 00 } \ $v2e = { 8D 46 10 68 } \ $v2f = { 68 24 0D 00 00 } \ $v2g = { 68 a0 02 00 00 } \ $v2h = { 68 e4 0a 00 00 } \ $enc1 = { C1 E? 03 C1 E? 07 2B ?? } \ $enc2 = { 32 5? ?? 81 E? ?? ?? 00 00 2A 5? ?? 89 ?? ?? 32 ?? 2A ?? 32 5? ?? 2A 5? ?? 32 } \ $enc3 = { B? 33 33 33 33} \ $enc4 = { B? 44 44 44 44} \ condition: $v1 at 0 or ($v2a and $v2b and $enc1) or ($v2c and $v2b and $enc1) or ($v2d and $v2b and $enc2) or ($v2d and $v2e and $enc2) or ($v2f and $v2g and $enc3 and $enc4) or ($v2h and $v2g and $enc3 and $enc4)}'}
FLAG_ENABLE = 0xFFFFFFFF
HKEY_CLASSES_ROOT = 0x80000000HKEY_CURRENT_USER = 0x80000001HKEY_LOCAL_MACHINE = 0x80000002
class plugxConfig(taskmods.DllList): """Parse the PlugX configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def parse_config(self, cfg_blob, cfg_sz, cfg_addr, vinfo): p_data = OrderedDict()
# config parsing SleepTime = unpack_from('>I', cfg_blob, 0x34)[0] NetworkFlag = unpack_from('<672B', cfg_blob, 0x3c) ServerURL = unpack_from('<128s128s128s128s', cfg_blob, 0x3fc) if cfg_sz == 0x1d18: InstallFolder = unpack_from('<512s', cfg_blob, 0x910)[0] ServiceName = unpack_from('<512s', cfg_blob, 0xb10)[0] ServiceDisplayName = unpack_from('<512s', cfg_blob, 0xd10)[0] InjectionProcess = unpack_from('<512s', cfg_blob, 0x1518)[0] ServerID1 = unpack_from('<512s', cfg_blob, 0x1718)[0] ServerID2 = unpack_from('<512s', cfg_blob, 0x1918)[0] Mutex = unpack_from('<256s', cfg_blob, 0x1b18)[0] RunKey = unpack_from('<512s', cfg_blob, 0x1114)[0] RunKeyValu = unpack_from('<512s', cfg_blob, 0x1314)[0] elif cfg_sz == 0x1510 or cfg_sz == 0x150c: InstallFolder = unpack_from('<512s', cfg_blob, 0x90c)[0] ServiceName = unpack_from('<512s', cfg_blob, 0xb0c)[0] ServiceDisplayName = unpack_from('<512s', cfg_blob, 0xd0c)[0] ServerID1 = unpack_from('<512s', cfg_blob, 0x110c)[0] ServerID2 = unpack_from('<512s', cfg_blob, 0x130c)[0]
ServerData = [[0] * 3] * 4 proxy = [[0] * 5] * 4 if unpack_from('<I', cfg_blob, 0xc)[0] == FLAG_ENABLE: DLLremove_flag = 'Enable' else: DLLremove_flag = 'Disable'
if unpack_from('<I', cfg_blob, 0x28)[0] == FLAG_ENABLE: FileDelete_flag = 'Enable' else: FileDelete_flag = 'Disable'
if unpack_from('<I', cfg_blob, 0x2c)[0] == FLAG_ENABLE: KeyLog_flag = 'Enable' else: KeyLog_flag = 'Disable'
(dns1, dns2, dns3, dns4) = unpack_from("<4L", cfg_blob, 0x2dc) custom_dns = cfg_blob[0x2dc:0x2ec]
for i in xrange(4): if unpack_from('<B', cfg_blob, 0x2ec + (i * 68))[0] != 0x0: ServerData[i] = unpack_from('<HH64s', cfg_blob, 0x2ec + (i * 68))
for i in xrange(4): proxy[i] = unpack_from('<2H64s64s64s', cfg_blob, 0x5fc + (i * 196))
if unpack_from('>B', cfg_blob, 0x90c)[0] == 0: AutorunSetup = 'Service setup' elif unpack_from('>B', cfg_blob, 0x90c)[0] == 1: AutorunSetup = 'Run Registry' elif unpack_from('>B', cfg_blob, 0x90c)[0] == 2: AutorunSetup = 'Disable'
if unpack_from('<I', cfg_blob, 0x1110)[0] == HKEY_CLASSES_ROOT: RegistrySubkey = 'HKEY_CLASSES_ROOT' elif unpack_from('<I', cfg_blob, 0x1110)[0] == HKEY_CURRENT_USER: RegistrySubkey = 'HKEY_CURRENT_USER' elif unpack_from('<I', cfg_blob, 0x1110)[0] == HKEY_LOCAL_MACHINE: RegistrySubkey = 'HKEY_LOCAL_MACHINE' else: RegistrySubkey = unpack_from('<I', cfg_blob, 0x1110)[0]
if cfg_sz > 0x1510: if unpack_from('>B', cfg_blob, 0x1514)[0] == 0: InjectionFlag = 'Enable' else: InjectionFlag = 'Disable'
CnCDay = 'Everyday' for x in xrange(672): if NetworkFlag[x] == 0x0: CnCDay = 'Network Activity Flag Enable(Check config file!)'
# config write file p_data["Version"] = 1 p_data["Version Info"] = vinfo p_data["Config Size"] = "0x{0:X}".format(cfg_sz) p_data["Delete DLL list"] = DLLremove_flag p_data["File Delete"] = FileDelete_flag p_data["Key Logger"] = KeyLog_flag p_data["Sleep Time"] = SleepTime p_data["Network Activity"] = CnCDay if dns1 not in (0, 0xffffffff): p_data["Custom DNS 1"] = inet_ntoa(custom_dns[:4]) if dns2 not in (0, 0xffffffff): p_data["Custom DNS 2"] = inet_ntoa(custom_dns[4:8]) if dns3 not in (0, 0xffffffff): p_data["Custom DNS 3"] = inet_ntoa(custom_dns[8:12]) if dns4 not in (0, 0xffffffff): p_data["Custom DNS 4"] = inet_ntoa(custom_dns[12:16])
for z in xrange(4): if ServerData[z][0]: p_data["Server {0}".format(z + 1)] = "{0}:{1} (Type {2})".format(ServerData[z][2].replace('\0', ''), ServerData[z][1], ServerData[z][0])
for y in xrange(4): if ServerURL[y]: p_data["Server URL {0}".format(y + 1)] = ServerURL[y].replace('\0', '')
for k in xrange(4): if proxy[k][1] != 0: p_data["Proxy {0}".format(k + 1)] = "{0}:{1}".format(proxy[k][2].replace('\0', ''), proxy[k][1]) if proxy[k][3] != '\x00': p_data["Proxy credentials {0}".format(k + 1)] = "{0}:{1}".format(proxy[k][3].replace('\0', ''), proxy[k][4].replace('\0', ''))
p_data["Install Folder"] = InstallFolder.replace('\0', '') p_data["Service Name"] = ServiceName.replace('\0', '') p_data["Service Display Name"] = ServiceDisplayName.replace('\0', '') p_data["Server ID1"] = ServerID1.replace('\0', '') p_data["Server ID2"] = ServerID2.replace('\0', '') if cfg_sz == 0x1d18: p_data["Auto Start"] = AutorunSetup p_data["Registry Subkey"] = RegistrySubkey.replace('\0', '') p_data["Registry Key"] = RunKey.replace('\0', '') p_data["Registry Value"] = RunKeyValu.replace('\0', '') p_data["Injection"] = InjectionFlag p_data["Injection Process"] = InjectionProcess.replace('\0', '') p_data["Mutex"] = Mutex.replace('\0', '')
return p_data
def parse_config2(self, cfg_blob, cfg_sz, cfg_addr, vinfo): p_data = OrderedDict()
# config parsing SleepTime = unpack_from('>I', cfg_blob, 0x34)[0] NetworkFlag = unpack_from('>672B', cfg_blob, 0x3c) ServerURL = unpack_from('<128s128s128s128s', cfg_blob, 0x3fc) InstallFolder = unpack_from('<512s', cfg_blob, 0x910)[0] ServiceName = unpack_from('<512s', cfg_blob, 0xb10)[0] ServiceDisplayName = unpack_from('<512s', cfg_blob, 0xd10)[0] InjectionProcess1 = unpack_from('<512s', cfg_blob, 0x1518)[0] InjectionProcess2 = unpack_from('<512s', cfg_blob, 0x1718)[0] InjectionProcess3 = unpack_from('<512s', cfg_blob, 0x1918)[0] InjectionProcess4 = unpack_from('<512s', cfg_blob, 0x1B18)[0] if cfg_sz == 0x2540: ServerID1 = unpack_from('<512s', cfg_blob, 0x1d18)[0] ServerID2 = unpack_from('<512s', cfg_blob, 0x1f18)[0] Mutex = unpack_from('<256s', cfg_blob, 0x2118)[0] ScreenCapFolder = unpack_from('<512s', cfg_blob, 0x2330)[0] else: ServerID1 = unpack_from('<512s', cfg_blob, 0x251c)[0] ServerID2 = unpack_from('<512s', cfg_blob, 0x271c)[0] Mutex = unpack_from('<256s', cfg_blob, 0x291c)[0] ScreenCapFolder = unpack_from('<512s', cfg_blob, 0x2b34)[0] RunKey = unpack_from('<512s', cfg_blob, 0x1114)[0] RunKeyValu = unpack_from('<512s', cfg_blob, 0x1314)[0]
ServerData = [[0] * 3] * 4 proxy = [[0] * 5] * 4 if unpack_from('<I', cfg_blob, 0xc)[0] == FLAG_ENABLE: DLLremove_flag = 'Enable' else: DLLremove_flag = 'Disable'
if unpack_from('<I', cfg_blob, 0x28)[0] == FLAG_ENABLE: FileDelete_flag = 'Enable' else: FileDelete_flag = 'Disable'
if unpack_from('<I', cfg_blob, 0x2c)[0] == FLAG_ENABLE: KeyLog_flag = 'Enable' else: KeyLog_flag = 'Disable'
(dns1, dns2, dns3, dns4) = unpack_from("<4L", cfg_blob, 0x2dc) custom_dns = cfg_blob[0x2dc:0x2ec]
for i in xrange(4): if unpack_from('<B', cfg_blob, 0x2ec + (i * 68))[0] != 0x0: ServerData[i] = unpack_from('<HH64s', cfg_blob, 0x2ec + (i * 68))
for i in xrange(4): proxy[i] = unpack_from('<2H64s64s64s', cfg_blob, 0x5fc + (i * 196))
if unpack_from('>B', cfg_blob, 0x90c)[0] == 0: AutorunSetup = 'Run Registry or Service setup' elif unpack_from('>B', cfg_blob, 0x90c)[0] == 1: AutorunSetup = 'Service setup' elif unpack_from('>B', cfg_blob, 0x90c)[0] == 2: AutorunSetup = 'Run Registry' elif unpack_from('>B', cfg_blob, 0x90c)[0] == 3: AutorunSetup = 'Disable'
if unpack_from('<I', cfg_blob, 0x1110)[0] == HKEY_CLASSES_ROOT: RegistrySubkey = 'HKEY_CLASSES_ROOT' elif unpack_from('<I', cfg_blob, 0x1110)[0] == HKEY_CURRENT_USER: RegistrySubkey = 'HKEY_CURRENT_USER' elif unpack_from('<I', cfg_blob, 0x1110)[0] == HKEY_LOCAL_MACHINE: RegistrySubkey = 'HKEY_LOCAL_MACHINE' else: RegistrySubkey = unpack_from('<I', cfg_blob, 0x1110)[0]
if unpack_from('>B', cfg_blob, 0x1514)[0] == 0: InjectionFlag = 'Enable' else: InjectionFlag = 'Disable'
if cfg_sz == 0x2540: if unpack_from('>B', cfg_blob, 0x2318)[0] == 0: ScCapFlug = 'Disable' else: ScCapFlug = 'Enable' else: if unpack_from('>B', cfg_blob, 0x2b1c)[0] == 0: ScCapFlug = 'Disable' else: ScCapFlug = 'Enable'
CnCDay = 'Everyday' for x in xrange(672): if NetworkFlag[x] == 0x0: CnCDay = 'Network Activity Flag Enable(Check config file!)'
# config write file p_data["Version"] = 2 p_data["Version Info"] = vinfo p_data["Config Size"] = "0x{0:X}".format(cfg_sz) p_data["Delete DLL list"] = DLLremove_flag p_data["File Delete"] = FileDelete_flag p_data["Key Logger"] = KeyLog_flag p_data["Sleep Time"] = SleepTime p_data["Network Activity"] = CnCDay if dns1 not in (0, 0xffffffff): p_data["Custom DNS 1"] = inet_ntoa(custom_dns[:4]) if dns2 not in (0, 0xffffffff): p_data["Custom DNS 2"] = inet_ntoa(custom_dns[4:8]) if dns3 not in (0, 0xffffffff): p_data["Custom DNS 3"] = inet_ntoa(custom_dns[8:12]) if dns4 not in (0, 0xffffffff): p_data["Custom DNS 4"] = inet_ntoa(custom_dns[12:16])
for z in xrange(4): if ServerData[z][0]: p_data["Server {0}".format(z + 1)] = "{0}:{1} (Type {2})".format(ServerData[z][2].replace('\0', ''), ServerData[z][1], ServerData[z][0])
for y in xrange(4): if ServerURL[y]: p_data["Server URL {0}".format(y + 1)] = ServerURL[y].replace('\0', '')
for k in xrange(4): if proxy[k][1] != 0: p_data["Proxy {0}".format(k + 1)] = "{0}:{1}".format(proxy[k][2].replace('\0', ''), proxy[k][1]) if proxy[k][3] != '\x00': p_data["Proxy credentials {0}".format(k + 1)] = "{0}:{1}".format(proxy[k][3].replace('\0', ''), proxy[k][4].replace('\0', ''))
p_data["Auto Start"] = AutorunSetup p_data["Install Folder"] = InstallFolder.replace('\0', '') p_data["Service Name"] = ServiceName.replace('\0', '') p_data["Service Display Name"] = ServiceDisplayName.replace('\0', '') p_data["Registry Subkey"] = RegistrySubkey p_data["Registry Key"] = RunKey.replace('\0', '') p_data["Registry Value"] = RunKeyValu.replace('\0', '') p_data["Injection"] = InjectionFlag p_data["Injection Process1"] = InjectionProcess1.replace('\0', '') p_data["Injection Process2"] = InjectionProcess2.replace('\0', '') p_data["Injection Process3"] = InjectionProcess3.replace('\0', '') p_data["Injection Process4"] = InjectionProcess4.replace('\0', '') p_data["Server ID1"] = ServerID1.replace('\0', '') p_data["Server ID2"] = ServerID2.replace('\0', '') p_data["Mutex"] = Mutex.replace('\0', '') p_data["Screen Capture"] = ScCapFlug p_data["Screen Capture Folder"] = ScreenCapFolder.replace('\0', '')
return p_data
def parse_config3(self, cfg_blob, cfg_sz, cfg_addr, vinfo): p_data = OrderedDict()
# config parsing timer1 = unpack_from('4B', cfg_blob, 0x28) SleepTime1 = "" if timer1[0] != 0: SleepTime1 += "%d days, " % timer1[0] if timer1[1] != 0: SleepTime1 += "%d hours, " % timer1[1] if timer1[2] != 0: SleepTime1 += "%d mins, " % timer1[2] SleepTime1 += "%d secs" % timer1[3]
timer2 = unpack_from('4B', cfg_blob, 0x2c) SleepTime2 = "" if timer2[0] != 0: SleepTime2 += "%d days, " % timer2[0] if timer2[1] != 0: SleepTime2 += "%d hours, " % timer2[1] if timer2[2] != 0: SleepTime2 += "%d mins, " % timer2[2] SleepTime2 += "%d secs" % timer2[3]
NetworkFlag = unpack_from('>672B', cfg_blob, 0x30) ServerURL = unpack_from('<128s128s128s128s128s128s128s128s128s128s128s128s128s128s128s128s', cfg_blob, 0x720) InstallFolder = unpack_from('<512s', cfg_blob, 0x1234)[0] ServiceName = unpack_from('<512s', cfg_blob, 0x1434)[0] ServiceDisplayName = unpack_from('<512s', cfg_blob, 0x1634)[0] ServiceComment = unpack_from('<512s', cfg_blob, 0x1834)[0] InjectionProcess1 = unpack_from('<512s', cfg_blob, 0x1e3c)[0] InjectionProcess2 = unpack_from('<512s', cfg_blob, 0x203c)[0] InjectionProcess3 = unpack_from('<512s', cfg_blob, 0x223c)[0] InjectionProcess4 = unpack_from('<512s', cfg_blob, 0x243c)[0] BypassProcess1 = unpack_from('<512s', cfg_blob, 0x2640)[0] BypassProcess2 = unpack_from('<512s', cfg_blob, 0x2840)[0] BypassProcess3 = unpack_from('<512s', cfg_blob, 0x2a40)[0] BypassProcess4 = unpack_from('<512s', cfg_blob, 0x2c40)[0] ServerID1 = unpack_from('<512s', cfg_blob, 0x2e40)[0] ServerID2 = unpack_from('<512s', cfg_blob, 0x3040)[0] Mutex = unpack_from('<256s', cfg_blob, 0x3240)[0] ScreenCapFolder = unpack_from('<512s', cfg_blob, 0x3458)[0] RunKey = unpack_from('<512s', cfg_blob, 0x1a38)[0] RunKeyValu = unpack_from('<512s', cfg_blob, 0x1c38)[0]
ServerData = [[0] * 3] * 16 proxy = [[0] * 5] * 6 if unpack_from('<I', cfg_blob, 0x0)[0] == FLAG_ENABLE: DLLremove_flag = 'Enable' else: DLLremove_flag = 'Disable'
if unpack_from('<I', cfg_blob, 0x14)[0] == FLAG_ENABLE: FileDelete_flag = 'Enable' else: FileDelete_flag = 'Disable'
if unpack_from('<I', cfg_blob, 0x18)[0] == FLAG_ENABLE: KeyLog_flag = 'Enable' else: KeyLog_flag = 'Disable'
if unpack_from('<I', cfg_blob, 0x20)[0] == 0: Unknown_flag = 'Disable' else: Unknown_flag = 'Enable'
if unpack_from('<I', cfg_blob, 0x263c)[0] == 0: BypassProcess_flag = 'Disable' else: BypassProcess_flag = 'Enable'
(dns1, dns2, dns3, dns4) = unpack_from("<4L", cfg_blob, 0x2d0) custom_dns = cfg_blob[0x2d0:0x2e0]
for i in xrange(16): if unpack_from('<B', cfg_blob, 0x2e0 + (i * 68))[0] != 0x0: ServerData[i] = unpack_from('<HH64s', cfg_blob, 0x2e0 + (i * 68))
for i in xrange(4): proxy[i] = unpack_from('<2H64s64s64s', cfg_blob, 0xf20 + (i * 196))
if unpack_from('>B', cfg_blob, 0x1230)[0] == 0: AutorunSetup = 'Run Registry or Service setup' elif unpack_from('>B', cfg_blob, 0x1230)[0] == 1: AutorunSetup = 'Service setup' elif unpack_from('>B', cfg_blob, 0x1230)[0] == 2: AutorunSetup = 'Run Registry' elif unpack_from('>B', cfg_blob, 0x1230)[0] == 3: AutorunSetup = 'Disable'
if unpack_from('<I', cfg_blob, 0x1a34)[0] == HKEY_CLASSES_ROOT: RegistrySubkey = 'HKEY_CLASSES_ROOT' elif unpack_from('<I', cfg_blob, 0x1a34)[0] == HKEY_CURRENT_USER: RegistrySubkey = 'HKEY_CURRENT_USER' elif unpack_from('<I', cfg_blob, 0x1a34)[0] == HKEY_LOCAL_MACHINE: RegistrySubkey = 'HKEY_LOCAL_MACHINE' else: RegistrySubkey = unpack_from('<I', cfg_blob, 0x1110)[0]
if unpack_from('>B', cfg_blob, 0x1e38)[0] == 0: InjectionFlag = 'Disable' else: InjectionFlag = 'Enable'
if unpack_from('>B', cfg_blob, 0x3440)[0] == 0: ScCapFlug = 'Disable' else: ScCapFlug = 'Enable'
CnCDay = 'Everyday' for x in xrange(672): if NetworkFlag[x] == 0x0: CnCDay = 'Network Activity Flag Enable(Check config file!)'
IPscanValu1 = unpack_from('<I', cfg_blob, 0x3658)[0] IPscanValu2 = unpack_from('<I', cfg_blob, 0x3660)[0] IPscanValu3 = unpack_from('<I', cfg_blob, 0x3668)[0] IPscanValu4 = unpack_from('<I', cfg_blob, 0x3670)[0] IPscanPort1 = unpack_from('<H', cfg_blob, 0x365c)[0] IPscanPort2 = unpack_from('<H', cfg_blob, 0x3664)[0] IPscanPort3 = unpack_from('<H', cfg_blob, 0x366c)[0] IPscanPort4 = unpack_from('<H', cfg_blob, 0x3674)[0] (ip1, ip2, ip3, ip4) = unpack_from("<4L", cfg_blob, 0x367c) scanip = cfg_blob[0x367c:0x369c]
if unpack_from('<I', cfg_blob, 0x3678)[0] == 0: IPscan_flag = 'Disable' else: IPscan_flag = 'Enable'
# config write file p_data["Version"] = 3 p_data["Version Info"] = vinfo p_data["Config Size"] = "0x{0:X}".format(cfg_sz) p_data["Delete DLL list"] = DLLremove_flag p_data["File Delete"] = FileDelete_flag p_data["Key Logger"] = KeyLog_flag p_data["Unknown Flag"] = Unknown_flag p_data["Sleep Time1"] = SleepTime1 p_data["Sleep Time2"] = SleepTime2 p_data["Network Activity"] = CnCDay if dns1 not in (0, 0xffffffff): p_data["Custom DNS 1"] = inet_ntoa(custom_dns[:4]) if dns2 not in (0, 0xffffffff): p_data["Custom DNS 2"] = inet_ntoa(custom_dns[4:8]) if dns3 not in (0, 0xffffffff): p_data["Custom DNS 3"] = inet_ntoa(custom_dns[8:12]) if dns4 not in (0, 0xffffffff): p_data["Custom DNS 4"] = inet_ntoa(custom_dns[12:16])
for z in xrange(16): if ServerData[z][0]: p_data["Server {0}".format(z + 1)] = "{0}:{1} (Type {2})".format(ServerData[z][2].replace('\0', ''), ServerData[z][1], ServerData[z][0])
for y in xrange(16): if ServerURL[y]: p_data["Server URL {0}".format(y + 1)] = ServerURL[y].replace('\0', '')
for k in xrange(4): if proxy[k][1] != 0: p_data["Proxy {0}".format(k + 1)] = "{0}:{1}".format(proxy[k][2].replace('\0', ''), proxy[k][1]) if proxy[k][3] != '\x00': p_data["Proxy credentials {0}".format(k + 1)] = "{0}:{1}".format(proxy[k][3].replace('\0', ''), proxy[k][4].replace('\0', ''))
p_data["Auto Start"] = AutorunSetup p_data["Install Folder"] = InstallFolder.replace('\0', '') p_data["Service Name"] = ServiceName.replace('\0', '') p_data["Service Display Name"] = ServiceDisplayName.replace('\0', '') p_data["Service Comment"] = ServiceComment.replace('\0', '') p_data["Registry Subkey"] = RegistrySubkey p_data["Registry Key"] = RunKey.replace('\0', '') p_data["Registry Value"] = RunKeyValu.replace('\0', '') p_data["Injection"] = InjectionFlag p_data["Injection Process1"] = InjectionProcess1.replace('\0', '') p_data["Injection Process2"] = InjectionProcess2.replace('\0', '') p_data["Injection Process3"] = InjectionProcess3.replace('\0', '') p_data["Injection Process4"] = InjectionProcess4.replace('\0', '') p_data["UACBypass"] = BypassProcess_flag p_data["UACBypass Process1"] = BypassProcess1.replace('\0', '') p_data["UACBypass Process2"] = BypassProcess2.replace('\0', '') p_data["UACBypass Process3"] = BypassProcess3.replace('\0', '') p_data["UACBypass Process4"] = BypassProcess4.replace('\0', '') p_data["Server ID1"] = ServerID1.replace('\0', '') p_data["Server ID2"] = ServerID2.replace('\0', '') p_data["Mutex"] = Mutex.replace('\0', '') p_data["Screen Capture"] = ScCapFlug p_data["Screen Capture Folder"] = ScreenCapFolder.replace('\0', '') p_data["IP Scan"] = IPscan_flag if IPscan_flag == "Enable": p_data["IP Scan value 1"] = IPscanValu1 p_data["IP Scan port 1"] = IPscanPort1 p_data["IP Scan value 2"] = IPscanValu2 p_data["IP Scan port 2"] = IPscanPort2 p_data["IP Scan value 3"] = IPscanValu3 p_data["IP Scan port 3"] = IPscanPort3 p_data["IP Scan value 4"] = IPscanValu4 p_data["IP Scan port 4"] = IPscanPort4
if ip1 not in (0, 0xffffffff): p_data["Scan IP 1"] = "{0} - {1}".format(inet_ntoa(scanip[:4]), (inet_ntoa(scanip[16:20]))) if ip2 not in (0, 0xffffffff): p_data["Scan IP 2"] = "{0} - {1}".format(inet_ntoa(scanip[4:8]), (inet_ntoa(scanip[20:24]))) if ip3 not in (0, 0xffffffff): p_data["Scan IP 3"] = "{0} - {1}".format(inet_ntoa(scanip[8:12]), (inet_ntoa(scanip[24:28]))) if ip4 not in (0, 0xffffffff): p_data["Scan IP 4"] = "{0} - {1}".format(inet_ntoa(scanip[12:16]), (inet_ntoa(scanip[28:32])))
return p_data
def parse_config_winnti(self, cfg_blob, cfg_sz, cfg_addr, vinfo): p_data = OrderedDict()
# config parsing SleepTime = unpack_from('>I', cfg_blob, 0x0c)[0] NetworkFlag = unpack_from('<672B', cfg_blob, 0x14)
if cfg_sz == 0xd24: InstallDll = unpack_from('<32s', cfg_blob, 0xae4)[0] InstallData = unpack_from('<32s', cfg_blob, 0xb04)[0] ServiceName = unpack_from('<32s', cfg_blob, 0xb24)[0] ServiceDisplayName = unpack_from('<256s', cfg_blob, 0xc24)[0]
ServerData = [[0] * 3] * 4 if unpack_from('<I', cfg_blob, 0xc)[0] == FLAG_ENABLE: unknown_flag = 'Enable' else: unknown_flag = 'Disable'
(dns1, dns2, dns3, dns4) = unpack_from("<4L", cfg_blob, 0x2b4) custom_dns = cfg_blob[0x2b4:0x2c4]
for i in xrange(4): if unpack_from('<B', cfg_blob, 0x2c4 + (i * 68))[0] != 0x0: ServerData[i] = unpack_from('<HH64s', cfg_blob, 0x2c4 + (i * 68))
CnCDay = 'Everyday' for x in xrange(672): if NetworkFlag[x] == 0x0: CnCDay = 'Network Activity Flag Enable(Check config file!)'
# config write file p_data["Version"] = "winnti" p_data["Version Info"] = vinfo p_data["Config Size"] = "0x{0:X}".format(cfg_sz) p_data["Unknown Flag"] = unknown_flag p_data["Sleep Time"] = SleepTime p_data["Network Activity"] = CnCDay if dns1 not in (0, 0xffffffff): p_data["Custom DNS 1"] = inet_ntoa(custom_dns[:4]) if dns2 not in (0, 0xffffffff): p_data["Custom DNS 2"] = inet_ntoa(custom_dns[4:8]) if dns3 not in (0, 0xffffffff): p_data["Custom DNS 3"] = inet_ntoa(custom_dns[8:12]) if dns4 not in (0, 0xffffffff): p_data["Custom DNS 4"] = inet_ntoa(custom_dns[12:16])
for z in xrange(4): if ServerData[z][0]: p_data["Server {0}".format(z + 1)] = "{0}:{1} (Type {2})".format(ServerData[z][2].replace('\0', ''), ServerData[z][1], ServerData[z][0])
if cfg_sz == 0xd24: p_data["Install DLL"] = InstallDll.replace('\0', '') p_data["Install Data"] = InstallData.replace('\0', '') p_data["Service Name"] = ServiceName.replace('\0', '') p_data["Service Display Name"] = ServiceDisplayName.replace('\0', '')
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=plugx_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = [] offset1 = data.find("\xFF\x68\xa0\x02\x00\x00\x47\x57\x68") # push 0x2a0 offset2 = data.find("\x00\x68\xa0\x02\x00\x00\x50") # push 0x2a0 offset3 = data.find("\xF6\x68\xa0\x02\x00\x00\x46\x56\x68") # push 0x2a0 offset4 = data.find("\xDB\x68\xa0\x02\x00\x00\x43\x53\x68") # push 0x2a0 offset5 = data.find("\x83\xc4\x0c\x68\x10\x27\x00\x00") # push 2710h # Config 0x36A4 offset6 = data.find("\x00\x68\xa0\x02\x00\x00\xB0") # push 0x2a0
if offset1 > 0: offset = offset1 elif offset2 > 0: offset = offset2 elif offset3 > 0: offset = offset3 elif offset4 > 0: offset = offset4 elif offset5 > 0: offset = offset5 elif offset6 > 0: offset = offset6 else: continue
while not (data[offset] == "\x68" and (data[offset + 5] == "\xe8" or data[offset + 6] == "\xe8")) and offset > 0: offset -= 1 if data[offset] != "\x68": continue
# Now were at: # push 0xxxxxx <- config address # call 0xxxxxx (config_addr, ) = unpack("=I", data[offset + 1:offset + 5])
# Find previous push imm offset -= 1 while not data[offset] == "\x68": offset -= 1 if data[offset] != "\x68": continue
# Version info info_start = data.find('\\work\\') if info_start > 0: info_end = data.find('\\', info_start + 6) version_info = str(data[info_start + 6: info_end]).decode("utf-8", "replace") else: version_info = "Null"
(config_size, ) = unpack("=I", data[offset + 1:offset + 5])
config_addr -= vad_base_addr if config_size == 0x1510: config_addr = config_addr + 4
config_blob = data[config_addr:config_addr + config_size] if config_size == 0xd24 or config_size == 0xae4: config_data.append(self.parse_config_winnti(config_blob, config_size, config_addr, version_info)) elif config_size == 0x2540: config_data.append(self.parse_config2(config_blob, config_size, config_addr, version_info)) elif config_size == 0x2d58: config_data.append(self.parse_config2(config_blob, config_size, config_addr, version_info)) elif config_size == 0x36A4: config_data.append(self.parse_config3(config_blob, config_size, config_addr, version_info)) else: config_data.append(self.parse_config(config_blob, config_size, config_addr, version_info))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<25}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164# Detecting PoisonIvy for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv poisonivyscan.py volatility/plugins/malware# 3. python vol.py poisonivyconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport pefilefrom struct import unpack, unpack_from
try: import yara has_yara = Trueexcept ImportError: has_yara = False
poisonivy_sig = { 'namespace1' : 'rule PoisonIvy { \ strings: \ $a1 = { 0E 89 02 44 } \ $b1 = { AD D1 34 41 } \ $c1 = { 66 35 20 83 66 81 F3 B8 ED } \ condition: all of them}'}
# idx listidx_list = { 0x012d: ["Install Name", 1], 0x0145: ["Password", 1], 0x0165: ["AcviteX Key", 1], 0x018c: ["C&C Servers Count", 0], 0x0190: ["Server", 1], 0x02c1: ["Proxy Servers Count", 0], 0x03f3: ["Install Path", 1], 0x03f6: ["AcviteX Flag", 2], 0x03f7: ["Installation Folder", 3], 0x03f8: ["Auto-remove Flag", 2], 0x03f9: ["Thread Persistence Flag", 2], 0x03fa: ["Keylog Flag", 2], 0x03fb: ["Mutex", 1], 0x040f: ["Active Setup Name", 1], 0x0418: ["Default Browser Path", 1], 0x0441: ["Injection Flag", 2], 0x0442: ["Injection Process", 1], 0x0456: ["Active Key", 1], 0x0af4: ["Proxy Hijack", 2], 0x0af5: ["Persistent Proxy", 2], 0x0afa: ["Campaign ID", 1], 0x0bf9: ["Group ID", 1], 0x0d08: ["Inject Default Browser", 2], 0x0d09: ["Registry Key Flag", 2], 0x0d12: ["ADS Flag", 2], 0x0e12: ["Registry Key Value", 1], 0x1201: ["Server", 1], 0xeffc: ["unknow 1", 2], 0xef8c: ["unknow 2", 2], 0xef7c: ["unknow 3", 2],}
# Config patternCONFIG_PATTERNS = [re.compile("\xFA\x0A(.)\x00", re.DOTALL)]
MODE = {0: "Disable", 1: "Enable"}FOLDER = {1: "%systemroot%", 2: "%systemroot%\system32"}
class poisonivyConfig(taskmods.DllList): """Parse the PoisonIvy configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def parse_config(self, idx, data): p_data = {} if idx in idx_list: field, field_type = idx_list[idx] else: field = hex(idx) field_type = 0
if field_type == 0: if unpack_from("<I", data)[0] == 0xffffffff: p_data[field] = 0 else: p_data[field] = unpack_from("<I", data)[0] if field_type == 1: p_data[field] = data if field_type == 2: p_data[field] = MODE[ord(data)] if field_type == 3: p_data[field] = FOLDER[ord(data)]
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=poisonivy_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
for pattern in CONFIG_PATTERNS: mc = re.search(pattern, data) if mc: offset = mc.start() while data[offset] != "\xC3": offset -= 1
while data[offset:offset + 2] != "\x00\x00": (idx, size) = unpack_from("<HH", data, offset + 1) if size > 0: enc = data[offset + 5:offset + 5 + size] config_data.append(self.parse_config(idx, enc)) offset = offset + size + 4
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<20}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215# Detecting QuasarRAT for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv quasarscan.py volatility/plugins/malware# 3. python vol.py quasarconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport hashlibfrom base64 import b64decodefrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
try: from Crypto.Cipher import AES has_crypto = Trueexcept ImportError: has_crypto = False
try: from pbkdf2 import PBKDF2 has_pbkdf2 = Trueexcept ImportError: has_pbkdf2 = False
quasar_sig = { 'namespace1' : 'rule Quasar { \ strings: \ $quasarstr1 = "Client.exe" wide \ $quasarstr2 = "({0}:{1}:{2})" wide \ $sql1 = "SELECT * FROM Win32_DisplayConfiguration" wide \ $sql2 = "{0}d : {1}h : {2}m : {3}s" wide \ $sql3 = "SELECT * FROM FirewallProduct" wide \ $net1 = "echo DONT CLOSE THIS WINDOW!" wide \ $net2 = "freegeoip.net/xml/" wide \ $net3 = "http://api.ipify.org/" wide \ $resource = { 52 00 65 00 73 00 6F 00 75 00 72 00 63 00 65 00 73 00 00 17 69 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00 00 } \ condition: ((all of ($quasarstr*) or all of ($sql*)) and $resource) or all of ($net*)}'}
# Config patternCONFIG_PATTERNS = [re.compile("\x52\x00\x65\x00\x73\x00\x6F\x00\x75\x00\x72\x00\x63\x00\x65\x00\x73\x00\x00\x17\x69\x00\x6E\x00\x66\x00\x6F\x00\x72\x00\x6D\x00\x61\x00\x74\x00\x69\x00\x6F\x00\x6E\x00\x00\x80", re.DOTALL), re.compile("\x61\x00\x70\x00\x69\x00\x2E\x00\x69\x00\x70\x00\x69\x00\x66\x00\x79\x00\x2E\x00\x6F\x00\x72\x00\x67\x00\x2F\x00\x00\x03\x5C\x00\x00", re.DOTALL), re.compile("\x3C\x00\x2F\x00\x73\x00\x74\x00\x79\x00\x6C\x00\x65\x00\x3E\x00\x00\x03\x5C\x00\x00\x80", re.DOTALL)]
idx_list = { 0: ["VERSION", True], 1: ["HOSTS", True], 2: ["KEY (Base64)", False], 3: ["AUTHKEY (Base64)", False], 4: ["SUBDIRECTORY", True], 5: ["INSTALLNAME",True], 6: ["MUTEX", True], 7: ["STARTUPKEY", True], 8: ["ENCRYPTIONKEY", False], 9: ["TAG", True], 10: ["LOGDIRECTORYNAME",True ], 11: ["unknown1", True], 12: ["unknown2", True]}
idx_list_2 = { 0: ["VERSION", True], 1: ["HOSTS", True], 2: ["KEY (Base64)", False], 3: ["SUBDIRECTORY", True], 4: ["INSTALLNAME",True], 5: ["MUTEX", True], 6: ["STARTUPKEY", True], 7: ["ENCRYPTIONKEY", False], 8: ["TAG", True]}
class quasarConfig(taskmods.DllList): """Parse the QuasarRAT configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def decrypt_string(self, key, configs, mode, idx): p_data = OrderedDict() for i, config in enumerate(configs): if idx[i][1] == True: if len(configs) < 10: config = b64decode(config) aes_iv = config[:16] cipher = AES.new(key, mode, IV=aes_iv) value = re.sub("[\x00-\x19]" ,"" , cipher.decrypt(config[16:])) else: config = b64decode(config) aes_iv = config[32:48] cipher = AES.new(key, mode, IV=aes_iv) value = re.sub("[\x00-\x19]" ,"" , cipher.decrypt(config[48:])) else: value = config p_data[idx[i][0]] = value
return p_data
def parse_config(self, configs): if len(configs) > 10: idx = idx_list key, salt = configs[8], 'BFEB1E56FBCD973BB219022430A57843003D5644D21E62B9D4F180E7E6C33941'.decode('hex')
generator = PBKDF2(key, salt, 50000) aes_key = generator.read(16) else: idx = idx_list_2 aes_key = hashlib.md5(configs[7]).digest()
if(len(configs) > 12): mode = AES.MODE_CFB else: mode = AES.MODE_CBC p_data = self.decrypt_string(aes_key, configs, mode, idx)
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
if not has_crypto: debug.error("pycrypto must be installed for this plugin")
if not has_pbkdf2: debug.error("pbkdf2 must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=quasar_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
offset = 0 for pattern in CONFIG_PATTERNS: mc = re.search(pattern, data) if mc: offset = mc.end()
if ord(data[offset]) == 0x0: offset += 1
configs = [] if offset > 0: while 1: strings = [] string_len = ord(data[offset]) if ord(data[offset]) == 0x80 or ord(data[offset]) == 0x81: string_len = ord(data[offset + 1]) + ((ord(data[offset]) - 0x80) * 256) offset += 1
offset += 1 for i in range(string_len): if data[offset + i] != "\x00": strings.append(data[offset + i]) configs.append("".join(strings)) offset = offset + string_len
if ord(data[offset]) < 0x20: break
config_data.append(self.parse_config(configs))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<21}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173# Detecting Ramnit for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv ramnitscan.py volatility/plugins/malware# 3. python vol.py ramnitconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport pefilefrom struct import unpack, unpack_fromfrom socket import inet_ntoafrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
ramnit_sig = { 'namespace1' : 'rule Ramnit { \ strings: \ $guid = "{%08X-%04X-%04X-%04X-%08X%04X}" \ $md5_magic_1 = "15Bn99gT" \ $md5_magic_2 = "1E4hNy1O" \ $init_dga = { C7 ?? ?? ?? ?? ?? FF FF FF FF FF ?? ?? ?? ?? ?? FF ?? ?? ?? ?? ?? FF ?? ?? ?? ?? ?? E8 ?? ?? ?? ?? 0B C0 75 ?? } \ $xor_secret = { 8A ?? ?? 32 ?? 88 ?? 4? 4? E2 ?? } \ $init_function = { FF 35 [4] 68 [4] 68 [2] 00 00 68 [4] E8 [4] FF 35 [4] 68 [4] 68 [2] 00 00 68 [4] E8 [4] FF 35 [4] 68 [4] 68 [2] 00 00 68 [4] E8 [4] FF 35 [4] 68 [4] 68 [2] 00 00 68 [4] E8 } \ $dga_rand_int = { B9 1D F3 01 00 F7 F1 8B C8 B8 A7 41 00 00 } \ $cookies = "cookies4.dat" \ $s3 = "pdatesDisableNotify" \ $get_domains = { a3 [4] a1 [4] 80 3? 00 75 ?? c7 05 [4] ff ff ff ff ff 35 [4] ff 35 [4] ff 35 [4] e8 } \ $add_tld = { 55 8B EC 83 ?? ?? 57 C7 ?? ?? 00 00 00 00 B? ?? ?? ?? ?? 8B ?? ?? 3B ?? ?? 75 ?? 8B ?? } \ $get_port = { 90 68 [4] 68 [4] FF 35 [4] FF 35 [4] E8 [4] 83 } \ condition: $init_dga and $init_function and 2 of ($guid, $md5_magic_*, $cookies, $s3) and any of ( $get_port, $add_tld, $dga_rand_int, $get_domains, $xor_secret)}'}
# MZ HeaderMZ_HEADER = b"\x4D\x5A\x90\x00"
# XOR key patternXOR_KEY_PATTERNS = [re.compile("\x68\x3C\x01\x00\x00\x68\x20", re.DOTALL)]
# FlagFLAG = {0x0: "Disable", 0x1: "Enable"}
class ramnitConfig(taskmods.DllList): """Parse the Ramnit configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def xor(self, encoded, xor_key): count = 0 decode = [] key_len = len(xor_key) for n in range(len(encoded)): if count == 0: count = key_len - 1 decode.append(chr(ord(encoded[n]) ^ ord(xor_key[count]))) count -= 1
return "".join(decode)
def parse_config(self, pe, data, base): p_data = OrderedDict() p_data["DGA Damain No"] = unpack_from("I", data, base)[0] p_data["DGA Damain Seed"] = unpack_from(">I", data, base + 4)[0] p_data["Magick Check"] = FLAG[unpack_from("I", data, base + 8)[0]] p_data["Magick"] = unpack_from(">I", data, base + 0xc)[0] p_data["Use IP Address"] = FLAG[unpack_from("I", data, base + 0x10)[0]] p_data["IP Address"] = inet_ntoa(data[base + 0x14:base + 0x18]) p_data["Port"] = unpack_from("I", data, base + 0x18)[0] key_len = unpack_from("I", data, base + 0x1c)[0] p_data["XOR key length"] = key_len
for pattern in XOR_KEY_PATTERNS: mk = re.search(pattern, data)
if mk: (resource_name_rva, ) = unpack("=I", data[mk.start() - 4:mk.start()]) rn_addr = pe.get_physical_by_rva(resource_name_rva - pe.NT_HEADERS.OPTIONAL_HEADER.ImageBase) xor_key = data[rn_addr:rn_addr + key_len] else: xor_key = "" outfd.write("[!] Not found XOR key.\n")
domain_encoded_data = data[base + 0x20:base + 0x15c].replace("\0","") botnet_encoded_data = data[base + 0x15c:base + 0x1ca].replace("\0","") encoded_data_1 = data[base + 0x1ca:base + 0x240].replace("\0","") encoded_data_2 = data[base + 0x240:base + 0x2b6].replace("\0","") rc4_encoded_data = data[base + 0x2b6:base + 0x2f1].replace("\0","")
p_data["Hardcode Domain"] = self.xor(domain_encoded_data, xor_key) p_data["Botnet name"] = self.xor(botnet_encoded_data, xor_key) p_data["Unknown 1"] = self.xor(encoded_data_1, xor_key) p_data["Unknown 2"] = self.xor(encoded_data_2, xor_key) p_data["RC4 Key"] = self.xor(rc4_encoded_data, xor_key)
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=ramnit_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
# resource PE search dll_index = data.rfind(MZ_HEADER) dll_data = data[dll_index:]
try: pe = pefile.PE(data=dll_data) except: outfd.write("[!] Can't mapped PE.\n") continue
for section in pe.sections: if ".data" in section.Name: data_address = section.PointerToRawData
config_data.append(self.parse_config(pe, dll_data, data_address))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<16}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207# Detecting RedLeaves for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv redleavesscan.py volatility/plugins/malware# 3. python vol.py redleavesconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom struct import unpack, unpack_fromfrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
redleaves_sig = { 'namespace1' : 'rule RedLeaves { \ strings: \ $v1 = "red_autumnal_leaves_dllmain.dll" \ $b1 = { FF FF 90 00 } \ condition: $v1 and $b1 at 0}', 'namespace2' : 'rule Himawari { \ strings: \ $h1 = "himawariA" \ $h2 = "himawariB" \ $h3 = "HimawariDemo" \ condition: $h1 and $h2 and $h3}', 'namespace3' : 'rule Lavender { \ strings: \ $l1 = {C7 ?? ?? 4C 41 56 45} \ $l2 = {C7 ?? ?? 4E 44 45 52} \ condition: $l1 and $l2}', 'namespace4' : 'rule Armadill { \ strings: \ $a1 = {C7 ?? ?? 41 72 6D 61 } \ $a2 = {C7 ?? ?? 64 69 6C 6C } \ condition: $a1 and $a2}', 'namespace5' : 'rule zark20rk { \ strings: \ $a1 = {C7 ?? ?? 7A 61 72 6B } \ $a2 = {C7 ?? ?? 32 30 72 6B } \ condition: $a1 and $a2}'}
CONF_PATTERNS = {"RedLeaves": re.compile("\x68\x88\x13\x00\x00\xFF", re.DOTALL), "Himawari": re.compile("\x68\x70\x03\x00\x00\xBF", re.DOTALL), "Lavender": re.compile("\x68\x70\x03\x00\x00\xBF", re.DOTALL), "Armadill": re.compile("\x68\x70\x03\x00\x00\xBF", re.DOTALL), "zark20rk": re.compile("\x68\x70\x03\x00\x00\x8D", re.DOTALL), }
CONNECT_MODE = {1: 'TCP', 2: 'HTTP', 3: 'HTTPS', 4: 'TCP and HTTP'}
class redleavesConfig(taskmods.DllList): """Detect processes infected with redleaves malware"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def parse_config(self, cfg_blob, cfg_sz, cfg_addr):
p_data = OrderedDict()
p_data["Server1"] = unpack_from('<64s', cfg_blob, 0x0)[0] p_data["Server2"] = unpack_from('<64s', cfg_blob, 0x40)[0] p_data["Server3"] = unpack_from('<64s', cfg_blob, 0x80)[0] p_data["Port"] = unpack_from('<I', cfg_blob, 0xC0)[0] mode = unpack_from('<I', cfg_blob, 0x1D0)[0] p_data["Mode"] = CONNECT_MODE[mode] p_data["ID"] = unpack_from('<64s', cfg_blob, 0x1E4)[0] p_data["Mutex"] = unpack_from('<550s', cfg_blob, 0x500)[0].replace('\0', '') p_data["Injection Process"] = unpack_from('<104s', cfg_blob, 0x726)[0].replace('\0', '') p_data["RC4 Key"] = unpack_from('<10s', cfg_blob, 0x82A)[0]
return p_data
def parse_config_himawari(self, cfg_blob, cfg_sz, cfg_addr):
p_data = OrderedDict()
p_data["Server1"] = unpack_from('<64s', cfg_blob, 0x4)[0] p_data["Server2"] = unpack_from('<64s', cfg_blob, 0x44)[0] p_data["Server3"] = unpack_from('<64s', cfg_blob, 0x84)[0] p_data["Server4"] = unpack_from('<64s', cfg_blob, 0xC4)[0] p_data["Port"] = unpack_from('<I', cfg_blob, 0x104)[0] mode = unpack_from('<I', cfg_blob, 0x1D8)[0] p_data["Mode"] = CONNECT_MODE[mode] p_data["ID"] = unpack_from('<64s', cfg_blob, 0x1E0)[0] p_data["Mutex"] = unpack_from('<62s', cfg_blob, 0x224)[0].replace('\0', '') p_data["Key"] = unpack_from('<10s', cfg_blob, 0x366)[0] p_data["UserAgent"] = unpack_from('<260s', cfg_blob, 0x262)[0] p_data["Proxy server"] = unpack_from('<64s', cfg_blob, 0x10C)[0] p_data["Proxy username"] = unpack_from('<64s', cfg_blob, 0x14C)[0] p_data["Proxy password"] = unpack_from('<64s', cfg_blob, 0x18C)[0]
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=redleaves_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
c_pt = CONF_PATTERNS[str(hit)] if re.search(c_pt, data): m_conf = re.search(c_pt, data) else: continue
offset_conf = m_conf.start()
if "RedLeaves" in str(hit): config_size = 2100
offset_conf -= 1 while data[offset_conf] != "\xC7" and data[offset_conf] != "\xBE" and data[offset_conf] != "\xBF": offset_conf -= 1
if data[offset_conf] != "\xC7" and data[offset_conf] != "\xBE" and data[offset_conf] != "\xBF": continue if data[offset_conf] == "\xC7" and data[offset_conf + 1] != "\x85" and data[offset_conf + 1] != "\x45": offset_conf -= 6
# get address if data[offset_conf] == "\xC7" and data[offset_conf + 1] != "\x85": (config_addr, ) = unpack("=I", data[offset_conf + 3:offset_conf + 7]) elif data[offset_conf] == "\xC7" and data[offset_conf + 1] == "\x85": (config_addr, ) = unpack("=I", data[offset_conf + 6:offset_conf + 10]) else: (config_addr, ) = unpack("=I", data[offset_conf + 1:offset_conf + 5])
if config_addr < vad_base_addr: continue config_addr -= vad_base_addr config = data[config_addr:config_addr + config_size] if len(config) > 0: config_data.append(self.parse_config(config, config_size, config_addr))
if str(hit) in ["Himawari", "Lavender", "Armadill", "zark20rk"]: offset_conf += 6 if str(hit) in ["zark20rk"]: offset_conf += 6 config_size = 880
# get address (config_addr, ) = unpack("=I", data[offset_conf:offset_conf + 4])
if config_addr < vad_base_addr: continue
config_addr -= vad_base_addr config = data[config_addr:config_addr + config_size] if len(config) > 0: config_data.append(self.parse_config_himawari(config, config_size, config_addr))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<16}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245# Detecting Remcos for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv remcosscan.py volatility/plugins/malware# 3. python vol.py remcosconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport pefilefrom struct import unpack, unpack_fromfrom socket import inet_ntoafrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
remcos_sig = { 'namespace1' : 'rule Remcos { \ strings: \ $remcos = "Remcos" ascii fullword \ $url1 = "Breaking-Security.Net" ascii fullword \ $url2 = "BreakingSecurity.Net" ascii fullword \ $resource = "SETTINGS" ascii wide fullword \ condition: 1 of ($url*) and $remcos and $resource}'}
# MZ HeaderMZ_HEADER = b"\x4D\x5A\x90\x00"
# Resource patternRESOURCE_PATTERNS = [re.compile("\xE0\x00\x00\x07\xE0\x00\x00\x07\xFF\xFF\xFF\xFF", re.DOTALL)]
# FlagFLAG = {"\x00": "Disable", "\x01": "Enable"}
idx_list = { 0: "Host:Port:Password", 1: "Assigned name", 2: "Connect interval", 3: "Install flag", 4: "Setup HKCU\\Run", 5: "Setup HKLM\\Run", 6: "Setup HKLM\\Explorer\\Run", 7: "Setup HKLM\\Winlogon\\Shell", 8: "Setup HKLM\\Winlogon\\Userinit", 9: "Install path", 10: "Copy file", 11: "Startup value", 12: "Hide file", 13: "Unknown13", 14: "Mutex", 15: "Keylog flag", 16: "Keylog path", 17: "Keylog file", 18: "Keylog crypt", 19: "Hide keylog file", 20: "Screenshot flag", 21: "Screenshot time", 22: "Take Screenshot option", 23: "Take screenshot title", 24: "Take screenshot time", 25: "Screenshot path", 26: "Screenshot file", 27: "Screenshot crypt", 28: "Mouse option", 29: "Unknown29", 30: "Delete file", 31: "Unknown31", 32: "Unknown32", 33: "Unknown33", 34: "Unknown34", 35: "Unknown35", 36: "Audio record time", 37: "Audio path", 38: "Audio folder", 39: "Unknown39", 40: "Unknown40", 41: "Connect delay", 42: "Unknown42", 43: "Unknown43", 44: "Unknown44", 45: "Unknown45", 46: "Unknown46", 47: "Unknown47", 48: "Copy folder", 49: "Keylog folder", 50: "Unknown50", 51: "Unknown51", 52: "Unknown52", 53: "Unknown53", 54: "Keylog file max size", 55: "Unknown55",}
setup_list = { 0: "Temp", 2: "Root", 3: "Windows", 4: "System32", 5: "Program Files", 6: "AppData", 7: "User Profile", 8: "Application path",}
class remcosConfig(taskmods.DllList): """Parse the Remcos configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
# RC4 def rc4(self, data, key): x = 0 box = range(256) for i in range(256): x = (x + box[i] + ord(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x = 0 y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 box[x], box[y] = box[y], box[x] out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256]))
return ''.join(out)
def parse_config(self, data): p_data = OrderedDict()
key_len = ord(data[0]) key = data[1:key_len + 1] enc_data = data[key_len + 1:] config = self.rc4(enc_data, key)
#configs = config.split("@@") configs = re.split("\x1E|@@", config)
for i, cont in enumerate(configs): if cont == "\x00" or cont == "\x01": p_data[idx_list[i]] = FLAG[cont] else: if i in [9, 16, 25, 37]: p_data[idx_list[i]] = setup_list[int(cont)] else: p_data[idx_list[i]] = cont
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=remcos_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
# resource PE search dll_index = data.rfind(MZ_HEADER) dll_data = data[dll_index:]
try: pe = pefile.PE(data=dll_data) except: outfd.write("[!] Can't mapped PE.\n") continue
rc_data = "" for idx in pe.DIRECTORY_ENTRY_RESOURCE.entries: for entry in idx.directory.entries: if str(entry.name) in "SETTINGS": try: data_rva = entry.directory.entries[0].data.struct.OffsetToData size = entry.directory.entries[0].data.struct.Size rc_data = dll_data[data_rva:data_rva + size] print("[*] Found SETTINGS resource.") except: debug.error("Faild to load SETTINGS resource.")
if not len(rc_data): for pattern in RESOURCE_PATTERNS: mc = re.search(pattern, dll_data) if mc: try: config_end = mc.end() + 1 while dll_data[config_end:config_end + 2] != "\x00\x00": config_end += 1 rc_data = dll_data[mc.end():config_end - 1] except: debug.error("Remcos resource not found.")
config_data.append(self.parse_config(rc_data))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<16}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176# Detecting SmokeLoader for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv smokeloaderscan.py volatility/plugins/malware# 3. python vol.py smokeloaderconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom struct import unpack, unpack_fromfrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
smokeloader_sig = { 'namespace1' : 'rule SmokeLoader { \ strings: \ $a1 = { B8 25 30 38 58 } \ $b1 = { 81 3D ?? ?? ?? ?? 25 00 41 00 } \ $c1 = { C7 ?? ?? ?? 25 73 25 73 } \ condition: $a1 and $b1 and $c1}'}
# Config patternCONFIG_PATTERNS = [re.compile("\x68\x58\x02\x00\x00\xFF(.....)\x4E\x75\xF2\x8B", re.DOTALL)]
STRINGS_PATTERNS = [re.compile("\x57\xBB(....)\x8B(.)\x8B(.)", re.DOTALL)]
class smokeloaderConfig(taskmods.DllList): """Parse the SmokeLoader configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
# RC4 def rc4(self, data, key): x = 0 box = range(256) for i in range(256): x = (x + box[i] + ord(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x = 0 y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 box[x], box[y] = box[y], box[x] out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256]))
return ''.join(out)
def decode(self, data, keydata): url = [] key = 0xff for i in range(0, 4): key = key ^ (keydata >> (i * 8) & 0xff) for y in data: url.append(chr(ord(y) ^ key))
return "".join(url)
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=smokeloader_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() dll_data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
mz_magic = unpack_from("=2s", dll_data, 0x0)[0] nt_magic = unpack_from("<H", dll_data, 0x3c)[0] if mz_magic == "\x00\x00": dll_data = "\x4d\x5a" + dll_data[2:] dll_data = dll_data[:nt_magic] + "\x50\x45" + dll_data[nt_magic + 2:]
p_data = OrderedDict() url_base = [] for pattern in CONFIG_PATTERNS: mc = re.search(pattern, dll_data) if mc: offset = mc.end() + 1 while dll_data[offset] != "\x8B": offset += 1
config_rva = unpack("=I", dll_data[offset + 3:offset + 7])[0] - vad_base_addr
d = 0 while dll_data[config_rva + d:config_rva + d + 4] != "\x00\x00\x00\x00": url_base.append(unpack("=I", dll_data[config_rva + d:config_rva + d + 4])[0])
d += 4
i = 1 for base in url_base: base -= vad_base_addr size = ord(dll_data[base]) key = unpack("=I", dll_data[base + size + 1:base + size + 5])[0] enc_data = dll_data[base + 1:base + size + 1] url = self.decode(enc_data, key) p_data["Static URL " + str(i)] = url i += 1
for pattern in STRINGS_PATTERNS: mc = re.search(pattern, dll_data) if mc: offset = mc.start() + 2 config_rva = unpack("=I", dll_data[offset:offset + 4])[0] - vad_base_addr key = dll_data[config_rva - 4:config_rva] enc = [] while dll_data[config_rva:config_rva + 2] != "\x00\x00": enc.append(dll_data[config_rva]) config_rva += 1 enc_strings = "".join(enc) x = 0 i = 1 while x < len(enc_strings): size = ord(enc_strings[x]) strings = self.rc4(enc_strings[x + 1:x + size + 1], key) x = x + size + 1 p_data["Encoded string " + str(i)] = strings i += 1
config_data.append(p_data)
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<18}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129# Detecting TrickBot for Volatilitv## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv trickbotconfigallocate.py volatility/plugins/malware# 3. python vol.py trickbotconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport xml.etree.ElementTree as ETfrom collections import OrderedDictfrom struct import unpack, unpack_from
try: import yara has_yara = Trueexcept ImportError: has_yara = False
trickbot_sig = { 'namespace1' : 'rule Trickbot { \ strings: \ $tagm1 = "<mcconf><ver>" wide \ $tagm2 = "</autorun></mcconf>" wide \ $tagc1 = "<moduleconfig><autostart>" wide \ $tagc2 = "</autoconf></moduleconfig>" wide \ $tagi1 = "<igroup><dinj>" wide \ $tagi2 = "</dinj></igroup>" wide \ $tags1 = "<servconf><expir>" wide \ $tags2 = "</plugins></servconf>" wide \ $tagl1 = "<slist><sinj>" wide \ $tagl2 = "</sinj></slist>" wide \ condition: all of ($tagm*) or all of ($tagc*) or all of ($tagi*) or all of ($tags*) or all of ($tagl*)}'}
# Config patternCONFIG_PATTERNS = [re.compile("\x3C\x00\x6D\x00\x63\x00\x63\x00\x6F\x00\x6E\x00\x66\x00\x3E\x00\x3C\x00\x76\x00\x65\x00\x72\x00\x3E\x00(.*)\x3C\x00\x2F\x00\x6D\x00\x63\x00\x63\x00\x6F\x00\x6E\x00\x66\x00\x3E\x00", re.DOTALL), re.compile("\x3C\x00\x6D\x00\x6F\x00\x64\x00\x75\x00\x6C\x00\x65\x00\x63\x00\x6F\x00\x6E\x00\x66\x00\x69\x00\x67\x00\x3E\x00\x3C\x00\x61\x00\x75\x00\x74\x00\x6F\x00\x73\x00\x74\x00\x61\x00\x72\x00\x74\x00\x3E\x00(.*)\x3C\x00\x2F\x00\x61\x00\x75\x00\x74\x00\x6F\x00\x63\x00\x6F\x00\x6E\x00\x66\x00\x3E\x00\x3C\x00\x2F\x00\x6D\x20\x6F\x00\x64\x00\x75\x00\x6C\x00\x65\x00\x63\x00\x6F\x00\x6E\x00\x66\x00\x69\x00\x67\x00\x3E\x00", re.DOTALL), re.compile("\x3C\x00\x69\x00\x67\x00\x72\x00\x6F\x00\x75\x00\x70\x00\x3E\x00\x3C\x00\x64\x00\x69\x00\x6E\x00\x6A\x00\x3E\x00(.*)\x3C\x00\x2F\x00\x64\x00\x69\x00\x6E\x00\x6A\x00\x3E\x00\x3C\x00\x2F\x00\x69\x00\x67\x00\x72\x00\x6F\x00\x75\x00\x70\x00\x3E\x00", re.DOTALL), re.compile("\x3C\x00\x73\x00\x65\x00\x72\x00\x76\x00\x63\x00\x6F\x00\x6E\x00\x66\x00\x3E\x00\x3C\x00\x65\x00\x78\x00\x70\x00\x69\x00\x72\x00\x3E\x00(.*)\x3C\x00\x2F\x00\x70\x00\x6C\x00\x75\x00\x67\x00\x69\x00\x6E\x00\x73\x00\x3E\x00\x3C\x00\x2F\x00\x73\x00\x65\x00\x72\x00\x76\x00\x63\x00\x6F\x00\x6E\x00\x66\x00\x3E\x00", re.DOTALL), re.compile("\x3C\x00\x73\x00\x6C\x00\x69\x00\x73\x00\x74\x00\x3E\x00\x3C\x00\x73\x00\x69\x00\x6E\x00\x6A\x00\x3E\x00(.*)\x3C\x00\x2F\x00\x73\x00\x69\x00\x6E\x00\x6A\x00\x3E\x00\x3C\x00\x2F\x00\x73\x00\x6C\x00\x69\x00\x73\x00\x74\x00\x3E\x00", re.DOTALL)]
class trickbotConfig(taskmods.DllList): "Parse the TrickBot configuration"
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End return None
def calculate(self):
if not has_yara: debug.error('Yara must be installed for this plugin.')
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error('This command does not support the selected profile.')
rules = yara.compile(sources=trickbot_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules) for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() memdata = proc_addr_space.get_available_addresses()
config_data = []
for m in memdata:
if m[1] <= 0x1000: continue
data = proc_addr_space.zread(m[0], m[1])
for pattern in CONFIG_PATTERNS: m = re.search(pattern, data)
if m: offset = m.start() else: continue
p_data = OrderedDict() xml_data = data[offset:m.end()] root = ET.fromstring(xml_data) i = 0 for e in root.getiterator(): if e.text is None: if len(e.attrib) != 0: p_data[i] = e.tag + ": " + str(e.attrib) else: p_data[i] = e.tag + ": " + str(e.text) i += 1 config_data.append(p_data)
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<4}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220# Detecting TSCookie for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv tscookiescan.py volatility/plugins/malware# 3. python vol.py tscookieconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport pefilefrom struct import unpack, unpack_fromfrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
tscookie_sig = { 'namespace1' : 'rule TSCookie { \ strings: \ $v1 = "Mozilla/4.0 (compatible; MSIE 8.0; Win32)" wide\ $mz = { 4D 5A 90 00 } \ $b1 = { 68 D4 08 00 00 } \ condition: all of them}', 'namespace2' : 'rule TSC_Loader { \ strings: \ $v1 = "Mozilla/4.0 (compatible; MSIE 8.0; Win32)" wide\ $mz = { 4D 5A 90 00 } \ $b1 = { 68 78 0B 00 00 } \ condition: all of them}'}
# MZ HeaderMZ_HEADER = b"\x4D\x5A\x90\x00"
# Config patternCONFIG_PATTERNS = [re.compile("\xC3\x90\x68\x00(...)\xE8(....)\x59\x6A\x01\x58\xC3", re.DOTALL), re.compile("\x6A\x04\x68(....)\x8D(.....)\x56\x50\xE8", re.DOTALL), re.compile("\x00\x00\x68(....)\xE8(....)\x59\x59\x6A\x01", re.DOTALL), re.compile("\x68(....)\xE8(....)\x59\x6A\x01\x58\xC3", re.DOTALL), re.compile("\x68(....)\xE8(....)\x59", re.DOTALL)]
CONNECT_MODE = {0: 'TCP', 1: 'HTTP with Credentials', 2: 'HTTP with Credentials', 3: 'HTTP with Credentials', 5: 'HTTP', 6: 'HTTPS', 7: 'HTTPS', 8: 'HTTPS'}PROXY_MODE = {0: 'Detect proxy settings', 1: 'Use config'}INJECTION_MODE = {0 : 'Create process' , 1 : 'Injection running process'}PROCESS_NAME = {0 : 'svchost.exe', 1 : 'iexplorer.exe', 2 : 'explorer.exe', 3 : 'Default browser' , 4: 'Setting process'}
class tscookieConfig(taskmods.DllList): """Parse the TSCookie configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def rc4(self, data, key): x = 0 box = range(256) for i in range(256): x = (x + box[i] + ord(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x = 0 y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 box[x], box[y] = box[y], box[x] out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256]))
return ''.join(out)
def parse_config(self, config): p_data = OrderedDict() for i in xrange(4): if config[0x10 + 0x100 * i] != "\x00": p_data["Server " + str(i)] = unpack_from("<240s", config, 0x10 + 0x100 * i)[0].replace("\0", "") p_data["Server " + str(i) + " (port 1)"] = unpack_from("<H", config, 0x4 + 0x100 * i)[0] p_data["Server " + str(i) + " (port 2)"] = unpack_from("<H", config, 0x8 + 0x100 * i)[0] if config[0x400] != "\x00": p_data["Proxy server"] = unpack_from("<128s", config, 0x400)[0].replace("\0", "") p_data["Proxy port"] = unpack_from("<H", config, 0x480)[0] p_data["ID"] = unpack_from("<256s", config, 0x500)[0] p_data["KEY"] = "0x{0:X}".format(unpack_from(">I", config, 0x604)[0]) if len(config) > 0x89C: p_data["Sleep time"] = unpack_from("<H", config, 0x89C)[0]
return p_data
def parse_loader_config(self, config): p_data = OrderedDict() p_data["Server name"] = unpack_from("<1024s", config, 0)[0] p_data["KEY"] = "0x{0:X}".format(unpack_from(">I", config, 0x400)[0]) p_data["Sleep count"] = unpack_from("<H", config, 0x404)[0] p_data["Mutex"] = unpack_from("<32s", config, 0x40c)[0] mode = unpack_from("<H", config, 0x44c)[0] p_data["Connect mode"] = CONNECT_MODE[mode] p_data["Connect keep"] = unpack_from("<H", config, 0x454)[0] icmp = unpack_from("<H", config, 0x458)[0] if icmp == 100: p_data["ICMP mode"] = "Enable" p_data["ICMP bind IP"] = unpack_from("<330s", config, 0x4D4)[0] else: p_data["ICMP mode"] = "Disable" injection = unpack_from("<H", config, 0x624)[0] p_data["Injection mode"] = INJECTION_MODE[injection] p_data["Injection process name"] = PROCESS_NAME[unpack_from("<H", config, 0x628)[0]] p_data["Injection custom name"] = unpack_from("<256s", config, 0x62c)[0].replace("\0", "") if config[0x72c] != "\x00": p_data["Proxy server"] = unpack_from("<64s", config, 0x72c)[0] p_data["Proxy port"] = unpack_from("<H", config, 0x76c)[0] p_data["Proxy username"] = unpack_from("<64s", config, 0x770)[0] p_data["Proxy password"] = unpack_from("<64s", config, 0x790)[0] proxy = unpack_from("<H", config, 0x7b0)[0] p_data["Proxy mode"] = PROXY_MODE[proxy] p_data["AuthScheme"] = unpack_from("<H", config, 0x7b4)[0]
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=tscookie_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
dll_index = data.find(MZ_HEADER) if dll_index: dll_data = data[dll_index:] dll = pefile.PE(data=dll_data) else: continue
if "TSCookie" in str(hit): d = 2 else: d = 0
for pattern in CONFIG_PATTERNS: mc = re.search(pattern, dll_data) if mc: try: (config_rva, ) = unpack("=I", dll_data[mc.start() + d + 1:mc.start() + d + 5]) config_addr = dll.get_physical_by_rva(config_rva - dll.NT_HEADERS.OPTIONAL_HEADER.ImageBase) break except: print("[!] Not found config data.\n")
config_size = 0 enc = [] while not (dll_data[config_addr + config_size] == "\x00" and dll_data[config_addr + config_size + 1] == "\x00" and dll_data[config_addr + config_size + 2] == "\x00"): enc.append(dll_data[config_addr + config_size]) config_size += 1
enc_config_data = "".join(enc) if config_size == 0x8D4: rc4key_length = 4 else: rc4key_length = 0x80
try: enc_config = enc_config_data[rc4key_length:] rc4key = enc_config_data[:rc4key_length] config = self.rc4(enc_config, rc4key) if len(config) > 0: if "TSCookie" in str(hit): config_data.append(self.parse_config(config)) else: config_data.append(self.parse_loader_config(config)) except: print("[!] Not found config data.\n")
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<25}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347# Detecting Ursnif for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv ursnifscan.py volatility/plugins/malware# 3. python vol.py ursnifconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport pefilefrom struct import unpack, unpack_from, packfrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
try: import aplib has_aplib = Trueexcept ImportError: has_aplib = False
ursnif_sig = { 'namespace1' : 'rule Ursnif { \ strings: \ $a1 = "soft=%u&version=%u&user=%08x%08x%08x%08x&server=%u&id=%u&crc=%x"\ $b1 = "client.dll" fullword\ $c1 = "version=%u"\ $c2 = "user=%08x%08x%08x%08x"\ $c3 = "server=%u"\ $c4 = "id=%u"\ $c5 = "crc=%u"\ $c6 = "guid=%08x%08x%08x%08x"\ $c7 = "name=%s"\ $c8 = "soft=%u"\ $d1 = "%s://%s%s"\ $d2 = "PRI \x2A HTTP/2.0"\ $e1 = { A1 ?? ?? ?? 00 35 E7 F7 8A 40 50 }\ $e2 = { 56 56 56 6A 06 5? FF ?? ?? ?? ?? 00 }\ $f1 = { 56 57 BE ?? ?? ?? ?? 8D ?? ?? A5 A5 A5 }\ $f2 = { 35 8F E3 B7 3F }\ $f3 = { 35 0A 60 2E 51 }\ condition: $a1 or ($b1 and 3 of ($c*)) or (5 of ($c*)) or ($b1 and all of ($d*)) or all of ($e*) or all of ($f*)}'}
# Magic patternmagic = "J[1J]"
# Config patternCONFIG_PATTERNS = [ re.compile("\x3D\xB7\x00\x00\x00\x0F\x84(...)\x00\xA1(....)\xC7(..)(....)\xC6(..)(.)\xC7(.)(....)", re.DOTALL), # cmp eax, 0B7h ; jz loc_xxxx; mov eax, dword_xxxx; mov dword ptr, offset c2_table; re.compile("\x3D\xB7\x00\x00\x00\x0F\x84(....)\x48\x8B\x05(....)\x48\x8D\x0D(....)(\x45\x8D)(..)\x48\x89(..)\x48\x8D\x0D(....)(\x33\xD2)", re.DOTALL), # 64bit]
# RSA key patternRSA_PATTERNS = [ re.compile("\x68(....)\x8D\x85(....)\x50\xE8(....)\x68(....)\x8D\x85(....)\x50\xE8(....)\x6A\x11", re.DOTALL), re.compile("\x57\x48\x83\xEC\x20\x4C\x8D\x0D(....)(\x4C\x8D)(...)\x48\x8B\xF1", re.DOTALL), # 64bit]
DT_STR = 1idx_list = { 0x0d20203c: ["lang_id", DT_STR], 0x11271c7f: ["sleep_time", DT_STR], 0x18a632bb: ["time_value", DT_STR], 0x31277bd5: ["SetWaitableTimer_value(CRC_TASKTIMEOUT)", DT_STR], 0x4b214f54: ["tor64_dll", DT_STR], 0x4fa8693e: ["serpent_key", DT_STR], 0x510f22d2: ["c2_tor_domain", DT_STR], 0x556aed8f: ["server", DT_STR], 0x584e5925: ["SetWaitableTimer_value", DT_STR], 0x602c2c26: ["capture_window_title?(CRC_KEYLOGLIST)", DT_STR], 0x656b798a: ["botnet", DT_STR], 0x6de85128: ["not_use(CRC_BCTIMEOUT)", DT_STR], 0x73177345: ["dga_base_url", DT_STR], 0x746ce763: ["movie_capture", DT_STR], 0x75e6145c: ["c2_domain", DT_STR], 0x758a4250: ["check_vm", DT_STR], 0x955879a6: ["SetWaitableTimer_value(CRC_SENDTIMEOUT)", DT_STR], 0x9fd13931: ["SOCKS_backconnect_server(CRC_BCSERVER)", DT_STR], 0xacc79a02: ["SetWaitableTimer_value(CRC_KNOCKERTIMEOUT)", DT_STR], 0xb892845a: ["tor_server3", DT_STR], 0xc61efa7a: ["dga_tld", DT_STR], 0xd0665bf6: ["c2_domain", DT_STR], 0xd7a003c9: ["SetWaitableTimer_value(CRC_CONFIGTIMEOUT)", DT_STR], 0xdf351e24: ["tor32_dll", DT_STR], 0xefc574ae: ["dga_seed", DT_STR], 0xec99df2e: ["ip_check_url", DT_STR], 0xea9ea760: ["p2p_bootstrap", DT_STR],}
class ursnifConfig(taskmods.DllList): """Parse the Ursnif configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def parse_config(self, data): p_data = OrderedDict() (count,) = unpack_from("<Q", data, 0x0) #print("[+] config > number of elements : %d" % count) for i in range(count): (idx, flags, off, uid) = unpack_from("<LLQQ", data, 8 + i * 24) field = "unknown" off += 8 + i * 24 if idx in idx_list: field = idx_list[idx][0] else: field = hex(idx) p_data[field] = data[off:].split("\x00")[0]
return p_data
def decode_data(self, data, pe, offset): xor_data = unpack("=H", data[offset:offset + 2])[0] xor_data2 = 0xCAFA
data_len = xor_data ^ unpack("=H", data[offset + 2:offset + 4])[0]
offset += 4 result = "" for i in range(0, data_len, 2): work = xor_data ^ xor_data2 ^ unpack("=H", data[offset + i:offset + 2 + i])[0] xor_data2 = (xor_data2 * (i + 2) ) & 0xffff result += pack("H", (work & 0xffff)) result = result[:data_len]
return result
def pe_magic_check(self, data): mz_magic = unpack_from("=2s", data, 0x0)[0] nt_magic = unpack_from("<H", data, 0x3c)[0]
if mz_magic == "\x00\x00": data = "\x4d\x5a" + data[2:] data = data[:nt_magic] + "\x50\x45" + data[nt_magic + 2:]
return data
def parse_joinned_data(self, data): data = self.pe_magic_check(data)
config_data = [] fnames = [] for m in re.finditer(magic + "\x00.", data): xor_dword = 0 magic_dword = data[m.start():m.start() + 4] if (magic_dword[0:1] == "J1" or magic_dword[3] == "\0"): (flags, crc32_name, addr, size) = unpack_from("<LLLL", data, m.start() + 4) print("[+] magic: {0} flags: 0x{1:X} crc32_name: 0x{2:X} addr: 0x{3:X} size: 0x{4:X}".format( repr(magic_dword), flags, crc32_name, addr, size)) elif (magic_dword[0:1] == "JJ" or (ord(magic_dword[3]) & 1) == 1): (xor_dword, crc32_name, addr, size) = unpack_from("<LLLL", data, m.start() + 4) print("[+] magic: {0} xor: 0x{1:X} crc32_name: 0x{2:X} addr: 0x{3:X} size: 0x{4:X}".format( repr(magic_dword), xor_dword, crc32_name, addr, size)) else: break
if size > 0x80000: print("[!] size is too large, skipped this entry") continue
try: offset = addr except: print("[!] This PE is old Ursnif (not DreamBot)") (addr, size, crc32_name, flags) = unpack_from( "<LLLL", data, m.start() + 4) print("[+] magic: {0} addr: 0x{1:X} size: 0x{2:X} crc32_name: 0x{3:X} flags: 0x{4:X}".format( repr(magic_dword), addr, size, crc32_name, flags)) offset = addr
try: joined_res = data[offset:offset + size] dec_data = aplib.decompress(joined_res).do()[0] except: pe = pefile.PE(data=data) offset = pe.get_offset_from_rva(addr) joined_res = data[offset:offset + size] dec_data = aplib.decompress(joined_res).do()[0] #print("[!] Cann't decode data.") #continue
if (xor_dword != 0): mod_data = "" for i in range(min(4, size + 1)): mod_data += chr(ord(dec_data[i]) ^ ((xor_dword >> 8 * i) & 0xff)) if (size >= 4): mod_data += dec_data[4:] dec_data = mod_data
if crc32_name in (0x4f75cea7, 0x9e154a0c): fname = "ursnif_client32.bin" open(fname, "wb").write(dec_data) print("[+] dumped 32 bit client dll: {0}".format(fname)) fnames.append(dec_data) elif crc32_name in (0x90f8aab4, 0x41982e1f): fname = "ursnif_client64.bin" open(fname, "wb").write(dec_data) print("[+] dumped 64 bit client dll: {0}".format(fname)) # fnames.append(fname)
elif crc32_name in (0xe1285e64,): fname = "ursnif_public_key.bin" open(fname, "wb").write(dec_data) print("[+] dumped public key: {0}".format(fname)) elif crc32_name in (0xd722afcb, 0x8365b957, 0x8fb1dde1): fname = "ursnif_st_config.bin" open(fname, "wb").write(dec_data) print("[+] dumped static config: {0}".format(fname)) config_data.append(self.parse_config(dec_data)) else: fname = "ursnif_" + hex(addr) + "_ap32_dec.bin" open(fname, "wb").write(dec_data) print("[+] dumped: {0}".format(fname))
for fname in fnames: config_data = self.parse_joinned_data(fname)
return config_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
if not has_aplib: debug.error("Aplib must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=ursnif_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
config_data = []
# Parse standard Ursnif config_data = self.parse_joinned_data(data)
# Parse static configuration type Ursnif if not config_data: p_data = OrderedDict() data = self.pe_magic_check(data) try: pe = pefile.PE(data=data) except: continue imagebase = pe.NT_HEADERS.OPTIONAL_HEADER.ImageBase for pattern in CONFIG_PATTERNS: m = re.search(pattern, data) if m: if pe.FILE_HEADER.Machine in (pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_IA64'], pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']): c2_num = unpack("b", data[m.start(7) + 19])[0] else: c2_num = unpack("b", data[m.start(6)])[0] if c2_num >= 16: c2_num = 1 for i in range(c2_num): if pe.FILE_HEADER.Machine in (pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_IA64'], pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']): c2_addr = m.start(4) + unpack("=I", data[m.start(3):m.start(3) + 4])[0] c2_table_offset = unpack("=Q", data[c2_addr + (8 * i):c2_addr + 8 + (8 * i)])[0] - imagebase else: c2_addr = unpack("=I", data[m.start(4):m.start(4) + 4])[0] - imagebase c2_table_offset = unpack("=I", data[c2_addr + (4 * i):c2_addr + 4 + (4 * i)])[0] - imagebase
try: c2 = self.decode_data(data, pe, c2_table_offset) except: c2 = "Decode fail"
p_data["Server " + str(i)] = c2
if pe.FILE_HEADER.Machine in (pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_IA64'], pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']): serpent_key_offset = m.start(8) + unpack("=I", data[m.start(7):m.start(7) + 4])[0] else: serpent_key_offset = unpack("=I", data[m.start(8):m.start(8) + 4])[0] - imagebase try: serpent_key = self.decode_data(data, pe, serpent_key_offset) except: serpent_key = "Decode fail" p_data["Serpent key"] = serpent_key
for pattern in RSA_PATTERNS: m = re.search(pattern, data) if m: if pe.FILE_HEADER.Machine in (pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_IA64'], pefile.MACHINE_TYPE['IMAGE_FILE_MACHINE_AMD64']): rsa_key_offset = m.start(2) + unpack("=I", data[m.start(1):m.start(1) + 4])[0] rsa_key = data[rsa_key_offset + 4:rsa_key_offset + 0x44]
rsa_mod = data[rsa_key_offset + 0x44:rsa_key_offset + 0x84] else: rsa_key_offset = unpack("=I", data[m.start(1):m.start(1) + 4])[0] - imagebase rsa_key = data[rsa_key_offset:rsa_key_offset + 0x40]
mod_offset = unpack("=I", data[m.start(4):m.start(4) + 4])[0] - imagebase rsa_mod = data[mod_offset:mod_offset + 0x40] p_data["RSA key"] = rsa_key.encode("hex") p_data["RSA modulus"] = rsa_mod.encode("hex")
config_data.append(p_data)
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<16}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145# Detecting Wellmess for Volatility## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv wellmessscan.py volatility/plugins/malware# 3. python vol.py wellmessconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport reimport pefilefrom struct import unpack, unpack_fromfrom collections import OrderedDict
try: import yara has_yara = Trueexcept ImportError: has_yara = False
wellmess_sig = { 'namespace1' : 'rule Wellmess { \ strings: \ $botlib1 = "botlib.wellMess" ascii\ $botlib2 = "botlib.Command" ascii\ $botlib3 = "botlib.Download" ascii\ $botlib4 = "botlib.AES_Encrypt" ascii\ $dotnet1 = "WellMess" ascii\ $dotnet2 = "<;head;><;title;>" ascii wide\ $dotnet3 = "<;title;><;service;>" ascii wide\ $dotnet4 = "AES_Encrypt" ascii\ condition: (uint16(0) == 0x5A4D) and (all of ($botlib*) or all of ($dotnet*))}'}
# Config patternCONFIG_PATTERNS = [re.compile("\x00(.)\x00\x00\x00\x8B\x05...\x00\x85\xC0\x0F\x85..\x00\x00\x8D\x05(....)\x89\x05...\x00\xC7\x05", re.DOTALL), re.compile("\x00(.)\x00\x00\x00\x8B\x05...\x00\x85\xC0\x0F\x85..\x00\x00\x48\x8D\x05(....)\x48\x89\x05...\x00\x48\xC7\x05", re.DOTALL)]
CONFIG_PATTERNS_DOTNET = [re.compile("\x00\x0B\x61\x00\x3A\x00\x31\x00\x5F\x00\x30\x00\x00\x0B\x61\x00\x3A\x00\x31\x00\x5F\x00\x31\x00\x00", re.DOTALL)]
class wellmessConfig(taskmods.DllList): """Parse the Wellmess configuration"""
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End
return None
def parse_config(self, config): p_data = OrderedDict() for i, d in enumerate(config): p_data["conf " + str(i)] = d
return p_data
def calculate(self):
if not has_yara: debug.error("Yara must be installed for this plugin")
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error("This command does not support the selected profile.")
rules = yara.compile(sources=wellmess_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules)
for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)
pe = pefile.PE(data=data)
config_data = [] configs = [] for pattern in CONFIG_PATTERNS: mc = list(re.finditer(pattern, data)) if mc: for m in mc: hit_adderss = m.span() config_rva = unpack("=I", m.groups()[1])[0]
if pe.FILE_HEADER.Machine == 0x14C: # for 32bit config_offset = config_rva - pe.NT_HEADERS.OPTIONAL_HEADER.ImageBase #config_offset = pe.get_physical_by_rva(config_rva - pe.NT_HEADERS.OPTIONAL_HEADER.ImageBase) + 0x1000 else: # for 64bit config_offset = config_rva + hit_adderss[0] + 26 configs.append(data[config_offset:config_offset + ord(m.groups()[0])])
for pattern in CONFIG_PATTERNS_DOTNET: mc = re.search(pattern, data) if mc: offset = mc.end() for i in range(6): strings = [] string_len = ord(data[offset])
if ord(data[offset]) == 0x80 or ord(data[offset]) == 0x83: string_len = ord(data[offset + 1]) + ((ord(data[offset]) - 0x80) * 256) offset += 1
offset += 1 for i in range(string_len): if data[offset + i] != "\x00": strings.append(data[offset + i]) if string_len != 1: configs.append("".join(strings)) offset = offset + string_len
config_data.append(self.parse_config(configs))
yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
outfd.write("[Config Info]\n") for p_data in config_data: for id, param in p_data.items(): outfd.write("{0:<25}: {1}\n".format(id, param))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183# Detecting xxmm config for Volatilitv## LICENSE# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/## How to use:# 1. cd "Volatility Folder"# 2. mv xxmmconfig.py volatility/plugins/malware# 3. python vol.py xxmmconfig -f images.mem --profile=Win7SP1x64
import volatility.plugins.taskmods as taskmodsimport volatility.win32.tasks as tasksimport volatility.utils as utilsimport volatility.debug as debugimport volatility.plugins.malware.malfind as malfindimport refrom struct import unpack, unpack_from
try: import yara has_yara = Trueexcept ImportError: has_yara = False
xxmm_sig = { 'namespace1' : 'rule xxmm { \ strings: \ $v1 = "setupParameter:" \ $v2 = "loaderParameter:" \ $v3 = "parameter:" \ condition: all of them}'}
DATA_TYPE = {0x10001: 'ASCII', 0x104DB: 'UTF-16LE', 0x104DC: 'UTF-16LE', 0x104DE: 'ASCII', 0x104DF: 'UTF-16LE', 0x104E0: 'UTF-16LE', 0x104E1: 'ASCII', 0x104E2: 'ASCII', 0x104E3: 'ASCII', 0x104E4: 'ASCII', 0x104E5: 'UTF-16LE', 0x104E6: 'UTF-16LE', 0x104E7: 'UTF-16LE', 0x104E8: 'UTF-16LE', 0x104E9: 'UTF-16LE', 0x104EA: 'UTF-16LE', 0x10502: 'ASCII', 0x10515: 'UTF-16LE', 0x10516: 'UTF-16LE', 0x10517: 'UTF-16LE', 0x10518: 'ASCII', 0x10519: 'UTF-16LE', 0x1051A: 'UTF-16LE', 0x1051B: 'UTF-16LE', 0x1051C: 'UTF-16LE', 0x1051D: 'UTF-16LE', 0x1051E: 'UTF-16LE', 0x1051F: 'UTF-16LE', 0x10522: 'UTF-16LE', 0x10525: 'UTF-16LE', 0x10534: 'UTF-16LE', 0x10535: 'UTF-16LE', 0x1053C: 'ASCII', 0x20520: 'DWORD', 0x20521: 'DWORD', 0x20523: 'DWORD', 0x20524: 'DWORD', 0x20526: 'DWORD', 0x20535: 'DWORD', 0x40500: 'BYTE', 0x40501: 'BYTE', 0x80503: 'BYTE', 0x80514: 'BYTE', 0x8052A: 'BYTE'}
class xxmmConfig(taskmods.DllList): "Parse the xxmm configuration"
@staticmethod def is_valid_profile(profile): return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')
def get_vad_base(self, task, address): for vad in task.VadRoot.traverse(): if address >= vad.Start and address < vad.End: return vad.Start, vad.End return None
def extract_param(self, conf_data, offset): l = unpack_from('>I', conf_data, offset)[0] if 8 <= l <= len(conf_data[offset:]): idnum = unpack_from('>I', conf_data, offset + 0x4)[0] s = conf_data[offset + 0x8:offset + l] else: return None, None, None return l, idnum, s
def calculate(self):
if not has_yara: debug.error('Yara must be installed for this plugin.')
addr_space = utils.load_as(self._config)
os, memory_model = self.is_valid_profile(addr_space.profile) if not os: debug.error('This command does not support the selected profile.')
rules = yara.compile(sources=xxmm_sig)
for task in self.filter_tasks(tasks.pslist(addr_space)): scanner = malfind.VadYaraScanner(task=task, rules=rules) for hit, address in scanner.scan():
vad_base_addr, end = self.get_vad_base(task, address) proc_addr_space = task.get_process_address_space() memdata = proc_addr_space.get_available_addresses()
config_data = []
for m in memdata: if 0x2000 < m[1]: continue p_data = {}
data = proc_addr_space.zread(m[0], m[1]) offset = 0 p_data['param'] = [] while(True): param = {} l, param['id'], param['data'] = self.extract_param(data, offset) if l == None: if len(p_data['param']) == 1 and p_data['param'][0]['type'] == 'Unknown': offset = 0 break for c in data[offset:]: if ord(c) != 0x00: offset = 0 break break offset += l if param['id'] in DATA_TYPE.keys(): param['type'] = DATA_TYPE[param['id']] else: param['type'] = 'Unknown' p_data['param'].append(param) if offset == 0: continue p_data['offset'] = m[0] p_data['length'] = offset config_data.append(p_data) yield task, vad_base_addr, end, hit, memory_model, config_data break
def render_text(self, outfd, data):
delim = '-' * 70
for task, start, end, malname, memory_model, config_data in data: self.table_row(outfd, task.ImageFileName, task.UniqueProcessId, start) outfd.write("{0}\n".format(delim)) outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))
for p_data in config_data: outfd.write(' Offset: %8Xh\n' % p_data['offset']) outfd.write(' Length: %8Xh\n' % p_data['length']) for param in p_data['param']: outfd.write(' ID:%6Xh Data(%s): ' % (param['id'], param['type'])) if param['type'] in {'ASCII', 'UTF-16LE'}: outfd.write('%s\n' % param['data']) elif param['type'] == 'DWORD': outfd.write('%d\n' % unpack('>I', param['data'])[0]) elif param['type'] in {'BYTE', 'Unknown'}: for c in param['data']: outfd.write('%X ' % ord(c)) outfd.write('\n') else: debug.error('Invalid type found.') outfd.write('%s\n' % ('-' * 10))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584/* YARA Rule Set for MalConfScan Author: JPCERT/CC Incident Response Group Date: 2019/04/22 Reference: https://github.com/JPCERTCC/MalConfScan/*/
rule TSCookie { meta: description = "detect TSCookie in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "https://blogs.jpcert.or.jp/en/2018/03/malware-tscooki-7aa0.html" hash1 = "6d2f5675630d0dae65a796ac624fb90f42f35fbe5dec2ec8f4adce5ebfaabf75"
strings: $v1 = "Mozilla/4.0 (compatible; MSIE 8.0; Win32)" wide $b1 = { 68 D4 08 00 00 }
condition: all of them}
rule TSC_Loader { meta: description = "detect TSCookie Loader in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $v1 = "Mozilla/4.0 (compatible; MSIE 8.0; Win32)" wide $b1 = { 68 78 0B 00 00 }
condition: all of them}
rule CobaltStrike { meta: description = "detect CobaltStrike Beacon in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "https://blogs.jpcert.or.jp/en/2018/08/volatility-plugin-for-detecting-cobalt-strike-beacon.html" hash1 = "154db8746a9d0244146648006cc94f120390587e02677b97f044c25870d512c3" hash2 = "f9b93c92ed50743cd004532ab379e3135197b6fb5341322975f4d7a98a0fcde7"
strings: $v1 = { 73 70 72 6E 67 00 } $v2 = { 69 69 69 69 69 69 69 69 }
condition: all of them}
rule RedLeaves { meta: description = "detect RedLeaves in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory block scan" reference = "https://blogs.jpcert.or.jp/en/2017/05/volatility-plugin-for-detecting-redleaves-malware.html" hash1 = "5262cb9791df50fafcb2fbd5f93226050b51efe400c2924eecba97b7ce437481"
strings: $v1 = "red_autumnal_leaves_dllmain.dll" $b1 = { FF FF 90 00 }
condition: $v1 and $b1 at 0}
rule Himawari { meta: description = "detect Himawari(a variant of RedLeaves) in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "https://www.jpcert.or.jp/present/2018/JSAC2018_01_nakatsuru.pdf" hash1 = "3938436ab73dcd10c495354546265d5498013a6d17d9c4f842507be26ea8fafb"
strings: $h1 = "himawariA" $h2 = "himawariB" $h3 = "HimawariDemo"
condition: all of them}
rule Lavender { meta: description = "detect Lavender(a variant of RedLeaves) in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research" hash1 = "db7c1534dede15be08e651784d3a5d2ae41963d192b0f8776701b4b72240c38d"
strings: $a1 = { C7 ?? ?? 4C 41 56 45 } $a2 = { C7 ?? ?? 4E 44 45 52 }
condition: all of them}
rule Armadill { meta: description = "detect Armadill(a variant of RedLeaves) in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $a1 = { C7 ?? ?? 41 72 6D 61 } $a2 = { C7 ?? ?? 64 69 6C 6C }
condition: all of them}
rule zark20rk { meta: description = "detect zark20rk(a variant of RedLeaves) in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research" hash1 = "d95ad7bbc15fdd112594584d92f0bff2c348f48c748c07930a2c4cc6502cd4b0"
strings: $a1 = { C7 ?? ?? 7A 61 72 6B } $a2 = { C7 ?? ?? 32 30 72 6B }
condition: all of them}
rule Ursnif { meta: description = "detect Ursnif(a.k.a. Dreambot, Gozi, ISFB) in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research" hash1 = "0207c06879fb4a2ddaffecc3a6713f2605cbdd90fc238da9845e88ff6aef3f85" hash2 = "ff2aa9bd3b9b3525bae0832d1e2b7c6dfb988dc7add310088609872ad9a7e714" hash3 = "1eca399763808be89d2e58e1b5e242324d60e16c0f3b5012b0070499ab482510"
strings: $a1 = "soft=%u&version=%u&user=%08x%08x%08x%08x&server=%u&id=%u&crc=%x" $b1 = "client.dll" fullword $c1 = "version=%u" $c2 = "user=%08x%08x%08x%08x" $c3 = "server=%u" $c4 = "id=%u" $c5 = "crc=%u" $c6 = "guid=%08x%08x%08x%08x" $c7 = "name=%s" $c8 = "soft=%u" $d1 = "%s://%s%s" $d2 = "PRI \x2A HTTP/2.0" $e1 = { A1 ?? ?? ?? 00 35 E7 F7 8A 40 50 } $e2 = { 56 56 56 6A 06 5? FF ?? ?? ?? ?? 00 } $f1 = { 56 57 BE ?? ?? ?? ?? 8D ?? ?? A5 A5 A5 } $f2 = { 35 8F E3 B7 3F } $f3 = { 35 0A 60 2E 51 }
condition: $a1 or ($b1 and 3 of ($c*)) or (5 of ($c*)) or ($b1 and all of ($d*)) or all of ($e*) or all of ($f*)}
rule Emotet { meta: description = "detect Emotet in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $v4a = { BB 00 C3 4C 84 } $v4b = { B8 00 C3 CC 84 } $v5a = { 6D 4E C6 41 33 D2 81 C1 39 30 00 00 } $v6a = { C7 40 20 ?? ?? ?? 00 C7 40 10 ?? ?? ?? 00 C7 40 0C 00 00 00 00 83 3C CD ?? ?? ?? ?? 00 74 0E 41 89 48 ?? 83 3C CD ?? ?? ?? ?? 00 75 F2 } $v7a = { 6A 06 33 D2 ?? F7 ?? 8B DA 43 74 } $v7b = { 83 E6 0F 8B CF 83 C6 04 50 8B D6 E8 ?? ?? ?? ?? 59 6A 2F 8D 3C 77 58 66 89 07 83 C7 02 4B 75 }
condition: all of ($v4*) or $v5a or $v6a or all of ($v7*)}
rule SmokeLoader { meta: description = "detect SmokeLoader in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "https://www.cert.pl/en/news/single/dissecting-smoke-loader/"
strings: $a1 = { B8 25 30 38 58 } $b1 = { 81 3D ?? ?? ?? ?? 25 00 41 00 } $c1 = { C7 ?? ?? ?? 25 73 25 73 }
condition: $a1 and $b1 and $c1}
rule Datper { meta: description = "detect Datper in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "https://blogs.jpcert.or.jp/en/2017/08/detecting-datper-malware-from-proxy-logs.html"
strings: $a1 = { E8 03 00 00 } $b1 = "|||" $c1 = "Content-Type: application/x-www-form-urlencoded" $delphi = "Borland\\Delphi" ascii wide $push7530h64 = { C7 C1 30 75 00 00 } $push7530h = { 68 30 75 00 00 }
condition: $a1 and $b1 and $c1 and $delphi and ($push7530h64 or $push7530h)}
rule PlugX { meta: description = "detect PlugX in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $v1 = { 47 55 4c 50 00 00 00 00 } $v2a = { 68 40 25 00 00 } $v2c = { 68 58 2D 00 00 } $v2b = { 68 a0 02 00 00 } $v2d = { 68 a4 36 00 00 } $v2e = { 8D 46 10 68 } $v2f = { 68 24 0D 00 00 } $v2g = { 68 a0 02 00 00 } $v2h = { 68 e4 0a 00 00 } $enc1 = { C1 E? 03 C1 E? 07 2B ?? } $enc2 = { 32 5? ?? 81 E? ?? ?? 00 00 2A 5? ?? 89 ?? ?? 32 ?? 2A ?? 32 5? ?? 2A 5? ?? 32 } $enc3 = { B? 33 33 33 33 } $enc4 = { B? 44 44 44 44 } condition: $v1 at 0 or ($v2a and $v2b and $enc1) or ($v2c and $v2b and $enc1) or ($v2d and $v2b and $enc2) or ($v2d and $v2e and $enc2) or ($v2f and $v2g and $enc3 and $enc4) or ($v2h and $v2g and $enc3 and $enc4)}
rule Ramnit { meta: description = "detect Ramnit" author = "nazywam" module = "ramnit" reference = "https://www.cert.pl/en/news/single/ramnit-in-depth-analysis/"
strings: $guid = "{%08X-%04X-%04X-%04X-%08X%04X}" $md5_magic_1 = "15Bn99gT" $md5_magic_2 = "1E4hNy1O" $init_dga = { C7 ?? ?? ?? ?? ?? FF FF FF FF FF ?? ?? ?? ?? ?? FF ?? ?? ?? ?? ?? FF ?? ?? ?? ?? ?? E8 ?? ?? ?? ?? 0B C0 75 ?? } $xor_secret = { 8A ?? ?? 32 ?? 88 ?? 4? 4? E2 ?? } $init_function = { FF 35 [4] 68 [4] 68 [2] 00 00 68 [4] E8 [4] FF 35 [4] 68 [4] 68 [2] 00 00 68 [4] E8 [4] FF 35 [4] 68 [4] 68 [2] 00 00 68 [4] E8 [4] FF 35 [4] 68 [4] 68 [2] 00 00 68 [4] E8 } $dga_rand_int = { B9 1D F3 01 00 F7 F1 8B C8 B8 A7 41 00 00 } $cookies = "cookies4.dat" $s3 = "pdatesDisableNotify" $get_domains = { a3 [4] a1 [4] 80 3? 00 75 ?? c7 05 [4] ff ff ff ff ff 35 [4] ff 35 [4] ff 35 [4] e8 } $add_tld = { 55 8B EC 83 ?? ?? 57 C7 ?? ?? 00 00 00 00 B? ?? ?? ?? ?? 8B ?? ?? 3B ?? ?? 75 ?? 8B ?? } $get_port = { 90 68 [4] 68 [4] FF 35 [4] FF 35 [4] E8 [4] 83 }
condition: $init_dga and $init_function and 2 of ($guid, $md5_magic_*, $cookies, $s3) and any of ( $get_port, $add_tld, $dga_rand_int, $get_domains, $xor_secret)}
rule Hawkeye { meta: description = "detect HawkEye in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $hawkstr1 = "HawkEye Keylogger" wide $hawkstr2 = "Dear HawkEye Customers!" wide $hawkstr3 = "HawkEye Logger Details:" wide
condition: all of them}
rule Lokibot { meta: description = "detect Lokibot in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research" hash1 = "6f12da360ee637a8eb075fb314e002e3833b52b155ad550811ee698b49f37e8c"
strings: $des3 = { 68 03 66 00 00 } $param = "MAC=%02X%02X%02XINSTALL=%08X%08X" $string = { 2d 00 75 00 00 00 46 75 63 6b 61 76 2e 72 75 00 00}
condition: all of them}
rule Bebloh { meta: description = "detect Bebloh(a.k.a. URLZone) in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $crc32f = { b8 EE 56 0b ca } $dga = "qwertyuiopasdfghjklzxcvbnm123945678" $post1 = "&vcmd=" $post2 = "?tver="
condition: all of them}
rule xxmm { meta: description = "detect xxmm in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $v1 = "setupParameter:" $v2 = "loaderParameter:" $v3 = "parameter:"
condition: all of them}
rule Azorult { meta: description = "detect Azorult in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $v1 = "Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1)" $v2 = "http://ip-api.com/json" $v3 = { c6 07 1e c6 47 01 15 c6 47 02 34 }
condition: all of them}
rule PoisonIvy { meta: description = "detect PoisonIvy in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $a1 = { 0E 89 02 44 } $b1 = { AD D1 34 41 } $c1 = { 66 35 20 83 66 81 F3 B8 ED }
condition: all of them}
rule netwire { meta: description = "detect netwire in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $v1 = "HostId-%Rand%" $v2 = "mozsqlite3" $v3 = "[Scroll Lock]" $v4 = "GetRawInputData" $ping = "ping 192.0.2.2" $log = "[Log Started] - [%.2d/%.2d/%d %.2d:%.2d:%.2d]"
condition: ($v1) or ($v2 and $v3 and $v4) or ($ping and $log)}
rule Nanocore { meta: description = "detect Nanocore in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $v1 = "NanoCore Client" $v2 = "PluginCommand" $v3 = "CommandType"
condition: all of them}
rule Formbook { meta: description = "detect Formbook in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $sqlite3step = { 68 34 1c 7b e1 } $sqlite3text = { 68 38 2a 90 c5 } $sqlite3blob = { 68 53 d8 7f 8c }
condition: all of them}
rule Agenttesla_type1 { meta: description = "detect Agenttesla in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research"
strings: $iestr = "C:\\\\Users\\\\Admin\\\\Desktop\\\\IELibrary\\\\IELibrary\\\\obj\\\\Debug\\\\IELibrary.pdb" $atstr = "C:\\\\Users\\\\Admin\\\\Desktop\\\\ConsoleApp1\\\\ConsoleApp1\\\\obj\\\\Debug\\\\ConsoleApp1.pdb" $sqlitestr = "Not a valid SQLite 3 Database File" wide condition: all of them}
rule Agenttesla_type2 { meta: description = "detect Agenttesla in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research" hash1 = "670a00c65eb6f7c48c1e961068a1cb7fd3653bd29377161cd04bf15c9d010da2 "
strings: $type2db1 = "1.85 (Hash, version 2, native byte-order)" wide $type2db2 = "Unknow database format" wide $type2db3 = "SQLite format 3" wide $type2db4 = "Berkelet DB" wide condition: (uint16(0) == 0x5A4D) and 3 of them}
rule Noderat { meta: description = "detect Noderat in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "https://blogs.jpcert.or.jp/ja/2019/02/tick-activity.html"
strings: $config = "/config/app.json" $key = "/config/.regeditKey.rc" $message = "uninstall error when readFileSync: "
condition: all of them}
rule Njrat { meta: description = "detect njRAT in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" hash1 = "d5f63213ce11798879520b0e9b0d1b68d55f7727758ec8c120e370699a41379d"
strings: $reg = "SEE_MASK_NOZONECHECKS" wide fullword $msg = "Execute ERROR" wide fullword $ping = "cmd.exe /c ping 0 -n 2 & del" wide fullword condition: all of them}
rule Trickbot { meta: description = "detect TrickBot in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" hash1 = "2153be5c6f73f4816d90809febf4122a7b065cbfddaa4e2bf5935277341af34c"
strings: $tagm1 = "<mcconf><ver>" wide $tagm2 = "</autorun></mcconf>" wide $tagc1 = "<moduleconfig><autostart>" wide $tagc2 = "</autoconf></moduleconfig>" wide $tagi1 = "<igroup><dinj>" wide $tagi2 = "</dinj></igroup>" wide $tags1 = "<servconf><expir>" wide $tags2 = "</plugins></servconf>" wide $tagl1 = "<slist><sinj>" wide $tagl2 = "</sinj></slist>" wide $dllname = { 6C 00 00 00 CC 00 00 00 19 01 00 00 00 00 00 00 1A 01 } condition: all of ($tagm*) or all of ($tagc*) or all of ($tagi*) or all of ($tags*) or all of ($tagl*) or $dllname}
rule Remcos { meta: description = "detect Remcos in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" hash1 = "7d5efb7e8b8947e5fe1fa12843a2faa0ebdfd7137582e5925a0b9c6a9350b0a5"
strings: $remcos = "Remcos" ascii fullword $url1 = "Breaking-Security.Net" ascii fullword $url2 = "BreakingSecurity.Net" ascii fullword $resource = "SETTINGS" ascii wide fullword condition: 1 of ($url*) and $remcos and $resource}
rule Quasar { meta: description = "detect QuasarRAT in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" hash1 = "390c1530ff62d8f4eddff0ac13bc264cbf4183e7e3d6accf8f721ffc5250e724"
strings: $quasarstr1 = "Client.exe" wide $quasarstr2 = "({0}:{1}:{2})" wide $sql1 = "SELECT * FROM Win32_DisplayConfiguration" wide $sql2 = "{0}d : {1}h : {2}m : {3}s" wide $sql3 = "SELECT * FROM FirewallProduct" wide $net1 = "echo DONT CLOSE THIS WINDOW!" wide $net2 = "freegeoip.net/xml/" wide $net3 = "http://api.ipify.org/" wide $resource = { 52 00 65 00 73 00 6F 00 75 00 72 00 63 00 65 00 73 00 00 17 69 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00 00 } condition: ((all of ($quasarstr*) or all of ($sql*)) and $resource) or all of ($net*)}
rule Elf_plead { meta: description = "ELF_PLEAD" author = "JPCERT/CC Incident Response Group" hash = "f704303f3acc2fd090145d5ee893914734d507bd1e6161f82fb34d45ab4a164b"
strings: $ioctl = "ioctl TIOCSWINSZ error" $class1 = "CPortForwardManager" $class2 = "CRemoteShell" $class3 = "CFileManager" $lzo = { 81 ?? FF 07 00 00 81 ?? 1F 20 00 00 }
condition: 3 of them}
rule asyncrat { meta: description = "detect AsyncRat in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research" hash1 = "1167207bfa1fed44e120dc2c298bd25b7137563fdc9853e8403027b645e52c19" hash2 = "588c77a3907163c3c6de0e59f4805df41001098a428c226f102ed3b74b14b3cc"
strings: $salt = {BF EB 1E 56 FB CD 97 3B B2 19 02 24 30 A5 78 43 00 3D 56 44 D2 1E 62 B9 D4 F1 80 E7 E6 C3 39 41} $b1 = {00 00 00 0D 53 00 48 00 41 00 32 00 35 00 36 00 00} $b2 = {09 50 00 6F 00 6E 00 67 00 00} $s1 = "pastebin" ascii wide nocase $s2 = "pong" wide $s3 = "Stub.exe" ascii wide condition: ($salt and (2 of ($s*) or 1 of ($b*))) or (all of ($b*) and 2 of ($s*))}
rule Wellmess { meta: description = "detect WellMess in memory" author = "JPCERT/CC Incident Response Group" rule_usage = "memory scan" reference = "internal research" hash1 = "0322c4c2d511f73ab55bf3f43b1b0f152188d7146cc67ff497ad275d9dd1c20f" hash2 = "8749c1495af4fd73ccfc84b32f56f5e78549d81feefb0c1d1c3475a74345f6a8 "
strings: $botlib1 = "botlib.wellMess" ascii $botlib2 = "botlib.Command" ascii $botlib3 = "botlib.Download" ascii $botlib4 = "botlib.AES_Encrypt" ascii $dotnet1 = "WellMess" ascii $dotnet2 = "<;head;><;title;>" ascii wide $dotnet3 = "<;title;><;service;>" ascii wide $dotnet4 = "AES_Encrypt" ascii condition: (uint16(0) == 0x5A4D) and (all of ($botlib*) or all of ($dotnet*))}
rule Elf_wellmess { meta: description = "ELF_Wellmess" author = "JPCERT/CC Incident Response Group" hash = "00654dd07721e7551641f90cba832e98c0acb030e2848e5efc0e1752c067ec07"
strings: $botlib1 = "botlib.wellMess" ascii $botlib2 = "botlib.Command" ascii $botlib3 = "botlib.Download" ascii $botlib4 = "botlib.AES_Encrypt" ascii
condition: (uint32(0) == 0x464C457F) and all of ($botlib*)}1234567891011121314{ "dataset_id": "cryptomining_detection", "processed_at": "2025-08-24T03:10:20.544187", "samples": 30000, "features": [ "cpu_usage", "memory_usage", "network_connections", "process_behavior", "file_modifications" ], "type": "cryptomining", "file_path": "..\\datasets\\cryptomining_detection\\cryptomining_detection_processed.csv"}cryptomining_detection/MalConfScan-master/.github/workflows/.yara-ci.ymlAdded+3
cryptomining_detection/MalConfScan-master/.gitignoreAdded+3
cryptomining_detection/MalConfScan-master/LICENSE.txtAdded+20
cryptomining_detection/MalConfScan-master/README.mdAdded+78
cryptomining_detection/MalConfScan-master/images/logo.svgAdded
cryptomining_detection/MalConfScan-master/images/sample1.pngAdded

Large File Pointer Details
- SHA256: 5e67bcc3f37617e14e1a0d7ae2e307126983dac812b793744290169804984e3b
- Pointer size: 130 Bytes
- Size of remote file: 63.2 kB
cryptomining_detection/MalConfScan-master/images/sample2.pngAdded

Large File Pointer Details
- SHA256: c1304852339987103dd1ebc87f61cdcd39cd11da86cacf87f83bf4b8c3dbccef
- Pointer size: 131 Bytes
- Size of remote file: 100 kB
cryptomining_detection/MalConfScan-master/images/sample3.pngAdded

Large File Pointer Details
- SHA256: 8f48a9dffd3b05777c0d0efd4fa3b64df26ca4e41b7aa09490831677384c9204
- Pointer size: 131 Bytes
- Size of remote file: 102 kB
cryptomining_detection/MalConfScan-master/images/sample4.pngAdded

Large File Pointer Details
- SHA256: 1df814cf1a4357a9c0d66b16906d290c4ec7729fa2d48803f5586f6a924a8e39
- Pointer size: 131 Bytes
- Size of remote file: 136 kB
cryptomining_detection/MalConfScan-master/images/title.svgAdded
cryptomining_detection/MalConfScan-master/malconfscan.pyAdded+380
cryptomining_detection/MalConfScan-master/requirements.txtAdded+6
cryptomining_detection/MalConfScan-master/utils/__init__.pyAdded
cryptomining_detection/MalConfScan-master/utils/agentteslascan.pyAdded+169
cryptomining_detection/MalConfScan-master/utils/aplib.pyAdded+384
cryptomining_detection/MalConfScan-master/utils/asyncratscan.pyAdded+211
cryptomining_detection/MalConfScan-master/utils/azorultscan.pyAdded+116
cryptomining_detection/MalConfScan-master/utils/beblohscan.pyAdded+199
cryptomining_detection/MalConfScan-master/utils/cobaltstrikescan.pyAdded+184
cryptomining_detection/MalConfScan-master/utils/datperscan.pyAdded+288
cryptomining_detection/MalConfScan-master/utils/elf_pleadscan.pyAdded+167
cryptomining_detection/MalConfScan-master/utils/elf_wellmess.pyAdded+131
cryptomining_detection/MalConfScan-master/utils/emotetscan.pyAdded+141
cryptomining_detection/MalConfScan-master/utils/formbook_decryption.pyAdded+315
cryptomining_detection/MalConfScan-master/utils/formbookscan.pyAdded+201
cryptomining_detection/MalConfScan-master/utils/hawkeyescan.pyAdded+205
cryptomining_detection/MalConfScan-master/utils/lokibotscan.pyAdded+168
cryptomining_detection/MalConfScan-master/utils/nanocorescan.pyAdded+150
cryptomining_detection/MalConfScan-master/utils/netwirescan.pyAdded+170
cryptomining_detection/MalConfScan-master/utils/njratscan.pyAdded+140
cryptomining_detection/MalConfScan-master/utils/noderatscan.pyAdded+109
cryptomining_detection/MalConfScan-master/utils/plugxscan.pyAdded+708
cryptomining_detection/MalConfScan-master/utils/poisonivyscan.pyAdded+164
cryptomining_detection/MalConfScan-master/utils/quasarscan.pyAdded+215
cryptomining_detection/MalConfScan-master/utils/ramnitscan.pyAdded+173
cryptomining_detection/MalConfScan-master/utils/redleavesscan.pyAdded+207
cryptomining_detection/MalConfScan-master/utils/remcosscan.pyAdded+245
cryptomining_detection/MalConfScan-master/utils/smokeloaderscan.pyAdded+176
cryptomining_detection/MalConfScan-master/utils/trickbotscan.pyAdded+129
cryptomining_detection/MalConfScan-master/utils/tscookiescan.pyAdded+220
cryptomining_detection/MalConfScan-master/utils/ursnifscan.pyAdded+347
cryptomining_detection/MalConfScan-master/utils/wellmessscan.pyAdded+145
cryptomining_detection/MalConfScan-master/utils/xxmmscan.pyAdded+183
cryptomining_detection/MalConfScan-master/yara/rule.yaraAdded+584
cryptomining_detection/cryptomining_detection_processed.csvAdded
cryptomining_detection/metadata.jsonAdded+14