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

离线解析 Telnet IAC(0xFF) 选项协商、NAWS 子协商帧及 ls/dir 明文会话风险

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

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

IAC = 255
DONT = 254
DO = 253
WONT = 252
WILL = 251
SB = 250
SE = 240
OPT_NAMES = {1: "ECHO", 3: "SGA", 24: "TTYPE", 31: "NAWS"}
CMD_NAMES = {WILL: "WILL", WONT: "WONT", DO: "DO", DONT: "DONT"}


def parse_telnet_stream(data: bytes):
    i = 0
    n = len(data)
    negotiations = []
    subnegs = []
    text_buf = bytearray()
    while i < n:
        b = data[i]
        if b != IAC:
            text_buf.append(b)
            i += 1
            continue
        if i + 1 >= n:
            break
        cmd = data[i + 1]
        if cmd == IAC:
            text_buf.append(IAC)
            i += 2
        elif cmd in CMD_NAMES and i + 2 < n:
            opt = data[i + 2]
            negotiations.append((CMD_NAMES[cmd], OPT_NAMES.get(opt, str(opt))))
            i += 3
        elif cmd == SB and i + 2 < n:
            opt = data[i + 2]
            j = i + 3
            sub_data = bytearray()
            while j < n:
                if data[j] == IAC and j + 1 < n and data[j + 1] == SE:
                    j += 2
                    break
                if data[j] == IAC and j + 1 < n and data[j + 1] == IAC:
                    sub_data.append(IAC)
                    j += 2
                else:
                    sub_data.append(data[j])
                    j += 1
            subnegs.append((OPT_NAMES.get(opt, str(opt)), bytes(sub_data)))
            i = j
        else:
            i += 2
    return negotiations, subnegs, bytes(text_buf)


def case_telnet_iac_option_negotiation():
    stream = bytes([IAC, WILL, 1, IAC, DO, 3, IAC, WONT, 24]) + b"Welcome" + bytes([IAC, IAC]) + b"!"
    negs, _, payload = parse_telnet_stream(stream)
    expected = {
        "negotiations": [["WILL", "ECHO"], ["DO", "SGA"], ["WONT", "TTYPE"]],
        "unescaped_iac_present": True,
        "payload_len": 9,
    }
    actual = {
        "negotiations": [list(x) for x in negs],
        "unescaped_iac_present": payload == b"Welcome\xff!",
        "payload_len": len(payload),
    }
    return {
        "name": "telnet_iac_option_negotiation",
        "summary": "解析 RFC 854/855 Telnet IAC(0xFF) 选项协商三字节序列与 0xFF 0xFF 数据转义还原",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_telnet_subnegotiation_sb_se():
    # NAWS (Option 31): width=80, height=24 as big-endian uint16 pair
    naws_frame = bytes([IAC, SB, 31]) + struct.pack("!HH", 80, 24) + bytes([IAC, SE])
    _, subnegs, _ = parse_telnet_stream(naws_frame)
    opt_name, body = subnegs[0]
    cols, rows = struct.unpack("!HH", body)
    expected = {"option": "NAWS", "cols": 80, "rows": 24}
    actual = {"option": opt_name, "cols": cols, "rows": rows}
    return {
        "name": "telnet_subnegotiation_sb_se",
        "summary": "解析 IAC SB NAWS ... IAC SE 子协商帧,还原终端窗口 80×24 尺寸参数",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_telnet_session_commands_and_plaintext():
    session_wire = (
        b"login: admin\r\n"
        b"Password: clearpass123\r\n"
        b"$ ls\r\nindex.html  config.ini\r\n"
        b"C:\\> dir\r\nREADME.TXT\r\n"
    )
    decoded = session_wire.decode("ascii")
    expected = {
        "default_port": 23,
        "has_ls_command": True,
        "has_dir_command": True,
        "password_exposed_plaintext": True,
    }
    actual = {
        "default_port": 23,
        "has_ls_command": "$ ls\r\n" in decoded,
        "has_dir_command": "> dir\r\n" in decoded,
        "password_exposed_plaintext": "clearpass123" in decoded,
    }
    return {
        "name": "telnet_session_commands_and_plaintext",
        "summary": "验证 Telnet 23 端口会话中 ls/dir 命令与登录密码完全以明文传输的窃听风险",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_telnet_remote_alternatives_compare():
    matrix = {
        "Telnet": {"port": 23, "encrypted": False, "mode": "CLI"},
        "SSH": {"port": 22, "encrypted": True, "mode": "CLI"},
        "RDP": {"port": 3389, "encrypted": True, "mode": "GUI"},
        "VNC": {"port": 5900, "encrypted": False, "mode": "GUI"},
    }
    expected = {
        "secure_cli_replacement": "SSH",
        "gui_protocols": ["RDP", "VNC"],
        "telnet_port": 23,
    }
    actual = {
        "secure_cli_replacement": next(k for k, v in matrix.items() if v["mode"] == "CLI" and v["encrypted"]),
        "gui_protocols": [k for k, v in matrix.items() if v["mode"] == "GUI"],
        "telnet_port": matrix["Telnet"]["port"],
    }
    return {
        "name": "telnet_remote_alternatives_compare",
        "summary": "对比 Telnet 与 SSH、RDP、VNC 在默认端口、加密保护与命令行/图形交互上的差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_telnet_iac_option_negotiation(),
        case_telnet_subnegotiation_sb_se(),
        case_telnet_session_commands_and_plaintext(),
        case_telnet_remote_alternatives_compare(),
    ]
    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-telnet-protocol-lab/explore-telnet-protocol.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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