Skip to content

Commit 0ffd03f

Browse files
authored
Update solve.py
1 parent e62fec2 commit 0ffd03f

File tree

1 file changed

+24
-17
lines changed

1 file changed

+24
-17
lines changed

lab8/solve.py

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,37 @@
44
import sys
55

66
def main():
7-
proj = angr.Project('./chal', auto_load_libs=False)
7+
# 載入二進位,不載入動態函式庫加快速度
8+
proj = angr.Project('./chal', auto_load_libs=False)
89

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)
1213

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)
1718

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))
2329

24-
#找到則輸出結果,否則輸出 "No solution found!"
2530
if simgr.found:
2631
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)
2936
else:
30-
print("No solution found!")
37+
print("No solution found.", file=sys.stderr)
3138
sys.exit(1)
3239

3340
if __name__ == '__main__':

0 commit comments

Comments
 (0)