Exemple #1
0
    def register_default(cls, name, xtr=None):
        if cls is SimStatePlugin:
            if once('simstateplugin_register_default deprecation'):
                l.critical("SimStatePlugin.register_default(name, cls) is deprecated, please use SimState.register_default(name)")

            from angr.sim_state import SimState
            SimState.register_default(name, xtr)

        else:
            if xtr is cls:
                if once('simstateplugin_register_default deprecation case 2'):
                    l.critical("SimStatePlugin.register_default(name, cls) is deprecated, please use cls.register_default(name)")
                xtr = None

            from angr.sim_state import SimState
            SimState.register_default(name, cls, xtr if xtr is not None else 'default')
Exemple #2
0
        if self._type is None:
            raise ValueError("Trying to store to location without specifying type")

        return self._type.store(self.state, self._addr, value)


class StructMode(object):
    def __init__(self, view):
        self._view = view

    def __dir__(self):
        return [x[7:] for x in SimMemView.types if x.startswith('struct ')]

    def __getattr__(self, k):
        assert k != '_view'
        return self._view._deeper(ty=SimMemView.types['struct ' + k].with_arch(self._view.state.arch))

    def __setattr__(self, k, v):
        if k == '_view':
            object.__setattr__(self, k, v)
        else:
            self.__getattr__(k).store(v)

from ..sim_type import ALL_TYPES, SimTypeFixedSizeArray, SimTypePointer
SimMemView.types = ALL_TYPES # identity purposefully here


from angr.sim_state import SimState
SimState.register_default('mem', SimMemView)
SimState.register_default('regs', SimRegNameView)
Exemple #3
0
                max_pair = (addr, sz)
                break

        if max_pair is None:
            return None

        remaining = max_pair[1] - length
        max_addr = max_pair[0] + remaining
        max_length = remaining

        self.sinkholes.remove(max_pair)

        if remaining:
            self.sinkholes.add((max_pair[0], max_length))

        return max_addr

    def add_sinkhole(self, address, length):
        """
        Add a sinkhole.

        Allow the possibility for the program to reuse the memory represented by the
        address length pair.
        """

        self.sinkholes.add((address, length))


from angr.sim_state import SimState
SimState.register_default('cgc', SimStateCGC)
Exemple #4
0
        if self.state.solver.eval(ptr) != 0:
            v = self.state.memory.load(ptr, size_int)
            self.state.memory.store(addr, v)

        return addr

    @SimStatePlugin.memo
    def copy(self, memo):# pylint: disable=unused-argument
        c = SimHeapBrk(heap_base=self.heap_base, heap_size=self.heap_size)
        c.heap_location = self.heap_location
        c.mmap_base = self.mmap_base
        return c

    def _combine(self, others):
        new_heap_location = max(o.heap_location for o in others)
        if self.heap_location != new_heap_location:
            self.heap_location = new_heap_location
            return True
        else:
            return False

    def merge(self, others, merge_conditions, common_ancestor=None):  #pylint:disable=unused-argument
        return self._combine(others)

    def widen(self, others):
        return self._combine(others)

from angr.sim_state import SimState
SimState.register_default('heap', SimHeapBrk)
Exemple #5
0
            if sz >= length:
                max_pair = (addr, sz)
                break

        if max_pair is None:
            return None

        remaining = max_pair[1] - length
        max_addr = max_pair[0] + remaining
        max_length = remaining

        self.sinkholes.remove(max_pair)

        if remaining:
            self.sinkholes.add((max_pair[0], max_length))

        return max_addr

    def add_sinkhole(self, address, length):
        """
        Add a sinkhole.

        Allow the possibility for the program to reuse the memory represented by the
        address length pair.
        """

        self.sinkholes.add((address, length))

from angr.sim_state import SimState
SimState.register_default('cgc', SimStateCGC)
Exemple #6
0
        if simplify:
            l.debug("simplifying solver...")
            self.state.solver.simplify()
            l.debug("...simplification done")

        self.state.solver._solver.result = None

    def reconstrain(self):
        """
        Re-apply preconstraints to improve solver time, hopefully these
        constraints still allow us to do meaningful things to state.
        """

        # test all solver splits
        subsolvers = self.state.solver._solver.split()

        for solver in subsolvers:
            solver.timeout = 1000 * 10  # 10 seconds
            if not solver.satisfiable():
                for var in solver.variables:
                    if var in self.variable_map:
                        self.state.add_constraints(self.variable_map[var])
                    else:
                        l.warning("var %s not found in self.variable_map", var)


from angr.sim_state import SimState

SimState.register_default('preconstrainer', SimStatePreconstrainer)
Exemple #7
0
    def copy(self, memo): # pylint: disable=unused-argument
        return SimFastMemory(
            endness=self.endness,
            contents=dict(self._contents),
            width=self.width,
            uninitialized_read_handler=self._uninitialized_read_handler,
            memory_id=self.id
        )

    def changed_bytes(self, other):
        """
        Gets the set of changed bytes between self and other.
        """

        changes = set()

        l.warning("FastMemory.changed_bytes(): This implementation is very slow and only for debug purposes.")
        for addr,v in self._contents.items():
            for i in range(self.width):
                other_byte = other.load(addr+i, 1)
                our_byte = v.get_byte(i)
                if other_byte is our_byte:
                    changes.add(addr+i)

        return changes

from angr.sim_state import SimState
SimState.register_default('fast_memory', SimFastMemory)

from .. import sim_options as options
Exemple #8
0
            return self._solver.simplify()
        elif isinstance(e, (int, float, bool)):
            return e
        elif isinstance(e, claripy.ast.Base) and e.op in claripy.operations.leaf_operations_concrete:
            return e
        elif isinstance(e, SimActionObject) and e.op in claripy.operations.leaf_operations_concrete:
            return e.ast
        elif not isinstance(e, (SimActionObject, claripy.ast.Base)):
            return e
        else:
            return self._claripy_simplify(e)

    @timed_function
    @ast_stripping_decorator
    @error_converter
    def _claripy_simplify(self, *args): #pylint:disable=no-self-use
        return claripy.simplify(args[0])

    def variables(self, e): #pylint:disable=no-self-use
        """
        Returns the symbolic variables present in the AST of `e`.
        """
        return e.variables

from angr.sim_state import SimState
SimState.register_default('solver', SimSolver)

from .. import sim_options as o
from .inspect import BP_AFTER
from ..errors import SimValueError, SimUnsatError, SimSolverModeError, SimSolverOptionError
Exemple #9
0
            if action_holder is None:
                self.state.history.add_event(r)
            else:
                action_holder.append(r)

        self.state._inspect('tmp_write', BP_AFTER)

    def copy(self):
        return SimStateScratch(scratch=self)

    def merge(self, others, merge_conditions, common_ancestor=None):
        return False

    def widen(self, others):
        return False

    def clear(self):
        s = self.state
        j = self.jumpkind
        self.__init__()
        self.state = s
        self.jumpkind = j # preserve jumpkind - "what is the previous jumpkind" is an important question sometimes

from .sim_action import SimActionObject, SimActionData
from ..errors import SimValueError
from .. import sim_options as o
from .inspect import BP_AFTER, BP_BEFORE

from angr.sim_state import SimState
SimState.register_default('scratch', SimStateScratch)
Exemple #10
0
    def __setitem__(self, k, v):
        self._backer[k] = v

    def __delitem__(self, k):
        del self._backer[k]

    def __contains__(self, k):
        return k in self._backer

    def keys(self):
        return self._backer.keys()

    def values(self):
        return self._backer.values()

    def items(self):
        return self._backer.items()

    def get(self, k, alt=None):
        return self._backer.get(k, alt)

    def pop(self, k, alt=None):
        return self._backer.pop(k, alt)

    def copy(self):
        return SimStateGlobals(dict(self._backer))


from angr.sim_state import SimState
SimState.register_default('globals', SimStateGlobals)
Exemple #11
0
        # 0x1089a: cmp  r3, #3
        # 0x1089c: ble  0x10818         -> the back edge
        #
        # And yes, another example for the latter case is a do-while loop!

        SimStatePlugin.__init__(self)
        self.back_edge_trip_counts = defaultdict(
            list) if back_edge_trip_counts is None else back_edge_trip_counts
        self.header_trip_counts = defaultdict(
            list) if header_trip_counts is None else header_trip_counts
        self.current_loop = [] if current_loop is None else current_loop

    def merge(self, others, merge_conditions, common_ancestor=None):  # pylint: disable=unused-argument
        l.warning("Merging is not implemented for loop data!")
        return False

    def widen(self, others):  # pylint: disable=unused-argument
        l.warning("Widening is not implemented for loop data!")
        return False

    @SimStatePlugin.memo
    def copy(self, memo):  # pylint: disable=unused-argument
        return SimStateLoopData(
            back_edge_trip_counts=copy.deepcopy(self.back_edge_trip_counts),
            header_trip_counts=copy.deepcopy(self.header_trip_counts),
            current_loop=list(self.current_loop))


from angr.sim_state import SimState
SimState.register_default('loop_data', SimStateLoopData)
Exemple #12
0
    def __init__(self, start, f, **kwargs):
        TreeIter.__init__(self, start, **kwargs)
        self._f = f

    def __reversed__(self):
        for hist in self._iter_nodes():
            a = self._f(hist)
            if a is not None:
                yield a


class LambdaIterIter(LambdaAttrIter):
    def __init__(self, start, f, reverse=True, **kwargs):
        LambdaAttrIter.__init__(self, start, f, **kwargs)
        self._f = f
        self._reverse = reverse

    def __reversed__(self):
        for hist in self._iter_nodes():
            for a in reversed(
                    self._f(hist)) if self._reverse else self._f(hist):
                yield a


from angr.sim_state import SimState

SimState.register_default('history', SimStateHistory)

from .sim_action import SimAction, SimActionConstraint
from .sim_event import SimEvent
Exemple #13
0
import logging

from ..storage import SimKVStore
from .plugin import SimStatePlugin

l = logging.getLogger("angr.state_plugins.keyvalue_memory")


class SimKeyValueMemory(SimKVStore):  # pylint: disable=abstract-method
    def __init__(self, memory_id, store=None):
        super(SimKeyValueMemory, self).__init__(store)
        self.memory_id = memory_id

    @SimStatePlugin.memo
    def copy(self, memo):  # pylint: disable=unused-argument,arguments-differ
        return SimKeyValueMemory(memory_id=self.memory_id,
                                 store=self._store.copy())


from angr.sim_state import SimState
SimState.register_default('keyvalue_memory', SimKeyValueMemory)
Exemple #14
0
            except SimSolverError:
                size_int = self.state.solver.min(size)
            self.state.add_constraints(size_int == size)
        else:
            size_int = self.state.solver.eval(size)

        addr = self.state.heap.allocate(size_int)

        if self.state.solver.eval(ptr) != 0:
            v = self.state.memory.load(ptr, size_int)
            self.state.memory.store(addr, v)

        return addr

    def _combine(self, others):
        new_heap_location = max(o.heap_location for o in others)
        if self.heap_location != new_heap_location:
            self.heap_location = new_heap_location
            return True
        else:
            return False

    def merge(self, others, merge_conditions, common_ancestor=None):  #pylint:disable=unused-argument
        return self._combine(others)

    def widen(self, others):
        return self._combine(others)

from angr.sim_state import SimState
SimState.register_default('heap', SimHeapBrk)
Exemple #15
0
        >>> self.state.inspect(xxxxxx, attr0=yyyy, attr1=zzzz)
        >>> # Get new attributes out of SimInspect in case they are modified by the user
        >>> new_attr0 = self.state._inspect.attr0
        >>> new_attr1 = self.state._inspect.attr1
        >>> # Remove them from SimInspect
        >>> self.state._inspect.downsize()
        """
        for k in inspect_attributes:
            if hasattr(self, k):
                setattr(self, k, None)

    def _combine(self, others):
        for t in event_types:
            seen = { id(e) for e in self._breakpoints[t] }
            for o in others:
                for b in o._breakpoints[t]:
                    if id(b) not in seen:
                        self._breakpoints[t].append(b)
                        seen.add(id(b))
        return False

    def merge(self, others, merge_conditions, common_ancestor=None): # pylint: disable=unused-argument
        return self._combine(others)

    def widen(self, others):
        return self._combine(others)


from angr.sim_state import SimState
SimState.register_default('inspect', SimInspector)
Exemple #16
0
    """
    Used in callstack backtrace, which is a history of callstacks along a path, to record individual actions occurred
    each time the callstack is changed.
    """
    def __init__(self, callstack_hash, callstack_depth, action, callframe=None, ret_site_addr=None):
        self.callstack_hash = callstack_hash
        self.callstack_depth = callstack_depth
        self.action = action

        if action not in ('push', 'pop'):
            raise AngrError('Unsupported action string "%s".' % action)

        self.callframe = callframe
        self.ret_site_addr = ret_site_addr

        if action == 'push' and self.callframe is None:
            raise AngrError('callframe must be specified when action is "push".')

        elif action == 'pop' and self.callframe is not None:
            raise AngrError('callframe must not be specified when action is "pop".')

    def __repr__(self):
        if self.action == 'push':
            return "<CallStackAction push with %s>" % self.callframe
        else: # pop
            return "<CallStackAction pop, ret site %#x>" % self.ret_site_addr


from angr.sim_state import SimState
SimState.register_default('callstack', CallStack)
Exemple #17
0
            endness=self.endness,
            contents=dict(self._contents),
            width=self.width,
            uninitialized_read_handler=self._uninitialized_read_handler,
            memory_id=self.id)

    def changed_bytes(self, other):
        """
        Gets the set of changed bytes between self and other.
        """

        changes = set()

        l.warning(
            "FastMemory.changed_bytes(): This implementation is very slow and only for debug purposes."
        )
        for addr, v in self._contents.iteritems():
            for i in range(self.width):
                other_byte = other.load(addr + i, 1)
                our_byte = v.get_byte(i)
                if other_byte is our_byte:
                    changes.add(addr + i)

        return changes


from angr.sim_state import SimState
SimState.register_default('fast_memory', SimFastMemory)

from .. import sim_options as options
Exemple #18
0
        self._backer[k] = v

    def __delitem__(self, k):
        del self._backer[k]

    def __contains__(self, k):
        return k in self._backer

    def keys(self):
        return self._backer.keys()

    def values(self):
        return self._backer.values()

    def items(self):
        return self._backer.items()

    def get(self, k, alt=None):
        return self._backer.get(k, alt)

    def pop(self, k, alt=None):
        return self._backer.pop(k, alt)

    @SimStatePlugin.memo
    def copy(self, memo):   # pylint: disable=unused-argument
        return SimStateGlobals(dict(self._backer))


from angr.sim_state import SimState
SimState.register_default('globals', SimStateGlobals)
Exemple #19
0
        ) and e.op in claripy.operations.leaf_operations_concrete:
            return e
        elif isinstance(
                e, SimActionObject
        ) and e.op in claripy.operations.leaf_operations_concrete:
            return e.ast
        elif not isinstance(e, (SimActionObject, claripy.ast.Base)):
            return e
        else:
            return self._claripy_simplify(e)

    @timed_function
    @ast_stripping_decorator
    @error_converter
    def _claripy_simplify(self, *args):  #pylint:disable=no-self-use
        return claripy.simplify(args[0])

    def variables(self, e):  #pylint:disable=no-self-use
        """
        Returns the symbolic variables present in the AST of `e`.
        """
        return e.variables


from angr.sim_state import SimState
SimState.register_default('solver', SimSolver)

from .. import sim_options as o
from .inspect import BP_AFTER
from ..errors import SimValueError, SimUnsatError, SimSolverModeError, SimSolverOptionError
Exemple #20
0
class LambdaAttrIter(TreeIter):
    def __init__(self, start, f, **kwargs):
        TreeIter.__init__(self, start, **kwargs)
        self._f = f

    def __reversed__(self):
        for hist in self._iter_nodes():
            a = self._f(hist)
            if a is not None:
                yield a


class LambdaIterIter(LambdaAttrIter):
    def __init__(self, start, f, reverse=True, **kwargs):
        LambdaAttrIter.__init__(self, start, f, **kwargs)
        self._f = f
        self._reverse = reverse

    def __reversed__(self):
        for hist in self._iter_nodes():
            for a in reversed(self._f(hist)) if self._reverse else self._f(hist):
                yield a


from angr.sim_state import SimState
SimState.register_default('history', SimStateHistory)


from .sim_action import SimAction, SimActionConstraint
from .sim_event import SimEvent
Exemple #21
0
    def __lt__(self, o):
        return (self.n_bits <
                o.n_bits) and (self._check_masked_bits_are_equals(o))

    def __ge__(self, o):
        return not self.__lt__(o)

    def __gt__(self, o):
        return not self.__le__(o)

    @SimStatePlugin.memo
    def copy(self, memo):
        return ConditionHistoryPlugin(self.bits, self.n_bits, self.cond)


SimState.register_default('cond_hist', ConditionHistoryPlugin)

claripyTrue = BoolV(True)


def exclude_identical_constraints(l1, l2):
    return [
        x for x in l1
        if list(filter(lambda y: (x == y) is claripyTrue, l2)) == []
    ]


class ConditionsHistoryUpdater(ExplorationTechnique):
    def successors(self, simgr, state, **kwargs):
        next_states = simgr.successors(state, **kwargs)
        if len(next_states.successors) > 2:
Exemple #22
0
        >>> # Remove them from SimInspect
        >>> self.state._inspect.downsize()
        """
        for k in inspect_attributes:
            if hasattr(self, k):
                setattr(self, k, None)

    def _combine(self, others):
        for t in event_types:
            seen = {id(e) for e in self._breakpoints[t]}
            for o in others:
                for b in o._breakpoints[t]:
                    if id(b) not in seen:
                        self._breakpoints[t].append(b)
                        seen.add(id(b))
        return False

    def merge(self, others, merge_conditions, common_ancestor=None):  # pylint: disable=unused-argument
        return self._combine(others)

    def widen(self, others):
        return self._combine(others)

    def set_state(self, state):
        super().set_state(state)
        state.supports_inspect = True


from angr.sim_state import SimState
SimState.register_default('inspect', SimInspector)
Exemple #23
0
        """
        l.warning('unmap_region() is not yet supported by SimAbstractMmeory.')
        return

    def was_written_to(self, dst):

        if type(dst) in (int, long):
            dst = self.state.se.BVV(dst, self.state.arch.bits)

        addrs = self._normalize_address_type(dst)

        for region, addr in addrs:
            address_wrapper = self._normalize_address(region, addr.min)

            return self.regions[address_wrapper.region].was_written_to(
                address_wrapper.address)

        return False

    def dbg_print(self):
        """
        Print out debugging information
        """
        for region_id, region in self.regions.items():
            print "Region [%s]:" % region_id
            region.dbg_print(indent=2)


from angr.sim_state import SimState
SimState.register_default('abs_memory', SimAbstractMemory)
Exemple #24
0
                    fmt_list = []
                    # For each formatter
                    for idx, _fmt in enumerate(fmt):
                        # Strings
                        if 's' in _fmt:
                            fmt_arg = str(
                                data[idx][:data[idx].find(0)].decode('utf8'))
                        # Integers
                        elif 'i' in _fmt:
                            fmt_arg = int(data[idx])
                        # Other types not supported yet
                        else:
                            raise NotImplementedError()
                        # Append to the list
                        fmt_list.append(fmt_arg)
                    # Return the formatted list
                    return fmt_list
                # If not formatted output
                # Merge them into a stream
                data = b''.join(data)
            # Return the merged stream
            return data
        # Any other file descriptor, concretize directly
        return self.get_fd(fd).concretize(**kwargs)


from angr.sim_state import SimState
SimState.register_default('posix', SimSystemPosix)

from ..errors import SimPosixError, SimSolverError, SimMergeError
Exemple #25
0

class StructMode(object):
    def __init__(self, view):
        self._view = view

    def __dir__(self):
        return [x[7:] for x in SimMemView.types if x.startswith('struct ')]

    def __getattr__(self, k):
        assert k != '_view'
        return self._view._deeper(
            ty=SimMemView.types['struct ' +
                                k].with_arch(self._view.state.arch))

    def __setattr__(self, k, v):
        if k == '_view':
            object.__setattr__(self, k, v)
        else:
            self.__getattr__(k).store(v)


from ..sim_type import ALL_TYPES, SimTypeFixedSizeArray, SimTypePointer

SimMemView.types = ALL_TYPES  # identity purposefully here

from angr.sim_state import SimState

SimState.register_default('mem', SimMemView)
SimState.register_default('regs', SimRegNameView)
Exemple #26
0
                self.state.history.add_event(r)
            else:
                action_holder.append(r)

        self.state._inspect('tmp_write', BP_AFTER)

    @SimStatePlugin.memo
    def copy(self, memo): # pylint: disable=unused-argument
        return SimStateScratch(scratch=self)

    def merge(self, others, merge_conditions, common_ancestor=None): # pylint: disable=unused-argument
        return False

    def widen(self, others): # pylint: disable=unused-argument
        return False

    def clear(self):
        s = self.state
        j = self.jumpkind
        self.__init__()
        self.state = s
        self.jumpkind = j # preserve jumpkind - "what is the previous jumpkind" is an important question sometimes

from .sim_action import SimActionObject, SimActionData
from ..errors import SimValueError
from .. import sim_options as o
from .inspect import BP_AFTER, BP_BEFORE

from angr.sim_state import SimState
SimState.register_default('scratch', SimStateScratch)
Exemple #27
0
        stack_shift = self.state.arch.initial_sp - self.real_stack_top
        self.state.registers.store(sp, self.state.regs.sp + stack_shift)

        if not self.omit_fp:
            self.state.registers.store(bp, self.state.regs.bp + stack_shift)

    @staticmethod
    def _read_data(path):
        if not os.path.exists(path):
            raise SimStateError("File does not exist")
        f = open(path, "rb")
        return f.read()

    def _write(self, addr, data):
        self.state.memory.store(addr, data)

    @staticmethod
    def _to_bvv(data):
        sz = len(data)
        num = int(binascii.hexlify(data), 16)
        return claripy.BVV(num, sz)

    @SimStatePlugin.memo
    def copy(self, memo): # pylint: disable=unused-argument
        return GDB()


from angr.sim_state import SimState
SimState.register_default('gdb', GDB)
Exemple #28
0
        :param path: file path as string
        :param kwargs: passed to state.se.eval
        :return: file contents as string
        """
        return self.state.fs.get(path).concretize(**kwargs)

    def dumps(self, fd, **kwargs):
        """
        Returns the concrete content for a file descriptor.

        BACKWARD COMPATIBILITY: if you ask for file descriptors 0 1 or 2, it will return the data from stdin, stdout,
        or stderr as a flat string.

        :param fd:  A file descriptor.
        :return:    The concrete content.
        :rtype:     str
        """
        if 0 <= fd <= 2:
            data = [self.stdin, self.stdout, self.stderr][fd].concretize(**kwargs)
            if type(data) is list:
                data = ''.join(data)
            return data
        return self.get_fd(fd).concretize(**kwargs)


from angr.sim_state import SimState
SimState.register_default('posix', SimSystemPosix)

from ..errors import SimPosixError, SimSolverError, SimMergeError
Exemple #29
0
                        type1violations.append(self.memory[m][1])
                    elif vType == 2:
                        type2violations.append(self.memory[m][1])
                        if not (self.state.options.__contains__(
                                simuvex.o.CONSERVATIVE_WRITE_STRATEGY)
                                and self.state.options.__contains__(
                                    simuvex.o.CONSERVATIVE_READ_STRATEGY)):
                            print(
                                "\033[93mFor better results you should probably run the analysis and with the initial states' options \"add_options={simuvex.o.CONSERVATIVE_WRITE_STRATEGY, simuvex.o.CONSERVATIVE_READ_STRATEGY}\"\033[0m"
                            )
                    elif vType == 3:
                        type3violations.append(self.memory[m][1])
                    import store
                    store.violations.append(
                        ("%s, @ 0x%x" %
                         (self.registers[m][1][0], self.registers[m][1][1]),
                         self.registers[m]))
                else:  #unknow violation type
                    print(
                        "\033[93mWarning: violation of unknown type at instruction: %s @ 0x%x\033[0m"
                        % (vType, self.registers[r][1][0],
                           self.registers[r][1][1]))

        bubble = claripy.backends.z3.simplify(bubble)
        dualPrevented = claripy.backends.z3.simplify(
            claripy.Or(dualPrevented, bubble))
        return (bubble, dualPrevented)


SimState.register_default('time', PluginTime)
Exemple #30
0
        :param length: length in bytes of region to map, will be rounded upwards to the page size
        """
        l.warning('unmap_region() is not yet supported by SimAbstractMmeory.')
        return

    def was_written_to(self, dst):

        if type(dst) in (int, long):
            dst = self.state.se.BVV(dst, self.state.arch.bits)

        addrs = self._normalize_address_type(dst)

        for region, addr in addrs:
            address_wrapper = self._normalize_address(region, addr.min)

            return self.regions[address_wrapper.region].was_written_to(address_wrapper.address)

        return False

    def dbg_print(self):
        """
        Print out debugging information
        """
        for region_id, region in self.regions.items():
            print "Region [%s]:" % region_id
            region.dbg_print(indent=2)


from angr.sim_state import SimState
SimState.register_default('abs_memory', SimAbstractMemory)
Exemple #31
0
):
    def _default_value(self, addr, size, **kwargs):
        # TODO: Make _default_value() a separate Mixin

        if kwargs.get("name", "").startswith("merge_uc_"):
            # this is a hack. when this condition is satisfied, _default_value() is called inside Listpage.merge() to
            # create temporary values. we simply return a TOP value here.
            return self.state.top(size * self.state.arch.byte_width)

        # we never fill default values for non-existent loads
        kwargs['fill_missing'] = False
        return super()._default_value(addr, size, **kwargs)


class KeyValueMemory(
        KeyValueMemoryMixin, ):
    pass


class JavaVmMemory(
        JavaVmMemoryMixin, ):
    pass


from angr.sim_state import SimState
SimState.register_default('sym_memory', DefaultMemory)
SimState.register_default('fast_memory', FastMemory)
SimState.register_default('abs_memory', AbstractMemory)
SimState.register_default('keyvalue_memory', KeyValueMemory)
SimState.register_default('javavm_memory', JavaVmMemory)
Exemple #32
0
        return c

    def merge(self, others, merge_conditions, common_ancestor=None): # pylint: disable=unused-argument
        return False

    def widen(self, others):
        return False

    @property
    def errno(self):
        return self.state.mem[self.errno_location].int.resolved

    @errno.setter
    def errno(self, val):
        self.state.mem[self.errno_location].int = val

    def ret_errno(self, val):
        try:
            ival = getattr(self.state.posix, val)
        except AttributeError as e:
            raise ValueError("Invalid errno constant %s" % val) from e

        if self.state.scratch.sim_procedure.is_syscall:
            return -ival
        else:
            self.errno = ival
            return -1

from angr.sim_state import SimState
SimState.register_default('libc', SimStateLibc)
Exemple #33
0
                 callframe=None,
                 ret_site_addr=None):
        self.callstack_hash = callstack_hash
        self.callstack_depth = callstack_depth
        self.action = action

        if action not in ('push', 'pop'):
            raise AngrError('Unsupported action string "%s".' % action)

        self.callframe = callframe
        self.ret_site_addr = ret_site_addr

        if action == 'push' and self.callframe is None:
            raise AngrError(
                'callframe must be specified when action is "push".')

        elif action == 'pop' and self.callframe is not None:
            raise AngrError(
                'callframe must not be specified when action is "pop".')

    def __repr__(self):
        if self.action == 'push':
            return "<CallStackAction push with %s>" % self.callframe
        else:  # pop
            return "<CallStackAction pop, ret site %#x>" % self.ret_site_addr


from angr.sim_state import SimState

SimState.register_default('callstack', CallStack)
Exemple #34
0
import logging

from ..storage import SimKVStore
from .plugin import SimStatePlugin

l = logging.getLogger("angr.state_plugins.keyvalue_memory")


class SimKeyValueMemory(SimKVStore): # pylint: disable=abstract-method
    def __init__(self, memory_id, store=None):
        super(SimKeyValueMemory, self).__init__(store)
        self.memory_id = memory_id

    @SimStatePlugin.memo
    def copy(self, memo): # pylint: disable=unused-argument,arguments-differ
        return SimKeyValueMemory(memory_id=self.memory_id,
                                 store=self._store.copy())

from angr.sim_state import SimState
SimState.register_default('keyvalue_memory', SimKeyValueMemory)
Exemple #35
0
        return SimStateLog(log=self)

    def _combine(self, others):
        all_events = [e.events for e in itertools.chain([self], others)]
        self.events = [SimEvent(self.state, 'merge', event_lists=all_events)]
        return False

    def merge(self, others, merge_conditions, common_ancestor=None):  # pylint: disable=unused-argument
        return self._combine(others)

    def widen(self, others):
        return self._combine(others)

    def clear(self):
        s = self.state
        self.__init__()
        self.state = s
        #self.events = [ ]
        #self.temps.clear()
        #self.used_variables.clear()
        #self.input_variables.clear()


from ..errors import SimEventError
from .sim_event import SimEvent
from .sim_action import SimAction, SimActionConstraint

from angr.sim_state import SimState

SimState.register_default('log', SimStateLog)
Exemple #36
0
        # 0x10868: add  r2, r0, r1      -> part B of the logic for all iterations is put in the loop header
        # ...
        # 0x10898: ldr  r3, [r7, #20]
        # 0x1089a: cmp  r3, #3
        # 0x1089c: ble  0x10818         -> the back edge
        #
        # And yes, another example for the latter case is a do-while loop!

        SimStatePlugin.__init__(self)
        self.back_edge_trip_counts = defaultdict(list) if back_edge_trip_counts is None else back_edge_trip_counts
        self.header_trip_counts = defaultdict(list) if header_trip_counts is None else header_trip_counts
        self.current_loop = [] if current_loop is None else current_loop

    def merge(self, others, merge_conditions, common_ancestor=None): # pylint: disable=unused-argument
        l.warning("Merging is not implemented for loop data!")
        return False

    def widen(self, others): # pylint: disable=unused-argument
        l.warning("Widening is not implemented for loop data!")
        return False

    @SimStatePlugin.memo
    def copy(self, memo): # pylint: disable=unused-argument
        return SimStateLoopData(back_edge_trip_counts=copy.deepcopy(self.back_edge_trip_counts),
                                header_trip_counts=copy.deepcopy(self.header_trip_counts),
                                current_loop=list(self.current_loop))


from angr.sim_state import SimState
SimState.register_default('loop_data', SimStateLoopData)
Exemple #37
0
    def copy(self, memo):  # pylint: disable=unused-argument
        return SimUCManager(man=self)

    def get_alloc_depth(self, addr):
        block_pos = (addr - self._region_base) // self._region_size

        if block_pos not in self._alloc_depth_map:
            return None

        return self._alloc_depth_map[block_pos]

    def is_bounded(self, ast):
        """
        Test whether an AST is bounded by any existing constraint in the related solver.

        :param ast: an claripy.AST object
        :return: True if there is at least one related constraint, False otherwise
        """

        return len(
            ast.variables.intersection(
                self.state.solver._solver.variables)) != 0

    def set_state(self, state):
        super(SimUCManager, self).set_state(state)
        self._region_base = 0xd0 << (self.state.arch.bits - 8)


from angr.sim_state import SimState
SimState.register_default('uc_manager', SimUCManager)
Exemple #38
0
    @SimStatePlugin.memo
    def copy(self, memo): # pylint: disable=unused-argument
        return SimUCManager(man=self)

    def get_alloc_depth(self, addr):
        block_pos = (addr - self._region_base) // self._region_size

        if block_pos not in self._alloc_depth_map:
            return None

        return self._alloc_depth_map[block_pos]

    def is_bounded(self, ast):
        """
        Test whether an AST is bounded by any existing constraint in the related solver.

        :param ast: an claripy.AST object
        :return: True if there is at least one related constraint, False otherwise
        """

        return len(ast.variables.intersection(self.state.solver._solver.variables)) != 0

    def set_state(self, state):
        super(SimUCManager, self).set_state(state)
        self._region_base = 0xd0 << (self.state.arch.bits - 8)


from angr.sim_state import SimState
SimState.register_default('uc_manager', SimUCManager)
Exemple #39
0
    def copy(self, memo): # pylint: disable=unused-argument
        return SimStateLog(log=self)

    def _combine(self, others):
        all_events = [ e.events for e in itertools.chain([self], others) ]
        self.events = [ SimEvent(self.state, 'merge', event_lists=all_events) ]
        return False

    def merge(self, others, merge_conditions, common_ancestor=None): # pylint: disable=unused-argument
        return self._combine(others)

    def widen(self, others):
        return self._combine(others)

    def clear(self):
        s = self.state
        self.__init__()
        self.state = s
        #self.events = [ ]
        #self.temps.clear()
        #self.used_variables.clear()
        #self.input_variables.clear()

from ..errors import SimEventError
from .sim_event import SimEvent
from .sim_action import SimAction, SimActionConstraint


from angr.sim_state import SimState
SimState.register_default('log', SimStateLog)
Exemple #40
0
        self.state.registers.store(sp, self.state.regs.sp + stack_shift)

        if not self.omit_fp:
            self.state.registers.store(bp, self.state.regs.bp + stack_shift)

    @staticmethod
    def _read_data(path):
        if not os.path.exists(path):
            raise SimStateError("File does not exist")
        f = open(path, "rb")
        return f.read()

    def _write(self, addr, data):
        for d in data:
            self.state.memory.store(addr, d, size=1)
            addr = addr + 1

    @staticmethod
    def _to_bvv(data):
        sz = len(data)
        num = int(binascii.hexlify(data), 16)
        return claripy.BVV(num, sz)

    @SimStatePlugin.memo
    def copy(self, memo): # pylint: disable=unused-argument
        return GDB()


from angr.sim_state import SimState
SimState.register_default('gdb', GDB)
Exemple #41
0
    def merge(self, others, merge_conditions, common_ancestor=None):  # pylint: disable=unused-argument
        return False

    def widen(self, others):
        return False

    @property
    def errno(self):
        return self.state.mem[self.errno_location].int.resolved

    @errno.setter
    def errno(self, val):
        self.state.mem[self.errno_location].int = val

    def ret_errno(self, val):
        try:
            ival = getattr(self.state.posix, val)
        except AttributeError as e:
            raise ValueError("Invalid errno constant %s" % val) from e

        if self.state.scratch.sim_procedure.is_syscall:
            return -ival
        else:
            self.errno = ival
            return -1


from angr.sim_state import SimState

SimState.register_default('libc', SimStateLibc)
Exemple #42
0
        self.state.downsize()

        if simplify:
            l.debug("simplifying solver...")
            self.state.solver.simplify()
            l.debug("...simplification done")

        self.state.solver._solver.result = None

    def reconstrain(self):
        """
        Re-apply preconstraints to improve solver time, hopefully these
        constraints still allow us to do meaningful things to state.
        """

        # test all solver splits
        subsolvers = self.state.solver._solver.split()

        for solver in subsolvers:
            solver.timeout = 1000 * 10  # 10 seconds
            if not solver.satisfiable():
                for var in solver.variables:
                    if var in self.variable_map:
                        self.state.add_constraints(self.variable_map[var])
                    else:
                        l.warning("var %s not found in self.variable_map", var)


from angr.sim_state import SimState
SimState.register_default('preconstrainer', SimStatePreconstrainer)
Exemple #43
0
        """
        take a path and make sure if fits within the chroot
        remove '../', './', and '/' from the beginning of path
        """
        normalized = os.path.normpath(os.path.abspath(name))

        # if it starts with the chroot after absolution and normalization it's good
        if normalized.startswith(self.chroot):
            return normalized

        normalized = os.path.normpath(name)
        # otherwise we trim the path and append it to the chroot
        while True:
            if normalized.startswith("/"):
                normalized = normalized[1:]
            elif normalized.startswith("./"):
                normalized = normalized[2:]
            elif normalized.startswith("../"):
                normalized = normalized[3:]
            else:
                break

        return os.path.join(self.chroot, normalized)


from angr.sim_state import SimState
SimState.register_default('posix', SimStateSystem)

from ..state_plugins.symbolic_memory import SimSymbolicMemory
from ..errors import SimPosixError, SimError