Python claripy.And() Examples

The following are 30 code examples of claripy.And(). 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: test_expression.py    From claripy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_canonical():
    x1 = claripy.BVS('x', 32)
    b1 = claripy.BoolS('b')
    c1 = claripy.BoolS('c')
    x2 = claripy.BVS('x', 32)
    b2 = claripy.BoolS('b')
    c2 = claripy.BoolS('c')

    assert x1.canonicalize()[-1] is x2.canonicalize()[-1]

    y1 = claripy.If(claripy.And(b1, c1), x1, ((x1+x1)*x1)+1)
    y2 = claripy.If(claripy.And(b2, c2), x2, ((x2+x2)*x2)+1)

    one_names = frozenset.union(x1.variables, b1.variables, c1.variables)
    two_names = frozenset.union(x2.variables, b2.variables, c2.variables)

    assert frozenset.union(*[a.variables for a in y1.recursive_leaf_asts]) == one_names
    assert frozenset.union(*[a.variables for a in y2.recursive_leaf_asts]) == two_names
    assert y1.canonicalize()[-1] is y2.canonicalize()[-1] 
Example #2
Source File: overflowExploiter.py    From Zeratool with GNU General Public License v3.0 6 votes vote down vote up
def constrainToAddress(state,sym_val,addr,endian='little'):

    bits = state.arch.bits
    padded_addr = 0

    if bits == 32:
        padded_addr = p32(addr,endian=endian)
    elif bits == 64:
        botAddr = addr & 0xFFFFFFFF
        topAddr = (addr >> 32) & 0xFFFFFFFF
        padded_addr = p32(topAddr,endian=endian) + p32(botAddr,endian=endian)

    constraints = []
    for i in range(bits / 8):
        curr_byte = sym_val.get_byte(i)
        constraint = claripy.And(curr_byte == padded_addr[i])
        if state.se.satisfiable(extra_constraints=[constraint]):
            constraints.append(constraint)

    return constraints

#TODO move filters out of this file 
Example #3
Source File: workers.py    From DROP-IDA-plugin with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        self.log_signal.emit("Start of ConcreteRunner!")

        # Make sure the CFG is built
        build_cfg(self.plugin, self.ida_func, self.log_signal)

        try:
            # Run the function concretely to get a 'trace'
            addr_trace = self.run_function_concrete()
 
            # And send the results back to the GUI thread
            self.result_signal.emit(addr_trace)
        except:
            self.result_signal.emit([])


        self.log_signal.emit("End of ConcreteRunner!") 
Example #4
Source File: trace_additions.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_same_length_constraints(self):
        constraints = []
        for str_var, int_var in self.str_to_int_pairs:
            int_var_name = list(int_var.variables)[0]
            base = int(int_var_name.split("_")[1], 10)
            original_len = str_var.size()//8
            abs_max = (1 << int_var.size())-1
            if str_var.cache_key in self.allows_negative_bvs:
                abs_max = (1 << (int_var.size()-1))-1
            max_val = base**(original_len)-1
            min_val = 0
            if str_var.cache_key in self.allows_negative_bvs and original_len > 1:
                min_val = -(base**(original_len-1)-1)

            max_val = min(max_val, abs_max)
            min_val = max(min_val, -abs_max)

            constraints.append(claripy.And(int_var.SGE(min_val), int_var <= max_val))
        return constraints 
Example #5
Source File: strtol.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _load_num_with_prefix(prefix, addr, region, state, base, signed, read_length=None):
        """
        loads a number from addr, and returns a condition that addr must start with the prefix
        """
        length = len(prefix)
        read_length = (read_length-length) if read_length else None
        condition, value, num_bytes = strtol._string_to_int(addr+length, state, region, base, signed, read_length)

        # the prefix must match
        if len(prefix) > 0:
            loaded_prefix = region.load(addr, length)
            condition = state.solver.And(loaded_prefix == state.solver.BVV(prefix), condition)
        total_num_bytes = num_bytes + length

        # negatives
        if prefix.startswith(b"-"):
            value = state.solver.BVV(0, state.arch.bits) - value
        return condition, value, total_num_bytes 
Example #6
Source File: structurer.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _make_condition_nodes(self, seq):

        # make all conditionally-reachable nodes ConditionNodes
        for i in range(len(seq.nodes)):
            node = seq.nodes[i]

            if isinstance(node, CodeNode):
                if isinstance(node.node, SequenceNode):
                    self._make_condition_nodes(node.node)

                if node.reaching_condition is not None and not claripy.is_true(node.reaching_condition):
                    if isinstance(node.node, ConditionalBreakNode):
                        # Put conditions together and simplify them
                        cond = claripy.And(node.reaching_condition, node.node.condition)
                        new_node = CodeNode(ConditionalBreakNode(node.node.addr, cond, node.node.target), None)
                    else:
                        new_node = ConditionNode(node.addr, None, node.reaching_condition, node,
                                                 None)
                    seq.nodes[i] = new_node 
Example #7
Source File: heap_condition_tracker.py    From heaphopper with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check_write(state):
    # If we found an arb_write we're done
    if state.heaphopper.vuln_type.startswith('arbitrary_write'):
        return

    # Check if we have an arbitrary_write
    addr = state.inspect.mem_write_address
    val = state.inspect.mem_write_expr
    #logger.debug('check_write: addr: %s' % addr)
    #logger.debug('check_write: val: %s' % val)
    constr = claripy.And(addr >= state.heaphopper.wtarget[0],
                         addr < state.heaphopper.wtarget[0] + state.heaphopper.wtarget[1])

    if state.solver.satisfiable(extra_constraints=[constr]):
        #logger.debug('check_write: Found arbitrary write')
        state.add_constraints(constr)
        state.heaphopper.vuln_state = state.copy()
        state.heaphopper.arb_write_info = dict(instr=state.addr, addr=addr, val=val)
        state.heaphopper.vuln_type = 'arbitrary_write'
        state.heaphopper.stack_trace = get_libc_stack_trace(state) 
Example #8
Source File: heap_condition_tracker.py    From heaphopper with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check_overlap(self, malloc_dict, addr, req_size):
        for dst in list(malloc_dict.keys()):
            alloc = malloc_dict[dst][1]
            condition1 = self.state.solver.And(alloc < addr, alloc + malloc_dict[dst][0] > addr)
            condition2 = self.state.solver.And(alloc > addr, addr + req_size > alloc)
            if self.state.solver.satisfiable(extra_constraints=[condition1]):
                logger.info('Found overlapping allocation')
                self.state.add_constraints(condition1)
                self.state.heaphopper.vulnerable = True
                self.state.heaphopper.vuln_type = 'malloc_allocated'
                self.state.heaphopper.vuln_state = self.state.copy()
                return True
            if self.state.solver.satisfiable(extra_constraints=[condition2]):
                logger.info('Found overlapping allocation')
                self.state.add_constraints(condition2)
                self.state.heaphopper.vulnerable = True
                self.state.heaphopper.vuln_type = 'malloc_allocated'
                self.state.heaphopper.vuln_state = self.state.copy()
                return True
        return False 
Example #9
Source File: heap_condition_tracker.py    From heaphopper with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def check_sym_data(state):
    # Check if we overwrite a sym_data structure passed to free
    addr = state.inspect.mem_write_address
    free_addr = state.heaphopper.curr_freed_chunk
    if free_addr in state.heaphopper.sym_data_states and not state.heaphopper.sym_data_states[free_addr]:
        #logger.debug('check_sym_data: curr_freed_chunk: 0x%x' % free_addr)
        #logger.debug('check_sym_data: addr: %s' % addr)
        constr = claripy.And(addr >= free_addr, addr < free_addr + state.heaphopper.sym_data_size)
        if not state.solver.symbolic(addr) and state.solver.satisfiable(extra_constraints=[constr]):
            #logger.debug('check_sym_data: Saving state')
            state.heaphopper.sym_data_states[free_addr] = state.copy() 
Example #10
Source File: test_solver.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_composite_solver_with_strings():
    try:
        s = claripy.SolverComposite(
            template_solver_string=claripy.SolverCompositeChild(backend=claripy.backend_manager.backends.smtlib_cvc4))
        x = claripy.BVS("x", 32)
        y = claripy.BVS("y", 32)
        z = claripy.BVS("z", 32)
        str_1 = claripy.StringS("sym_str_1", 1024)
        c = claripy.And(x == 1, y == 2, z == 3, str_1 == claripy.StringV("cavallo"))
        s.add(c)
        nose.tools.assert_equal(len(s._solver_list), 4)
        nose.tools.assert_true(s.satisfiable())
        nose.tools.assert_equal(list(s.eval(str_1, 1)), ["cavallo"])
    except claripy.errors.MissingSolverError:
        raise nose.SkipTest() 
Example #11
Source File: memory_8.py    From angrdbg with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _store_symbolic_addr(self, address,  addresses, size, data, endness, condition):
        size = self.state.solver.eval(size)
        segments = self._get_segments(addresses, size)

        if condition is None:
            condition = claripy.BoolV(True)

        original_values = [ self._read_from(segment['start'], segment['size']) for segment in segments ]
        if endness == "Iend_LE" or (endness is None and self.endness == "Iend_LE"):
            original_values = [ ov.reversed  for ov in original_values ]

        stored_values = []
        for segment, original_value  in zip(segments, original_values):
            conditional_value = original_value

            for opt in segment['options']:

                if endness == "Iend_LE" or (endness is None and self.endness == "Iend_LE"):
                    high = ((opt['idx']+segment['size']) * self.state.arch.byte_width)-1
                    low = opt['idx']*self.state.arch.byte_width
                else:
                    high = len(data) - 1 - (opt['idx']*self.state.arch.byte_width)
                    low = len(data) - ((opt['idx']+segment['size']) *self.state.arch.byte_width)

                data_slice = data[high:low]
                conditional_value = self.state.solver.If(self.state.solver.And(address == segment['start']-opt['idx'], condition), data_slice, conditional_value)

            stored_values.append(dict(value=conditional_value, addr=segment['start'], size=segment['size']))

        return stored_values 
Example #12
Source File: memory_8.py    From angrdbg with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _store_fully_symbolic(self, address, addresses, size, data, endness, condition):
        stored_values = [ ]
        byte_dict = defaultdict(list)
        max_bytes = data.length//self.state.arch.byte_width

        if condition is None:
            condition = claripy.BoolV(True)

        # chop data into byte-chunks
        original_values = [self._read_from(a, max_bytes) for a in addresses]
        if endness == "Iend_LE" or (endness is None and self.endness == "Iend_LE"):
            original_values = [ ov.reversed  for ov in original_values ]
        data_bytes = data.chop(bits=self.state.arch.byte_width)

        for a, fv in zip(addresses, original_values):
            original_bytes = fv.chop(self.state.arch.byte_width)
            for index, (d_byte, o_byte) in enumerate(zip(data_bytes, original_bytes)):
                # create a dict of all all possible values for a certain address
                byte_dict[a+index].append((a, index, d_byte, o_byte))

        for byte_addr in sorted(byte_dict.keys()):
            write_list = byte_dict[byte_addr]
            # If this assertion fails something is really wrong!
            assert all(v[3] is write_list[0][3] for v in write_list)
            conditional_value = write_list[0][3]
            for a, index, d_byte, o_byte in write_list:
                # create the ast for each byte
                conditional_value = self.state.solver.If(self.state.solver.And(address == a, size > index, condition), d_byte, conditional_value)

            stored_values.append(dict(value=conditional_value, addr=byte_addr, size=1))

        return stored_values 
Example #13
Source File: input.py    From heaphopper with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def check_input(state, values, fd):
    if values == 'printable':
        ranges = [['!', '~']]
    elif values == 'alphanumeric':
        ranges = [['0', '9'], ['A', 'Z'], ['a', 'z']]
    elif values == 'letters':
        ranges = [['A', 'Z'], ['a', 'z']]
    elif values == 'zero-bytes':
        ranges = [['\0', '\0']]
    elif values == 'ascii':
        ranges = [['\0', '\x7f']]
    elif values == 'any':
        return state
    else:
        logger.error('Invalid input constraint')
        sys.exit(-1)


    stdin = state.posix.get_fd(fd).all_bytes().chop(8)
    constraints = claripy.And()
    for c in stdin:
        constraint = claripy.And()
        for r in ranges:
            constraint = claripy.And(c >= r[0], c <= r[1], constraint)
        constraints = claripy.And(constraint, constraints)
    if state.solver.satisfiable(extra_constraints=[constraints]):
        state.add_constraints(constraints)
        return state
    else:
        return None 
Example #14
Source File: input.py    From heaphopper with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def constrain_input(state, stdin, values):
    if values == 'printable':
        ranges = [['!', '~']]
    elif values == 'alphanumeric':
        ranges = [['0', '9'], ['A', 'Z'], ['a', 'z']]
    elif values == 'letters':
        ranges = [['A', 'Z'], ['a', 'z']]
    elif values == 'zero-bytes':
        ranges = [['\0', '\0']]
    elif values == 'ascii':
        ranges = [['\0', '\x7f']]
    elif values == 'any':
        return state
    else:
        logger.error('Invalid input constraint')
        sys.exit(-1)

    constraints = claripy.And()
    for c in stdin:
        constraint = claripy.And()
        for r in ranges:
            constraint = claripy.And(c >= r[0], c <= r[1], constraint)
        constraints = claripy.And(constraint, constraints)
    if state.solver.satisfiable(extra_constraints=[constraints]):
        state.add_constraints(constraints)
        return state
    else:
        return None 
Example #15
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 #16
Source File: specvex.py    From pitchfork with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def overlaps(addrA, sizeInBytesA, addrB, sizeInBytesB):
    """
    Returns a symbolic constraint representing the two intervals overlapping.
    If this constraint is simply True, then the intervals must overlap; if it is False, they cannot;
        and if it is some symbolic expression that may take either value, that expression encodes the
        condition under which they overlap.
    """
    a_left = addrA
    a_right = addrA + sizeInBytesA
    b_left = addrB
    b_right = addrB + sizeInBytesB
    return claripy.And(a_right > b_left, a_left < b_right) 
Example #17
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 #18
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 #19
Source File: solve.py    From angr-doc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, _, length): # pylint: disable=W0221
        bvs = claripy.BVS("Random.nextInt", 32)
        cs =  claripy.And(claripy.SGE(bvs, 0), claripy.SLE(bvs, length))
        self.state.add_constraints(cs)
        return bvs 
Example #20
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 #21
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 #22
Source File: heavy.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _perform_vex_stmt_Exit(self, guard, target, jumpkind):
        cont_state = None
        exit_state = None
        guard = guard != 0

        if o.COPY_STATES not in self.state.options:
            # very special logic to try to minimize copies
            # first, check if this branch is impossible
            if guard.is_false():
                cont_state = self.state
            elif o.LAZY_SOLVES not in self.state.options and not self.state.solver.satisfiable(extra_constraints=(guard,)):
                cont_state = self.state

            # then, check if it's impossible to continue from this branch
            elif guard.is_true():
                exit_state = self.state
            elif o.LAZY_SOLVES not in self.state.options and not self.state.solver.satisfiable(extra_constraints=(claripy.Not(guard),)):
                exit_state = self.state
            else:
                exit_state = self.state.copy()
                cont_state = self.state
        else:
            exit_state = self.state.copy()
            cont_state = self.state

        if exit_state is not None:
            self.successors.add_successor(exit_state, target, guard, jumpkind,
                                     exit_stmt_idx=self.stmt_idx, exit_ins_addr=self.state.scratch.ins_addr)

        if cont_state is None:
            raise VEXEarlyExit

        # Do our bookkeeping on the continuing self.state
        cont_condition = ~guard
        cont_state.add_constraints(cont_condition)
        cont_state.scratch.guard = claripy.And(cont_state.scratch.guard, cont_condition) 
Example #23
Source File: arrayref.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def check_array_bounds(idx, array, state):
        # a valid idx fullfills the constraint
        # 0 <= idx < length
        zero = state.solver.BVV(0, 32)
        length = array.size
        bound_constraint = state.solver.And(
            length.SGT(idx), zero.SLE(idx),
        )

        # evaluate the constraint
        # Note: if index and/or the array length are symbolic, the result
        #       can be True and False and the same time
        idx_stays_within_bounds = state.solver.eval_upto(bound_constraint, 2)

        # There are 3 cases:
        # 1) idx has only valid solutions
        # 2) idx has only invalid solutions
        #    TODO: raise a java.lang.ArrayIndexOutOfBoundsException
        # 3) idx has some valid and some invalid solutions
        #    TODO: split current SimState into two successors:
        #          --> one w/ all valid indexes
        #          --> one w/ all invalid indexes and a raised exception
        #
        # For now we just constraint the index to stay within the bounds

        # raise exception, if index is *always* invalid
        if not True in idx_stays_within_bounds:
            raise SimEngineError("Access of %s[%s] (length %s) is always invalid. "
                                 "Cannot continue w/o raising java.lang.ArrayIndexOutOfBoundsException."
                                 "" % (array.id, idx, length))

        # bound index and/or length, if there are *some* invalid values
        if False in idx_stays_within_bounds:
            l.warning("Possible out-of-bounds access! Index and/or length gets constraint to "
                      "valid values. (%s[%s], length %s)", array.id, idx, length)
            state.solver.add(And(length.SGT(idx), zero.SLE(idx))) 
Example #24
Source File: symbolic_memory.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _store_symbolic_addr(self, address,  addresses, size, data, endness, condition):
        size = self.state.solver.eval(size)
        segments = self._get_segments(addresses, size)

        if condition is None:
            condition = claripy.BoolV(True)

        original_values = [ self._read_from(segment['start'], segment['size']) for segment in segments ]
        if endness == "Iend_LE" or (endness is None and self.endness == "Iend_LE"):
            original_values = [ ov.reversed  for ov in original_values ]

        stored_values = []
        for segment, original_value  in zip(segments, original_values):
            conditional_value = original_value

            for opt in segment['options']:

                if endness == "Iend_LE" or (endness is None and self.endness == "Iend_LE"):
                    high = ((opt['idx']+segment['size']) * self.state.arch.byte_width)-1
                    low = opt['idx']*self.state.arch.byte_width
                else:
                    high = len(data) - 1 - (opt['idx']*self.state.arch.byte_width)
                    low = len(data) - ((opt['idx']+segment['size']) *self.state.arch.byte_width)

                data_slice = data[high:low]
                conditional_value = self.state.solver.If(self.state.solver.And(address == segment['start']-opt['idx'], condition), data_slice, conditional_value)

            stored_values.append(dict(value=conditional_value, addr=segment['start'], size=segment['size']))

        return stored_values 
Example #25
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 #26
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 #27
Source File: test_expression.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def raw_ite(solver_type):
    s = solver_type()
    x = claripy.BVS("x", 32)
    y = claripy.BVS("y", 32)
    z = claripy.BVS("z", 32)

    ite = claripy.ite_dict(x, {1:11, 2:22, 3:33, 4:44, 5:55, 6:66, 7:77, 8:88, 9:99}, claripy.BVV(0, 32))
    nose.tools.assert_equal(sorted(s.eval(ite, 100)), [ 0, 11, 22, 33, 44, 55, 66, 77, 88, 99 ] )

    ss = s.branch()
    ss.add(ite == 88)
    nose.tools.assert_equal(sorted(ss.eval(ite, 100)), [ 88 ] )
    nose.tools.assert_equal(sorted(ss.eval(x, 100)), [ 8 ] )

    ity = claripy.ite_dict(x, {1:11, 2:22, 3:y, 4:44, 5:55, 6:66, 7:77, 8:88, 9:99}, claripy.BVV(0, 32))
    ss = s.branch()
    ss.add(ity != 11)
    ss.add(ity != 22)
    ss.add(ity != 33)
    ss.add(ity != 44)
    ss.add(ity != 55)
    ss.add(ity != 66)
    ss.add(ity != 77)
    ss.add(ity != 88)
    ss.add(ity != 0)
    ss.add(y == 123)
    nose.tools.assert_equal(sorted(ss.eval(ity, 100)), [ 99, 123 ] )
    nose.tools.assert_equal(sorted(ss.eval(x, 100)), [ 3, 9 ] )
    nose.tools.assert_equal(sorted(ss.eval(y, 100)), [ 123 ] )

    itz = claripy.ite_cases([ (claripy.And(x == 10, y == 20), 33), (claripy.And(x==1, y==2), 3), (claripy.And(x==100, y==200), 333) ], claripy.BVV(0, 32))
    ss = s.branch()
    ss.add(z == itz)
    ss.add(itz != 0)
    nose.tools.assert_equal(ss.eval(y/x, 100), ( 2, ))
    nose.tools.assert_equal(sorted(ss.eval(x, 100)), [ 1, 10, 100 ])
    nose.tools.assert_equal(sorted(ss.eval(y, 100)), [ 2, 20, 200 ]) 
Example #28
Source File: test_expression.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_ite_reverse():
    a = claripy.BVS('a', 32)
    cases = [(a == i, claripy.BVV(i, 32)) for i in range(30)]
    ast = claripy.ite_cases(cases, -1)
    ext_cases = list(claripy.reverse_ite_cases(ast))

    assert sum(1 if case.op == 'And' else 0 for case, _ in ext_cases)
    for case, val in ext_cases:
        if case.op == 'And':
            assert claripy.is_true(val == -1)
        else:
            assert any(case is orig_case and val is orig_val for orig_case, orig_val in cases) 
Example #29
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 #30
Source File: test_simplify.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def perf_boolean_and_simplification_1():
    # Create a gigantic And AST with many operands, many variables at a time
    bool_vars = [ claripy.BoolS("b%d" % i) for i in range(500) ]
    v = bool_vars[0]
    for i in range(1, len(bool_vars)):
        if v.op == "And":
            v = claripy.And(*(v.args + (bool_vars[i] == False,)))  # pylint:disable=singleton-comparison
        else:
            v = claripy.And(v, bool_vars[i])