*very clear explanation for everyone* ## intro Now you've got the hang of the various encodings you'll be encountering, let's have a look at automating it. Can you pass all 100 levels to get the flag? The _13377.py_ file attached below is the source code for what's running on the server. The _pwntools_example.py_ file provides the start of a solution using the incredibly convenient pwntools library. which we recommend. If you'd prefer to use Python's in-built telnetlib, _telnetlib_example.py_ is also provided. For more information about connecting to interactive challenges, see the [FAQ](https://cryptohack.org/faq#netcat). Feel free to skip ahead to the cryptography if you aren't in the mood for a coding challenge! Connect at `nc socket.cryptohack.org 13377` ## chall file ### chall.py ```python #!/usr/bin/env python3 from Crypto.Util.number import bytes_to_long, long_to_bytes from utils import listener # this is cryptohack's server-side module and not part of python import base64 import codecs import random FLAG = "crypto{????????????????????}" ENCODINGS = [ "base64", "hex", "rot13", "bigint", "utf-8", ] with open('/usr/share/dict/words') as f: WORDS = [line.strip().replace("'", "") for line in f.readlines()] class Challenge(): def __init__(self): self.challenge_words = "" self.stage = 0 def create_level(self): self.stage += 1 self.challenge_words = "_".join(random.choices(WORDS, k=3)) encoding = random.choice(ENCODINGS) if encoding == "base64": encoded = base64.b64encode(self.challenge_words.encode()).decode() # wow so encode elif encoding == "hex": encoded = self.challenge_words.encode().hex() elif encoding == "rot13": encoded = codecs.encode(self.challenge_words, 'rot_13') elif encoding == "bigint": encoded = hex(bytes_to_long(self.challenge_words.encode())) elif encoding == "utf-8": encoded = [ord(b) for b in self.challenge_words] return {"type": encoding, "encoded": encoded} # # This challenge function is called on your input, which must be JSON # encoded # def challenge(self, your_input): if self.stage == 0: return self.create_level() elif self.stage == 100: self.exit = True return {"flag": FLAG} if self.challenge_words == your_input["decoded"]: return self.create_level() return {"error": "Decoding fail"} listener.start_server(port=13377) ``` * Đoạn mã này định nghĩa một lớp `Challenge` để quản lý thách thức. - `__init__`: Phương thức khởi tạo, thiết lập các biến `challenge_words` và `stage`. `stage` là một biến để theo dõi tiến trình của thách thức. - `create_level`: Phương thức này tạo một cấp độ thách thức mới. Nó chọn ngẫu nhiên ba từ từ danh sách `WORDS`, mã hóa chúng theo một phương thức ngẫu nhiên trong `ENCODINGS`, và trả về một từ điển chứa loại mã hóa và văn bản đã mã hóa. * Phương thức `challenge` nhận đầu vào từ người chơi, được truyền dưới dạng dữ liệu JSON. - Nếu `stage` là 0, nó tạo một cấp độ thách thức bằng cách gọi `create_level`. - Nếu `stage` là 100, nó thoát và trả về flag. - Nếu văn bản được giải mã từ đầu vào người dùng trùng khớp với `challenge_words`, nó tạo một cấp độ thách thức mới. - Nếu không, nó trả về một thông báo lỗi. ### telnetlib_example_5b11a835055df17c7c8f8f2a08782c44.py ```python import telnetlib import json HOST = "socket.cryptohack.org" PORT = 13377 tn = telnetlib.Telnet(HOST, PORT) def readline(): return tn.read_until(b"\n") def json_recv(): line = readline() return json.loads(line.decode()) def json_send(hsh): request = json.dumps(hsh).encode() tn.write(request) received = json_recv() print("Received type: ") print(received["type"]) print("Received encoded value: ") print(received["encoded"]) to_send = { "decoded": "changeme" } json_send(to_send) json_recv() ``` * import hai thư viện cần thiết: `telnetlib` cho việc tạo kết nối Telnet và `json` cho việc làm việc với dữ liệu JSON. - tạo một đối tượng Telnet và thiết lập kết nối đến máy chủ từ xa với thông tin HOST và PORT đã được định nghĩa. * hàm tùy chỉnh được định nghĩa để đọc dòng văn bản từ kết nối Telnet bằng cách sử dụng phương thức `read_until`. Hàm này đọc dữ liệu từ máy chủ cho đến khi gặp ký tự xuống dòng (`\n`) và trả về dòng văn bản đã đọc. * hàm tùy chỉnh để gửi dữ liệu JSON đến máy chủ từ xa. Hàm này nhận một từ điển Python `hsh` làm đối số, mã hóa nó thành chuỗi JSON bằng cách sử dụng `json.dumps`, sau đó chuyển đổi nó thành dạng bytes và gửi nó đến máy chủ từ xa bằng cách sử dụng `tn.write`. * gọi hàm `json_recv` để nhận một thông điệp JSON từ máy chủ và lưu trữ nó trong biến `received`. Sau đó, nó in ra loại ("type") và giá trị mã hóa ("encoded") từ thông điệp JSON nhận được. * tạo một từ điển `to_send` với một trường "decoded" có giá trị là "changeme" và sau đó gửi nó đến máy chủ bằng cách sử dụng `json_send`. Sau đó, nó gọi `json_recv` một lần nữa để nhận một phản hồi từ máy chủ, nhưng kết quả không được lưu trữ hoặc in ra. ### pwntools_example_f93ca6ccef2def755aa8f6d9aa6e9c5b.py ```python from pwn import * # pip install pwntools import json r = remote('socket.cryptohack.org', 13377, level = 'debug') def json_recv(): line = r.recvline() return json.loads(line.decode()) def json_send(hsh): request = json.dumps(hsh).encode() r.sendline(request) received = json_recv() print("Received type: ") print(received["type"]) print("Received encoded value: ") print(received["encoded"]) to_send = { "decoded": "changeme" } json_send(to_send) json_recv() ``` * module `json` có sẵn trong Python, được sử dụng để làm việc với dữ liệu JSON, bao gồm việc mã hóa các cấu trúc dữ liệu Python thành JSON và giải mã dữ liệu JSON thành các cấu trúc dữ liệu Python. * Tham số `'debug'` được chỉ định để bật chế độ gỡ lỗi cho kết nối. * hàm có tên `json_recv` dùng để đọc một dòng văn bản từ kết nối từ xa (`r.recvline()`) và giải mã nó thành dữ liệu JSON bằng cách sử dụng `json.loads`. Sau đó, hàm trả về cấu trúc dữ liệu Python tương ứng. * hàm có tên `json_send` nhận một từ điển Python `hsh` làm đối số. Hàm này mã hóa từ điển này thành một chuỗi JSON bằng `json.dumps`, chuyển đổi nó thành dạng bytes và gửi đến máy chủ từ xa bằng `r.sendline`. * hàm `json_recv` để nhận dữ liệu JSON từ máy chủ từ xa và lưu trữ nó trong biến `received`. * in ra thông tin từ dữ liệu JSON nhận được. Nó in ra trường "type" và "encoded" từ phản hồi JSON nhận từ máy chủ. * một từ điển Python `to_send` được định nghĩa với một cặp khóa-giá trị, trong đó khóa là "decoded" và giá trị là "changeme". Sau đó, hàm `json_send` được gọi để gửi từ điển này đến máy chủ từ xa. * hàm `json_recv`, có lẽ để nhận một phản hồi JSON khác từ máy chủ. Tuy nhiên, phản hồi này không được lưu trữ hoặc sử dụng trong đoạn mã cung cấp. ## solution sau khi phân tích từng file ( file chall và các file ví dụ cách interact with server ) thì mình bắt đầu thôi, connect at nc socket.cryptohack.org 13377 ![](https://hackmd.io/_uploads/BJmXU4-bT.png) server cho ta một đoạn json chứa loại encode và dòng đã được encode bằng loại encode đó, việc của mình là gửi lại server dòng đã được decode dưới dạng json, sau khi gửi đúng 100 lần ta sẽ có flag. mình sẽ chia ra những phần nhỏ nhau sau: * đầu tiên là connect to server, mình import thư viện pwntools dùng cho việc tương tác với server, sau đó connect bằng câu lệnh : r = remote(host,port), thêm level = 'debug' sẽ thấy được quá trình debug, vậy trong bài này là : `r=remote('socket.cryptohack.org', 13377, level = 'debug')` * tiếp theo mình phải biết cách nhận dữ liệu từ server, ta có một hàm thực hiện việc nhận dữ liệu từ server đó là `recvline()`, `recvline()` nhận dữ liệu từ một socket (được truyền làm đối số) cho đến khi gặp ký tự xuống dòng (`"\n"`). Nó tiếp tục đọc một byte mỗi lần cho đến khi tìm thấy ký tự xuống dòng hoặc khi kết nối bị đóng, và lưu ý là dữ liệu nhận được ở dưới dạng byte. * sau khi nhận dữ liệu dưới dạng byte ta cần decode nó sang string bằng cách sử dụng mã hóa mặc định (thường là UTF-8) bằng `decode()`, nhưng để string thì ta không lấy được dữ liệu theo cách ta muốn nên ta cần hàm `json.loads()` để parse as json(Phân tích (Parsing) là quá trình phân tích một chuỗi văn bản và chuyển đổi nó thành một định dạng dữ liệu có cấu trúc có thể được thao tác dễ dàng trong mã lập trình), mình hiểu nôm na nó nhận một chuỗi đã định dạng JSON làm đầu vào và trả về cấu trúc dữ liệu Python tương ứng, ở đây là dict. Code sau khi phân tích : ```python def json_recv(): line = r.recvline() return json.loads(line.decode()) ``` * sau bước lấy dữ liệu từ server thì ta tiến hành giải mã với các loại mã hóa tương ứng, đọc qua source code có cách loại mã hóa sau : ![](https://hackmd.io/_uploads/SJ0zvKGW6.png) ta sẽ code giải mã dựa vào source code trên. ```python def decode(t, data): if t == 'base64': return base64.b64decode(data).decode('utf-8') elif t == 'hex': return binascii.unhexlify(data).decode('utf-8') elif t == 'bigint': return binascii.unhexlify(data.replace('0x', '')).decode('utf-8') elif t == 'rot13': return codecs.decode(data, 'rot_13') elif t == 'utf-8': s = "" for c in data: s += chr(c) return s ``` * kết quả được chuyển vào dict sau: ```python to_send = { "decoded": decode(received["type"], received["encoded"]) } ``` * sau đó ta chuyển kiểu dữ liệu trên thành json để gửi cho server bằng hàm `json.dumps()`, tương tự với nhận dữ liệu từ server, gửi kết quả đến server cũng dùng hàm của pwntools là `sendline()`, lưu ý hàm `sendline()` thường tự động thêm ký tự xuống dòng (`\n`) vào cuối chuỗi, `encode() `trước khi gửi đến server để chuyển nó thành byte. ```python def json_send(hsh): request = json.dumps(hsh).encode() r.sendline(request) ``` Full code: ```python from pwn import * import json import binascii import base64 import codecs import sys conn=remote('socket.cryptohack.org', 13377, level='debug') # line= r.recvline().decode() # line_js=json.loads(line) # print(line_js) def dec(t,e): if t == "base64": return base64.b64decode(e).decode() if t == "hex": return binascii.unhexlify(e).decode() if t == "rot13": return codecs.decode(e, 'rot_13') if t == "bigint": return binascii.unhexlify(e.replace("0x","")).decode() if t == "utf-8": c = "" for i in e: c += chr(i) return c def json_recv(): line = conn.recvline().decode() return json.loads(line) def json_send(r): result = json.dumps(r) conn.sendline(result.encode()) while True : received = json_recv() # print(type(received)) if "flag" in received: print(received["flag"]) sys.exit(0) t = received["type"] # print(t) e = received["encoded"] to_send = { "decoded": dec(t,e) } json_send(to_send) ``` **==>`FLAG: crypto{3nc0d3_d3c0d3_3nc0d3}`**