Example #1
0
def get_entry_state_of_method(project, method_fullname):
    # get SootAddressDescriptor of method entry
    soot_method = project.loader.main_object.get_soot_method(method_fullname)
    method = SootMethodDescriptor.from_soot_method(soot_method)
    addr = SootAddressDescriptor(method, 0, 0)
    # create call state
    return project.factory.blank_state(addr=addr, add_options={angr.options.ZERO_FILL_UNCONSTRAINED_MEMORY})
Example #2
0
def get_entry_state_of_method(project, method_fullname):
    # get SootAddressDescriptor of method entry
    soot_method = project.loader.main_object.get_soot_method(method_fullname)
    method = SootMethodDescriptor.from_soot_method(soot_method)
    addr = SootAddressDescriptor(method, 0, 0)
    # create call state
    return project.factory.blank_state(addr=addr)
Example #3
0
def get_entry_state_of_method(project, method_fullname):
    # get SootAddressDescriptor of method entry
    soot_method = project.loader.main_object.get_soot_method(method_fullname)
    method = SootMethodDescriptor.from_soot_method(soot_method)
    addr = SootAddressDescriptor(method, 0, 0)
    # create call state
    return project.factory.blank_state(addr=addr)
Example #4
0
def resolve_method(state, method_name, class_name, params=(), ret_type=None,
                   include_superclasses=True, init_class=True,
                   raise_exception_if_not_found=False):
    """
    Resolves the method based on the given characteristics (name, class and
    params) The method may be defined in one of the superclasses of the given
    class (TODO: support interfaces).

    :rtype: archinfo.arch_soot.SootMethodDescriptor
    """
    base_class = state.javavm_classloader.get_class(class_name)
    if include_superclasses:
        class_hierarchy = state.javavm_classloader.get_class_hierarchy(base_class)
    else:
        class_hierarchy = [base_class]
    # walk up in class hierarchy, until method is found
    for class_descriptor in class_hierarchy:
        java_binary = state.project.loader.main_object
        soot_method = java_binary.get_soot_method(method_name, class_descriptor.name,
                                                  params, none_if_missing=True)
        if soot_method is not None:
            # init the class
            if init_class:
                state.javavm_classloader.init_class(class_descriptor)
            return SootMethodDescriptor.from_soot_method(soot_method)

    # method could not be found
    # => we are executing code that is not loaded (typically library code)
    # => fallback: continue with infos available from the invocation, so we
    #              still can use SimProcedures
    if raise_exception_if_not_found:
        raise SootMethodNotLoadedException()
    else:
        return SootMethodDescriptor(class_name, method_name, params, ret_type=ret_type)
Example #5
0
File: soot.py Project: angr/cle
    def __init__(self, path, entry_point=None, entry_point_params=(), input_format=None,
                 additional_jars=None, additional_jar_roots=None,
                 jni_libs_ld_path=None, jni_libs=None,
                 android_sdk=None, **kwargs):

        if not pysoot:
            raise ImportError('Cannot import PySoot. The Soot backend requires PySoot.')

        if kwargs.get('has_memory', False):
            raise CLEError('The parameter "has_memory" must be False for Soot backend.')

        super(Soot, self).__init__(path, has_memory=False, **kwargs)

        # load the classes
        l.debug("Lifting to Soot IR ...")
        start_time = time.time()
        pysoot_lifter = Lifter(path,
                               input_format=input_format,
                               android_sdk=android_sdk,
                               additional_jars=additional_jars,
                               additional_jar_roots=additional_jar_roots)
        end_time = time.time()
        l.debug("Lifting completed in %ds", round(end_time - start_time, 2))
        self._classes = pysoot_lifter.classes

        # find entry method
        if entry_point:
            try:
                ep_method = self.get_soot_method(entry_point, params=entry_point_params)
                ep_method_descriptor = SootMethodDescriptor.from_soot_method(ep_method)
                self._entry = SootAddressDescriptor(ep_method_descriptor, 0, 0)
                l.debug("Entry point set to %s", self._entry)
            except CLEError:
                l.warning("Couldn't find entry point %s.", entry_point)
                self._entry = None

        self.os = 'javavm'
        self.rebase_addr = None
        self.set_arch(ArchSoot())

        if jni_libs:
            # native libraries are getting loaded by adding them as a dependency of this object
            self.deps += [jni_libs] if type(jni_libs) in (str, bytes) else jni_libs
            # if available, add additional load path(s)
            if jni_libs_ld_path:
                path_list = [jni_libs_ld_path] if type(jni_libs_ld_path) in (str, bytes) else jni_libs_ld_path
                self.extra_load_path += path_list
            self.jni_support = True
        else:
            self.jni_support = False
Example #6
0
    def setup_caller(self, caller):
        # returns true if the caller itself adds entropy
        params = tuple(caller[2])
        method_name = caller[0] + '.' + caller[1]
        soot_method = self.angr_p.loader.main_object.get_soot_method(
            method_name, params=params)
        target_method = SootMethodDescriptor.from_soot_method(soot_method)
        base_state = self.angr_p.factory.blank_state()
        base_state.ip = SootAddressTerminator()
        args_target_method, caller_args = self._get_initialized_method_args(
            base_state, soot_method)

        return self.angr_p.factory.call_state(
            target_method.addr, *args_target_method,
            base_state=base_state), caller_args
Example #7
0
 def _get_next_linear_instruction(state, stmt_idx):
     addr = state.addr.copy()
     addr.stmt_idx = stmt_idx
     method = state.regs._ip_binary.get_soot_method(addr.method)
     current_bb = method.blocks[addr.block_idx]
     new_stmt_idx = addr.stmt_idx + 1
     if new_stmt_idx < len(current_bb.statements):
         return SootAddressDescriptor(addr.method, addr.block_idx, new_stmt_idx)
     else:
         new_bb_idx = addr.block_idx + 1
         if new_bb_idx < len(method.blocks):
             return SootAddressDescriptor(addr.method, new_bb_idx, 0)
         else:
             l.warning("falling into a non existing bb: %d in %s",
                       new_bb_idx, SootMethodDescriptor.from_soot_method(method))
             raise IncorrectLocationException()
Example #8
0
def resolve_method(state,
                   method_name,
                   class_name,
                   params=(),
                   ret_type=None,
                   include_superclasses=True,
                   init_class=True,
                   raise_exception_if_not_found=False):
    """
    Resolves the method based on the given characteristics (name, class and
    params) The method may be defined in one of the superclasses of the given
    class (TODO: support interfaces).

    :rtype: archinfo.arch_soot.SootMethodDescriptor
    """
    base_class = state.javavm_classloader.get_class(class_name)
    if include_superclasses:
        class_hierarchy = state.javavm_classloader.get_class_hierarchy(
            base_class)
    else:
        class_hierarchy = [base_class]
    # walk up in class hierarchy, until method is found
    for class_descriptor in class_hierarchy:
        java_binary = state.project.loader.main_object
        soot_method = java_binary.get_soot_method(method_name,
                                                  class_descriptor.name,
                                                  params,
                                                  none_if_missing=True)
        if soot_method is not None:
            # init the class
            if init_class:
                state.javavm_classloader.init_class(class_descriptor)
            return SootMethodDescriptor.from_soot_method(soot_method)

    # method could not be found
    # => we are executing code that is not loaded (typically library code)
    # => fallback: continue with infos available from the invocation, so we
    #              still can use SimProcedures
    if raise_exception_if_not_found:
        raise SootMethodNotLoadedException()
    else:
        return SootMethodDescriptor(class_name,
                                    method_name,
                                    params,
                                    ret_type=ret_type)
Example #9
0
 def _get_next_linear_instruction(state, stmt_idx):
     addr = state.addr.copy()
     addr.stmt_idx = stmt_idx
     method = state.regs._ip_binary.get_soot_method(addr.method)
     current_bb = method.blocks[addr.block_idx]
     new_stmt_idx = addr.stmt_idx + 1
     if new_stmt_idx < len(current_bb.statements):
         return SootAddressDescriptor(addr.method, addr.block_idx,
                                      new_stmt_idx)
     else:
         new_bb_idx = addr.block_idx + 1
         if new_bb_idx < len(method.blocks):
             return SootAddressDescriptor(addr.method, new_bb_idx, 0)
         else:
             l.warning("falling into a non existing bb: %d in %s",
                       new_bb_idx,
                       SootMethodDescriptor.from_soot_method(method))
             raise IncorrectLocationException()
Example #10
0
    def __init__(self,
                 path,
                 entry_point=None,
                 entry_point_params=(),
                 input_format=None,
                 additional_jars=None,
                 additional_jar_roots=None,
                 jni_libs_ld_path=None,
                 jni_libs=None,
                 android_sdk=None,
                 **kwargs):

        if not pysoot:
            raise ImportError(
                'Cannot import PySoot. The Soot backend requires PySoot.')

        if kwargs.get('has_memory', False):
            raise CLEError(
                'The parameter "has_memory" must be False for Soot backend.')

        super(Soot, self).__init__(path, has_memory=False, **kwargs)

        # load the classes
        l.debug("Lifting to Soot IR ...")
        start_time = time.time()
        pysoot_lifter = Lifter(path,
                               input_format=input_format,
                               android_sdk=android_sdk,
                               additional_jars=additional_jars,
                               additional_jar_roots=additional_jar_roots)
        end_time = time.time()
        l.debug("Lifting completed in %ds", round(end_time - start_time, 2))
        self._classes = pysoot_lifter.classes

        # find entry method
        if entry_point:
            try:
                ep_method = self.get_soot_method(entry_point,
                                                 params=entry_point_params)
                ep_method_descriptor = SootMethodDescriptor.from_soot_method(
                    ep_method)
                self._entry = SootAddressDescriptor(ep_method_descriptor, 0, 0)
                l.debug("Entry point set to %s", self._entry)
            except CLEError:
                l.warning("Couldn't find entry point %s.", entry_point)
                self._entry = None

        self.os = 'javavm'
        self.rebase_addr = None
        self.set_arch(ArchSoot())

        if jni_libs:
            # native libraries are getting loaded by adding them as a dependency of this object
            self.deps += [jni_libs] if type(jni_libs) in (str,
                                                          bytes) else jni_libs
            # if available, add additional load path(s)
            if jni_libs_ld_path:
                path_list = [jni_libs_ld_path] if type(jni_libs_ld_path) in (
                    str, bytes) else jni_libs_ld_path
                self.extra_load_path += path_list
            self.jni_support = True
        else:
            self.jni_support = False
Example #11
0
def solve_given_numbers_angr(numbers):
    global fake_input_fd, fake_output_fd

    binary_path = os.path.join(self_dir, "bin/service.jar")
    jni_options = {'jni_libs': ['libnotfun.so']}
    project = angr.Project(binary_path, main_opts=jni_options)

    # hooks
    project.hook(
        SootMethodDescriptor(class_name="java.util.Random",
                             name="nextInt",
                             params=('int', )).address(), Random_nextInt())
    project.hook(
        SootMethodDescriptor(class_name="java.lang.Integer",
                             name="valueOf",
                             params=('int', )).address(), Dummy_valueOf())
    project.hook(
        SootMethodDescriptor(class_name="NotFun",
                             name="print",
                             params=('java.lang.Object', )).address(),
        Custom_Print())
    project.hook(
        SootMethodDescriptor(class_name="NotFun", name="getInt",
                             params=()).address(), Custom_getInt())

    # set entry point to the 'game' method
    game_method = [
        m for m in project.loader.main_object.classes['NotFun'].methods
        if m.name == "game"
    ][0]
    game_entry = SootMethodDescriptor.from_soot_method(game_method).address()
    entry = project.factory.blank_state(addr=game_entry)
    simgr = project.factory.simgr(entry)

    # Create a fake file with what it is going to be printed to the user (concrete)
    fake_output_fd = entry.posix.open(b"/fake/output", Flags.O_RDWR)
    ff = entry.posix.fd[fake_output_fd]
    tstr = b"".join([bytes(str(n), 'utf-8') + b"\n" for n in numbers])
    ff.write_data(tstr, len(tstr))
    ff.seek(0)

    # Create a fake file with what the user as to insert (symbolic)
    fake_input_fd = entry.posix.open(b"/fake/input", Flags.O_RDWR)
    ff = entry.posix.fd[fake_input_fd]
    solutions = [claripy.BVS("solution%d" % (i), 32) for i in range(3)]
    for s in solutions:
        ff.write_data(s, 4)
    ff.seek(0)

    print("=" * 10 + " SYMBOLIC EXECUTION STARTED")
    while (len(simgr.active) > 0):
        simgr.step()
        print("===== " + str(simgr))
        print("===== " + ",".join([
            str(a.addr)
            for a in simgr.active if type(a.addr) == SootAddressDescriptor
        ]))

        # If we reach block_idx 30, it means that we solved 1 round of the game --> we stash the state
        # If we reach the gameFail() method, it means that we failed --> we prune the state
        simgr.move(
            'active', 'stashed',
            lambda a: type(a.addr) == SootAddressDescriptor and a.addr.method
            == SootMethodDescriptor("NotFun", "game",
                                    ()) and a.addr.block_idx == 30)
        simgr.move(
            'active', 'pruned', lambda a: type(a.addr) == SootAddressDescriptor
            and a.addr.method == SootMethodDescriptor("NotFun", "gameFail",
                                                      ()))

    print("=" * 10 + " SYMBOLIC EXECUTION ENDED")
    assert len(simgr.stashed) == 1
    win_state = simgr.stashed[0]
    numeric_solutions = []
    for s in solutions:
        es = win_state.solver.eval_atmost(s, 2)
        assert len(es) == 1
        numeric_solutions.append(es[0])
    return numeric_solutions