Python claripy.Or() Examples

The following are 17 code examples of claripy.Or(). 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 claripy , or try the search function .
Example #1
Source File: common_backend_smt_solver.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_or(self):
        str_symb = claripy.StringS("Symb_or", 4, explicit_name=True)
        solver = self.get_solver()
        res = claripy.Or((str_symb == claripy.StringV("abc")),
                         (str_symb == claripy.StringV("ciao")))
        solver.add(res)
        self.assertTrue(solver.satisfiable())

        result = solver.eval(str_symb, 3 if KEEP_TEST_PERFORMANT else 100)
        self.assertEqual({'ciao', 'abc'}, set(result)) 
Example #2
Source File: solve.py    From angr-doc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, idx): # pylint: disable=W0221
        cidxlist = self.state.solver.eval_upto(idx, 256)
        if len(cidxlist) == 1:
            cidx = cidxlist[0]
            ii = int(self.tstr.split(" ")[cidx], 10)
            return claripy.BVV(ii, 32)
        else:
            bvs = claripy.BVS("gsn", 32)
            contraint_list = [claripy.And(bvs == int(self.tstr.split(" ")[cidx], 10), idx==cidx) for cidx in cidxlist]
            fc = claripy.Or(*contraint_list)
            print(repr(fc)[:200]+" ... "+repr(fc)[-200:])
            self.state.add_constraints(fc)
            return bvs 
Example #3
Source File: oob.py    From pitchfork with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _concretize(self, memory, addr):
        """
        Attempts to resolve the address to a value *outside* all of the in-bounds
        intervals if possible.
        Else, defers to fallback strategies.
        """
        try:
            constraints = [memory.state.solver.Or(addr < mn, addr >= mx) for (mn, mx) in memory.state.oob.inbounds_intervals]
            return [ self._any(memory, addr, extra_constraints=constraints) ]
        except angr.errors.SimUnsatError:
            # no solution
            return None 
Example #4
Source File: oob.py    From pitchfork with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def can_be_oob(state, addr, length):
    l.debug("checking if {} can be oob".format(addr))
    inbounds_intervals = state.oob.inbounds_intervals + [get_stack_interval(state)]
    oob_constraints = [claripy.Or(addr < mn, addr+length > mx) for (mn,mx) in inbounds_intervals]
    if state.solver.satisfiable(extra_constraints=oob_constraints): return True  # there is a solution to current constraints such that the access is OOB
    return False  # operation must be inbounds 
Example #5
Source File: spectre.py    From pitchfork with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def concretize(self, memory, addr):
        """
        Attempts to resolve the address to a value in the targeted interval(s)
        if possible. Else, defers to fallback strategies.
        """
        if not self.targetedIntervals: return None
        try:
            constraint = claripy.Or(*[claripy.And(addr >= mn, addr < mx) for (mn,mx) in self.targetedIntervals])
            return [ self._any(memory, addr, extra_constraints=[constraint]) ]
        except angr.errors.SimUnsatError:
            # no solution
            return None 
Example #6
Source File: spectre.py    From pitchfork with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _can_point_to_secret(state, ast):
    if not isinstance(state.spectre, SpectreExplicitState): return False
    in_each_interval = [claripy.And(ast >= mn, ast < mx) for (mn,mx) in state.spectre.secretIntervals]
    if state.solver.satisfiable(extra_constraints=[claripy.Or(*in_each_interval)]): return True  # there is a solution to current constraints such that the ast points to secret
    return False  # ast cannot point to secret 
Example #7
Source File: test_backend_smt.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_or(self):
        correct_script = '''(set-logic ALL)
(declare-fun {0}Symb_or () String)
(assert (let ((.def_0 (= {0}Symb_or "ciao"))) (let ((.def_1 (= {0}Symb_or "abc"))) (let ((.def_2 (or .def_1 .def_0))) .def_2))))
(check-sat)
'''.format(String.STRING_TYPE_IDENTIFIER)
        str_symb = claripy.StringS("Symb_or", 4, explicit_name=True)
        solver = self.get_solver()
        res = claripy.Or((str_symb == claripy.StringV("abc")),
                         (str_symb == claripy.StringV("ciao")))
        solver.add(res)
        script = solver.get_smtlib_script_satisfiability()
        # with open("dump_or.smt2", "w") as dump_f:
        #     dump_f.write(script)
        self.assertEqual(correct_script, script) 
Example #8
Source File: test_simplify.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_bool_simplification():
    def assert_correct(a, b):
        nose.tools.assert_true(claripy.backends.z3.identical(claripy.simplify(a), b))

    a, b, c = (claripy.BoolS(name) for name in ('a', 'b', 'c'))

    assert_correct(claripy.And(a, claripy.Not(a)), claripy.false)
    assert_correct(claripy.Or(a, claripy.Not(a)), claripy.true)

    complex_true_expression = claripy.Or(
        claripy.And(a,b),
        claripy.Or(claripy.And(a, claripy.Not(b)), claripy.And(claripy.Not(a), c)),
        claripy.Or(claripy.And(a, claripy.Not(b)), claripy.And(claripy.Not(a), claripy.Not(c))))
    assert_correct(complex_true_expression, claripy.true) 
Example #9
Source File: test_expression.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_bool():
    bc = claripy.backends.concrete

    a = claripy.And(*[False, False, True])
    nose.tools.assert_equal(bc.convert(a), False)
    a = claripy.And(*[True, True, True])
    nose.tools.assert_equal(bc.convert(a), True)

    o = claripy.Or(*[False, False, True])
    nose.tools.assert_equal(bc.convert(o), True)
    o = claripy.Or(*[False, False, False])
    nose.tools.assert_equal(bc.convert(o), False) 
Example #10
Source File: rop_leak_memory.py    From rex with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_circumstantial_constraints(self, state, rop_uncontrolled):
        # for those registers which are uncontrolled by rop, can we control it
        # circumstantially?

        constraints = [ ]
        for register in rop_uncontrolled:
            # if it's eax we can't control with rop, make sure it can be 2
            if register == "eax":
                constraints.append(state.regs.eax == 2)
            # if it's ebx we need to make sure it can stdout
            if register == "ebx":
                constraints.append(state.regs.ebx == 1)
            if register == "ecx":
                constraints.append(state.regs.ecx >= 0x4347c000)
                constraints.append(state.regs.ecx <= (0x4347d000 - 4))
            # if it's edx, we need to be able to set it to just above 4 bytes
            if register == "edx":
                constraints.append(state.regs.edx > 0x4)
            # if it's esi, we need to point to NULL or a writable page
            # TODO support setting to a writable page
            if register == "esi":
                or_cons = [ ]
                for page_start, page_end in self._get_writable_pages(state):
                    or_cons.append(claripy.And(state.regs.esi >= page_start, state.regs.esi <= (page_end - 4)))

                combine_cons = or_cons[0]
                for con in or_cons[1:]:
                    combine_cons = claripy.Or(combine_cons, con)

                constraints.append(combine_cons)

        return constraints 
Example #11
Source File: condition_processor.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _fold_double_negations(cond):

        # !(!A) ==> A
        # !((!A) && (!B)) ==> A || B
        # !((!A) && B) ==> A || !B
        # !(A || B) ==> (!A && !B)

        if cond.op != "Not":
            return None
        if cond.args[0].op == "Not":
            return cond.args[0]

        if cond.args[0].op == "And" and len(cond.args[0].args) == 2:
            and_0, and_1 = cond.args[0].args
            if and_0.op == "Not" and and_1.op == "Not":
                expr = claripy.Or(and_0.args[0], and_1.args[0])
                return expr

            if and_0.op == "Not":  # and_1.op != "Not"
                expr = claripy.Or(
                    and_0.args[0],
                    ConditionProcessor.simplify_condition(
                        claripy.Not(and_1)
                    )
                )
                return expr

        if cond.args[0].op == "Or" and len(cond.args[0].args) == 2:
            or_0, or_1 = cond.args[0].args
            expr = claripy.And(
                ConditionProcessor.simplify_condition(claripy.Not(or_0)),
                ConditionProcessor.simplify_condition(claripy.Not(or_1)),
            )
            return expr

        return None


# delayed import 
Example #12
Source File: strtol.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _char_to_val(char, base):
        """
        converts a symbolic char to a number in the given base
        returns expression, result
        expression is a symbolic boolean indicating whether or not it was a valid number
        result is the value
        """
        cases = []
        # 0-9
        max_digit = claripy.BVV(b"9")
        min_digit = claripy.BVV(b"0")
        if base < 10:
            max_digit = claripy.BVV(ord("0") + base, 8)
        is_digit = claripy.And(char >= min_digit, char <= max_digit)
        # return early here so we don't add unnecessary statements
        if base <= 10:
            return is_digit, char - min_digit

        # handle alphabetic chars
        max_char_lower = claripy.BVV(ord("a") + base-10 - 1, 8)
        max_char_upper = claripy.BVV(ord("A") + base-10 - 1, 8)
        min_char_lower = claripy.BVV(ord("a"), 8)
        min_char_upper = claripy.BVV(ord("A"), 8)

        cases.append((is_digit, char - min_digit))
        is_alpha_lower = claripy.And(char >= min_char_lower, char <= max_char_lower)
        cases.append((is_alpha_lower, char - min_char_lower + 10))
        is_alpha_upper = claripy.And(char >= min_char_upper, char <= max_char_upper)
        cases.append((is_alpha_upper, char - min_char_upper + 10))

        expression = claripy.Or(is_digit, is_alpha_lower, is_alpha_upper)
        # use the last case as the default, the expression will encode whether or not it's satisfiable
        result = claripy.ite_cases(cases[:-1], cases[-1][1])

        return expression, result 
Example #13
Source File: strtol.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def strtol_inner(s, state, region, base, signed, read_length=None):
        """
        :param s: the string address/offset
        :param state: SimState
        :param region: memory, file, etc
        :param base: the base to use to interpret the number
        note: all numbers may start with +/- and base 16 may start with 0x
        :param signed: boolean, true means the result will be signed, otherwise unsigned
        :param read_length: int, the number of bytes parsed in strtol
        :return: expression, value, num_bytes
        the returned expression is a symbolic boolean indicating success, value will be set to 0 on failure
        value is the returned value (set to min/max on overflow)
        num_bytes is the number of bytes read in the string
        """

        # sanity check
        if base < 2 or base > 36:
            raise SimProcedureError("base should be in the range [2,36]")

        # order matters here since we will use an if then else tree, and -0x will have precedence over -
        prefixes = [b"-", b"+", b""]
        if base == 16:
            prefixes = [b"0x", b"-0x", b"+0x"] + prefixes

        cases = []
        conditions = []
        possible_num_bytes = []

        for prefix in prefixes:
            if read_length and read_length < len(prefix):
                continue
            condition, value, num_bytes = strtol._load_num_with_prefix(prefix, s, region, state, base, signed, read_length)
            conditions.append(condition)
            cases.append((condition, value))
            possible_num_bytes.append(num_bytes)

        # only one of the cases needed to match
        result = state.solver.ite_cases(cases[:-1], cases[-1][1])
        expression = state.solver.Or(*conditions)
        num_bytes = state.solver.ite_cases(zip(conditions, possible_num_bytes), 0)
        return expression, result, num_bytes 
Example #14
Source File: command_injection.py    From Firmware_Slap with GNU General Public License v3.0 5 votes vote down vote up
def constrain_control(self,
                          state,
                          symbolic_variable,
                          start_loc,
                          select_string="`ls`"):
        for i in range(len(select_string)):
            current_byte = state.memory.load(start_loc + i).get_byte(0)
            state.add_constraints(
                claripy.Or(claripy.And(select_string[i] == current_byte))) 
Example #15
Source File: condition_processor.py    From angr with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def convert_claripy_bool_ast_core(self, cond, memo):
        if isinstance(cond, ailment.Expr.Expression):
            return cond

        if cond.op == "BoolS" and claripy.is_true(cond):
            return cond
        if cond in self._condition_mapping:
            return self._condition_mapping[cond]

        def _binary_op_reduce(op, args, signed=False):
            r = None
            for arg in args:
                if r is None:
                    r = self.convert_claripy_bool_ast(arg, memo=memo)
                else:
                    r = ailment.Expr.BinaryOp(None, op, (r, self.convert_claripy_bool_ast(arg, memo=memo)), signed)
            return r

        _mapping = {
            'Not': lambda cond_: _binary_op_reduce('Not', cond_.args),
            'And': lambda cond_: _binary_op_reduce('LogicalAnd', cond_.args),
            'Or': lambda cond_: _binary_op_reduce('LogicalOr', cond_.args),
            '__le__': lambda cond_: _binary_op_reduce('CmpLE', cond_.args, signed=True),
            'SLE': lambda cond_: _binary_op_reduce('CmpLE', cond_.args, signed=True),
            '__lt__': lambda cond_: _binary_op_reduce('CmpLT', cond_.args, signed=True),
            'SLT': lambda cond_: _binary_op_reduce('CmpLT', cond_.args, signed=True),
            'UGT': lambda cond_: _binary_op_reduce('CmpGT', cond_.args),
            'UGE': lambda cond_: _binary_op_reduce('CmpGE', cond_.args),
            '__gt__': lambda cond_: _binary_op_reduce('CmpGT', cond_.args, signed=True),
            '__ge__': lambda cond_: _binary_op_reduce('CmpGE', cond_.args, signed=True),
            'SGT': lambda cond_: _binary_op_reduce('CmpGT', cond_.args, signed=True),
            'SGE': lambda cond_: _binary_op_reduce('CmpGE', cond_.args, signed=True),
            'ULT': lambda cond_: _binary_op_reduce('CmpLT', cond_.args),
            'ULE': lambda cond_: _binary_op_reduce('CmpLE', cond_.args),
            '__eq__': lambda cond_: _binary_op_reduce('CmpEQ', cond_.args),
            '__ne__': lambda cond_: _binary_op_reduce('CmpNE', cond_.args),
            '__add__': lambda cond_: _binary_op_reduce('Add', cond_.args, signed=False),
            '__sub__': lambda cond_: _binary_op_reduce('Sub', cond_.args),
            '__mul__': lambda cond_: _binary_op_reduce('Mul', cond_.args),
            '__xor__': lambda cond_: _binary_op_reduce('Xor', cond_.args),
            '__or__': lambda cond_: _binary_op_reduce('Or', cond_.args, signed=False),
            '__and__': lambda cond_: _binary_op_reduce('And', cond_.args),
            '__lshift__': lambda cond_: _binary_op_reduce('Shl', cond_.args),
            '__rshift__': lambda cond_: _binary_op_reduce('Sar', cond_.args),
            'LShR': lambda cond_: _binary_op_reduce('Shr', cond_.args),
            'BVV': lambda cond_: ailment.Expr.Const(None, None, cond_.args[0], cond_.size()),
            'BoolV': lambda cond_: ailment.Expr.Const(None, None, True, 1) if cond_.args[0] is True
                                                                        else ailment.Expr.Const(None, None, False, 1),
        }

        if cond.op in _mapping:
            return _mapping[cond.op](cond)
        raise NotImplementedError(("Condition variable %s has an unsupported operator %s. "
                                   "Consider implementing.") % (cond, cond.op)) 
Example #16
Source File: structurer.py    From angr with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def _merge_conditional_breaks(seq):

        # Find consecutive ConditionalBreakNodes and merge their conditions

        def _handle_SequenceNode(seq_node, parent=None, index=0, label=None):  # pylint:disable=unused-argument
            new_nodes = []
            i = 0
            while i < len(seq_node.nodes):
                old_node = seq_node.nodes[i]
                if type(old_node) is CodeNode:
                    node = old_node.node
                else:
                    node = old_node
                new_node = None
                if isinstance(node, ConditionalBreakNode) and new_nodes:
                    prev_node = new_nodes[-1]
                    if type(prev_node) is CodeNode:
                        prev_node = prev_node.node
                    if isinstance(prev_node, ConditionalBreakNode):
                        # found them!
                        # pop the previously added node
                        if new_nodes:
                            new_nodes = new_nodes[:-1]
                        merged_condition = ConditionProcessor.simplify_condition(claripy.Or(node.condition,
                                                                                            prev_node.condition))
                        new_node = ConditionalBreakNode(node.addr,
                                                        merged_condition,
                                                        node.target
                                                        )
                        walker.merged = True
                else:
                    walker._handle(node, parent=seq_node, index=i)

                if new_node is not None:
                    new_nodes.append(new_node)
                else:
                    new_nodes.append(old_node)
                i += 1

            seq_node.nodes = new_nodes

        handlers = {
            SequenceNode: _handle_SequenceNode,
        }

        walker = SequenceWalker(handlers=handlers)
        walker.merged = False  # this is just a hack
        walker.walk(seq)
        return walker.merged, seq 
Example #17
Source File: strtol.py    From angr with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def run(self, nptr, endptr, base):  # pylint: disable=arguments-differ
        if self.state.solver.symbolic(base):
            l.warning("Concretizing symbolic base in strtol")
            base_concrete = self.state.solver.eval(base)
            self.state.add_constraints(base == base_concrete)

        base = self.state.solver.eval(base)

        if base == 0:
            # in this case the base is 16 if it starts with 0x, 8 if it starts with 0, 10 otherwise
            # here's the possibilities
            base_16_pred = self.state.solver.Or(
                self.state.memory.load(nptr, 2) == self.state.solver.BVV(b"0x"),
                self.state.memory.load(nptr, 3) == self.state.solver.BVV(b"+0x"),
                self.state.memory.load(nptr, 3) == self.state.solver.BVV(b"-0x"))
            base_8_pred = self.state.solver.And(
                self.state.solver.Or(
                    self.state.memory.load(nptr, 1) == self.state.solver.BVV(b"0"),
                    self.state.memory.load(nptr, 2) == self.state.solver.BVV(b"+0"),
                    self.state.memory.load(nptr, 2) == self.state.solver.BVV(b"-0")),
                self.state.solver.Not(base_16_pred))
            base_10_pred = self.state.solver.And(
                self.state.solver.Not(base_16_pred),
                self.state.solver.Not(base_8_pred)
            )
            expressions = []
            values = []
            num_bytes_arr = []

            # read a string to long for each possibility
            pred_base = zip([base_16_pred, base_10_pred, base_8_pred], [16, 10, 8])
            for pred, sub_base in pred_base:
                expression, value, num_bytes = self.strtol_inner(nptr, self.state, self.state.memory, sub_base, True)
                expressions.append(self.state.solver.And(expression, pred))
                values.append(value)
                num_bytes_arr.append(num_bytes)

            # we would return the Or(expressions) as the indicator whether or not it succeeded, but it's not needed
            # for strtol
            # expression = self.state.solver.Or(expressions)
            value = self.state.solver.ite_cases(zip(expressions, values), 0)
            num_bytes = self.state.solver.ite_cases(zip(expressions, num_bytes_arr), 0)

            self.state.memory.store(endptr, nptr+num_bytes,
                                    condition=(endptr != 0), endness=self.state.arch.memory_endness)

            return value

        else:
            expression, value, num_bytes = self.strtol_inner(nptr, self.state, self.state.memory, base, True)
            self.state.memory.store(endptr, nptr+num_bytes, condition=(endptr != 0), endness=self.state.arch.memory_endness)
            return self.state.solver.If(expression, value, 0)