missbc
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    *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}`**

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully