Challenge

A game challenge that only coughs up the flag on a win. Playing by hand was not realistic, so the move was to script the client and let it grind.

Approach

We wrote a play.py that drove the game automatically:

  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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
from pwn import remote
import re
import math
import random
import time

ROWS = 6
COLUMNS = 7
WINDOW_LENGTH = 4
EMPTY = ''
PLAYER_PIECE = 'X'
AI_PIECE = 'O'

def parse_board(board_str):
    lines = board_str.strip().split('\n')
    board = []
    for line in lines[-7:-1]:
        row = line.strip('|').split('|')
        row = [cell.strip() if cell.strip() != '' else EMPTY for cell in row]
        board.append(row)
    return board

def is_valid_location(board, col):
    return board[0][col] == EMPTY

def get_next_open_row(board, col):
    for row in range(ROWS-1, -1, -1):
        if board[row][col] == EMPTY:
            return row
    return None

def drop_piece(board, row, col, piece):
    board[row][col] = piece

def pop_piece(board, col):
    for row in range(ROWS-1):
        board[row+1][col] = board[row][col]
    board[0][col] = EMPTY

def copy_board(board):
    return [row[:] for row in board]

def winning_move(board, piece):

    for c in range(COLUMNS - 3):
        for r in range(ROWS):
            if all(board[r][c+i] == piece for i in range(WINDOW_LENGTH)):
                return True

    for c in range(COLUMNS):
        for r in range(ROWS - 3):
            if all(board[r+i][c] == piece for i in range(WINDOW_LENGTH)):
                return True

    for c in range(COLUMNS - 3):
        for r in range(ROWS - 3):
            if all(board[r+i][c+i] == piece for i in range(WINDOW_LENGTH)):
                return True

    for c in range(COLUMNS - 3):
        for r in range(WINDOW_LENGTH - 1, ROWS):
            if all(board[r-i][c+i] == piece for i in range(WINDOW_LENGTH)):
                return True

    return False

def evaluate_window(window, piece):
    score = 0
    opp_piece = PLAYER_PIECE if piece == AI_PIECE else AI_PIECE

    if window.count(piece) == 4:
        score += 10000
    elif window.count(piece) == 3 and window.count(EMPTY) == 1:
        score += 100
    elif window.count(piece) == 2 and window.count(EMPTY) == 2:
        score += 10

    if window.count(opp_piece) == 4:
        score -= 10000
    elif window.count(opp_piece) == 3 and window.count(EMPTY) == 1:
        score -= 80

    return score

def score_position(board, piece):
    score = 0

    position_score = [
        [3, 4, 5, 7, 5, 4, 3],
        [4, 6, 8,10, 8, 6, 4],
        [5, 8,11,13,11, 8, 5],
        [5, 8,11,13,11, 8, 5],
        [4, 6, 8,10, 8, 6, 4],
        [3, 4, 5, 7, 5, 4, 3],
    ]

    for r in range(ROWS):
        for c in range(COLUMNS):
            if board[r][c] == piece:
                score += position_score[r][c]

    for r in range(ROWS):
        row_array = [board[r][c] for c in range(COLUMNS)]
        for c in range(COLUMNS - 3):
            window = row_array[c:c+WINDOW_LENGTH]
            score += evaluate_window(window, piece)

    for c in range(COLUMNS):
        col_array = [board[r][c] for r in range(ROWS)]
        for r in range(ROWS - 3):
            window = col_array[r:r+WINDOW_LENGTH]
            score += evaluate_window(window, piece)

    for r in range(ROWS - 3):
        for c in range(COLUMNS - 3):
            window = [board[r+i][c+i] for i in range(WINDOW_LENGTH)]
            score += evaluate_window(window, piece)

    for r in range(3, ROWS):
        for c in range(COLUMNS - 3):
            window = [board[r-i][c+i] for i in range(WINDOW_LENGTH)]
            score += evaluate_window(window, piece)

    return score

def get_valid_locations(board):
    valid_locations = []
    for c in range(COLUMNS):
        if is_valid_location(board, c):
            valid_locations.append(('d', c))

        if board[ROWS-1][c] == AI_PIECE:
            valid_locations.append(('p', c))
    return valid_locations

def is_terminal_node(board):
    return winning_move(board, PLAYER_PIECE) or winning_move(board, AI_PIECE) or len(get_valid_locations(board)) == 0

def minimax(board, depth, alpha, beta, maximizingPlayer, start_time, time_limit):
    if time.time() - start_time > time_limit:
        return (None, score_position(board, AI_PIECE))

    valid_locations = get_valid_locations(board)
    is_terminal = is_terminal_node(board)
    if depth == 0 or is_terminal:
        if is_terminal:
            if winning_move(board, AI_PIECE):
                return (None, float('inf'))
            elif winning_move(board, PLAYER_PIECE):
                return (None, float('-inf'))
            else:
                return (None, 0)
        else:
            return (None, score_position(board, AI_PIECE))
    if maximizingPlayer:
        value = float('-inf')
        best_move = random.choice(valid_locations)
        for action, col in valid_locations:
            b_copy = copy_board(board)
            if action == 'd':
                row = get_next_open_row(b_copy, col)
                drop_piece(b_copy, row, col, AI_PIECE)
            elif action == 'p':
                pop_piece(b_copy, col)
            new_score = minimax(b_copy, depth-1, alpha, beta, False, start_time, time_limit)[1]
            if new_score > value:
                value = new_score
                best_move = (action, col)
            alpha = max(alpha, value)
            if alpha >= beta:
                break
            if time.time() - start_time > time_limit:
                break
        return best_move, value
    else:
        value = float('inf')
        best_move = random.choice(valid_locations)
        for action, col in valid_locations:
            b_copy = copy_board(board)
            if action == 'd':
                row = get_next_open_row(b_copy, col)
                drop_piece(b_copy, row, col, PLAYER_PIECE)
            elif action == 'p':
                pop_piece(b_copy, col)
            new_score = minimax(b_copy, depth-1, alpha, beta, True, start_time, time_limit)[1]
            if new_score < value:
                value = new_score
                best_move = (action, col)
            beta = min(beta, value)
            if alpha >= beta:
                break
            if time.time() - start_time > time_limit:
                break
        return best_move, value

def find_best_move(board):
    start_time = time.time()
    time_limit = 1.8

    best_move = ('d', random.choice(range(COLUMNS)))
    best_score = float('-inf')

    depth = 1
    while True:
        if time.time() - start_time > time_limit:
            break
        move, minimax_score = minimax(board, depth, float('-inf'), float('inf'), True, start_time, time_limit)
        if time.time() - start_time > time_limit:
            break
        if minimax_score > best_score:
            best_score = minimax_score
            best_move = move
        depth += 1
        if depth > 6:
            break

    action, col = best_move
    if action == 'd' and is_valid_location(board, col):
        return action, col + 1
    elif action == 'p':
        return action, col + 1
    else:
        for c in range(COLUMNS):
            if is_valid_location(board, c):
                return 'd', c + 1
        return 'd', 1

def main():
    host = '0.cloud.chals.io'
    port = 30265
    conn = remote(host, port)

    conn.recvuntil(b'Play in practice mode? [y/N]')
    conn.sendline(b'n')

    while True:
        try:
            output = conn.recvuntil([b'Do you want to drop or pop a piece? [d/p]', b'You win!', b'You lost', b'You lost the match.', b'Game'], timeout=10).decode()
            print(output)

            if 'You win!' in output or 'You lost!' in output or 'You lost the match.' in output:
                if 'Game' in output:
                    continue
                else:
                    break

            if 'Game' in output and 'of 3' in output:
                continue

            board_match = re.search(r'Board:\n((?:.*\n){7})', output)
            if board_match:
                board_str = board_match.group(1)
                board = parse_board(board_str)
                action, column = find_best_move(board)
                conn.sendline(action.encode())
                conn.recvuntil(b'Which column? [1-7]')
                conn.sendline(str(column).encode())
            else:
                pass

        except EOFError:
            print("Connection closed by the server.")
            break
        except Exception as e:
            print(f"An error occurred: {e}")
            break

    try:
        final_output = conn.recvall(timeout=5).decode()
        print(final_output)
    except EOFError:
        pass

    conn.close()

if __name__ == '__main__':
    main()

Flag

ictf{k33p_1t_uP_4nd_1t_w1ll_b3_0k4y}