Python z3.sat() Examples

The following are 13 code examples of z3.sat(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module z3 , or try the search function .
Example #1
Source File: find_name_for_bits.py    From on-pwning with MIT License 8 votes vote down vote up
def find_name_for_bit_at_index(index, bit):
    solver = z3.Solver()

    NAME_LENGTH = 12  # arbitrary
    name = [z3.BitVec("c%d" % i, 32) for i in range(NAME_LENGTH)]
    for i in range(len(name)):
        solver.add(z3.And(name[i] > 0, name[i] <= 0xff))

    h1 = hash1(name)
    solver.add(h1 == index)

    h2 = hash2(name)
    solver.add(h2 == bit)

    h3 = hash3(name)
    solver.add(z3.Extract(15, 0, h3) == h2)  # for simplicity

    if solver.check() == z3.sat:
        return "".join(chr(solver.model()[c].as_long()) for c in name).encode("latin-1") 
Example #2
Source File: backend_z3.py    From claripy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _satisfiable(self, extra_constraints=(), solver=None, model_callback=None):
        global solve_count

        solve_count += 1
        if len(extra_constraints) > 0:
            solver.push()
            solver.add(*extra_constraints)

        try:

            l.debug("Doing a check!")
            #print "CHECKING"
            if solver.check() != z3.sat:
                return False

            if model_callback is not None:
                model_callback(self._generic_model(solver.model()))
        finally:
            if len(extra_constraints) > 0:
                solver.pop()
        return True 
Example #3
Source File: policy_symbolic.py    From ilf with Apache License 2.0 5 votes vote down vote up
def get_state_solver(gstate):
        solver = z3.Solver()
        solver.set('timeout',  3 * 60 * 1000)
        solver.add(gstate.wstate.constraints)
        res = solver.check()
        if res == z3.unknown: logging.info(f'{gstate.wstate.trace} gstate check timeout')
        return solver if res == z3.sat else None 
Example #4
Source File: policy_sym_plus.py    From ilf with Apache License 2.0 5 votes vote down vote up
def get_state_solver(gstate):
        if gstate.wstate.status == WorldStateStatus.INFEASIBLE:
            return None
        solver = z3.Solver()
        solver.set('timeout',  3 * 60 * 1000)
        solver.add(gstate.wstate.constraints)
        res = solver.check()
        if res == z3.unknown: logging.info(f'{gstate.wstate.trace} gstate check timeout')
        gstate.wstate.status = WorldStateStatus.FEASIBLE if res == z3.sat else WorldStateStatus.INFEASIBLE
        return solver if res == z3.sat else None 
Example #5
Source File: svm.py    From ilf with Apache License 2.0 5 votes vote down vote up
def trim_unrechable_states(self):
        # (parent, trace, child) tuples
        pending_parent_trace_child_tuples = [(None, None, self.root_wstate)]
        deleted_counter = 0
        s = Solver()
        while(len(pending_parent_trace_child_tuples)):
            s.push()
            parent_wstate, trace, curr_wstate = pending_parent_trace_child_tuples.pop()
            if curr_wstate.status != WorldStateStatus.REACHABLE:
                s.add(curr_wstate.constraints)
                res = s.check()
                if res == sat:
                    curr_wstate.status = WorldStateStatus.REACHABLE
                elif res == unsat:
                    curr_wstate.status = WorldStateStatus.UNREACHABLE
                elif res == z3.unknown:
                    print(curr_wstate.get_full_trace())
                    raise Exception("pdb")
            if curr_wstate.status == WorldStateStatus.REACHABLE:
                if curr_wstate != self.root_wstate:
                    parent_wstate.trace_to_children[trace].append(curr_wstate)
                for child_trace, children in curr_wstate.trace_to_children.items():
                    for child_wstate in children:
                        pending_parent_trace_child_tuples.append((curr_wstate, child_trace, child_wstate))
                curr_wstate.trace_to_children.clear()
            else:
                curr_wstate.status = WorldStateStatus.DELETED
                self.gen_to_wstates[curr_wstate.gen].remove(curr_wstate)
                deleted_counter += 1
            s.pop()
        logging.info('%d WorldStates are deleted', deleted_counter)

        logging.info('SVM initialized') 
Example #6
Source File: svm_utils.py    From ilf with Apache License 2.0 5 votes vote down vote up
def solve_wstate(wstate):
    solver = z3.Solver()
    solver.add(wstate.constraints)
    res = solver.check()
    if res == z3.unknown: logging.info('gstate check timeout')
    return solver if res == z3.sat else None 
Example #7
Source File: z3_common.py    From acsploit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_collisions(hash_func, target, target_type, length, n_collisions, hash_table_size, *args):
    ret = []
    s = z3.Solver()
    # houses the z3 variables for the potential hash match
    res = _generate_ascii_printable_string('res', length, s)
    # enforces the z3 constraint that the hash matches the target
    # if the target_type is 'preimage', then we compare the hash to the hash of target
    if target_type == 'preimage':
        s.add(hash_func(res, hash_table_size, *args) == hash_func(_str_to_BitVecVals8(target), hash_table_size, *args))
        if length == len(target):  # don't generate the given preimage as an output if generating inputs of that length
            s.add(z3.Or([r != ord(t) for r, t in zip(res, target)]))
    # otherwise the target_type is 'image', and we compare the hash to the target itself
    else:
        s.add(hash_func(res, hash_table_size, *args) == target)
    count = 0
    # z3 isn't stateful; you have to run it again and again while adding constraints to ignore previous solutions
    while s.check() == z3.sat:
        x = s.model()  # This is a z3 solution
        y = ''.join(chr(x[i].as_long()) for i in res)
        ret.append(y)
        count += 1
        # add constraints
        s.add(z3.Or([r != x[r] for r in res]))
        if count >= n_collisions:
            ret.sort()
            break
    return ret 
Example #8
Source File: game.py    From syntia with GNU General Public License v2.0 5 votes vote down vote up
def evaluate_expr_z3(self, expr, constraints, output_size):
        """
        Tramsforms an expression to z3
        :param expr: str
        :param constraints: list of constraints
        :return: int
        """
        # to z3 expression
        expr = self.to_z3(expr)
        # initialise solver
        solver = z3.Solver()
        # output variable
        output = z3.BitVec("o", output_size)

        solver.add(expr == output)

        # add constraints
        for c in constraints:
            solver.add(c)

        # check sat
        assert (solver.check() == z3.sat)
        # parse output
        ret = solver.model()[output].as_long()

        return ret 
Example #9
Source File: deflatten.py    From ollvm-breaker with MIT License 5 votes vote down vote up
def compute_reaching_states(bv, mlil, from_bb, to_bb, states):
    visitor = ConditionVisitor(bv)
    path = next(dfs_paths_backward(from_bb, to_bb))
    reaching_conditions = []
    cond = None
    for edge in path:
        terminator = edge.source[-1]
        # assert terminator.operation == MediumLevelILOperation.MLIL_IF
        if terminator.operation == MediumLevelILOperation.MLIL_IF:
            cond = terminator.condition
            if cond.operation == MediumLevelILOperation.MLIL_VAR:
                cond = mlil.get_var_definitions(cond.src)[0].src
            condition = visitor.visit(cond)
            if edge.type == BranchType.TrueBranch:
                reaching_conditions.append(condition)
            else:
                reaching_conditions.append(z3.Not(condition))

    solver = z3.Solver()
    for condition in reaching_conditions:
        solver.add(condition)

    reaching_states = set()
    if cond.operation == MediumLevelILOperation.MLIL_VAR:
        cond = mlil.get_var_definitions(cond.src)[0].src
    symbolic_state = make_variable(cond.left.src)
    for state in states:
        solver.push()
        solver.add(symbolic_state == state)
        if solver.check() == z3.sat:
            reaching_states.add(state)
        solver.pop()
    return list(reaching_states) 
Example #10
Source File: Z3.py    From jeeves with MIT License 5 votes vote down vote up
def isSatisfiable(self):
    r = self.solver.check()
    if r == z3.sat:
      return True
    elif r == z3.unsat:
      return False
    else:
      raise ValueError("got neither sat nor unsat from solver") 
Example #11
Source File: backend_z3.py    From claripy with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def _batch_eval(self, exprs, n, extra_constraints=(), solver=None, model_callback=None):
        global solve_count

        result_values = [ ]

        if len(extra_constraints) > 0 or n != 1:
            solver.push()
        if len(extra_constraints) > 0:
            solver.add(*extra_constraints)

        for i in range(n):
            solve_count += 1
            l.debug("Doing a check!")
            if solver.check() != z3.sat:
                break
            model = solver.model()

            # construct results
            r = [ ]
            for expr in exprs:
                if not isinstance(expr, (numbers.Number, str, bool)):
                    v = self._primitive_from_model(model, expr)
                    r.append(v)
                else:
                    r.append(expr)

            # Append the solution to the result list
            if model_callback is not None:
                model_callback(self._generic_model(solver.model()))
            result_values.append(tuple(r))

            # Construct the extra constraint so we don't get the same result anymore
            if i + 1 != n:
                if len(exprs) == 1:
                    solver.add(exprs[0] != r[0])
                else:
                    solver.add(self._op_raw_Not(self._op_raw_And(*[(ex == ex_v) for ex, ex_v in zip(exprs, r)])))
                model = None

        if len(extra_constraints) > 0 or n != 1:
            solver.pop()

        return result_values 
Example #12
Source File: execution.py    From ilf with Apache License 2.0 4 votes vote down vote up
def evaluate(self, gstate):
        stack_len_start = len(gstate.mstate.stack)
        self.pre_evaluate(gstate)
        if gstate.halt:
            return

        instr = gstate.environment.disassembly.instruction_list[gstate.mstate.pc]
        instr_address = instr['address']


        op = instr['opcode']
        match = re.match(r'^(PUSH|DUP|LOG|SWAP)\d{1,2}', op)
        op = match.group(1) if match else op
        eval_func = getattr(self, op, None)
        if eval_func is None:
            raise SVMRuntimeError(f'op evaluator not found: {op}')

        active_account = gstate.wstate.address_to_account[gstate.environment.active_address]
        current_func = '?'  if gstate.wstate.trace is None else gstate.wstate.trace
        arg = instr.get('argument', '')
        arg = (arg[0:10] + '..') if len(arg) > 12 else arg.ljust(12)
        logging.debug(f'{BColors.BLUE}{BColors.BOLD}OP{BColors.ENDC} '
                      f'{op.ljust(12)}\t'
                      f'{arg},\t'
                      f'addr={instr_address},\t'
                      f'pc={gstate.mstate.pc},\t'
                      f'contract={active_account.contract.name}\t'
                      f'func={current_func}\t'
                      f'sender={gstate.environment.sender}')
        arglist = inspect.getargspec(eval_func).args
        try:
            stack_args = [gstate.mstate.stack.pop() for arg in arglist[2:]]
            res = eval_func(gstate, *stack_args)
            gstate.mstate.pc += 1
            stack_len_stop = len(gstate.mstate.stack)
            self.op_to_stack_len[op] = (stack_len_stop - stack_len_start)
            return res
        except Exception as e:
            s = z3.Solver()
            s.add(gstate.wstate.constraints)
            if s.check() == z3.sat:
                raise e 
Example #13
Source File: custom_hash.py    From acsploit with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def run(output):
    ast = parse_input(options['hash'])
    variables = {}  # map from names to z3_vars
    z3_expression = ast.convert_to_z3(variables)

    solver = z3.Solver()
    if options['target_type'] == 'image':
        solver.add(options['image'] == z3_expression)
    elif options['target_type'] == 'preimage':
        # extract and validate the user-provided preimage
        preimage = options['preimage']
        var_defs = preimage.split(',')
        variable_values = {}
        if len(var_defs) < len(variables):
            raise ValueError('Not enough preimage values given for all variables used in the equation')
        for var_def in var_defs:
            try:
                variable_name, value = var_def.split('=', 1)
            except ValueError:
                raise ValueError('Invalid syntax for preimage values')
            variable_name = variable_name.strip()
            if variable_name in variable_values:
                raise ValueError('Multiple preimage values given for variable "%s"' % variable_name)
            try:
                value = int(value)
            except ValueError:
                raise ValueError('Preimage value "%s" for variable "%s" is not an integer' % (value, variable_name))
            variable_values[variable_name] = value
        for variable_name in variables:
            if variable_name not in variable_values:
                raise ValueError('Preimage value not given for variable "%s"' % variable_name)

        # we have a preimage but we want an image to set z3_expression equal to for solving
        # so we set a new variable equal to z3_expression, provide the preimage values,
        #  and then ask Z3 to solve for our new variable
        target_var = z3.BitVec('__v', ast.target_width)
        sub_solver = z3.Solver()
        sub_solver.add(target_var == z3_expression)
        for variable in variables:
            sub_solver.add(variables[variable] == variable_values[variable])
        assert sub_solver.check() == z3.sat  # this should always hold, since the target var is unbounded
        solution = sub_solver.model()
        target_value = solution[target_var]

        # we can now set z3_expression equal to the appropriate image
        solver.add(target_value == z3_expression)
        # and also prevent the preimage values being generated as a solution
        solver.add(z3.Or([var() != solution[var] for var in solution if var.name() != '__v']))

    solutions = []
    while solver.check() == z3.sat and len(solutions) < options['n_collisions']:
        solution = solver.model()
        solutions.append(solution)
        # prevent duplicate solutions
        solver.add(z3.Or([var() != solution[var] for var in solution]))

    output.output(solutions)