Refactor all references to Context.memory to Context.layers.

This commit is contained in:
Mike Auty
2019-07-07 17:42:51 +01:00
parent ba868c7c27
commit 272224a1b0
55 changed files with 158 additions and 158 deletions
+3 -3
View File
@@ -35,13 +35,13 @@ if __name__ == '__main__':
"filename")] = filename "filename")] = filename
data = layers.physical.FileLayer(ctx, 'config' + str(args.filenames.index(filename)), data = layers.physical.FileLayer(ctx, 'config' + str(args.filenames.index(filename)),
'data' + str(args.filenames.index(filename))) 'data' + str(args.filenames.index(filename)))
ctx.memory.add_layer(data) ctx.layers.add_layer(data)
if args.lime: if args.lime:
ctx.config[interfaces.configuration.path_join('lime-config' + str(args.filenames.index(filename)), ctx.config[interfaces.configuration.path_join('lime-config' + str(args.filenames.index(filename)),
"base_layer")] = 'data' + str(args.filenames.index(filename)) "base_layer")] = 'data' + str(args.filenames.index(filename))
data = layers.lime.LimeLayer(ctx, 'lime-config' + str(args.filenames.index(filename)), data = layers.lime.LimeLayer(ctx, 'lime-config' + str(args.filenames.index(filename)),
'lime-data' + str(args.filenames.index(filename))) 'lime-data' + str(args.filenames.index(filename)))
ctx.memory.add_layer(data) ctx.layers.add_layer(data)
layername = 'data' layername = 'data'
if args.lime: if args.lime:
@@ -64,7 +64,7 @@ if __name__ == '__main__':
if tests: if tests:
for i in range(len(args.filenames)): for i in range(len(args.filenames)):
print("[*] Scanning " + args.filenames[i] + "...") print("[*] Scanning " + args.filenames[i] + "...")
scan_results = ctx.memory[layername + str(i)].scan(ctx, windows.PageMapScanner(tests)) scan_results = ctx.layers[layername + str(i)].scan(ctx, windows.PageMapScanner(tests))
# Self-referential tests need post-processing to gather the most likely offset # Self-referential tests need post-processing to gather the most likely offset
if args.selfref: if args.selfref:
+6 -6
View File
@@ -85,7 +85,7 @@ def find_pd_mapping(ctx, layer_name, entries):
pt_offset = (entry & PHYS_MASK) >> 12 pt_offset = (entry & PHYS_MASK) >> 12
try: try:
pt = ctx.memory.read(baselayer_name, pt_offset, PAGE_SIZE) pt = ctx.layers.read(baselayer_name, pt_offset, PAGE_SIZE)
except exceptions.InvalidAddressException: except exceptions.InvalidAddressException:
# print("page fault at " + hex(pt_offset)) # print("page fault at " + hex(pt_offset))
return False return False
@@ -109,7 +109,7 @@ def find_pdpt_mapping(ctx, layer_name, entries):
pd_offset = (entry & PHYS_MASK) >> 12 pd_offset = (entry & PHYS_MASK) >> 12
try: try:
pd = ctx.memory.read(baselayer_name, pd_offset, PAGE_SIZE) pd = ctx.layers.read(baselayer_name, pd_offset, PAGE_SIZE)
except exceptions.InvalidAddressException: except exceptions.InvalidAddressException:
# print("page fault at " + hex(pd_offset)) # print("page fault at " + hex(pd_offset))
return False return False
@@ -129,7 +129,7 @@ def find_pml4_mapping(ctx, layer_name, entries):
pdpte_offset = (entry & PHYS_MASK) >> 12 pdpte_offset = (entry & PHYS_MASK) >> 12
try: try:
pdpte = ctx.memory.read(baselayer_name, pdpte_offset, PAGE_SIZE) pdpte = ctx.layers.read(baselayer_name, pdpte_offset, PAGE_SIZE)
except exceptions.InvalidAddressException: except exceptions.InvalidAddressException:
# print("page fault at " + hex(pdpte_offset)) # print("page fault at " + hex(pdpte_offset))
return False return False
@@ -158,13 +158,13 @@ if __name__ == '__main__':
"filename")] = filename "filename")] = filename
data = layers.physical.FileLayer(ctx, 'config' + str(args.filenames.index(filename)), data = layers.physical.FileLayer(ctx, 'config' + str(args.filenames.index(filename)),
'data' + str(args.filenames.index(filename))) 'data' + str(args.filenames.index(filename)))
ctx.memory.add_layer(data) ctx.layers.add_layer(data)
if args.lime: if args.lime:
ctx.config[interfaces.configuration.path_join('lime-config' + str(args.filenames.index(filename)), ctx.config[interfaces.configuration.path_join('lime-config' + str(args.filenames.index(filename)),
"base_layer")] = 'data' + str(args.filenames.index(filename)) "base_layer")] = 'data' + str(args.filenames.index(filename))
data = layers.lime.LimeLayer(ctx, 'lime-config' + str(args.filenames.index(filename)), data = layers.lime.LimeLayer(ctx, 'lime-config' + str(args.filenames.index(filename)),
'lime-data' + str(args.filenames.index(filename))) 'lime-data' + str(args.filenames.index(filename)))
ctx.memory.add_layer(data) ctx.layers.add_layer(data)
layername = 'data' layername = 'data'
if args.lime: if args.lime:
@@ -175,7 +175,7 @@ if __name__ == '__main__':
for i in range(len(args.filenames)): for i in range(len(args.filenames)):
print("[*] Scanning " + args.filenames[i] + "...") print("[*] Scanning " + args.filenames[i] + "...")
baselayer_name = layername + str(i) baselayer_name = layername + str(i)
scan_results = ctx.memory[baselayer_name].scan(ctx, PML4EScanner()) scan_results = ctx.layers[baselayer_name].scan(ctx, PML4EScanner())
for (dtb, entries) in scan_results: for (dtb, entries) in scan_results:
# print("trying: " + hex(dtb)) # print("trying: " + hex(dtb))
+3 -3
View File
@@ -27,17 +27,17 @@ if __name__ == '__main__':
ctx.config[interfaces.configuration.path_join(config_name, "filename")] = filename ctx.config[interfaces.configuration.path_join(config_name, "filename")] = filename
base = layers.physical.FileLayer(ctx, config_name, base_name) base = layers.physical.FileLayer(ctx, config_name, base_name)
ctx.memory.add_layer(base) ctx.layers.add_layer(base)
# XXX What's the right way to check for LiME? # XXX What's the right way to check for LiME?
(magic, ) = struct.unpack('<I', ctx.memory.read(base_name, 0, 4)) (magic, ) = struct.unpack('<I', ctx.layers.read(base_name, 0, 4))
if magic == layers.lime.LimeLayer.MAGIC: if magic == layers.lime.LimeLayer.MAGIC:
lime_name = 'data-lime' + str(index) lime_name = 'data-lime' + str(index)
lime_config_name = 'config-lime' + str(index) lime_config_name = 'config-lime' + str(index)
ctx.config[interfaces.configuration.path_join(lime_config_name, "base_layer")] = base_name ctx.config[interfaces.configuration.path_join(lime_config_name, "base_layer")] = base_name
lime = layers.lime.LimeLayer(ctx, lime_config_name, lime_name) lime = layers.lime.LimeLayer(ctx, lime_config_name, lime_name)
ctx.memory.add_layer(lime) ctx.layers.add_layer(lime)
base_name = lime_name base_name = lime_name
scan_layers.append((filename, base_name)) scan_layers.append((filename, base_name))
+1 -1
View File
@@ -48,7 +48,7 @@ class Volshell(interfaces.plugins.PluginInterface):
context = self.context context = self.context
config = self.config config = self.config
layer_name = self.config['primary'] layer_name = self.config['primary']
kvo = context.memory[layer_name].config.get('kernel_virtual_offset') kvo = context.layers[layer_name].config.get('kernel_virtual_offset')
members = lambda x: list(sorted(x.vol.members)) members = lambda x: list(sorted(x.vol.members))
# Determine locals # Determine locals
+2 -2
View File
@@ -40,7 +40,7 @@ class Volshell(shellplugin.Volshell):
# We only use the object factory to demonstrate how to use one # We only use the object factory to demonstrate how to use one
layer_name = self.config['primary'] layer_name = self.config['primary']
kvo = self.context.memory[layer_name].config['kernel_virtual_offset'] kvo = self.context.layers[layer_name].config['kernel_virtual_offset']
ntkrnlmp = self.context.module(self.config['nt_symbols'], layer_name = layer_name, offset = kvo) ntkrnlmp = self.context.module(self.config['nt_symbols'], layer_name = layer_name, offset = kvo)
ps_aph_offset = ntkrnlmp.get_symbol("PsActiveProcessHead").address ps_aph_offset = ntkrnlmp.get_symbol("PsActiveProcessHead").address
@@ -74,7 +74,7 @@ class Volshell(shellplugin.Volshell):
# Provide some OS-agnostic convenience elements for ease # Provide some OS-agnostic convenience elements for ease
layer_name = self.config['primary'] layer_name = self.config['primary']
kvo = self.context.memory[layer_name].config['kernel_virtual_offset'] kvo = self.context.layers[layer_name].config['kernel_virtual_offset']
nt = self.context.module(self.config['nt_symbols'], layer_name = layer_name, offset = kvo) nt = self.context.module(self.config['nt_symbols'], layer_name = layer_name, offset = kvo)
ps = lambda: list(self.list_processes()) ps = lambda: list(self.list_processes())
+4 -4
View File
@@ -56,7 +56,7 @@ class LintelStacker(interfaces.automagic.StackerLayerInterface):
progress_callback: constants.ProgressCallback = None) -> Optional[interfaces.layers.DataLayerInterface]: progress_callback: constants.ProgressCallback = None) -> Optional[interfaces.layers.DataLayerInterface]:
"""Attempts to identify linux within this layer""" """Attempts to identify linux within this layer"""
# Bail out by default unless we can stack properly # Bail out by default unless we can stack properly
layer = context.memory[layer_name] layer = context.layers[layer_name]
join = interfaces.configuration.path_join join = interfaces.configuration.path_join
# Never stack on top of an intel layer # Never stack on top of an intel layer
@@ -96,7 +96,7 @@ class LintelStacker(interfaces.automagic.StackerLayerInterface):
table.get_symbol(dtb_symbol_name).address + kaslr_shift) table.get_symbol(dtb_symbol_name).address + kaslr_shift)
# Build the new layer # Build the new layer
new_layer_name = context.memory.free_layer_name("IntelLayer") new_layer_name = context.layers.free_layer_name("IntelLayer")
config_path = join("IntelHelper", new_layer_name) config_path = join("IntelHelper", new_layer_name)
context.config[join(config_path, "memory_layer")] = layer_name context.config[join(config_path, "memory_layer")] = layer_name
context.config[join(config_path, "page_map_offset")] = dtb context.config[join(config_path, "page_map_offset")] = dtb
@@ -274,7 +274,7 @@ class LinuxUtilities(object):
aslr_shift = 0): aslr_shift = 0):
sym_table = context.symbol_space[symbol_table] sym_table = context.symbol_space[symbol_table]
sym_layer = context.memory[layer_name] sym_layer = context.layers[layer_name]
if aslr_shift == 0: if aslr_shift == 0:
if not isinstance(sym_layer, layers.intel.Intel): if not isinstance(sym_layer, layers.intel.Intel):
@@ -297,7 +297,7 @@ class LinuxUtilities(object):
swapper_signature = rb"swapper(\/0|\x00\x00)\x00\x00\x00\x00\x00\x00" swapper_signature = rb"swapper(\/0|\x00\x00)\x00\x00\x00\x00\x00\x00"
module = context.module(symbol_table, layer_name, 0) module = context.module(symbol_table, layer_name, 0)
for offset in context.memory[layer_name].scan( for offset in context.layers[layer_name].scan(
scanner = scanners.RegExScanner(swapper_signature), scanner = scanners.RegExScanner(swapper_signature),
context = context, context = context,
progress_callback = progress_callback): progress_callback = progress_callback):
+8 -8
View File
@@ -56,7 +56,7 @@ class MacintelStacker(interfaces.automagic.StackerLayerInterface):
progress_callback: constants.ProgressCallback = None) -> Optional[interfaces.layers.DataLayerInterface]: progress_callback: constants.ProgressCallback = None) -> Optional[interfaces.layers.DataLayerInterface]:
"""Attempts to identify mac within this layer""" """Attempts to identify mac within this layer"""
# Bail out by default unless we can stack properly # Bail out by default unless we can stack properly
layer = context.memory[layer_name] layer = context.layers[layer_name]
new_layer = None new_layer = None
join = interfaces.configuration.path_join join = interfaces.configuration.path_join
@@ -102,7 +102,7 @@ class MacintelStacker(interfaces.automagic.StackerLayerInterface):
bootpml4_addr = MacUtilities.virtual_to_physical_address( bootpml4_addr = MacUtilities.virtual_to_physical_address(
table.get_symbol("BootPML4").address + kaslr_shift) table.get_symbol("BootPML4").address + kaslr_shift)
new_layer_name = context.memory.free_layer_name("MacDTBTempLayer") new_layer_name = context.layers.free_layer_name("MacDTBTempLayer")
config_path = join("automagic", "MacIntelHelper", new_layer_name) config_path = join("automagic", "MacIntelHelper", new_layer_name)
context.config[join(config_path, "memory_layer")] = layer_name context.config[join(config_path, "memory_layer")] = layer_name
context.config[join(config_path, "page_map_offset")] = bootpml4_addr context.config[join(config_path, "page_map_offset")] = bootpml4_addr
@@ -117,7 +117,7 @@ class MacintelStacker(interfaces.automagic.StackerLayerInterface):
dtb = idlepml4_addr dtb = idlepml4_addr
# Build the new layer # Build the new layer
new_layer_name = context.memory.free_layer_name("IntelLayer") new_layer_name = context.layers.free_layer_name("IntelLayer")
config_path = join("automagic", "MacIntelHelper", new_layer_name) config_path = join("automagic", "MacIntelHelper", new_layer_name)
context.config[join(config_path, "memory_layer")] = layer_name context.config[join(config_path, "memory_layer")] = layer_name
context.config[join(config_path, "page_map_offset")] = dtb context.config[join(config_path, "page_map_offset")] = dtb
@@ -142,7 +142,7 @@ class MacUtilities(object):
aslr_shift = 0): aslr_shift = 0):
sym_table = context.symbol_space[symbol_table] sym_table = context.symbol_space[symbol_table]
sym_layer = context.memory[layer_name] sym_layer = context.layers[layer_name]
if aslr_shift == 0: if aslr_shift == 0:
if not isinstance(sym_layer, layers.intel.Intel): if not isinstance(sym_layer, layers.intel.Intel):
@@ -156,11 +156,11 @@ class MacUtilities(object):
def _scan_generator(cls, context, layer_name, progress_callback): def _scan_generator(cls, context, layer_name, progress_callback):
darwin_signature = rb"Darwin Kernel Version \d{1,3}\.\d{1,3}\.\d{1,3}: [^\x00]+\x00" darwin_signature = rb"Darwin Kernel Version \d{1,3}\.\d{1,3}\.\d{1,3}: [^\x00]+\x00"
for offset in context.memory[layer_name].scan( for offset in context.layers[layer_name].scan(
scanner = scanners.RegExScanner(darwin_signature), context = context, scanner = scanners.RegExScanner(darwin_signature), context = context,
progress_callback = progress_callback): progress_callback = progress_callback):
banner = context.memory[layer_name].read(offset, 128) banner = context.layers[layer_name].read(offset, 128)
idx = banner.find(b"\x00") idx = banner.find(b"\x00")
if idx != -1: if idx != -1:
@@ -200,13 +200,13 @@ class MacUtilities(object):
tmp_aslr_shift = offset - cls.virtual_to_physical_address(version_json_address) tmp_aslr_shift = offset - cls.virtual_to_physical_address(version_json_address)
major_string = context.memory[layer_name].read(version_major_phys_offset + tmp_aslr_shift, 4) major_string = context.layers[layer_name].read(version_major_phys_offset + tmp_aslr_shift, 4)
major = struct.unpack("<I", major_string)[0] major = struct.unpack("<I", major_string)[0]
if major != banner_major: if major != banner_major:
continue continue
minor_string = context.memory[layer_name].read(version_minor_phys_offset + tmp_aslr_shift, 4) minor_string = context.layers[layer_name].read(version_minor_phys_offset + tmp_aslr_shift, 4)
minor = struct.unpack("<I", minor_string)[0] minor = struct.unpack("<I", minor_string)[0]
if minor != banner_minor: if minor != banner_minor:
+10 -10
View File
@@ -110,21 +110,21 @@ def scan(ctx: interfaces.context.ContextInterface,
pdb_names = [bytes(name + ".pdb", "utf-8") for name in constants.windows.KERNEL_MODULE_NAMES] pdb_names = [bytes(name + ".pdb", "utf-8") for name in constants.windows.KERNEL_MODULE_NAMES]
if start is None: if start is None:
start = ctx.memory[layer_name].minimum_address start = ctx.layers[layer_name].minimum_address
if end is None: if end is None:
end = ctx.memory[layer_name].maximum_address end = ctx.layers[layer_name].maximum_address
for (GUID, age, pdb_name, signature_offset) in ctx.memory[layer_name].scan( for (GUID, age, pdb_name, signature_offset) in ctx.layers[layer_name].scan(
ctx, PdbSignatureScanner(pdb_names), progress_callback = progress_callback, sections = [(start, ctx, PdbSignatureScanner(pdb_names), progress_callback = progress_callback, sections = [(start,
end - start)]): end - start)]):
mz_offset = None mz_offset = None
sig_pfn = signature_offset // page_size sig_pfn = signature_offset // page_size
for i in range(sig_pfn, min_pfn, -1): for i in range(sig_pfn, min_pfn, -1):
if not ctx.memory[layer_name].is_valid(i * page_size, 2): if not ctx.layers[layer_name].is_valid(i * page_size, 2):
break break
data = ctx.memory[layer_name].read(i * page_size, 2) data = ctx.layers[layer_name].read(i * page_size, 2)
if data == b'MZ': if data == b'MZ':
mz_offset = i * page_size mz_offset = i * page_size
break break
@@ -179,7 +179,7 @@ class KernelPDBScanner(interfaces.automagic.AutomagicInterface):
virtual_layer_name = context.config.get(sub_config_path, None) virtual_layer_name = context.config.get(sub_config_path, None)
layer_name = context.config.get(interfaces.configuration.path_join(sub_config_path, "memory_layer"), None) layer_name = context.config.get(interfaces.configuration.path_join(sub_config_path, "memory_layer"), None)
if layer_name and virtual_layer_name: if layer_name and virtual_layer_name:
memlayer = context.memory[virtual_layer_name] memlayer = context.layers[virtual_layer_name]
if isinstance(memlayer, intel.Intel): if isinstance(memlayer, intel.Intel):
results = [virtual_layer_name] results = [virtual_layer_name]
else: else:
@@ -285,7 +285,7 @@ class KernelPDBScanner(interfaces.automagic.AutomagicInterface):
""" """
for virtual_layer in valid_kernels: for virtual_layer in valid_kernels:
# Set the virtual offset under the TranslationLayer it applies to # Set the virtual offset under the TranslationLayer it applies to
kvo_path = interfaces.configuration.path_join(context.memory[virtual_layer].config_path, kvo_path = interfaces.configuration.path_join(context.layers[virtual_layer].config_path,
'kernel_virtual_offset') 'kernel_virtual_offset')
kvo, kernel = valid_kernels[virtual_layer] kvo, kernel = valid_kernels[virtual_layer]
context.config[kvo_path] = kvo context.config[kvo_path] = kvo
@@ -345,7 +345,7 @@ class KernelPDBScanner(interfaces.automagic.AutomagicInterface):
# If we're here, chances are high we're in a Win10 x64 image with kernel base randomization # If we're here, chances are high we're in a Win10 x64 image with kernel base randomization
virtual_layer_name = vlayer.name virtual_layer_name = vlayer.name
physical_layer_name = self.get_physical_layer_name(context, vlayer) physical_layer_name = self.get_physical_layer_name(context, vlayer)
physical_layer = context.memory[physical_layer_name] physical_layer = context.layers[physical_layer_name]
# TODO: On older windows, this might be \WINDOWS\system32\nt rather than \SystemRoot\system32\nt # TODO: On older windows, this might be \WINDOWS\system32\nt rather than \SystemRoot\system32\nt
results = physical_layer.scan( results = physical_layer.scan(
context, scanners.BytesScanner(b"\\SystemRoot\\system32\\nt"), progress_callback = progress_callback) context, scanners.BytesScanner(b"\\SystemRoot\\system32\\nt"), progress_callback = progress_callback)
@@ -375,7 +375,7 @@ class KernelPDBScanner(interfaces.automagic.AutomagicInterface):
vollog.debug("Kernel base determination - using KDBG structure for kernel offset") vollog.debug("Kernel base determination - using KDBG structure for kernel offset")
valid_kernels = {} # type: ValidKernelsType valid_kernels = {} # type: ValidKernelsType
physical_layer_name = self.get_physical_layer_name(context, vlayer) physical_layer_name = self.get_physical_layer_name(context, vlayer)
physical_layer = context.memory[physical_layer_name] physical_layer = context.layers[physical_layer_name]
results = physical_layer.scan(context, scanners.BytesScanner(b"KDBG"), progress_callback = progress_callback) results = physical_layer.scan(context, scanners.BytesScanner(b"KDBG"), progress_callback = progress_callback)
seen = set() # type: Set[int] seen = set() # type: Set[int]
@@ -446,7 +446,7 @@ class KernelPDBScanner(interfaces.automagic.AutomagicInterface):
""" """
valid_kernels = {} # type: ValidKernelsType valid_kernels = {} # type: ValidKernelsType
for virtual_layer_name in potential_layers: for virtual_layer_name in potential_layers:
vlayer = context.memory.get(virtual_layer_name, None) vlayer = context.layers.get(virtual_layer_name, None)
if isinstance(vlayer, layers.intel.Intel): if isinstance(vlayer, layers.intel.Intel):
for method in self.methods: for method in self.methods:
valid_kernels = method(self, context, vlayer, progress_callback) valid_kernels = method(self, context, vlayer, progress_callback)
+3 -3
View File
@@ -107,7 +107,7 @@ class LayerStacker(interfaces.automagic.AutomagicInterface):
location = self.config.get('single_location', None) location = self.config.get('single_location', None)
# Setup the local copy of the resource # Setup the local copy of the resource
current_layer_name = context.memory.free_layer_name("FileLayer") current_layer_name = context.layers.free_layer_name("FileLayer")
current_config_path = interfaces.configuration.path_join(config_path, "stack", current_layer_name) current_config_path = interfaces.configuration.path_join(config_path, "stack", current_layer_name)
# This must be specific to get us started, setup the config and run # This must be specific to get us started, setup the config and run
@@ -130,7 +130,7 @@ class LayerStacker(interfaces.automagic.AutomagicInterface):
vollog.log(constants.LOGLEVEL_VVVV, "Attempting to stack using {}".format(stacker_cls.__name__)) vollog.log(constants.LOGLEVEL_VVVV, "Attempting to stack using {}".format(stacker_cls.__name__))
new_layer = stacker.stack(new_context, current_layer_name, progress_callback) new_layer = stacker.stack(new_context, current_layer_name, progress_callback)
if new_layer: if new_layer:
new_context.memory.add_layer(new_layer) new_context.layers.add_layer(new_layer)
vollog.log(constants.LOGLEVEL_VVVV, vollog.log(constants.LOGLEVEL_VVVV,
"Stacked {} using {}".format(new_layer.name, stacker_cls.__name__)) "Stacked {} using {}".format(new_layer.name, stacker_cls.__name__))
break break
@@ -153,7 +153,7 @@ class LayerStacker(interfaces.automagic.AutomagicInterface):
if result: if result:
path, layer = result path, layer = result
# splice in the new configuration into the original context # splice in the new configuration into the original context
context.config.merge(path, new_context.memory[layer].build_configuration()) context.config.merge(path, new_context.layers[layer].build_configuration())
# Call the construction magic now we may have new things to construct # Call the construction magic now we may have new things to construct
constructor = construct_layers.ConstructionMagic( constructor = construct_layers.ConstructionMagic(
@@ -98,7 +98,7 @@ class SymbolFinder(interfaces.automagic.AutomagicInterface):
mss = scanners.MultiStringScanner([x for x in self.banners if x is not None]) mss = scanners.MultiStringScanner([x for x in self.banners if x is not None])
layer = context.memory[layer_name] layer = context.layers[layer_name]
# Check if the Stacker has already found what we're looking for # Check if the Stacker has already found what we're looking for
if layer.config.get(self.banner_config_key, None): if layer.config.get(self.banner_config_key, None):
@@ -106,7 +106,7 @@ class SymbolFinder(interfaces.automagic.AutomagicInterface):
else: else:
# Swap to the physical layer for scanning # Swap to the physical layer for scanning
# TODO: Fix this so it works for layers other than just Intel # TODO: Fix this so it works for layers other than just Intel
layer = context.memory[layer.config['memory_layer']] layer = context.layers[layer.config['memory_layer']]
banner_list = layer.scan(context = context, scanner = mss, progress_callback = progress_callback) banner_list = layer.scan(context = context, scanner = mss, progress_callback = progress_callback)
for _, banner in banner_list: for _, banner in banner_list:
+6 -6
View File
@@ -263,7 +263,7 @@ class WintelHelper(interfaces.automagic.AutomagicInterface):
context, sub_config_path) context, sub_config_path)
if not isinstance(physical_layer_name, str): if not isinstance(physical_layer_name, str):
raise TypeError("Physical layer name is not a string: {}".format(sub_config_path)) raise TypeError("Physical layer name is not a string: {}".format(sub_config_path))
physical_layer = context.memory[physical_layer_name] physical_layer = context.layers[physical_layer_name]
# Check lower layer metadata first # Check lower layer metadata first
if physical_layer.metadata.get('page_map_offset', None): if physical_layer.metadata.get('page_map_offset', None):
context.config[page_map_offset_path] = physical_layer.metadata['page_map_offset'] context.config[page_map_offset_path] = physical_layer.metadata['page_map_offset']
@@ -296,7 +296,7 @@ class WintelStacker(interfaces.automagic.StackerLayerInterface):
that range, and ignore any that contain multiple self-references (since the DTB is very unlikely to point to that range, and ignore any that contain multiple self-references (since the DTB is very unlikely to point to
itself more than once). itself more than once).
""" """
base_layer = context.memory[layer_name] base_layer = context.layers[layer_name]
if isinstance(base_layer, intel.Intel): if isinstance(base_layer, intel.Intel):
return None return None
if base_layer.metadata.get('os', None) not in ['Windows', 'Unknown']: if base_layer.metadata.get('os', None) not in ['Windows', 'Unknown']:
@@ -315,7 +315,7 @@ class WintelStacker(interfaces.automagic.StackerLayerInterface):
elif base_layer.metadata.get('pae', False): elif base_layer.metadata.get('pae', False):
layer_type = intel.WindowsIntelPAE layer_type = intel.WindowsIntelPAE
# Construct the layer # Construct the layer
new_layer_name = context.memory.free_layer_name("IntelLayer") new_layer_name = context.layers.free_layer_name("IntelLayer")
config_path = interfaces.configuration.path_join("IntelHelper", new_layer_name) config_path = interfaces.configuration.path_join("IntelHelper", new_layer_name)
context.config[interfaces.configuration.path_join(config_path, "memory_layer")] = layer_name context.config[interfaces.configuration.path_join(config_path, "memory_layer")] = layer_name
context.config[interfaces.configuration.path_join( context.config[interfaces.configuration.path_join(
@@ -328,7 +328,7 @@ class WintelStacker(interfaces.automagic.StackerLayerInterface):
layer = None layer = None
config_path = None config_path = None
for test, dtb in hits: for test, dtb in hits:
new_layer_name = context.memory.free_layer_name("IntelLayer") new_layer_name = context.layers.free_layer_name("IntelLayer")
config_path = interfaces.configuration.path_join("IntelHelper", new_layer_name) config_path = interfaces.configuration.path_join("IntelHelper", new_layer_name)
context.config[interfaces.configuration.path_join(config_path, "memory_layer")] = layer_name context.config[interfaces.configuration.path_join(config_path, "memory_layer")] = layer_name
context.config[interfaces.configuration.path_join(config_path, "page_map_offset")] = dtb context.config[interfaces.configuration.path_join(config_path, "page_map_offset")] = dtb
@@ -340,7 +340,7 @@ class WintelStacker(interfaces.automagic.StackerLayerInterface):
if layer is None: if layer is None:
vollog.debug("Self-referential pointer not in well-known location, moving to recent windows heuristic") vollog.debug("Self-referential pointer not in well-known location, moving to recent windows heuristic")
# There is a very high chance that the DTB will live in this narrow segment, assuming we couldn't find it previously # There is a very high chance that the DTB will live in this narrow segment, assuming we couldn't find it previously
hits = context.memory[layer_name].scan( hits = context.layers[layer_name].scan(
context, context,
PageMapScanner([DtbSelfRef64bit()]), PageMapScanner([DtbSelfRef64bit()]),
sections = [(0x1a0000, 0x50000)], sections = [(0x1a0000, 0x50000)],
@@ -350,7 +350,7 @@ class WintelStacker(interfaces.automagic.StackerLayerInterface):
if hits: if hits:
# TODO: Decide which to use if there are multiple options # TODO: Decide which to use if there are multiple options
test, page_map_offset = hits[0] test, page_map_offset = hits[0]
new_layer_name = context.memory.free_layer_name("IntelLayer") new_layer_name = context.layers.free_layer_name("IntelLayer")
config_path = interfaces.configuration.path_join("IntelHelper", new_layer_name) config_path = interfaces.configuration.path_join("IntelHelper", new_layer_name)
context.config[interfaces.configuration.path_join(config_path, "memory_layer")] = layer_name context.config[interfaces.configuration.path_join(config_path, "memory_layer")] = layer_name
context.config[interfaces.configuration.path_join(config_path, "page_map_offset")] = page_map_offset context.config[interfaces.configuration.path_join(config_path, "page_map_offset")] = page_map_offset
@@ -197,7 +197,7 @@ class ComplexListRequirement(MultiRequirement, configuration.ConfigurableRequire
value_path = configuration.path_join(config_path, self.name, req.name) value_path = configuration.path_join(config_path, self.name, req.name)
value = context.config.get(value_path, None) value = context.config.get(value_path, None)
if value is not None: if value is not None:
result.splice(req.name, context.memory[value].build_configuration()) result.splice(req.name, context.layers[value].build_configuration())
result[req.name] = value result[req.name] = value
return result return result
@@ -260,14 +260,14 @@ class TranslationLayerRequirement(configuration.ConstructableRequirementInterfac
config_path = configuration.path_join(config_path, self.name) config_path = configuration.path_join(config_path, self.name)
value = self.config_value(context, config_path, None) value = self.config_value(context, config_path, None)
if isinstance(value, str): if isinstance(value, str):
if value not in context.memory: if value not in context.layers:
vollog.log(constants.LOGLEVEL_V, "IndexError - Layer not found in memory space: {}".format(value)) vollog.log(constants.LOGLEVEL_V, "IndexError - Layer not found in memory space: {}".format(value))
return {config_path: self} return {config_path: self}
if self.oses and context.memory[value].metadata.get('os', None) not in self.oses: if self.oses and context.layers[value].metadata.get('os', None) not in self.oses:
vollog.log(constants.LOGLEVEL_V, "TypeError - Layer is not the required OS: {}".format(value)) vollog.log(constants.LOGLEVEL_V, "TypeError - Layer is not the required OS: {}".format(value))
return {config_path: self} return {config_path: self}
if (self.architectures if (self.architectures
and context.memory[value].metadata.get('architecture', None) not in self.architectures): and context.layers[value].metadata.get('architecture', None) not in self.architectures):
vollog.log(constants.LOGLEVEL_V, "TypeError - Layer is not the required Architecture: {}".format(value)) vollog.log(constants.LOGLEVEL_V, "TypeError - Layer is not the required Architecture: {}".format(value))
return {config_path: self} return {config_path: self}
return {} return {}
@@ -292,7 +292,7 @@ class TranslationLayerRequirement(configuration.ConstructableRequirementInterfac
# Determine the layer name # Determine the layer name
name = self.name name = self.name
counter = 2 counter = 2
while name in context.memory: while name in context.layers:
name = self.name + str(counter) name = self.name + str(counter)
counter += 1 counter += 1
@@ -312,7 +312,7 @@ class TranslationLayerRequirement(configuration.ConstructableRequirementInterfac
def build_configuration(self, context: interfaces.context.ContextInterface, _: str, def build_configuration(self, context: interfaces.context.ContextInterface, _: str,
value: Any) -> configuration.HierarchicalDict: value: Any) -> configuration.HierarchicalDict:
"""Builds the appropriate configuration for the specified requirement""" """Builds the appropriate configuration for the specified requirement"""
return context.memory[value].build_configuration() return context.layers[value].build_configuration()
class SymbolTableRequirement(configuration.ConstructableRequirementInterface, class SymbolTableRequirement(configuration.ConstructableRequirementInterface,
+4 -4
View File
@@ -46,7 +46,7 @@ class Context(interfaces.context.ContextInterface):
"""Initializes the context.""" """Initializes the context."""
super().__init__() super().__init__()
self._symbol_space = symbols.SymbolSpace() self._symbol_space = symbols.SymbolSpace()
self._memory = interfaces.layers.Memory() self._memory = interfaces.layers.LayerContainer()
self._config = interfaces.configuration.HierarchicalDict() self._config = interfaces.configuration.HierarchicalDict()
# ## Symbol Space Functions # ## Symbol Space Functions
@@ -69,8 +69,8 @@ class Context(interfaces.context.ContextInterface):
return self._symbol_space return self._symbol_space
@property @property
def memory(self) -> interfaces.layers.Memory: def layers(self) -> interfaces.layers.LayerContainer:
"""A Memory object, allowing access to all data and translation layers currently available within the context""" """A LayerContainer object, allowing access to all data and translation layers currently available within the context"""
return self._memory return self._memory
# ## Translation Layer Functions # ## Translation Layer Functions
@@ -240,7 +240,7 @@ class SizedModule(Module):
The mapping should be sorted and should be quicker than reading the data The mapping should be sorted and should be quicker than reading the data
We turn it into JSON to make a common string and use a quick hash, because collissions are unlikely""" We turn it into JSON to make a common string and use a quick hash, because collissions are unlikely"""
layer = self._context.memory[self.layer_name] layer = self._context.layers[self.layer_name]
if not isinstance(layer, interfaces.layers.TranslationLayerInterface): if not isinstance(layer, interfaces.layers.TranslationLayerInterface):
raise TypeError("Hashing modules on non-TranslationLayers is not allowed") raise TypeError("Hashing modules on non-TranslationLayers is not allowed")
return hashlib.md5(bytes(str(list(layer.mapping(self.offset, self.size, ignore_errors = True))), return hashlib.md5(bytes(str(list(layer.mapping(self.offset, self.size, ignore_errors = True))),
+3 -3
View File
@@ -58,9 +58,9 @@ class ContextInterface(object, metaclass = ABCMeta):
@property @property
@abstractmethod @abstractmethod
def memory(self) -> 'interfaces.layers.Memory': def layers(self) -> 'interfaces.layers.LayerContainer':
"""Returns the memory object for the context""" """Returns the memory object for the context"""
raise NotImplementedError("Memory has not been implemented.") raise NotImplementedError("LayerContainer has not been implemented.")
def add_layer(self, layer: 'interfaces.layers.DataLayerInterface'): def add_layer(self, layer: 'interfaces.layers.DataLayerInterface'):
"""Adds a named translation layer to the context memory """Adds a named translation layer to the context memory
@@ -68,7 +68,7 @@ class ContextInterface(object, metaclass = ABCMeta):
Args: Args:
layer: Layer object to be added to the context memory layer: Layer object to be added to the context memory
""" """
self.memory.add_layer(layer) self.layers.add_layer(layer)
# ## Object Factory Functions # ## Object Factory Functions
+5 -5
View File
@@ -296,7 +296,7 @@ class DataLayerInterface(interfaces.configuration.ConfigurableInterface, metacla
data = b'' data = b''
for layer_name, address, chunk_size in data_to_scan: for layer_name, address, chunk_size in data_to_scan:
try: try:
data += self.context.memory[layer_name].read(address, chunk_size) data += self.context.layers[layer_name].read(address, chunk_size)
except exceptions.InvalidAddressException: except exceptions.InvalidAddressException:
vollog.debug("Invalid address in layer {} found scanning {} at address {:x}".format( vollog.debug("Invalid address in layer {} found scanning {} at address {:x}".format(
layer_name, self.name, address)) layer_name, self.name, address))
@@ -329,7 +329,7 @@ class DataLayerInterface(interfaces.configuration.ConfigurableInterface, metacla
@property @property
def metadata(self) -> Mapping: def metadata(self) -> Mapping:
"""Returns a ReadOnly copy of the metadata published by this layer""" """Returns a ReadOnly copy of the metadata published by this layer"""
maps = [self.context.memory[layer_name].metadata for layer_name in self.dependencies] maps = [self.context.layers[layer_name].metadata for layer_name in self.dependencies]
return interfaces.objects.ReadOnlyMapping(collections.ChainMap({}, self._direct_metadata, *maps)) return interfaces.objects.ReadOnlyMapping(collections.ChainMap({}, self._direct_metadata, *maps))
@@ -384,7 +384,7 @@ class TranslationLayerInterface(DataLayerInterface, metaclass = ABCMeta):
elif offset < current_offset: elif offset < current_offset:
raise exceptions.LayerException("Mapping returned an overlapping element") raise exceptions.LayerException("Mapping returned an overlapping element")
if mapped_length > 0: if mapped_length > 0:
output += [self._context.memory.read(layer, mapped_offset, mapped_length, pad)] output += [self._context.layers.read(layer, mapped_offset, mapped_length, pad)]
current_offset += mapped_length current_offset += mapped_length
recovered_data = b"".join(output) recovered_data = b"".join(output)
return recovered_data + b"\x00" * (length - len(recovered_data)) return recovered_data + b"\x00" * (length - len(recovered_data))
@@ -399,7 +399,7 @@ class TranslationLayerInterface(DataLayerInterface, metaclass = ABCMeta):
self.name, current_offset, "Layer {} cannot map offset: {}".format(self.name, current_offset)) self.name, current_offset, "Layer {} cannot map offset: {}".format(self.name, current_offset))
elif offset < current_offset: elif offset < current_offset:
raise exceptions.LayerException("Mapping returned an overlapping element") raise exceptions.LayerException("Mapping returned an overlapping element")
self._context.memory.write(layer, mapped_offset, value) self._context.layers.write(layer, mapped_offset, value)
current_offset += length current_offset += length
# ## Scan implementation with knowledge of pages # ## Scan implementation with knowledge of pages
@@ -420,7 +420,7 @@ class TranslationLayerInterface(DataLayerInterface, metaclass = ABCMeta):
offset += chunk_size offset += chunk_size
class Memory(collections.abc.Mapping): class LayerContainer(collections.abc.Mapping):
"""Container for multiple layers of data""" """Container for multiple layers of data"""
def __init__(self) -> None: def __init__(self) -> None:
+1 -1
View File
@@ -104,7 +104,7 @@ class ObjectInterface(metaclass = ABCMeta):
# #
# Normalize offsets # Normalize offsets
mask = context.memory[object_info.layer_name].address_mask mask = context.layers[object_info.layer_name].address_mask
normalized_offset = object_info.offset & mask normalized_offset = object_info.offset & mask
self._vol = collections.ChainMap({}, object_info, {'type_name': type_name, 'offset': normalized_offset}, kwargs) self._vol = collections.ChainMap({}, object_info, {'type_name': type_name, 'offset': normalized_offset}, kwargs)
+3 -3
View File
@@ -54,7 +54,7 @@ class WindowsCrashDump32Layer(segmented.SegmentedLayer):
# Create a custom SymbolSpace # Create a custom SymbolSpace
self._crash_table_name = intermed.IntermediateSymbolTable.create(context, self._config_path, 'windows', 'crash') self._crash_table_name = intermed.IntermediateSymbolTable.create(context, self._config_path, 'windows', 'crash')
# Check Header # Check Header
hdr_layer = self._context.memory[self._base_layer] hdr_layer = self._context.layers[self._base_layer]
hdr_offset = 0 hdr_offset = 0
self._check_header(hdr_layer, hdr_offset) self._check_header(hdr_layer, hdr_offset)
@@ -118,9 +118,9 @@ class WindowsCrashDump32Stacker(interfaces.automagic.StackerLayerInterface):
layer_name: str, layer_name: str,
progress_callback: constants.ProgressCallback = None) -> Optional[interfaces.layers.DataLayerInterface]: progress_callback: constants.ProgressCallback = None) -> Optional[interfaces.layers.DataLayerInterface]:
try: try:
WindowsCrashDump32Layer._check_header(context.memory[layer_name]) WindowsCrashDump32Layer._check_header(context.layers[layer_name])
except WindowsCrashDump32FormatException: except WindowsCrashDump32FormatException:
return None return None
new_name = context.memory.free_layer_name("WindowsCrashDump32Layer") new_name = context.layers.free_layer_name("WindowsCrashDump32Layer")
context.config[interfaces.configuration.path_join(new_name, "base_layer")] = layer_name context.config[interfaces.configuration.path_join(new_name, "base_layer")] = layer_name
return WindowsCrashDump32Layer(context, new_name, new_name) return WindowsCrashDump32Layer(context, new_name, new_name)
+4 -4
View File
@@ -179,7 +179,7 @@ class Intel(interfaces.layers.TranslationLayerInterface):
@functools.lru_cache(1025) @functools.lru_cache(1025)
def _get_valid_table(self, base_address: int) -> Optional[bytes]: def _get_valid_table(self, base_address: int) -> Optional[bytes]:
"""Extracts the table, validates it and returns it if it's valid""" """Extracts the table, validates it and returns it if it's valid"""
table = self._context.memory.read(self._base_layer, base_address, self.page_size) table = self._context.layers.read(self._base_layer, base_address, self.page_size)
# If the table is entirely duplicates, then mark the whole table as bad # If the table is entirely duplicates, then mark the whole table as bad
if (table == table[:self._entry_size] * self._entry_number): if (table == table[:self._entry_size] * self._entry_number):
@@ -191,7 +191,7 @@ class Intel(interfaces.layers.TranslationLayerInterface):
try: try:
# TODO: Consider reimplementing this, since calls to mapping can call is_valid # TODO: Consider reimplementing this, since calls to mapping can call is_valid
return all([ return all([
self._context.memory[layer].is_valid(mapped_offset) self._context.layers[layer].is_valid(mapped_offset)
for _, mapped_offset, _, layer in self.mapping(offset, length) for _, mapped_offset, _, layer in self.mapping(offset, length)
]) ])
except exceptions.InvalidAddressException: except exceptions.InvalidAddressException:
@@ -205,7 +205,7 @@ class Intel(interfaces.layers.TranslationLayerInterface):
if length == 0: if length == 0:
try: try:
mapped_offset, _, layer_name = self._translate(offset) mapped_offset, _, layer_name = self._translate(offset)
if not self._context.memory[layer_name].is_valid(mapped_offset): if not self._context.layers[layer_name].is_valid(mapped_offset):
raise exceptions.InvalidAddressException(layer_name = layer_name, invalid_address = mapped_offset) raise exceptions.InvalidAddressException(layer_name = layer_name, invalid_address = mapped_offset)
except exceptions.InvalidAddressException: except exceptions.InvalidAddressException:
if not ignore_errors: if not ignore_errors:
@@ -217,7 +217,7 @@ class Intel(interfaces.layers.TranslationLayerInterface):
try: try:
chunk_offset, page_size, layer_name = self._translate(offset) chunk_offset, page_size, layer_name = self._translate(offset)
chunk_size = min(page_size - (chunk_offset % page_size), length) chunk_size = min(page_size - (chunk_offset % page_size), length)
if not self._context.memory[layer_name].is_valid(chunk_offset, chunk_size): if not self._context.layers[layer_name].is_valid(chunk_offset, chunk_size):
raise exceptions.InvalidAddressException(layer_name = layer_name, invalid_address = chunk_offset) raise exceptions.InvalidAddressException(layer_name = layer_name, invalid_address = chunk_offset)
except (exceptions.PagedInvalidAddressException, exceptions.InvalidAddressException) as excp: except (exceptions.PagedInvalidAddressException, exceptions.InvalidAddressException) as excp:
if not ignore_errors: if not ignore_errors:
+3 -3
View File
@@ -49,7 +49,7 @@ class LimeLayer(segmented.SegmentedLayer):
# The base class loads the segments on initialization, but otherwise this must to get the right min/max addresses # The base class loads the segments on initialization, but otherwise this must to get the right min/max addresses
def _load_segments(self) -> None: def _load_segments(self) -> None:
base_layer = self._context.memory[self._base_layer] base_layer = self._context.layers[self._base_layer]
base_maxaddr = base_layer.maximum_address base_maxaddr = base_layer.maximum_address
maxaddr = 0 maxaddr = 0
offset = 0 offset = 0
@@ -96,9 +96,9 @@ class LimeStacker(interfaces.automagic.StackerLayerInterface):
layer_name: str, layer_name: str,
progress_callback: constants.ProgressCallback = None) -> Optional[interfaces.layers.DataLayerInterface]: progress_callback: constants.ProgressCallback = None) -> Optional[interfaces.layers.DataLayerInterface]:
try: try:
LimeLayer._check_header(context.memory[layer_name]) LimeLayer._check_header(context.layers[layer_name])
except LimeFormatException: except LimeFormatException:
return None return None
new_name = context.memory.free_layer_name("LimeLayer") new_name = context.layers.free_layer_name("LimeLayer")
context.config[interfaces.configuration.path_join(new_name, "base_layer")] = layer_name context.config[interfaces.configuration.path_join(new_name, "base_layer")] = layer_name
return LimeLayer(context, new_name, new_name) return LimeLayer(context, new_name, new_name)
+2 -2
View File
@@ -56,7 +56,7 @@ class SegmentedLayer(interfaces.layers.TranslationLayerInterface, metaclass = AB
def is_valid(self, offset: int, length: int = 1) -> bool: def is_valid(self, offset: int, length: int = 1) -> bool:
"""Returns whether the address offset can be translated to a valid address""" """Returns whether the address offset can be translated to a valid address"""
try: try:
base_layer = self._context.memory[self._base_layer] base_layer = self._context.layers[self._base_layer]
return all( return all(
[base_layer.is_valid(mapped_offset) for _i, mapped_offset, _i, _s in self.mapping(offset, length)]) [base_layer.is_valid(mapped_offset) for _i, mapped_offset, _i, _s in self.mapping(offset, length)])
except exceptions.InvalidAddressException: except exceptions.InvalidAddressException:
@@ -72,7 +72,7 @@ class SegmentedLayer(interfaces.layers.TranslationLayerInterface, metaclass = AB
self._load_segments() self._load_segments()
# Find rightmost value less than or equal to x # Find rightmost value less than or equal to x
i = bisect_right(self._segments, (offset, self.context.memory[self._base_layer].maximum_address)) i = bisect_right(self._segments, (offset, self.context.layers[self._base_layer].maximum_address))
if i and not next: if i and not next:
segment = self._segments[i - 1] segment = self._segments[i - 1]
if segment[0] <= offset < segment[0] + segment[2]: if segment[0] <= offset < segment[0] + segment[2]:
+6 -6
View File
@@ -55,7 +55,7 @@ class VmwareLayer(segmented.SegmentedLayer):
if "vmware" not in self._context.symbol_space: if "vmware" not in self._context.symbol_space:
self._context.symbol_space.append(native.NativeTable("vmware", native.std_ctypes)) self._context.symbol_space.append(native.NativeTable("vmware", native.std_ctypes))
meta_layer = self.context.memory.get(self._meta_layer, None) meta_layer = self.context.layers.get(self._meta_layer, None)
header_size = struct.calcsize(self.header_structure) header_size = struct.calcsize(self.header_structure)
data = meta_layer.read(0, header_size) data = meta_layer.read(0, header_size)
magic, unknown, groupCount = struct.unpack(self.header_structure, data) magic, unknown, groupCount = struct.unpack(self.header_structure, data)
@@ -131,21 +131,21 @@ class VmwareStacker(interfaces.automagic.StackerLayerInterface):
layer_name: str, layer_name: str,
progress_callback: constants.ProgressCallback = None) -> Optional[interfaces.layers.DataLayerInterface]: progress_callback: constants.ProgressCallback = None) -> Optional[interfaces.layers.DataLayerInterface]:
"""Attempt to stack this based on the starting information""" """Attempt to stack this based on the starting information"""
memlayer = context.memory[layer_name] memlayer = context.layers[layer_name]
if not isinstance(memlayer, physical.FileLayer): if not isinstance(memlayer, physical.FileLayer):
return None return None
location = memlayer.location location = memlayer.location
if location.endswith(".vmem"): if location.endswith(".vmem"):
vmss = location[:-5] + ".vmss" vmss = location[:-5] + ".vmss"
vmsn = location[:-5] + ".vmsn" vmsn = location[:-5] + ".vmsn"
current_layer_name = context.memory.free_layer_name("VmwareMetaLayer") current_layer_name = context.layers.free_layer_name("VmwareMetaLayer")
current_config_path = interfaces.configuration.path_join("automagic", "layer_stacker", "stack", current_config_path = interfaces.configuration.path_join("automagic", "layer_stacker", "stack",
current_layer_name) current_layer_name)
try: try:
_ = resources.ResourceAccessor().open(vmss).read(10) _ = resources.ResourceAccessor().open(vmss).read(10)
context.config[interfaces.configuration.path_join(current_config_path, "location")] = vmss context.config[interfaces.configuration.path_join(current_config_path, "location")] = vmss
context.memory.add_layer(physical.FileLayer(context, current_config_path, current_layer_name)) context.layers.add_layer(physical.FileLayer(context, current_config_path, current_layer_name))
vmss_success = True vmss_success = True
except IOError: except IOError:
vmss_success = False vmss_success = False
@@ -154,14 +154,14 @@ class VmwareStacker(interfaces.automagic.StackerLayerInterface):
try: try:
_ = resources.ResourceAccessor().open(vmsn).read(10) _ = resources.ResourceAccessor().open(vmsn).read(10)
context.config[interfaces.configuration.path_join(current_config_path, "location")] = vmsn context.config[interfaces.configuration.path_join(current_config_path, "location")] = vmsn
context.memory.add_layer(physical.FileLayer(context, current_config_path, current_layer_name)) context.layers.add_layer(physical.FileLayer(context, current_config_path, current_layer_name))
vmsn_success = True vmsn_success = True
except IOError: except IOError:
vmsn_success = False vmsn_success = False
if not vmss_success and not vmsn_success: if not vmss_success and not vmsn_success:
return None return None
new_layer_name = context.memory.free_layer_name("VmwareLayer") new_layer_name = context.layers.free_layer_name("VmwareLayer")
context.config[interfaces.configuration.path_join(current_config_path, "base_layer")] = layer_name context.config[interfaces.configuration.path_join(current_config_path, "base_layer")] = layer_name
context.config[interfaces.configuration.path_join(current_config_path, "meta_layer")] = current_layer_name context.config[interfaces.configuration.path_join(current_config_path, "meta_layer")] = current_layer_name
new_layer = VmwareLayer(context, current_config_path, new_layer_name) new_layer = VmwareLayer(context, current_config_path, new_layer_name)
+8 -8
View File
@@ -143,7 +143,7 @@ class PrimitiveObject(interfaces.objects.ObjectInterface):
@classmethod @classmethod
def _unmarshall(cls, context: interfaces.context.ContextInterface, data_format: DataFormatInfo, def _unmarshall(cls, context: interfaces.context.ContextInterface, data_format: DataFormatInfo,
object_info: ObjectInformation) -> TUnion[int, float, bool, bytes, str]: object_info: ObjectInformation) -> TUnion[int, float, bool, bytes, str]:
data = context.memory.read(object_info.layer_name, object_info.offset, data_format.length) data = context.layers.read(object_info.layer_name, object_info.offset, data_format.length)
return convert_data_to_value(data, cls._struct_type, data_format) return convert_data_to_value(data, cls._struct_type, data_format)
class VolTemplateProxy(interfaces.objects.ObjectInterface.VolTemplateProxy): class VolTemplateProxy(interfaces.objects.ObjectInterface.VolTemplateProxy):
@@ -156,7 +156,7 @@ class PrimitiveObject(interfaces.objects.ObjectInterface):
def write(self, value: TUnion[int, float, bool, bytes, str]) -> None: def write(self, value: TUnion[int, float, bool, bytes, str]) -> None:
"""Writes the object into the layer of the context at the current offset""" """Writes the object into the layer of the context at the current offset"""
data = convert_value_to_data(value, self._struct_type, self._data_format) data = convert_value_to_data(value, self._struct_type, self._data_format)
return self._context.memory.write(self.vol.layer_name, self.vol.offset, data) return self._context.layers.write(self.vol.layer_name, self.vol.offset, data)
class Boolean(PrimitiveObject, int): class Boolean(PrimitiveObject, int):
@@ -285,8 +285,8 @@ class Pointer(Integer):
length, endian, signed = data_format length, endian, signed = data_format
if signed: if signed:
raise TypeError("Pointers cannot have signed values") raise TypeError("Pointers cannot have signed values")
mask = context.memory[object_info.native_layer_name].address_mask mask = context.layers[object_info.native_layer_name].address_mask
data = context.memory.read(object_info.layer_name, object_info.offset, length) data = context.layers.read(object_info.layer_name, object_info.offset, length)
value = int.from_bytes(data, byteorder = endian, signed = signed) value = int.from_bytes(data, byteorder = endian, signed = signed)
return value & mask return value & mask
@@ -297,7 +297,7 @@ class Pointer(Integer):
If layer_name is None, it defaults to the same layer that the pointer is currently instantiated in. If layer_name is None, it defaults to the same layer that the pointer is currently instantiated in.
""" """
layer_name = layer_name or self.vol.native_layer_name layer_name = layer_name or self.vol.native_layer_name
mask = self._context.memory[layer_name].address_mask mask = self._context.layers[layer_name].address_mask
offset = self & mask offset = self & mask
return self.vol.subtype( return self.vol.subtype(
context = self._context, context = self._context,
@@ -306,7 +306,7 @@ class Pointer(Integer):
def is_readable(self, layer_name: Optional[str] = None) -> bool: def is_readable(self, layer_name: Optional[str] = None) -> bool:
"""Determines whether the address of this pointer can be read from memory""" """Determines whether the address of this pointer can be read from memory"""
layer_name = layer_name or self.vol.layer_name layer_name = layer_name or self.vol.layer_name
return self._context.memory[layer_name].is_valid(self) return self._context.layers[layer_name].is_valid(self)
def __getattr__(self, attr: str) -> Any: def __getattr__(self, attr: str) -> Any:
"""Convenience function to access unknown attributes by getting them from the subtype object""" """Convenience function to access unknown attributes by getting them from the subtype object"""
@@ -547,7 +547,7 @@ class Array(interfaces.objects.ObjectInterface, abc.Sequence):
def __getitem__(self, i): def __getitem__(self, i):
"""Returns the i-th item from the array""" """Returns the i-th item from the array"""
result = [] # type: List[interfaces.objects.Template] result = [] # type: List[interfaces.objects.Template]
mask = self._context.memory[self.vol.layer_name].address_mask mask = self._context.layers[self.vol.layer_name].address_mask
# We use the range function to deal with slices for us # We use the range function to deal with slices for us
series = range(self.vol.count)[i] series = range(self.vol.count)[i]
return_list = True return_list = True
@@ -652,7 +652,7 @@ class Struct(interfaces.objects.ObjectInterface):
if attr in self._concrete_members: if attr in self._concrete_members:
return self._concrete_members[attr] return self._concrete_members[attr]
elif attr in self.vol.members: elif attr in self.vol.members:
mask = self._context.memory[self.vol.layer_name].address_mask mask = self._context.layers[self.vol.layer_name].address_mask
relative_offset, member = self.vol.members[attr] relative_offset, member = self.vol.members[attr]
member = member( member = member(
context = self._context, context = self._context,
+4 -4
View File
@@ -56,16 +56,16 @@ class LayerWriter(plugins.PluginInterface):
def _generator(self): def _generator(self):
if self.config.get('layer_name', None) is None: if self.config.get('layer_name', None) is None:
for layer_name in self.context.memory: for layer_name in self.context.layers:
yield 0, ("Layer '{}' available as '{}'".format(layer_name, yield 0, ("Layer '{}' available as '{}'".format(layer_name,
self.context.memory[layer_name].__class__.__name__), ) self.context.layers[layer_name].__class__.__name__), )
elif self.config['layer_name'] not in self.context.memory: elif self.config['layer_name'] not in self.context.layers:
yield 0, ('Layer Name does not exist', ) yield 0, ('Layer Name does not exist', )
elif os.path.exists(self.config.get('output', self.default_output_name)): elif os.path.exists(self.config.get('output', self.default_output_name)):
yield 0, ('Refusing to overwrite existing output file', ) yield 0, ('Refusing to overwrite existing output file', )
else: else:
chunk_size = self.config.get('block_size', self.default_block_size) chunk_size = self.config.get('block_size', self.default_block_size)
layer = self.context.memory[self.config['layer_name']] layer = self.context.layers[self.config['layer_name']]
try: try:
filedata = plugins.FileInterface(self.config.get('output', self.default_output_name)) filedata = plugins.FileInterface(self.config.get('output', self.default_output_name))
+1 -1
View File
@@ -69,7 +69,7 @@ class Bash(plugins.PluginInterface, timeliner.TimeLinerInterface):
if not proc_layer_name: if not proc_layer_name:
continue continue
proc_layer = self.context.memory[proc_layer_name] proc_layer = self.context.layers[proc_layer_name]
bang_addrs = [] bang_addrs = []
@@ -118,7 +118,7 @@ class Check_syscall(plugins.PluginInterface):
# if we can't find the disassemble function then bail and rely on a different method # if we can't find the disassemble function then bail and rely on a different method
return 0 return 0
data = self.context.memory.read(self.config['primary'], func_addr, 6) data = self.context.layers.read(self.config['primary'], func_addr, 6)
for (address, size, mnemonic, op_str) in md.disasm_lite(data, func_addr): for (address, size, mnemonic, op_str) in md.disasm_lite(data, func_addr):
if mnemonic == 'CMP': if mnemonic == 'CMP':
+1 -1
View File
@@ -48,7 +48,7 @@ class Elfs(plugins.PluginInterface):
if not proc_layer_name: if not proc_layer_name:
continue continue
proc_layer = self.context.memory[proc_layer_name] proc_layer = self.context.layers[proc_layer_name]
name = utility.array_to_string(task.comm) name = utility.array_to_string(task.comm)
@@ -50,7 +50,7 @@ class Malfind(interfaces_plugins.PluginInterface):
if not proc_layer_name: if not proc_layer_name:
return return
proc_layer = self.context.memory[proc_layer_name] proc_layer = self.context.layers[proc_layer_name]
for vma in task.mm.get_mmap_iter(): for vma in task.mm.get_mmap_iter():
if vma.is_suspicious() and vma.get_name(self.context, task) != "[vdso]": if vma.is_suspicious() and vma.get_name(self.context, task) != "[vdso]":
+1 -1
View File
@@ -69,7 +69,7 @@ class Bash(plugins.PluginInterface, timeliner.TimeLinerInterface):
if proc_layer_name == None: if proc_layer_name == None:
continue continue
proc_layer = self.context.memory[proc_layer_name] proc_layer = self.context.layers[proc_layer_name]
bang_addrs = [] bang_addrs = []
+1 -1
View File
@@ -48,7 +48,7 @@ class Malfind(interfaces_plugins.PluginInterface):
if proc_layer_name is None: if proc_layer_name is None:
return return
proc_layer = self.context.memory[proc_layer_name] proc_layer = self.context.layers[proc_layer_name]
for vma in task.get_map_iter(): for vma in task.get_map_iter():
if vma.is_suspicious(self.context, self.config['darwin']): if vma.is_suspicious(self.context, self.config['darwin']):
+1 -1
View File
@@ -44,7 +44,7 @@ class Psaux(plugins.PluginInterface):
if proc_layer_name is None: if proc_layer_name is None:
continue continue
proc_layer = self.context.memory[proc_layer_name] proc_layer = self.context.layers[proc_layer_name]
argsstart = task.user_stack - task.p_argslen argsstart = task.user_stack - task.p_argslen
@@ -58,7 +58,7 @@ class Check_syscall(plugins.PluginInterface):
subtype = kernel.get_type('mac_policy_list_element'), subtype = kernel.get_type('mac_policy_list_element'),
count = policy_list.staticmax + 1) count = policy_list.staticmax + 1)
mask = self.context.memory[self.config['primary']].address_mask mask = self.context.layers[self.config['primary']].address_mask
mods_list = [(mod.name, mod.address & mask, (mod.address & mask) + mod.size) for mod in mods] mods_list = [(mod.name, mod.address & mask, (mod.address & mask) + mod.size) for mod in mods]
for i, ent in enumerate(entries): for i, ent in enumerate(entries):
@@ -79,7 +79,7 @@ class Handles(interfaces_plugins.PluginInterface):
try: try:
# before windows 7 # before windows 7
if not self.context.memory[virtual].is_valid(handle_table_entry.Object): if not self.context.layers[virtual].is_valid(handle_table_entry.Object):
return None return None
fast_ref = handle_table_entry.Object.cast(self.config["nt_symbols"] + constants.BANG + "_EX_FAST_REF") fast_ref = handle_table_entry.Object.cast(self.config["nt_symbols"] + constants.BANG + "_EX_FAST_REF")
object_header = fast_ref.dereference().cast(self.config["nt_symbols"] + constants.BANG + "_OBJECT_HEADER") object_header = fast_ref.dereference().cast(self.config["nt_symbols"] + constants.BANG + "_OBJECT_HEADER")
@@ -116,7 +116,7 @@ class Handles(interfaces_plugins.PluginInterface):
return None return None
virtual_layer_name = self.config['primary'] virtual_layer_name = self.config['primary']
kvo = self.context.memory[virtual_layer_name].config['kernel_virtual_offset'] kvo = self.context.layers[virtual_layer_name].config['kernel_virtual_offset']
ntkrnlmp = self.context.module(self.config["nt_symbols"], layer_name = virtual_layer_name, offset = kvo) ntkrnlmp = self.context.module(self.config["nt_symbols"], layer_name = virtual_layer_name, offset = kvo)
try: try:
@@ -124,7 +124,7 @@ class Handles(interfaces_plugins.PluginInterface):
except exceptions.SymbolError: except exceptions.SymbolError:
return None return None
data = self.context.memory.read(virtual_layer_name, kvo + func_addr, 0x200) data = self.context.layers.read(virtual_layer_name, kvo + func_addr, 0x200)
if data == None: if data == None:
return None return None
@@ -153,7 +153,7 @@ class Handles(interfaces_plugins.PluginInterface):
type_map = {} type_map = {}
kvo = context.memory[layer_name].config['kernel_virtual_offset'] kvo = context.layers[layer_name].config['kernel_virtual_offset']
ntkrnlmp = context.module(symbol_table, layer_name = layer_name, offset = kvo) ntkrnlmp = context.module(symbol_table, layer_name = layer_name, offset = kvo)
try: try:
@@ -192,7 +192,7 @@ class Handles(interfaces_plugins.PluginInterface):
except exceptions.SymbolError: except exceptions.SymbolError:
return None return None
kvo = context.memory[layer_name].config['kernel_virtual_offset'] kvo = context.layers[layer_name].config['kernel_virtual_offset']
return context.object(symbol_table + constants.BANG + "unsigned int", layer_name, offset = kvo + offset) return context.object(symbol_table + constants.BANG + "unsigned int", layer_name, offset = kvo + offset)
def _make_handle_array(self, offset, level, depth = 0): def _make_handle_array(self, offset, level, depth = 0):
@@ -200,7 +200,7 @@ class Handles(interfaces_plugins.PluginInterface):
entries, going as deep into the table "levels" as necessary.""" entries, going as deep into the table "levels" as necessary."""
virtual = self.config["primary"] virtual = self.config["primary"]
kvo = self.context.memory[virtual].config['kernel_virtual_offset'] kvo = self.context.layers[virtual].config['kernel_virtual_offset']
ntkrnlmp = self.context.module(self.config["nt_symbols"], layer_name = virtual, offset = kvo) ntkrnlmp = self.context.module(self.config["nt_symbols"], layer_name = virtual, offset = kvo)
@@ -211,12 +211,12 @@ class Handles(interfaces_plugins.PluginInterface):
subtype = ntkrnlmp.get_type("_HANDLE_TABLE_ENTRY") subtype = ntkrnlmp.get_type("_HANDLE_TABLE_ENTRY")
count = 0x1000 / subtype.size count = 0x1000 / subtype.size
if not self.context.memory[virtual].is_valid(offset): if not self.context.layers[virtual].is_valid(offset):
return return
table = ntkrnlmp.object(type_name = "array", offset = offset, subtype = subtype, count = int(count)) table = ntkrnlmp.object(type_name = "array", offset = offset, subtype = subtype, count = int(count))
layer_object = self.context.memory[virtual] layer_object = self.context.layers[virtual]
masked_offset = (offset & layer_object.maximum_address) masked_offset = (offset & layer_object.maximum_address)
for entry in table: for entry in table:
+3 -3
View File
@@ -48,12 +48,12 @@ class Info(plugins.PluginInterface):
layer_name: the name of the starting layer layer_name: the name of the starting layer
index: the index/order of the layer index: the index/order of the layer
""" """
layer = self.context.memory[layer_name] layer = self.context.layers[layer_name]
yield index, layer yield index, layer
try: try:
for depends in layer.dependencies: for depends in layer.dependencies:
for j, dep in self.get_depends(depends, index + 1): for j, dep in self.get_depends(depends, index + 1):
yield j, self.context.memory[dep.name] yield j, self.context.layers[dep.name]
except AttributeError: except AttributeError:
# FileLayer won't have dependencies # FileLayer won't have dependencies
pass pass
@@ -61,7 +61,7 @@ class Info(plugins.PluginInterface):
def _generator(self): def _generator(self):
virtual_layer_name = self.config["primary"] virtual_layer_name = self.config["primary"]
virtual_layer = self.context.memory[virtual_layer_name] virtual_layer = self.context.layers[virtual_layer_name]
if not isinstance(virtual_layer, layers.intel.Intel): if not isinstance(virtual_layer, layers.intel.Intel):
raise TypeError("Virtual Layer is not an intel layer") raise TypeError("Virtual Layer is not an intel layer")
@@ -78,7 +78,7 @@ class Malfind(interfaces.plugins.PluginInterface):
""" """
proc_layer_name = proc.add_process_layer() proc_layer_name = proc.add_process_layer()
proc_layer = context.memory[proc_layer_name] proc_layer = context.layers[proc_layer_name]
for vad in proc.get_vad_root().traverse(): for vad in proc.get_vad_root().traverse():
protection_string = vad.get_protection( protection_string = vad.get_protection(
@@ -98,7 +98,7 @@ class ModDump(interfaces.plugins.PluginInterface):
""" """
for layer_name in session_layers: for layer_name in session_layers:
if context.memory[layer_name].is_valid(base_address): if context.layers[layer_name].is_valid(base_address):
return layer_name return layer_name
return None return None
@@ -63,7 +63,7 @@ class Modules(interfaces.plugins.PluginInterface):
def list_modules(cls, context: interfaces.context.ContextInterface, layer_name: str, symbol_table: str): def list_modules(cls, context: interfaces.context.ContextInterface, layer_name: str, symbol_table: str):
"""Lists all the modules in the primary layer""" """Lists all the modules in the primary layer"""
kvo = context.memory[layer_name].config['kernel_virtual_offset'] kvo = context.layers[layer_name].config['kernel_virtual_offset']
ntkrnlmp = context.module(symbol_table, layer_name = layer_name, offset = kvo) ntkrnlmp = context.module(symbol_table, layer_name = layer_name, offset = kvo)
try: try:
@@ -260,9 +260,9 @@ class PoolScanner(plugins.PluginInterface):
# registry hives # registry hives
PoolConstraint( PoolConstraint(
b'CM10', b'CM10',
type_name=symbol_table + constants.BANG + "_CMHIVE", type_name = symbol_table + constants.BANG + "_CMHIVE",
size=(800, None), size = (800, None),
page_type=PoolType.PAGED | PoolType.NONPAGED | PoolType.FREE), page_type = PoolType.PAGED | PoolType.NONPAGED | PoolType.FREE),
] ]
if not tags_filter: if not tags_filter:
@@ -292,7 +292,7 @@ class PoolScanner(plugins.PluginInterface):
# switch to a non-virtual layer if necessary # switch to a non-virtual layer if necessary
if not is_windows_10: if not is_windows_10:
scan_layer = context.memory[scan_layer].config['memory_layer'] scan_layer = context.layers[scan_layer].config['memory_layer']
for constraint, header in cls.pool_scan(context, scan_layer, symbol_table, constraints, alignment = 8): for constraint, header in cls.pool_scan(context, scan_layer, symbol_table, constraints, alignment = 8):
@@ -355,7 +355,7 @@ class PoolScanner(plugins.PluginInterface):
header_offset = header_type.relative_child_offset('PoolTag') header_offset = header_type.relative_child_offset('PoolTag')
# Run the scan locating the offsets of a particular tag # Run the scan locating the offsets of a particular tag
layer = context.memory[layer_name] layer = context.layers[layer_name]
scanner = scanners.MultiStringScanner([c for c in constraint_lookup.keys()]) scanner = scanners.MultiStringScanner([c for c in constraint_lookup.keys()])
for offset, pattern in layer.scan(context, scanner, progress_callback = progress_callback): for offset, pattern in layer.scan(context, scanner, progress_callback = progress_callback):
for constraint in constraint_lookup[pattern]: for constraint in constraint_lookup[pattern]:
@@ -72,7 +72,7 @@ class PsList(plugins.PluginInterface, timeliner.TimeLinerInterface):
"""Lists all the processes in the primary layer that are in the pid config option""" """Lists all the processes in the primary layer that are in the pid config option"""
# We only use the object factory to demonstrate how to use one # We only use the object factory to demonstrate how to use one
kvo = context.memory[layer_name].config['kernel_virtual_offset'] kvo = context.layers[layer_name].config['kernel_virtual_offset']
ntkrnlmp = context.module(symbol_table, layer_name = layer_name, offset = kvo) ntkrnlmp = context.module(symbol_table, layer_name = layer_name, offset = kvo)
ps_aph_offset = ntkrnlmp.get_symbol("PsActiveProcessHead").address ps_aph_offset = ntkrnlmp.get_symbol("PsActiveProcessHead").address
@@ -108,7 +108,7 @@ class PsList(plugins.PluginInterface, timeliner.TimeLinerInterface):
offset = proc.vol.offset offset = proc.vol.offset
else: else:
layer_name = self.config['primary'] layer_name = self.config['primary']
memory = self.context.memory[layer_name] memory = self.context.layers[layer_name]
if not isinstance(memory, layers.intel.Intel): if not isinstance(memory, layers.intel.Intel):
raise TypeError("Primary layer is not an intel layer") raise TypeError("Primary layer is not an intel layer")
(_, offset, _, _) = list(memory.mapping(offset = proc.vol.offset, length = 0))[0] (_, offset, _, _) = list(memory.mapping(offset = proc.vol.offset, length = 0))[0]
@@ -56,7 +56,7 @@ class PsTree(pslist.PsList):
offset = proc.vol.offset offset = proc.vol.offset
else: else:
layer_name = self.config['primary'] layer_name = self.config['primary']
memory = self.context.memory[layer_name] memory = self.context.layers[layer_name]
(_, offset, _, _) = list(memory.mapping(offset = proc.vol.offset, length = 0))[0] (_, offset, _, _) = list(memory.mapping(offset = proc.vol.offset, length = 0))[0]
self._processes[proc.UniqueProcessId] = proc self._processes[proc.UniqueProcessId] = proc
@@ -59,7 +59,7 @@ class HiveList(plugins.PluginInterface):
"""Lists all the hives in the primary layer""" """Lists all the hives in the primary layer"""
# We only use the object factory to demonstrate how to use one # We only use the object factory to demonstrate how to use one
kvo = context.memory[layer_name].config['kernel_virtual_offset'] kvo = context.layers[layer_name].config['kernel_virtual_offset']
ntkrnlmp = context.module(symbol_table, layer_name = layer_name, offset = kvo) ntkrnlmp = context.module(symbol_table, layer_name = layer_name, offset = kvo)
list_head = ntkrnlmp.get_symbol("CmpHiveListHead").address list_head = ntkrnlmp.get_symbol("CmpHiveListHead").address
@@ -98,7 +98,7 @@ class PrintKey(interfaces.plugins.PluginInterface):
hive_offset = hive_offset, base_layer = self.config['primary'], nt_symbols = self.config['nt_symbols']) hive_offset = hive_offset, base_layer = self.config['primary'], nt_symbols = self.config['nt_symbols'])
hive = RegistryHive(self.context, reg_config_path, name = 'hive' + hex(hive_offset)) hive = RegistryHive(self.context, reg_config_path, name = 'hive' + hex(hive_offset))
try: try:
self.context.memory.add_layer(hive) self.context.layers.add_layer(hive)
# Walk it # Walk it
if 'key' in self.config: if 'key' in self.config:
@@ -82,7 +82,7 @@ class UserAssist(interfaces.plugins.PluginInterface):
if len(userassist_data) < self._userassist_size: if len(userassist_data) < self._userassist_size:
return item return item
userassist_layer_name = self.context.memory.free_layer_name("userassist_buffer") userassist_layer_name = self.context.layers.free_layer_name("userassist_buffer")
buffer = BufferDataLayer(self.context, self._config_path, userassist_layer_name, userassist_data) buffer = BufferDataLayer(self.context, self._config_path, userassist_layer_name, userassist_data)
self.context.add_layer(buffer) self.context.add_layer(buffer)
userassist_obj = self.context.object( userassist_obj = self.context.object(
@@ -247,7 +247,7 @@ class UserAssist(interfaces.plugins.PluginInterface):
try: try:
hive = RegistryHive(self.context, reg_config_path, name = 'hive' + hex(hive_offset)) hive = RegistryHive(self.context, reg_config_path, name = 'hive' + hex(hive_offset))
hive_name = hive.hive.cast(self.config["nt_symbols"] + constants.BANG + "_CMHIVE").get_name() hive_name = hive.hive.cast(self.config["nt_symbols"] + constants.BANG + "_CMHIVE").get_name()
self.context.memory.add_layer(hive) self.context.layers.add_layer(hive)
yield from self.list_userassist(hive) yield from self.list_userassist(hive)
continue continue
except exceptions.PagedInvalidAddressException as excp: except exceptions.PagedInvalidAddressException as excp:
+1 -1
View File
@@ -77,7 +77,7 @@ class SSDT(plugins.PluginInterface):
layer_name = self.config['primary'] layer_name = self.config['primary']
collection = self.build_module_collection(self.context, self.config["primary"], self.config["nt_symbols"]) collection = self.build_module_collection(self.context, self.config["primary"], self.config["nt_symbols"])
kvo = self.context.memory[layer_name].config['kernel_virtual_offset'] kvo = self.context.layers[layer_name].config['kernel_virtual_offset']
ntkrnlmp = self.context.module(self.config["nt_symbols"], layer_name = layer_name, offset = kvo) ntkrnlmp = self.context.module(self.config["nt_symbols"], layer_name = layer_name, offset = kvo)
# this is just one way to enumerate the native (NT) service table. # this is just one way to enumerate the native (NT) service table.
@@ -78,7 +78,7 @@ class Strings(interfaces.plugins.PluginInterface):
def generate_mapping(self, layer_name: str) -> Dict[int, Set[Tuple[str, int]]]: def generate_mapping(self, layer_name: str) -> Dict[int, Set[Tuple[str, int]]]:
"""Creates a reverse mapping between virtual addresses and physical addresses""" """Creates a reverse mapping between virtual addresses and physical addresses"""
layer = self._context.memory[layer_name] layer = self._context.layers[layer_name]
reverse_map = dict() # type: Dict[int, Set[Tuple[str, int]]] reverse_map = dict() # type: Dict[int, Set[Tuple[str, int]]]
if isinstance(layer, intel.Intel): if isinstance(layer, intel.Intel):
# We don't care about errors, we just wanted chunks that map correctly # We don't care about errors, we just wanted chunks that map correctly
@@ -95,7 +95,7 @@ class Strings(interfaces.plugins.PluginInterface):
for process in pslist.PsList.list_processes(self.context, self.config['primary'], for process in pslist.PsList.list_processes(self.context, self.config['primary'],
self.config['nt_symbols']): self.config['nt_symbols']):
proc_layer_name = process.add_process_layer() proc_layer_name = process.add_process_layer()
proc_layer = self.context.memory[proc_layer_name] proc_layer = self.context.layers[proc_layer_name]
if isinstance(proc_layer, interfaces.layers.TranslationLayerInterface): if isinstance(proc_layer, interfaces.layers.TranslationLayerInterface):
for mapval in proc_layer.mapping(0x0, proc_layer.maximum_address, ignore_errors = True): for mapval in proc_layer.mapping(0x0, proc_layer.maximum_address, ignore_errors = True):
kpage, vpage, page_size, maplayer = mapval kpage, vpage, page_size, maplayer = mapval
@@ -62,7 +62,7 @@ class VadDump(interfaces_plugins.PluginInterface):
# TODO: what kind of exceptions could this raise and what should we do? # TODO: what kind of exceptions could this raise and what should we do?
proc_layer_name = proc.add_process_layer() proc_layer_name = proc.add_process_layer()
proc_layer = self.context.memory[proc_layer_name] proc_layer = self.context.layers[proc_layer_name]
for vad in vadinfo.VadInfo.list_vads(proc, filter_func = filter_func): for vad in vadinfo.VadInfo.list_vads(proc, filter_func = filter_func):
try: try:
@@ -75,7 +75,7 @@ class VadInfo(interfaces.plugins.PluginInterface):
These don't change often, but if they do in the future, then finding them These don't change often, but if they do in the future, then finding them
# dynamically versus hard-coding here will ensure we parse them properly.""" # dynamically versus hard-coding here will ensure we parse them properly."""
kvo = context.memory[virtual_layer].config["kernel_virtual_offset"] kvo = context.layers[virtual_layer].config["kernel_virtual_offset"]
ntkrnlmp = context.module(nt_symbols, layer_name = virtual_layer, offset = kvo) ntkrnlmp = context.module(nt_symbols, layer_name = virtual_layer, offset = kvo)
addr = ntkrnlmp.get_symbol("MmProtectToValue").address addr = ntkrnlmp.get_symbol("MmProtectToValue").address
values = ntkrnlmp.object( values = ntkrnlmp.object(
@@ -58,7 +58,7 @@ class VadYaraScan(interfaces.plugins.PluginInterface):
def _generator(self): def _generator(self):
layer = self.context.memory[self.config['primary']] layer = self.context.layers[self.config['primary']]
rules = None rules = None
if self.config.get('yara_rules', None) is not None: if self.config.get('yara_rules', None) is not None:
rule = self.config['yara_rules'] rule = self.config['yara_rules']
+1 -1
View File
@@ -80,7 +80,7 @@ class YaraScan(plugins.PluginInterface):
def _generator(self): def _generator(self):
layer = self.context.memory[self.config['primary']] layer = self.context.layers[self.config['primary']]
rules = None rules = None
if self.config.get('yara_rules', None) is not None: if self.config.get('yara_rules', None) is not None:
rule = self.config['yara_rules'] rule = self.config['yara_rules']
@@ -42,13 +42,13 @@ class GenericIntelProcess(objects.Struct):
# Figure out a suitable name we can use for the new layer # Figure out a suitable name we can use for the new layer
if preferred_name is None: if preferred_name is None:
preferred_name = context.memory.free_layer_name(prefix = self.vol.layer_name + "_Process_") preferred_name = context.layers.free_layer_name(prefix = self.vol.layer_name + "_Process_")
else: else:
if preferred_name in context.memory: if preferred_name in context.layers:
preferred_name = context.memory.free_layer_name(prefix = preferred_name) preferred_name = context.layers.free_layer_name(prefix = preferred_name)
# Copy the parent's config and then make suitable changes # Copy the parent's config and then make suitable changes
parent_layer = context.memory[self.vol.layer_name] parent_layer = context.layers[self.vol.layer_name]
parent_config = parent_layer.build_configuration() parent_config = parent_layer.build_configuration()
# It's an intel layer, because we hardwire the "memory_layer" config option # It's an intel layer, because we hardwire the "memory_layer" config option
# FIXME: this could be for other architectures if we don't hardwire this/these values # FIXME: this could be for other architectures if we don't hardwire this/these values
@@ -61,5 +61,5 @@ class GenericIntelProcess(objects.Struct):
new_layer = parent_layer.__class__(context, config_path = config_path, name = preferred_name) new_layer = parent_layer.__class__(context, config_path = config_path, name = preferred_name)
# Add the constructed layer and return the name # Add the constructed layer and return the name
context.memory.add_layer(new_layer) context.layers.add_layer(new_layer)
return preferred_name return preferred_name
@@ -61,7 +61,7 @@ class task_struct(generic.GenericIntelProcess):
Returns the name of the Layer or None. Returns the name of the Layer or None.
""" """
parent_layer = self._context.memory[self.vol.layer_name] parent_layer = self._context.layers[self.vol.layer_name]
try: try:
pgd = self.mm.pgd pgd = self.mm.pgd
except exceptions.PagedInvalidAddressException: except exceptions.PagedInvalidAddressException:
@@ -36,7 +36,7 @@ class proc(generic.GenericIntelProcess):
"""Constructs a new layer based on the process's DTB. """Constructs a new layer based on the process's DTB.
Returns the name of the Layer or None. Returns the name of the Layer or None.
""" """
parent_layer = self._context.memory[self.vol.layer_name] parent_layer = self._context.layers[self.vol.layer_name]
if not isinstance(parent_layer, interfaces.layers.TranslationLayerInterface): if not isinstance(parent_layer, interfaces.layers.TranslationLayerInterface):
raise TypeError("Parent layer is not a translation layer, unable to construct process layer") raise TypeError("Parent layer is not a translation layer, unable to construct process layer")
@@ -472,12 +472,12 @@ class _FILE_OBJECT(objects.Struct, ExecutiveObject):
def is_valid(self) -> bool: def is_valid(self) -> bool:
"""Determine if the object is valid""" """Determine if the object is valid"""
return self.FileName.Length > 0 and self._context.memory[self.vol.layer_name].is_valid(self.FileName.Buffer) return self.FileName.Length > 0 and self._context.layers[self.vol.layer_name].is_valid(self.FileName.Buffer)
def file_name_with_device(self) -> Union[str, interfaces.renderers.BaseAbsentValue]: def file_name_with_device(self) -> Union[str, interfaces.renderers.BaseAbsentValue]:
name = renderers.UnreadableValue() # type: Union[str, interfaces.renderers.BaseAbsentValue] name = renderers.UnreadableValue() # type: Union[str, interfaces.renderers.BaseAbsentValue]
if self._context.memory[self.vol.layer_name].is_valid(self.DeviceObject): if self._context.layers[self.vol.layer_name].is_valid(self.DeviceObject):
name = "\\Device\\{}".format(self.DeviceObject.get_device_name()) name = "\\Device\\{}".format(self.DeviceObject.get_device_name())
try: try:
@@ -550,7 +550,7 @@ class _OBJECT_HEADER(objects.Struct):
# http://codemachine.com/article_objectheader.html (Windows 7 and later) # http://codemachine.com/article_objectheader.html (Windows 7 and later)
name_info_bit = 0x2 name_info_bit = 0x2
layer = self._context.memory[self.vol.native_layer_name] layer = self._context.layers[self.vol.native_layer_name]
kvo = layer.config.get("kernel_virtual_offset", None) kvo = layer.config.get("kernel_virtual_offset", None)
if kvo == None: if kvo == None:
@@ -638,7 +638,7 @@ class _EPROCESS(generic.GenericIntelProcess, ExecutiveObject):
def add_process_layer(self, config_prefix: str = None, preferred_name: str = None): def add_process_layer(self, config_prefix: str = None, preferred_name: str = None):
"""Constructs a new layer based on the process's DirectoryTableBase""" """Constructs a new layer based on the process's DirectoryTableBase"""
parent_layer = self._context.memory[self.vol.layer_name] parent_layer = self._context.layers[self.vol.layer_name]
if not isinstance(parent_layer, intel.Intel): if not isinstance(parent_layer, intel.Intel):
# We can't get bits_per_register unless we're an intel space (since that's not defined at the higher layer) # We can't get bits_per_register unless we're an intel space (since that's not defined at the higher layer)
@@ -663,7 +663,7 @@ class _EPROCESS(generic.GenericIntelProcess, ExecutiveObject):
proc_layer_name = self.add_process_layer() proc_layer_name = self.add_process_layer()
proc_layer = self._context.memory[proc_layer_name] proc_layer = self._context.layers[proc_layer_name]
if not proc_layer.is_valid(self.Peb): if not proc_layer.is_valid(self.Peb):
return return
@@ -694,7 +694,7 @@ class _EPROCESS(generic.GenericIntelProcess, ExecutiveObject):
return renderers.NotApplicableValue() return renderers.NotApplicableValue()
symbol_table_name = self.get_symbol_table().name symbol_table_name = self.get_symbol_table().name
kvo = self._context.memory[self.vol.native_layer_name].config['kernel_virtual_offset'] kvo = self._context.layers[self.vol.native_layer_name].config['kernel_virtual_offset']
ntkrnlmp = self._context.module( ntkrnlmp = self._context.module(
symbol_table_name, symbol_table_name,
layer_name = self.vol.native_layer_name, layer_name = self.vol.native_layer_name,
@@ -119,7 +119,7 @@ class _IMAGE_DOS_HEADER(objects.Struct):
if size_of_image > (1024 * 1024 * 100): if size_of_image > (1024 * 1024 * 100):
raise ValueError("The claimed SizeOfImage is too large: {}".format(size_of_image)) raise ValueError("The claimed SizeOfImage is too large: {}".format(size_of_image))
read_layer = self._context.memory[layer_name] read_layer = self._context.layers[layer_name]
raw_data = read_layer.read(self.vol.offset, nt_header.OptionalHeader.SizeOfImage, pad = True) raw_data = read_layer.read(self.vol.offset, nt_header.OptionalHeader.SizeOfImage, pad = True)
@@ -140,13 +140,13 @@ class _CM_KEY_NODE(objects.Struct):
"""Extension to allow traversal of registry keys""" """Extension to allow traversal of registry keys"""
def get_volatile(self) -> bool: def get_volatile(self) -> bool:
if not isinstance(self._context.memory[self.vol.layer_name], RegistryHive): if not isinstance(self._context.layers[self.vol.layer_name], RegistryHive):
raise ValueError("Cannot determine volatility of registry key without an offset in a RegistryHive layer") raise ValueError("Cannot determine volatility of registry key without an offset in a RegistryHive layer")
return bool(self.vol.offset & 0x80000000) return bool(self.vol.offset & 0x80000000)
def get_subkeys(self) -> Iterable[interfaces.objects.ObjectInterface]: def get_subkeys(self) -> Iterable[interfaces.objects.ObjectInterface]:
"""Returns a list of the key nodes""" """Returns a list of the key nodes"""
hive = self._context.memory[self.vol.layer_name] hive = self._context.layers[self.vol.layer_name]
if not isinstance(hive, RegistryHive): if not isinstance(hive, RegistryHive):
raise TypeError("CM_KEY_NODE was not instantiated on a RegistryHive layer") raise TypeError("CM_KEY_NODE was not instantiated on a RegistryHive layer")
for index in range(2): for index in range(2):
@@ -184,7 +184,7 @@ class _CM_KEY_NODE(objects.Struct):
def get_values(self) -> Iterable[interfaces.objects.ObjectInterface]: def get_values(self) -> Iterable[interfaces.objects.ObjectInterface]:
"""Returns a list of the Value nodes for a key""" """Returns a list of the Value nodes for a key"""
hive = self._context.memory[self.vol.layer_name] hive = self._context.layers[self.vol.layer_name]
if not isinstance(hive, RegistryHive): if not isinstance(hive, RegistryHive):
raise TypeError("CM_KEY_NODE was not instantiated on a RegistryHive layer") raise TypeError("CM_KEY_NODE was not instantiated on a RegistryHive layer")
child_list = hive.get_cell(self.ValueList.List).u.KeyList child_list = hive.get_cell(self.ValueList.List).u.KeyList
@@ -200,7 +200,7 @@ class _CM_KEY_NODE(objects.Struct):
return self.Name.cast("string", max_length = self.NameLength, encoding = "latin-1") return self.Name.cast("string", max_length = self.NameLength, encoding = "latin-1")
def get_key_path(self) -> interfaces.objects.ObjectInterface: def get_key_path(self) -> interfaces.objects.ObjectInterface:
reg = self._context.memory[self.vol.layer_name] reg = self._context.layers[self.vol.layer_name]
if not isinstance(reg, RegistryHive): if not isinstance(reg, RegistryHive):
raise TypeError("Key was not instantiated on a RegistryHive layer") raise TypeError("Key was not instantiated on a RegistryHive layer")
# Using the offset adds a significant delay (since it cannot be cached easily) # Using the offset adds a significant delay (since it cannot be cached easily)
@@ -224,7 +224,7 @@ class _CM_KEY_VALUE(objects.Struct):
datalen = self.DataLength & 0x7fffffff datalen = self.DataLength & 0x7fffffff
data = b"" data = b""
# Check if the data is stored inline # Check if the data is stored inline
layer = self._context.memory[self.vol.layer_name] layer = self._context.layers[self.vol.layer_name]
if not isinstance(layer, RegistryHive): if not isinstance(layer, RegistryHive):
raise TypeError("Key value was not instantiated on a RegistryHive layer") raise TypeError("Key value was not instantiated on a RegistryHive layer")
+1 -1
View File
@@ -37,7 +37,7 @@ class Statistics(plugins.PluginInterface):
def _generator(self): def _generator(self):
# Do mass mapping and determine the number of different layers and how many pages go to each one # Do mass mapping and determine the number of different layers and how many pages go to each one
layer = self.context.memory[self.config['primary']] layer = self.context.layers[self.config['primary']]
page_count = swap_count = invalid_page_count = large_page_count = large_swap_count = large_invalid_count = 0 page_count = swap_count = invalid_page_count = large_page_count = large_swap_count = large_invalid_count = 0