Tidy up several areas using PyCharm corrections.

This commit is contained in:
Mike Auty
2014-03-30 00:46:31 +00:00
parent 1a555140eb
commit 89e7e6e7ff
12 changed files with 90 additions and 50 deletions
+8
View File
@@ -0,0 +1,8 @@
<component name="ProjectDictionaryState">
<dictionary name="mike">
<words>
<w>iter</w>
<w>struct</w>
</words>
</dictionary>
</component>
+5 -2
View File
@@ -23,10 +23,13 @@ def require_version(*args):
"""Checks the required version of a plugin"""
if len(args):
if args[0] != version()[0]:
raise Exception("Framework version " + str(version()[0]) + " is incompatible with required version " + str(args[0]))
raise Exception("Framework version " + str(version()[0]) +
" is incompatible with required version " + str(args[0]))
if len(args) > 1:
if args[1] > version()[1]:
raise Exception("Framework version " + ".".join([str(x) for x in version()[0:1]]) + " is an older revision than the required version " + ".".join([str(x) for x in args[0:2]]))
raise Exception("Framework version " + ".".join([str(x) for x in version()[0:1]]) +
" is an older revision than the required version " +
".".join([str(x) for x in args[0:2]]))
from volatility.framework import interfaces, symbols, layers
+2 -2
View File
@@ -1,8 +1,8 @@
'''
"""
Created on 1 Dec 2012
@author: mike
'''
"""
class VolatilityException(Exception):
"""Class to allow filtering of all VolatilityExceptions"""
+1 -1
View File
@@ -7,4 +7,4 @@ Created on 12 Apr 2013
# Import the submodules we want people to be able to use without importing them themselves
# This will also avoid namespace issues, because people can use interfaces.layers to
# avoid clashing with the layers package
from volatility.framework.interfaces import layers, symbols, context, objects
from volatility.framework.interfaces import layers, symbols, context, objects, plugins
@@ -61,8 +61,10 @@ class TranslationLayerInterface(DataLayerInterface):
"""
return []
@property
def dependencies(self):
"""Returns a list of layer names that this layer translates onto"""
raise NotImplementedError("Abstract method dependencies")
### Read/Write functions for mapped pages
+3 -1
View File
@@ -20,9 +20,11 @@ class TreeRow(validity.ValidityRoutines):
def add_child(self, child):
"""Appends a child to the current Row"""
raise NotImplementedError("Abstract method add_child not implemented.")
def insert_child(self, child, position):
"""Adds a child at the specified position"""
raise NotImplementedError("Abstract method insert_child not implemented")
def clear(self):
"""Removes all children from this row"""
@@ -64,4 +66,4 @@ class TreeGrid(TreeRow):
"""Takes a list of values and verified them against the column types"""
for i in range(len(self._columns)):
if not isinstance(values[i], self._columns[i]):
raise TypeError("Column ")
raise TypeError("Column type " + str(i) + " is incorrect.")
+10 -2
View File
@@ -1,8 +1,8 @@
'''
"""
Created on 4 May 2013
@author: mike
'''
"""
from volatility.framework import validity, exceptions
@@ -20,10 +20,12 @@ class SymbolTableInterface(validity.ValidityRoutines):
If the symbol isn't found, it raises a SymbolError exception
"""
raise NotImplementedError("Abstract property get_constant not implemented by subclass.")
@ property
def constants(self):
"""Returns an iterator of the constant symbols"""
raise NotImplementedError("Abstract property constants not implemented by subclass.")
### Required Structure symbol functions
@@ -32,10 +34,12 @@ class SymbolTableInterface(validity.ValidityRoutines):
If the symbol isn't found it raises a SymbolError exception
"""
raise NotImplementedError("Abstract method get_structure not implemented by subclass.")
@property
def structures(self):
"""Returns an iterator of the structure symbols"""
raise NotImplementedError("Abstract property structures not implemented by subclass.")
### Native Type Handler
@@ -51,12 +55,15 @@ class SymbolTableInterface(validity.ValidityRoutines):
Name *must* be present in self.structures
"""
raise NotImplementedError("Abstract method set_structure_class not implemented yet.")
def get_structure_class(self, name):
"""Returns the class associated with a structure symbol"""
raise NotImplementedError("Abstract method get_structure_class not implemented yet.")
def del_structure_class(self, name):
"""Removes the associated class override for a specific structure symbol"""
raise NotImplementedError("Abstract method del_structure_class not implemented yet.")
# ### Helper functions that can be overridden
#
@@ -82,6 +89,7 @@ class SymbolTableInterface(validity.ValidityRoutines):
class NativeTableInterface(SymbolTableInterface):
"""Class to distinguish NativeSymbolLists from other symbol lists"""
@staticmethod
def constant(self):
raise exceptions.SymbolError("NativeTables never hold constants")
+6 -4
View File
@@ -1,8 +1,8 @@
'''
"""
Created on 4 May 2013
@author: mike
'''
"""
from volatility.framework import validity, interfaces, exceptions
from volatility.framework.layers import physical, intel
@@ -35,7 +35,8 @@ class Memory(validity.ValidityRoutines):
raise exceptions.LayerException("")
missing_list = [sublayer for sublayer in layer.dependencies if sublayer not in self._layers]
if missing_list:
raise exceptions.LayerException("Layer " + layer.name + " has unmet dependencies of " + ", ".join(missing_list))
raise exceptions.LayerException("Layer " + layer.name +
" has unmet dependencies of " + ", ".join(missing_list))
self._layers[layer.name] = layer
def del_layer(self, name):
@@ -46,7 +47,8 @@ class Memory(validity.ValidityRoutines):
for layer in self._layers:
depend_list = [superlayer for superlayer in self._layers if name in superlayer.dependencies]
if depend_list:
raise exceptions.LayerException("Layer " + layer.name + " is depended upon by " + ", ".join(depend_list))
raise exceptions.LayerException("Layer " + layer.name +
" is depended upon by " + ", ".join(depend_list))
del self._layers[name]
def __getitem__(self, name):
+12 -9
View File
@@ -1,8 +1,8 @@
'''
"""
Created on 7 May 2013
@author: mike
'''
"""
import math
import struct
@@ -27,18 +27,19 @@ class Intel(interfaces.layers.TranslationLayerInterface):
self._structure = [('page directory', 10, False),
('page table', 10, True)]
def _mask(self, value, high_bit, low_bit):
@staticmethod
def _mask(value, high_bit, low_bit):
"""Returns the bits of a value between highbit and lowbit inclusive"""
high_mask = (2 ** (high_bit + 1)) - 1
low_mask = (2 ** (low_bit)) - 1
low_mask = (2 ** low_bit) - 1
mask = (high_mask ^ low_mask)
# print(high_bit, low_bit, bin(mask), bin(value))
return value & mask
def _page_is_valid(self, entry):
@staticmethod
def _page_is_valid(entry):
"""Returns whether a particular page is valid based on its entry"""
return (entry & 1)
return entry & 1
def _translate(self, offset):
"""Translates a specific offset based on paging tables
@@ -71,7 +72,8 @@ class Intel(interfaces.layers.TranslationLayerInterface):
# Create the offset for the next entry
table_offset = base_address | (index << self._index_shift)
# Read out the new entry from memory
entry, = struct.unpack(self._entry_format, self._context.memory.read(self._base_layer, table_offset, struct.calcsize(self._entry_format)))
entry, = struct.unpack(self._entry_format, self._context.memory.read(self._base_layer, table_offset,
struct.calcsize(self._entry_format)))
# Now we're do
if not self._page_is_valid(entry):
@@ -132,7 +134,8 @@ class Intel32e(Intel):
class WindowsMixin(object):
def _page_is_valid(self, entry):
@staticmethod
def _page_is_valid(entry):
"""Returns whether a particular page is valid based on its entry
Windows uses additional "available" bits to store flags
+7 -6
View File
@@ -1,8 +1,8 @@
'''
"""
Created on 6 May 2013
@author: mike
'''
"""
import os.path
from volatility.framework import interfaces, exceptions
@@ -26,7 +26,7 @@ class BufferDataLayer(interfaces.layers.DataLayerInterface):
def is_valid(self, offset):
"""Returns whether the offset is valid or not"""
return offset >= self.minimum_address and offset <= self.maximum_address
return self.minimum_address <= offset <= self.maximum_address
def read(self, address, length, pad = False):
"""Reads the data from the buffer"""
@@ -59,7 +59,7 @@ class FileLayer(interfaces.layers.DataLayerInterface):
def is_valid(self, offset):
"""Returns whether the offset is valid or not"""
return (offset >= self.minimum_address and offset <= self.maximum_address)
return self.minimum_address <= offset <= self.maximum_address
def read(self, offset, length, pad = False):
"""Reads from the file at offset for length"""
@@ -75,13 +75,14 @@ class FileLayer(interfaces.layers.DataLayerInterface):
if pad:
data += (b"\x00" * (length - len(data)))
else:
raise exceptions.InvalidAddressException("Could not read sufficient bytes from the " + self.name + " file")
raise exceptions.InvalidAddressException("Could not read sufficient bytes from the " +
self.name + " file")
return data
def write(self, offset, data):
"""Writes to the file
This will tehcnically allow writes beyond the extent of the file
This will technically allow writes beyond the extent of the file
"""
if not self.is_valid(offset):
raise exceptions.InvalidAddressException("Offset outside of the " + self.name + " file boundaries")
+22 -15
View File
@@ -1,8 +1,8 @@
'''
"""
Created on 17 Feb 2013
@author: mike
'''
"""
import struct
import collections
@@ -88,9 +88,10 @@ class Float(PrimitiveObject, float):
class Bytes(PrimitiveObject, bytes):
"""Primitive Object that handles specific series of bytes"""
def __init__(self, context, layer_name, offset, structure_name, size = None, parent = None, length = 1, **kwargs):
def __init__(self, context, layer_name, offset, structure_name, size = None, parent = None, length = 1):
bytes.__init__(self)
PrimitiveObject.__init__(self, context, layer_name, offset, structure_name, size, parent, struct_format = str(length) + 's')
PrimitiveObject.__init__(self, context, layer_name, offset, structure_name,
size, parent, struct_format = str(length) + 's')
self.length = length
def __new__(cls, context, layer_name, offset, structure_name, length = 1, **kwargs):
@@ -109,9 +110,10 @@ class String(PrimitiveObject, str):
length: specifies the maximum possible length that the string could hold in memory
"""
def __init__(self, context, layer_name, offset, structure_name, size = None, parent = None, length = 1, **kwargs):
def __init__(self, context, layer_name, offset, structure_name, size = None, parent = None, length = 1):
str.__init__(self)
PrimitiveObject.__init__(self, context, layer_name, offset, structure_name, size, parent, struct_format = str(length) + 's')
PrimitiveObject.__init__(self, context, layer_name, offset, structure_name,
size, parent, struct_format = str(length) + 's')
self.length = length
def __new__(cls, context, layer_name, offset, structure_name, length = 1, **kwargs):
@@ -126,7 +128,8 @@ class String(PrimitiveObject, str):
class Pointer(Integer):
"""Pointer which points to another object"""
def __init__(self, context, layer_name, offset, structure_name, size = None, parent = None, struct_format = None, target = None):
def __init__(self, context, layer_name, offset, structure_name, size = None,
parent = None, struct_format = None, target = None):
if not isinstance(target, templates.ObjectTemplate):
raise TypeError("Pointer targets must be an ObjectTemplate")
Integer.__init__(self,
@@ -169,7 +172,8 @@ class Pointer(Integer):
class BitField(PrimitiveObject, int):
"""Object containing a field which is made up of bits rather than whole bytes"""
def __new__(cls, context, layer_name, offset, structure_name, size = None, parent = None, target = None, start_bit = 0, end_bit = 0, **kwargs):
def __new__(cls, context, layer_name, offset, structure_name, size = None,
parent = None, target = None, start_bit = 0, end_bit = 0, **kwargs):
value = target(context = context,
layer_name = layer_name,
offset = offset,
@@ -200,7 +204,8 @@ class Enumeration(interfaces.objects.ObjectInterface):
class Array(interfaces.objects.ObjectInterface, collections.Sequence):
"""Object which can contain a fixed number of an object type"""
def __init__(self, context, layer_name, offset, structure_name, size = None, parent = None, count = 0, target = None):
def __init__(self, context, layer_name, offset, structure_name, size = None,
parent = None, count = 0, target = None):
if not isinstance(target, templates.ObjectTemplate):
raise TypeError("Array target must be an ObjectTemplate")
interfaces.objects.ObjectInterface.__init__(self,
@@ -236,7 +241,8 @@ class Array(interfaces.objects.ObjectInterface, collections.Sequence):
def __getitem__(self, i):
"""Returns the i-th item from the array"""
return self._target(context = self._context, layer_name = self._layer_name, offset = self._offset + (self._target.size * i), parent = self)
return self._target(context = self._context, layer_name = self._layer_name,
offset = self._offset + (self._target.size * i), parent = self)
def __len__(self):
"""Returns the length of the array"""
@@ -264,7 +270,7 @@ class Struct(interfaces.objects.ObjectInterface):
def template_children(cls, arguments):
"""Method to list children of a template"""
cls.check_members(arguments.get('members', None))
return [ member for _, member in arguments['members'].values()]
return [member for _, member in arguments['members'].values()]
@classmethod
def template_size(cls, arguments):
@@ -285,8 +291,8 @@ class Struct(interfaces.objects.ObjectInterface):
def check_members(cls, members):
# Members should be an iterable mapping of symbol names to tuples of (relative_offset, ObjectTemplate)
# An object template is a callable that when called with a context, offset, layer_name and structure_name
if not isinstance(members, collections.Iterable):
raise TypeError("Struct members parameter must be iterable not " + type(members))
if not isinstance(members, collections.Mapping):
raise TypeError("Struct members parameter must be a mapping not " + type(members))
if not all([(isinstance(member, tuple) and len(member) == 2) for member in members.values()]):
raise TypeError("Struct members must be a tuple of relative_offsets and templates")
@@ -296,10 +302,11 @@ class Struct(interfaces.objects.ObjectInterface):
return self._concrete_members[attr]
elif attr in self._members:
relative_offset, member = self._members[attr]
member = member(context = self._context, layer_name = self._layer_name, offset = self._offset + relative_offset, parent = self)
member = member(context = self._context, layer_name = self._layer_name,
offset = self._offset + relative_offset, parent = self)
self._concrete_members[attr] = member
return member
raise AttributeError("'" + self._structure_name + "' Struct has no attribute '" + attr + "'")
def write(self, value):
raise TypeError("Structs cannot be written to directly, invidivual members must be written instead")
raise TypeError("Structs cannot be written to directly, individual members must be written instead")
+12 -8
View File
@@ -1,28 +1,32 @@
'''
"""
Created on 4 May 2013
@author: mike
'''
"""
class ValidityRoutines(object):
"""Class to hold all validation routines, such as type checking"""
def type_check(self, value, valid_type):
"""Checks that value is an instance of valid_type, and returns value if it is, or throws a TypeError otherwise"""
"""Checks that value is an instance of valid_type, and returns value if it is, or throws a TypeError otherwise
"""
if not isinstance(value, valid_type):
print(repr(valid_type), repr(type(value).__name__))
raise TypeError(self.__class__.__name__ + " expected " + valid_type.__name__ + ", not " + type(value).__name__)
raise TypeError(self.__class__.__name__ + " expected " +
valid_type.__name__ + ", not " + type(value).__name__)
return value
def class_check(self, klass, valid_class):
"""Checks that value is an instance of valid_type, and returns value if it is, or throws a TypeError otherwise"""
"""Checks that class is an instance of valid_class, and returns klass if it is, or throws a TypeError otherwise
"""
if not issubclass(klass, valid_class):
raise TypeError(self.__class__.__name__ + " expected " + valid_class.__name__ + ", not " + klass.__name__)
raise TypeError(self.__class__.__name__ + " expected " +
valid_class.__name__ + ", not " + klass.__name__)
return klass
def confirm(self, assertion, error):
def confirm(assertion, error):
"""Acts like an assertion, but will not be disabled when __debug__ is disabled"""
if not assertion:
if error is None:
error = "An unspecified Assertion was not met"
error = "An unspecified Assertion was not met in " + self.__class__.__name__
raise AssertionError(error)