|
4 | 4 | import sys |
5 | 5 |
|
6 | 6 | def main(): |
7 | | - proj = angr.Project('./chal', auto_load_libs=False) |
| 7 | + # 載入二進位,不載入動態函式庫加快速度 |
| 8 | + proj = angr.Project('./chal', auto_load_libs=False) |
8 | 9 |
|
9 | | - #建立8-bit輸入 |
10 | | - sym_chars = [claripy.BVS(f'byte_{i}', 8) for i in range(8)] |
11 | | - sym_input = claripy.Concat(*sym_chars) |
| 10 | + # 建立 8 個符號字元 |
| 11 | + flag_chars = [claripy.BVS(f'c{i}', 8) for i in range(8)] |
| 12 | + flag = claripy.Concat(*flag_chars) |
12 | 13 |
|
13 | | - #初始化執行狀態並模擬stdin輸入 |
14 | | - state = proj.factory.full_init_state( |
15 | | - stdin = angr.SimFileStream(name='stdin', content=sym_input, has_end=True) |
16 | | - ) |
| 14 | + # 製作帶有符號輸入的初始狀態 |
| 15 | + # has_end=True 表示讀到 flag 後即結束輸入 |
| 16 | + stdin = angr.SimFileStream(name='stdin', content=flag, has_end=True) |
| 17 | + state = proj.factory.full_init_state(stdin=stdin) |
17 | 18 |
|
18 | | - #建立模擬器並開始搜尋個別狀態 |
19 | | - simgr = proj.factory.simgr(state) |
20 | | - simgr.explore( |
21 | | - find = lambda s:b"Correct!" in s.posix.dumps(1) |
22 | | - ) |
| 19 | + # 限制每個字元為可列印 ASCII(32~126) |
| 20 | + for c in flag_chars: |
| 21 | + state.solver.add(c >= 0x20) |
| 22 | + state.solver.add(c <= 0x7e) |
| 23 | + |
| 24 | + simgr = proj.factory.simulation_manager(state) |
| 25 | + |
| 26 | + # 尋找印出「Correct! The flag is」的路徑 |
| 27 | + target = b"Correct! The flag is" |
| 28 | + simgr.explore(find=lambda s: target in s.posix.dumps(1)) |
23 | 29 |
|
24 | | - #找到則輸出結果,否則輸出 "No solution found!" |
25 | 30 | if simgr.found: |
26 | 31 | found = simgr.found[0] |
27 | | - secret_key = found.solver.eval(sym_input, cast_to=bytes) |
28 | | - sys.stdout.buffer.write(secret_key) |
| 32 | + # 求解出具體 key |
| 33 | + solution = found.solver.eval(flag, cast_to=bytes) |
| 34 | + # 輸出到 stdout,供 validate.sh 傳給 chal |
| 35 | + sys.stdout.buffer.write(solution) |
29 | 36 | else: |
30 | | - print("No solution found!") |
| 37 | + print("No solution found.", file=sys.stderr) |
31 | 38 | sys.exit(1) |
32 | 39 |
|
33 | 40 | if __name__ == '__main__': |
|
0 commit comments