---
# System prepended metadata

title: '[CH] ASAP'
tags: [Chinese, Pwn, Writeup]

---

# [CH] ASAP
###### tags:`Writeup` `Pwn` `Chinese`
> [name=FlyDragon]

## Step.1
`nc lotuxctf.com 10000` 或查看`server.py`可以發現這題要求你通過兩道關卡。
- 關卡一：猜測數字
- 關卡二：簡單數學題
## Step.2
題目說明要在一分鐘內通過兩道關卡，可知手動輸入是不可行的。
使用`pwntools`就可以輕鬆解決這道題目。
```python=
from pwn import *
r = remote("lotuxctf.com", 10000)
```
## Step.3
第一關猜測數字後，會告訴你太小或太大，根據這個特性可以使用二分搜尋法找到答案。
```python=
while not number_found:
    #檢查數字太小或太大，調整左右邊界
    if("lower" in response):
        high_num = int(guess)
    elif("higher" in  response):
        low_num = int(guess)
    
    #猜測左右邊界的中間值
    guess = str((high_num+low_num) // 2)
    print(guess)
    r.sendline(guess.encode())
    
    #猜到正確答案就跳出迴圈
    response = r.recvline().decode()
    print(response, end='')
    if "clear" in response:
        number_found = True
```
## Step.4
第二關要回答數學問題，使用`for`迴圈可以輕鬆解決。
```python=
for i in range(101):
    question = r.recvuntil(b'=')[:-1].decode()
    ans = eval(question)
    print(f"Question{i+1}:"+question+f"={ans}")
    r.sendline(str(ans).encode())
```

## 完整代碼
```python=
from pwn import *

r = remote("lotuxctf.com", 10000)

print(r.recvline().decode())

low_num = 0
high_num = 10000000
guess = 0
number_found = False
response = ""
while not number_found:
    if("lower" in response):
        high_num = int(guess)
    elif("higher" in  response):
        low_num = int(guess)
    guess = str((high_num+low_num) // 2)
    print(guess)
    r.sendline(guess.encode())
    response = r.recvline().decode()
    print(response, end='')
    if "clear" in response:
        number_found = True
print(r.recvline().decode(), end='')
for i in range(101):
    question = r.recvuntil(b'=')[:-1].decode()
    ans = eval(question)
    print(f"Question{i+1}:"+question+f"={ans}")
    r.sendline(str(ans).encode())
print(r.recvline().decode())
    
r.close()
```

{%hackmd M1bgOPoiQbmM0JRHWaYA1g %}