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

离线解析 RDP TPKT+X.224 连接协商帧、键鼠输入与脏矩形位图增量更新及 NLA 防护

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

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


def case_rdp_tpkt_x224_connection_request():
    # RFC 1006 TPKT (4B) + ITU-T X.224 Connection Request TPDU (7B) + RDP Negotiation Request (8B, MS-RDPBCGR)
    # requestedProtocols: 0x00000003 = PROTOCOL_SSL(0x01) | PROTOCOL_HYBRID_NLA(0x02)
    rdp_neg_req = struct.pack("<BBHI", 0x01, 0x00, 8, 0x00000003)
    x224_payload = b"Cookie: mstshash=admin\r\n" + rdp_neg_req
    x224_li = 6 + len(x224_payload)
    x224_cr = struct.pack("!BBHHB", x224_li, 0xE0, 0x0000, 0x1234, 0x00) + x224_payload
    total_len = 4 + len(x224_cr)
    tpkt_frame = struct.pack("!BBH", 3, 0, total_len) + x224_cr

    # Decode
    tpkt_ver, tpkt_res, tpkt_len = struct.unpack("!BBH", tpkt_frame[:4])
    u_li, u_code, u_dst, u_src, u_cls = struct.unpack("!BBHHB", tpkt_frame[4:11])
    neg_type, neg_flags, neg_len, req_protos = struct.unpack("<BBHI", tpkt_frame[-8:])

    expected = {
        "default_rdp_port": 3389,
        "tpkt_version": 3,
        "tpkt_len_matches": True,
        "x224_cr_code": "0xe0",
        "neg_type_request": 1,
        "tls_requested": True,
        "nla_hybrid_requested": True,
    }
    actual = {
        "default_rdp_port": 3389,
        "tpkt_version": tpkt_ver,
        "tpkt_len_matches": tpkt_res == 0 and tpkt_len == len(tpkt_frame) and u_li == len(x224_cr) - 1,
        "x224_cr_code": f"0x{u_code:02x}",
        "neg_type_request": neg_type,
        "tls_requested": bool(req_protos & 0x01),
        "nla_hybrid_requested": bool(req_protos & 0x02),
    }
    return {
        "name": "rdp_tpkt_x224_connection_request",
        "summary": "构造并解析 MS-RDPBCGR TPKT(v3)+X.224 Connection Request(0xE0)+RDP 协商请求(TLS/NLA)帧",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_rdp_security_protocol_negotiation():
    # X.224 Connection Confirm (0xD0) carrying RDP Negotiation Response (type=0x02, selected=0x02 Hybrid NLA)
    neg_rsp = struct.pack("<BBHI", 0x02, 0x01, 8, 0x00000002)
    x224_cc = struct.pack("!BBHHB", 6 + len(neg_rsp), 0xD0, 0x1234, 0x5678, 0x00) + neg_rsp
    frame = struct.pack("!BBH", 3, 0, 4 + len(x224_cc)) + x224_cc

    u_code = frame[5]
    rsp_type, rsp_flags, rsp_len, selected_proto = struct.unpack("<BBHI", frame[11:19])
    proto_names = {0: "RDP_STANDARD", 1: "TLS", 2: "HYBRID_NLA", 4: "RDSTLS"}

    expected = {
        "x224_cc_code": "0xd0",
        "rsp_type_confirm": 2,
        "selected_protocol": "HYBRID_NLA",
        "ext_client_data_supported": True,
    }
    actual = {
        "x224_cc_code": f"0x{u_code:02x}",
        "rsp_type_confirm": rsp_type,
        "selected_protocol": proto_names.get(selected_proto, "UNKNOWN"),
        "ext_client_data_supported": bool(rsp_flags & 0x01) and rsp_len == 8,
    }
    return {
        "name": "rdp_security_protocol_negotiation",
        "summary": "解析 X.224 Connection Confirm(0xD0) 中的 RDP 安全协议协商响应,确认选中 CredSSP/NLA",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_rdp_input_and_bitmap_update_pdu():
    # Simplified RDP client input event (type=1 keyboard scancode, type=2 mouse move) & server dirty-rect bitmap update
    kb_event = struct.pack("<BHH", 1, 0x001E, 0x0000)  # scancode 0x1E ('A'), keydown
    mouse_event = struct.pack("<BHH", 2, 640, 360)
    et1, scan, flags = struct.unpack("<BHH", kb_event)
    et2, mx, my = struct.unpack("<BHH", mouse_event)

    full_frame_bytes = 1920 * 1080 * 4
    dirty_rect = (100, 100, 356, 228)  # 256 x 128 changed region
    dirty_bytes = (dirty_rect[2] - dirty_rect[0]) * (dirty_rect[3] - dirty_rect[1]) * 4
    savings_pct = round((1.0 - dirty_bytes / full_frame_bytes) * 100, 2)

    expected = {
        "kb_scancode": "0x001e",
        "mouse_xy": [640, 360],
        "dirty_rect_bytes": 131072,
        "bandwidth_saved_over_98pct": True,
    }
    actual = {
        "kb_scancode": f"0x{scan:04x}" if et1 == 1 and flags == 0 else "",
        "mouse_xy": [mx, my] if et2 == 2 else [],
        "dirty_rect_bytes": dirty_bytes,
        "bandwidth_saved_over_98pct": savings_pct > 98.0,
    }
    return {
        "name": "rdp_input_and_bitmap_update_pdu",
        "summary": "解析客户端键鼠输入 PDU 与服务端脏矩形位图增量更新,验证局部刷新对带宽占用的优化",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_rdp_nla_and_remote_alternatives():
    def connect_rdp(nla_enabled, cred_valid):
        if nla_enabled and not cred_valid:
            return {"session_created": False, "result": "REJECTED_BEFORE_SESSION"}
        if cred_valid:
            return {"session_created": True, "result": "DESKTOP_ACTIVE"}
        return {"session_created": True, "result": "LOGIN_SCREEN_EXPOSED"}

    blocked = connect_rdp(True, False)
    allowed = connect_rdp(True, True)
    alternatives = {
        "RDP": {"port": 3389, "gui": True, "built_in_tls": True},
        "VNC": {"port": 5900, "gui": True, "built_in_tls": False},
        "SSH": {"port": 22, "gui": False, "built_in_tls": True},
    }
    expected = {
        "nla_blocks_unauth_before_session": True,
        "nla_allows_valid_user": True,
        "rdp_port": 3389,
        "alternative_count": 3,
    }
    actual = {
        "nla_blocks_unauth_before_session": (not blocked["session_created"]) and blocked["result"] == "REJECTED_BEFORE_SESSION",
        "nla_allows_valid_user": allowed["session_created"] and allowed["result"] == "DESKTOP_ACTIVE",
        "rdp_port": alternatives["RDP"]["port"],
        "alternative_count": len(alternatives),
    }
    return {
        "name": "rdp_nla_and_remote_alternatives",
        "summary": "验证网络级身份验证(NLA)在分配桌面会话前拦截未认证请求,并对比 RDP/VNC/SSH 特性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_rdp_tpkt_x224_connection_request(),
        case_rdp_security_protocol_negotiation(),
        case_rdp_input_and_bitmap_update_pdu(),
        case_rdp_nla_and_remote_alternatives(),
    ]
    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-rdp-protocol-lab/explore-rdp-protocol.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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