蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 WebView JS 桥接白名单、WebChromeClient 三对话框与 CVE-2012-6636 防护离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-webview-javascrip.py
explore-tutorial-webview-javascrip.py151 行
"""Offline Android WebView-JavaScript bridge, dialogs & CVE-2012-6636 allowlist verifier (Ch 96: tutorial-webview-javascrip)."""
from __future__ import annotations

import json
import sys

VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"


class JsBridgeSecurityModel:
    """Models Android WebView addJavascriptInterface exposure before/after API 17 (@JavascriptInterface)."""

    def __init__(self, target_sdk: int, exposed_methods: dict[str, dict]):
        self.target_sdk = target_sdk
        self.exposed_methods = exposed_methods

    def invoke(self, method_name: str, arg: str | None = None) -> dict:
        if method_name == "getClass":
            # CVE-2012-6636: pre-API 17 exposed java.lang.Object.getClass() enabling reflection RCE
            if self.target_sdk < 17:
                return {"allowed": True, "security_risk": "CVE-2012-6636_reflection_rce"}
            return {"allowed": False, "reason": "blocked_missing_JavascriptInterface_annotation"}
        meta = self.exposed_methods.get(method_name)
        if not meta:
            return {"allowed": False, "reason": "method_not_found"}
        if self.target_sdk >= 17 and not meta.get("annotated", False):
            return {"allowed": False, "reason": "blocked_missing_JavascriptInterface_annotation"}
        return {"allowed": True, "result": meta["handler"](arg)}


def main() -> None:
    cases = []

    # Case 1: HTML -> JS -> Java MyObject bridge (showToast / showDialog) + file:///android_asset/ URL
    my_obj = JsBridgeSecurityModel(
        target_sdk=21,
        exposed_methods={
            "showToast": {"annotated": True, "handler": lambda msg: f"Toast:{msg}"},
            "showDialog": {"annotated": True, "handler": lambda _: "AlertDialog:联系人列表(5项)"},
            "legacyUnannotated": {"annotated": False, "handler": lambda _: "should_not_run"},
        },
    )
    actual1 = {
        "asset_url": "file:///android_asset/demo1.html",
        "toast_call": my_obj.invoke("showToast", "Hello JS"),
        "dialog_call": my_obj.invoke("showDialog"),
        "unannotated_blocked": my_obj.invoke("legacyUnannotated")["allowed"] is False,
    }
    expected1 = {
        "asset_url": "file:///android_asset/demo1.html",
        "toast_call": {"allowed": True, "result": "Toast:Hello JS"},
        "dialog_call": {"allowed": True, "result": "AlertDialog:联系人列表(5项)"},
        "unannotated_blocked": True,
    }
    cases.append({
        "name": "js_to_java_myobject_bridge",
        "summary": "Verify file:///android_asset/ HTML invocation of @JavascriptInterface methods and blocking of unannotated methods.",
        "expected": expected1,
        "actual": actual1,
        "passed": actual1 == expected1,
    })

    # Case 2: WebChromeClient onJsAlert / onJsConfirm / onJsPrompt JsResult lifecycle
    def handle_js_dialog(kind: str, message: str, user_action: str, prompt_input: str = "") -> dict:
        if kind == "alert":
            return {"handled": True, "js_result": "confirm()", "message": message}
        if kind == "confirm":
            return {
                "handled": True,
                "js_result": "confirm()" if user_action == "ok" else "cancel()",
                "return_to_js": user_action == "ok",
            }
        if kind == "prompt":
            if user_action == "ok":
                return {"handled": True, "js_result": f"confirm({prompt_input})", "return_to_js": prompt_input}
            return {"handled": True, "js_result": "cancel()", "return_to_js": None}
        raise ValueError(kind)

    actual2 = {
        "alert": handle_js_dialog("alert", "Alert警告对话框!", "ok"),
        "confirm_cancel": handle_js_dialog("confirm", "访问站点?", "cancel"),
        "prompt_ok": handle_js_dialog("prompt", "请输入", "ok", "Android"),
    }
    expected2 = {
        "alert": {"handled": True, "js_result": "confirm()", "message": "Alert警告对话框!"},
        "confirm_cancel": {"handled": True, "js_result": "cancel()", "return_to_js": False},
        "prompt_ok": {"handled": True, "js_result": "confirm(Android)", "return_to_js": "Android"},
    }
    cases.append({
        "name": "webchromeclient_js_dialogs",
        "summary": "Verify WebChromeClient onJsAlert/onJsConfirm/onJsPrompt JsResult.confirm/cancel return semantics.",
        "expected": expected2,
        "actual": actual2,
        "passed": actual2 == expected2,
    })

    # Case 3: Contacts JSON serialization & safe JSON.parse (replacing unsafe eval(jsondata)) + tel: URI
    contacts = [
        {"id": "1", "name": "张工", "phone": "13800001111"},
        {"id": "2", "name": "李工", "phone": "13900002222"},
    ]
    json_str = json.dumps(contacts, ensure_ascii=False)
    parsed = json.loads(json_str)
    dial_uri = f"tel:{parsed[0]['phone']}"
    actual3 = {
        "count": len(parsed),
        "first_name": parsed[0]["name"],
        "dial_uri": dial_uri,
        "prefer_json_parse_over_eval": True,
    }
    expected3 = {
        "count": 2,
        "first_name": "张工",
        "dial_uri": "tel:13800001111",
        "prefer_json_parse_over_eval": True,
    }
    cases.append({
        "name": "contacts_json_bridge_and_tel_uri",
        "summary": "Verify Contact list JSON serialization, safe JSON parsing instead of eval(), and tel: dial intent URI.",
        "expected": expected3,
        "actual": actual3,
        "passed": actual3 == expected3,
    })

    # Case 4: CVE-2012-6636 reflection attack vector (pre-API 17 vulnerable vs API 17+ blocked)
    legacy_bridge = JsBridgeSecurityModel(target_sdk=16, exposed_methods={})
    modern_bridge = JsBridgeSecurityModel(target_sdk=17, exposed_methods={})
    actual4 = {
        "pre_api17_getClass_exposed": legacy_bridge.invoke("getClass")["security_risk"],
        "api17_plus_getClass_blocked": modern_bridge.invoke("getClass")["allowed"] is False,
        "modern_bridge_reason": modern_bridge.invoke("getClass")["reason"],
    }
    expected4 = {
        "pre_api17_getClass_exposed": "CVE-2012-6636_reflection_rce",
        "api17_plus_getClass_blocked": True,
        "modern_bridge_reason": "blocked_missing_JavascriptInterface_annotation",
    }
    cases.append({
        "name": "cve_2012_6636_javascriptinterface_guard",
        "summary": "Verify CVE-2012-6636 getClass() reflection exposure on API < 17 vs @JavascriptInterface allowlist on API 17+.",
        "expected": expected4,
        "actual": actual4,
        "passed": actual4 == expected4,
    })

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    sys.exit(main())
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-webview-javascrip-lab/explore-tutorial-webview-javascrip.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-webview-javascrip.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1978.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习