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

离线解析 TLS 记录层与 ClientHello 帧、密码套件协商、X.509 证书校验及 HKDF 密钥派生

PYTHONWindows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。explore-https-protocol.py
explore-https-protocol.py176 行
"""Offline network protocol verification lab for Chapter 12 (https-protocol)."""
import hashlib
import hmac
import json
import struct

VERSION = "CPython 3.12.14 offline network protocol frame & state-machine verifier"


def case_tls_record_header_and_client_hello():
    # Build minimal RFC 8446 / 5246 TLS Record (ContentType=22 Handshake, LegacyVersion=0x0303)
    # containing Handshake Type=1 (ClientHello) with SNI extension for www.example.com
    sni_host = b"www.example.com"
    sni_entry = struct.pack("!BH", 0, len(sni_host)) + sni_host
    sni_list = struct.pack("!H", len(sni_entry)) + sni_entry
    sni_ext = struct.pack("!HH", 0x0000, len(sni_list)) + sni_list
    extensions = struct.pack("!H", len(sni_ext)) + sni_ext

    client_random = bytes(range(32))
    cipher_suites = struct.pack("!HHH", 4, 0x1301, 0x1302)  # TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384
    ch_body = struct.pack("!H", 0x0303) + client_random + b"\x00" + cipher_suites + b"\x01\x00" + extensions
    # Handshake header: 1B type + 3B length
    hs_msg = bytes([1]) + len(ch_body).to_bytes(3, "big") + ch_body
    tls_record = struct.pack("!BHH", 22, 0x0303, len(hs_msg)) + hs_msg

    # Parse back
    rec_type, rec_ver, rec_len = struct.unpack("!BHH", tls_record[:5])
    hs_type = tls_record[5]
    hs_len = int.from_bytes(tls_record[6:9], "big")
    body = tls_record[9 : 9 + hs_len]
    cs_len = struct.unpack("!H", body[35:37])[0]
    suites = list(struct.unpack(f"!{cs_len // 2}H", body[37 : 37 + cs_len]))

    expected = {
        "record_type_handshake": 22,
        "legacy_version": "0x0303",
        "record_len_matches": True,
        "handshake_type_client_hello": 1,
        "offered_suites": ["0x1301", "0x1302"],
        "sni_present": True,
    }
    actual = {
        "record_type_handshake": rec_type,
        "legacy_version": f"0x{rec_ver:04x}",
        "record_len_matches": rec_len == len(hs_msg) and hs_len == len(ch_body),
        "handshake_type_client_hello": hs_type,
        "offered_suites": [f"0x{s:04x}" for s in suites],
        "sni_present": b"www.example.com" in body,
    }
    return {
        "name": "tls_record_header_and_client_hello",
        "summary": "打包并解析 TLS 5 字节记录层首部与 ClientHello 握手子帧(含密码套件列表与 SNI 扩展)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_tls_cipher_suite_negotiation():
    client_offered = [
        "TLS_AES_128_GCM_SHA256",
        "TLS_CHACHA20_POLY1305_SHA256",
        "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
    ]
    server_preferred = [
        "TLS_CHACHA20_POLY1305_SHA256",
        "TLS_AES_128_GCM_SHA256",
    ]
    selected = next((s for s in server_preferred if s in client_offered), None)
    expected = {
        "selected_suite": "TLS_CHACHA20_POLY1305_SHA256",
        "aead_integrity_included": True,
    }
    actual = {
        "selected_suite": selected,
        "aead_integrity_included": selected is not None and ("GCM" in selected or "POLY1305" in selected),
    }
    return {
        "name": "tls_cipher_suite_negotiation",
        "summary": "模拟客户端与服务端 TLS 密码套件优先级交集协商并确认 AEAD 加密完整性模式",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_x509_certificate_chain_validation():
    ca_signing_key = b"offline-demo-root-ca-secret"

    def issue_cert(san_domains, not_before, not_after, pubkey_hex):
        body = json.dumps(
            {"san": san_domains, "not_before": not_before, "not_after": not_after, "pubkey": pubkey_hex},
            sort_keys=True,
        ).encode("utf-8")
        sig = hmac.new(ca_signing_key, body, hashlib.sha256).hexdigest()
        return {"body": body, "sig": sig}

    def verify_cert(cert, target_host, now_ts):
        calc = hmac.new(ca_signing_key, cert["body"], hashlib.sha256).hexdigest()
        if not hmac.compare_digest(calc, cert["sig"]):
            return "INVALID_SIGNATURE"
        info = json.loads(cert["body"].decode("utf-8"))
        if not (info["not_before"] <= now_ts <= info["not_after"]):
            return "EXPIRED"
        if target_host not in info["san"]:
            return "HOSTNAME_MISMATCH"
        return "VALID"

    cert = issue_cert(["www.example.com", "api.example.com"], 1700000000, 1800000000, "04a1b2c3")
    expected = {
        "valid_host_in_window": "VALID",
        "wrong_host": "HOSTNAME_MISMATCH",
        "expired_time": "EXPIRED",
    }
    actual = {
        "valid_host_in_window": verify_cert(cert, "www.example.com", 1750000000),
        "wrong_host": verify_cert(cert, "evil.example.net", 1750000000),
        "expired_time": verify_cert(cert, "www.example.com", 1900000000),
    }
    return {
        "name": "x509_certificate_chain_validation",
        "summary": "离线验证 CA 签名、SAN 域名匹配与有效时间窗三项 HTTPS 服务器证书校验逻辑",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_https_key_derivation_and_hsts_redirect():
    # RFC 5869 HKDF-Extract & single-block HKDF-Expand with SHA-256
    salt = b"\x00" * 32
    ikm = b"shared-ecdhe-pre-master-secret"
    prk = hmac.new(salt, ikm, hashlib.sha256).digest()
    client_key = hmac.new(prk, b"tls13 c ap traffic\x01", hashlib.sha256).digest()[:16]
    server_key = hmac.new(prk, b"tls13 s ap traffic\x01", hashlib.sha256).digest()[:16]

    http_url = "http://www.example.com/login"
    redirect_resp = {
        "status": 301,
        "location": http_url.replace("http://", "https://", 1),
        "hsts": "max-age=31536000; includeSubDomains",
    }
    expected = {
        "derived_keys_distinct": True,
        "key_bits": 128,
        "redirect_status": 301,
        "redirect_location": "https://www.example.com/login",
    }
    actual = {
        "derived_keys_distinct": client_key != server_key,
        "key_bits": len(client_key) * 8,
        "redirect_status": redirect_resp["status"],
        "redirect_location": redirect_resp["location"],
    }
    return {
        "name": "https_key_derivation_and_hsts_redirect",
        "summary": "使用 HKDF-SHA256 派生独立上下行流量密钥,并校验 HTTP 到 HTTPS 的 301 重定向与 HSTS 配置",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_tls_record_header_and_client_hello(),
        case_tls_cipher_suite_negotiation(),
        case_x509_certificate_chain_validation(),
        case_https_key_derivation_and_hsts_redirect(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。

入口文件:projects/np-https-protocol-lab/explore-https-protocol.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-https-protocol.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:网络协议

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

下载课程关联工程包:网络协议

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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