Ejemplo n.º 1
0
def z3_adversarial_unfold(n=10, to_pass=True):
    from z3 import Reals, Solver, sat
    s = Solver()
    A0, B0 = Reals('A0 B0')
    s.add(A0 == 0)
    # if to_pass:
    s.add(B0 == n)
    #
    # s.add(B0 == n+1)

    A_prev = A0
    B_prev = B0
    for i in range(1, n + 1):
        A_temp, B_temp = Reals('A{} B{}'.format(i, i))
        # This is the invariant
        if to_pass:
            s.add(A_temp == A_prev + 1)
        else:
            s.add(A_temp == A_prev + 0.9)
        s.add(B_temp == B_prev)
        A_prev = A_temp
        B_prev = B_temp

    s.add(A_temp < B_temp)

    # print(s)
    t = s.check()
    if t == sat:
        # print("z3 result:", s.model())
        return False
    else:
        # print("z3 result:", t)
        return True
Ejemplo n.º 2
0
def check_adversarial_robustness_z3():
    from z3 import Reals, Int, Solver, If, And
    sk, sk_1, zk, zk_1 = Reals('sk sk_1 zk zk_1')
    i = Int('i')

    s = Solver()
    s.add(And(i >= 0, i <= 20, sk_1 >= 0, sk >= 0, zk >= 0, zk_1 >= 0))
    A = If(sk * 1 >= 0, sk * 1, 0)
    B = If(zk * 1 >= 0, zk * 1, 0)

    s.add(If(i == 0,
             And(sk >= 0, sk <= 3, zk >= 10, zk <= 21, sk_1 == 0, zk_1 == 0),
             sk - zk >= sk_1 - zk_1 + 21 / i))

    s.add(And(A < B, i == 20))
    # # we negate the condition, instead if for all sk condition we check if there exists sk not condition
    # s.add(sk_ReLU * w > ylim)

    t = s.check()
    if t == sat:
        print("z3 result:", s.model())
        return False
    else:
        # print("z3 result:", t)
        return True
Ejemplo n.º 3
0
def get_state(doubles, browser):
    if browser == "node":
        browser = "chrome"
    elif browser not in ("chrome", "firefox", "safari"):
        raise ValueError(f"invalid browser {browser}")
    if browser == "chrome":
        doubles = doubles[::-1]

    # from the doubles, generate known piece of the original uint64
    generated = [from_double(double, browser) for double in doubles]

    # setup symbolic state for xorshift128+
    ostate0, ostate1 = BitVecs("ostate0 ostate1", 64)
    sym_state0 = ostate0
    sym_state1 = ostate1
    solver = Solver()
    conditions = []

    # run symbolic xorshift128+ algorithm for three iterations
    # using the recovered numbers as constraints
    for val in generated:
        sym_state0, sym_state1, ret_conditions = sym_xs128p(
            solver, sym_state0, sym_state1, val, browser)
        conditions += ret_conditions
    if solver.check(conditions) == sat:
        # get a solved state
        m = solver.model()
        state0 = m[ostate0].as_long()
        state1 = m[ostate1].as_long()
        solver.add(Or(ostate0 != m[ostate0], ostate1 != m[ostate1]))
        if solver.check(conditions) == sat:
            print("WARNING: multiple solutions found! use more doubles!")
        return state0, state1
    else:
        raise ValueError("unsat model")
Ejemplo n.º 4
0
def sat_solve_prev(keystream, next, prev):
    """Find previous keystream by solving boolean satisfiability problem.

    Parameters
    ----------
    keystream : list of bool
        Current keystream converted to list of boolean representing binary
        values

    next : list of z3.BoolRef
        list containing bit triplet DNF constraints from the original next()

    prev :  list of z3.BoolRef
        list containing bool representation of the previous keystream, to be
        used as an index for Solver().model()

    Returns
    -------
    keystream : list of bool
        bool representation of keystream input from the previous call of next()

    """
    solver = Solver()
    for idx in range(N):
        # add next keystream bools as constraints
        solver.add(next[idx] == keystream[idx])
    # check() should be 'sat' because we know we can get back to seed with
    # these constraints, but we want to catch semantic errors just in case
    if solver.check() == unsat:
        raise Exception('Error in SAT DNF constraints')
    model = solver.model()
    # replace current keystream with solved previous values
    for idx in range(N):
        keystream[idx] = bool(model[prev[idx]])
    return keystream
Ejemplo n.º 5
0
def collide(target_str, base_str, count=10, size_suffix=6, prefix=False):
    '''Generates a string with the following properties:
            * strcmp(res, base_str) = 0
            * H(res) == H(target_str)'''
    solver = Solver()

    if prefix:
        res = generate_ascii_printable_string(
            'res', size_suffix, solver) + str_to_BitVecVals8(base_str)
    else:
        res = str_to_BitVecVals8(base_str) + generate_ascii_printable_string(
            'res', size_suffix, solver)

    target_checksum = H(str_to_BitVecVals8(target_str))
    res_checksum = H(res)
    solver.add(res_checksum == target_checksum)

    for i in range(count):
        if solver.check() == sat:
            model = solver.model()

            if prefix:
                solution = "".join(
                    chr(model[x].as_long())
                    for x in res[:size_suffix]) + base_str
                solver.add(
                    [x != model[x].as_long() for x in res[:size_suffix]])
            else:
                solution = base_str + "".join(
                    chr(model[x].as_long()) for x in res[-size_suffix:])
                solver.add(
                    [x != model[x].as_long() for x in res[-size_suffix:]])

            yield solution
Ejemplo n.º 6
0
 def solve(self, actions, initial_state, goal_state):
     """Solves the planning problem given the elements of the problem
     """
     # encode the problem
     for length in range(0, self.max_length):
         if self.simplify:
             # s = Then('sat-preprocess', 'psmt').solver()
             # s = With('psmt').solver()
             # s = Then('aig', 'elim-and','psmt').solver()
             # s = Then('aig', 'psmt').solver()
             # s = Then('simplify', 'propagate-values', 'ctx-simplify').solver()
             s = Then('simplify', 'propagate-values', 'psmt').solver()
         else:
             s = Solver()
         self.props.clear()
         self.action_map.clear()
         print("Encoding domain with length {0}".format(length))
         self.encode_formula(s, actions, initial_state, goal_state, length)
         if self.verbose: print(s.to_smt2())
         # print(s)
         if s.check() == sat:
             if self.verbose:
                 print("Model found with length {0}".format(length))
             # print(s.model())
             return self.extract_plan(s.model(), length)
         else:
             if self.verbose:
                 print("No model found with length {0}".format(length))
     return None
Ejemplo n.º 7
0
def Password():
    from z3 import Int, Solver

    Buffer = Int('Buffer')
    v9 = Int('v9')
    v10 = Int('v10')
    v11 = Int('v11')
    v12 = Int('v12')
    v13 = Int('v13')
    v14 = Int('v14')
    v15 = Int('v15')
    v16 = Int('v16')
    v17 = Int('v17')

    s = Solver()

    s.add(v14 + v15 == 205)
    s.add(v13 + v16 == 201)
    s.add(v11 + v14 + v15 == 314)
    s.add(v13 + v16 + v12 + v17 == 367)
    s.add(Buffer + v9 == 194)
    s.add(v17 + v16 + v15 + v14 + v13 + v12 + v11 + v10 + v9 + Buffer == 923)
    s.add(v16 == 85)
    s.add(Buffer + v10 == 128)
    s.add(v12 - v15 == -50)
    s.add(v14 + v17 == 219)

    return "Status : %s \nPassword = %s" % (
        s.check(),
        chr(s.model()[Buffer].as_long()) + chr(s.model()[v9].as_long()) +
        chr(s.model()[v10].as_long()) + chr(s.model()[v11].as_long()) +
        chr(s.model()[v12].as_long()) + chr(s.model()[v13].as_long()) +
        chr(s.model()[v14].as_long()) + chr(s.model()[v15].as_long()) +
        chr(s.model()[v16].as_long()) + chr(s.model()[v17].as_long()))
Ejemplo n.º 8
0
def get_mus(constraints):
    '''
    Returns a single MUS
    '''
    seed = set(range(len(constraints)))
    idx2indicator = {i:Bool(str(i)) for i in seed}
    indicator2idx = {b.get_id():i for (i,b) in idx2indicator.items()}

    s = Solver()
    for i, b in idx2indicator.items():
        s.add(Implies(b, constraints[i]))

    def check_subset(current_seed):
        assumptions = [idx2indicator[i] for i in current_seed]
        return (s.check(assumptions) == sat)

    current = set(seed)
    for i in seed:
        if i not in current:
            continue
        current.remove(i)
        if not check_subset(current):
            core = s.unsat_core()
            # FIXME: do constraints never show up in the core? Seems like we could get a key error
            current = set(indicator2idx[ind.get_id()] for ind in core)
        else:
            current.add(i)
    assert not check_subset(current), "Expecting unsat at end of get_mus"
    return [constraints[i] for i in current]
Ejemplo n.º 9
0
def init_solver(cols):
    s = Solver()
    for col in cols:
        cond = And(col >= 0,
                   col < len(COLORS))  #possible values for each column
        s.add(cond)
    cond_unicity = Distinct(cols)  #each column is different
    s.add(cond_unicity)
    return s
Ejemplo n.º 10
0
def get_z3_result(query, debug=False) -> bool:
    s = Solver()

    s.add(query)
    if s.check() == sat:
        if debug:
            print(s, s.model())
        return True
    return False
Ejemplo n.º 11
0
 def test_knaves_3(self):
     """
     It can not be that a person has the role of a knave and tells the truth.
     """
     f = knaves_tell_lies()
     s = Solver()
     s.add(f)
     s.add(And(R(C) == Knave, S(C) == True))
     self.assertEqual(unsat,s.check(), "Your formula should say that being a knave implies not telling the truth for all persons.")
Ejemplo n.º 12
0
 def test_knaves_2(self):
     """
     The formula returned by `knaves_tell_lies` and a lying knave must be satisfiable.
     """
     f = knaves_tell_lies()
     s = Solver()
     s.add(f)
     s.add(And(R(A) == Knave, S(A) == False))
     self.assertEqual(sat,s.check(), "Your formula should say that being a knave implies not telling the truth for all persons.")
Ejemplo n.º 13
0
def myprove(claim):
    s = Solver()
    s.set(timeout=1*1000) 
    s.add(claim)
    rs = s.check()
    if rs == unsat:
        return True
    else:
        return False
Ejemplo n.º 14
0
    def solve_z3(self):

        print("[+] {}".format("Sovling using Z3\n"))

        symbols = {e: Int(e) for e in self.elements}

        # first we build a solver with the general constraints for sudoku puzzles:
        s = Solver()

        # assure that every cell holds a value of [1,9]
        for symbol in symbols.values():
            s.add(Or([symbol == int(i) for i in self.cols]))

        # assure that every row covers every value:
        for row in "ABCDEFGHI":
            s.add(Distinct([symbols[row + col] for col in "123456789"]))

        # assure that every column covers every value:
        for col in "123456789":
            s.add(Distinct([symbols[row + col] for row in "ABCDEFGHI"]))

        # assure that every block covers every value:
        for i in range(3):
            for j in range(3):
                s.add(
                    Distinct([
                        symbols["ABCDEFGHI"[m + i * 3] +
                                "123456789"[n + j * 3]] for m in range(3)
                        for n in range(3)
                    ]))

        # adding sum constraints if provided
        if self.constraints is not None:
            print("[+] {}\n{}".format("Applying constraints",
                                      self.constraints))
            sum_constr = self.get_constraints()
            for c in sum_constr:
                expr = []

                for i in c[0]:
                    expr.append("symbols['" + i + "']")

                s.add(eval("+".join(expr) + "==" + str(c[1])))

        # now we put the assumptions of the given puzzle into the solver:
        for elem, value in self.values.items():
            if value in "123456789":
                s.add(symbols[elem] == value)

        if not s.check() == sat:
            raise Exception("Unsolvable")

        model = s.model()
        values = {e: model.evaluate(s).as_string() for e, s in symbols.items()}

        self.solution = values