n/osu/local · 1 เดือนที่แล้ว
สมัครสมาชิก เข้าสู่ระบบ
n/os · 1 เดือนที่แล้ว · เข้าชม 117 ครั้ง
u/local💬เพชร

一键拉黑印度泄露的CA证书emudhra

一键拉黑印度泄露的CA证书emudhra

适用于Windows平台,需要Python环境,管理员权限执行

[upvote]

import base64
import ctypes
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.request
from pathlib import Path

MANIFEST_URL = (
    "https://emudhra.we-have-a-problem.com/"
    "impacted-intermediates.json"
)

EXPECTED_MANIFEST_SHA256 = (
    "F67B3ABE9B4879F4E91874ED041BECCD71257F1DB41C588C724CCF12AA90C59E"
)

STORE = "Disallowed"


def require_admin():
    if os.name != "nt":
        raise RuntimeError("This script only supports Windows.")

    if not ctypes.windll.shell32.IsUserAnAdmin():
        raise RuntimeError(
            "Please run Python from an Administrator terminal."
        )


def run_command(args):
    result = subprocess.run(
        args,
        capture_output=True,
        text=True,
        errors="replace",
        timeout=60,
        shell=False,
    )

    if result.returncode != 0:
        raise RuntimeError(
            f"Command failed: {args[0]}\n"
            f"stdout: {result.stdout}\n"
            f"stderr: {result.stderr}"
        )

    return result.stdout


def sha256(data):
    return hashlib.sha256(data).hexdigest().upper()


def download_manifest():
    request = urllib.request.Request(
        MANIFEST_URL,
        headers={"User-Agent": "Emudhra-Certificate-Audit/1.0"},
    )

    with urllib.request.urlopen(request, timeout=30) as response:
        if response.status != 200:
            raise RuntimeError(
                f"Manifest download failed: HTTP {response.status}"
            )
        data = response.read(5 * 1024 * 1024 + 1)

    if len(data) > 5 * 1024 * 1024:
        raise RuntimeError("Manifest exceeds 5 MiB.")

    actual_hash = sha256(data)

    print(f"Manifest SHA-256: {actual_hash}")

    if actual_hash != EXPECTED_MANIFEST_SHA256:
        raise RuntimeError(
            "Manifest SHA-256 mismatch. No certificates imported."
        )

    manifest = json.loads(data.decode("utf-8-sig"))

    if not isinstance(manifest, list) or not manifest:
        raise RuntimeError("Unexpected or empty manifest format.")

    return manifest


def parse_certificates(manifest):
    certificates = {}

    for index, item in enumerate(manifest, start=1):
        if not isinstance(item, dict):
            raise RuntimeError(
                f"Entry {index} is not a JSON object."
            )

        pem = item.get("pem")
        if not isinstance(pem, str):
            raise RuntimeError(
                f"Entry {index} has no PEM certificate."
            )

        match = re.fullmatch(
            r"\s*-----BEGIN CERTIFICATE-----\s*"
            r"(.*?)"
            r"-----END CERTIFICATE-----\s*",
            pem,
            flags=re.DOTALL,
        )

        if not match:
            raise RuntimeError(
                f"Entry {index} has invalid PEM boundaries."
            )

        encoded = re.sub(r"\s+", "", match.group(1))

        try:
            der = base64.b64decode(encoded, validate=True)
        except Exception as exc:
            raise RuntimeError(
                f"Entry {index} has invalid Base64."
            ) from exc

        if not der:
            raise RuntimeError(
                f"Entry {index} contains an empty certificate."
            )

        fingerprint = sha256(der)

        if fingerprint in certificates:
            print(f"Duplicate manifest certificate: {fingerprint}")
            continue

        certificates[fingerprint] = der

    if not certificates:
        raise RuntimeError("No valid certificates found.")

    print(f"Unique certificates in manifest: {len(certificates)}")
    return certificates


def get_disallowed_fingerprints():
    # Read the actual LocalMachine\Disallowed store through PowerShell.
    ps_script = r"""
$ErrorActionPreference = 'Stop'
Get-ChildItem -Path 'Cert:\LocalMachine\Disallowed' |
    ForEach-Object {
        $sha = [Security.Cryptography.SHA256]::Create()
        try {
            [BitConverter]::ToString(
                $sha.ComputeHash($_.RawData)
            ).Replace('-', '')
        }
        finally {
            $sha.Dispose()
        }
    }
"""

    output = run_command([
        "powershell.exe",
        "-NoProfile",
        "-NonInteractive",
        "-Command",
        ps_script,
    ])

    return {
        line.strip().upper()
        for line in output.splitlines()
        if re.fullmatch(r"[0-9A-Fa-f]{64}", line.strip())
    }


def import_certificate(certutil, der, directory, index):
    cert_path = Path(directory) / f"certificate_{index}.cer"
    cert_path.write_bytes(der)

    try:
        run_command([
            certutil,
            "-addstore",
            "-f",
            STORE,
            str(cert_path),
        ])
    finally:
        cert_path.unlink(missing_ok=True)


def main():
    require_admin()

    certutil = shutil.which("certutil.exe")
    if not certutil:
        raise RuntimeError("Windows certutil.exe was not found.")

    manifest = download_manifest()
    certificates = parse_certificates(manifest)
    expected = set(certificates)

    before = get_disallowed_fingerprints()

    already_present = expected & before
    to_import = expected - before

    print(f"Already blocked: {len(already_present)}")
    print(f"To import: {len(to_import)}")

    import_errors = {}

    with tempfile.TemporaryDirectory(
        prefix="emudhra_block_"
    ) as temp_dir:
        for index, fingerprint in enumerate(
            sorted(to_import), start=1
        ):
            try:
                import_certificate(
                    certutil,
                    certificates[fingerprint],
                    temp_dir,
                    index,
                )
                print(f"Import command succeeded: {fingerprint}")
            except Exception as exc:
                import_errors[fingerprint] = str(exc)
                print(f"IMPORT ERROR: {fingerprint}")
                print(exc)

    # Re-read the store instead of trusting command exit codes.
    after = get_disallowed_fingerprints()

    verified = expected & after
    missing = expected - after

    print("\n========== FINAL VERIFICATION ==========")
    print(f"Manifest certificates: {len(expected)}")
    print(f"Verified in Disallowed: {len(verified)}")
    print(f"Missing: {len(missing)}")

    if already_present:
        print(f"Already present before run: {len(already_present)}")

    if missing:
        print("\nCertificates NOT verified:")
        for fingerprint in sorted(missing):
            print(f"  {fingerprint}")
            if fingerprint in import_errors:
                print(f"    Error: {import_errors[fingerprint]}")

        print(
            "\nRESULT: INCOMPLETE. "
            "Some certificates are not in the Windows store."
        )
        return 1

    print(
        "\nRESULT: SUCCESS. All manifest certificates "
        "were found in LocalMachine\\Disallowed."
    )
    print(
        "Note: This confirms Windows store membership only; "
        "it does not prove that every browser honors this store."
    )
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception as exc:
        print(f"\nFATAL ERROR: {exc}", file=sys.stderr)
        sys.exit(2)

[/upvote]

17
1
เข้าสู่ระบบเพื่อร่วมพูดคุย

1 การตอบกลับ

การเรียงลำดับ
  1. hangdahuangli 💬 ทอง 3 YEARS 1 เดือนที่แล้ว

    感谢分享

    1