"""Offline network protocol verification lab for Chapter 22 (dhcp-protocol)."""
import ipaddress
import json
import struct
VERSION = "CPython 3.12.14 offline network protocol frame & state-machine verifier"
DHCP_MAGIC_COOKIE = b"\x63\x82\x53\x63"
MSG_DISCOVER, MSG_OFFER, MSG_REQUEST, MSG_ACK = 1, 2, 3, 5
def pack_tlv(code: int, value: bytes) -> bytes:
return struct.pack("!BB", code, len(value)) + value
def parse_tlvs(options: bytes) -> dict[int, bytes]:
assert options[:4] == DHCP_MAGIC_COOKIE
pos = 4
parsed = {}
while pos < len(options):
code = options[pos]
pos += 1
if code == 255:
break
if code == 0:
continue
length = options[pos]
pos += 1
parsed[code] = options[pos : pos + length]
pos += length
return parsed
def pack_dhcp_packet(op: int, xid: int, yiaddr: str, giaddr: str, chaddr_6: bytes, tlvs: bytes) -> bytes:
header = struct.pack(
"!BBBBIHH4s4s4s4s16s64s128s",
op,
1, # htype Ethernet
6, # hlen
0 if giaddr == "0.0.0.0" else 1, # hops
xid,
0,
0x8000, # broadcast flag
b"\x00\x00\x00\x00",
ipaddress.IPv4Address(yiaddr).packed,
b"\x00\x00\x00\x00",
ipaddress.IPv4Address(giaddr).packed,
chaddr_6 + b"\x00" * 10,
b"\x00" * 64,
b"\x00" * 128,
)
return header + DHCP_MAGIC_COOKIE + tlvs + b"\xff"
def unpack_dhcp_packet(pkt: bytes) -> dict:
op, htype, hlen, hops, xid, secs, flags, ci, yi, si, gi, chaddr = struct.unpack("!BBBBIHH4s4s4s4s16s", pkt[:44])
opts = parse_tlvs(pkt[236:])
return {
"op": op,
"hops": hops,
"xid": xid,
"yiaddr": str(ipaddress.IPv4Address(yi)),
"giaddr": str(ipaddress.IPv4Address(gi)),
"chaddr": ":".join(f"{b:02x}" for b in chaddr[:hlen]),
"options": opts,
}
def case_dhcp_dora_state_machine_and_tlv():
mac = bytes.fromhex("aabbcc112233")
xid = 0x3903F326
states = ["INIT"]
# 1. Discover
disc = pack_dhcp_packet(1, xid, "0.0.0.0", "0.0.0.0", mac, pack_tlv(53, bytes([MSG_DISCOVER])))
d_disc = unpack_dhcp_packet(disc)
states.append("SELECTING")
# 2. Offer
offer_opts = (
pack_tlv(53, bytes([MSG_OFFER]))
+ pack_tlv(1, ipaddress.IPv4Address("255.255.255.0").packed)
+ pack_tlv(3, ipaddress.IPv4Address("192.168.50.1").packed)
+ pack_tlv(6, ipaddress.IPv4Address("192.168.50.2").packed)
+ pack_tlv(51, struct.pack("!I", 86400))
+ pack_tlv(54, ipaddress.IPv4Address("192.168.50.1").packed)
)
offer = pack_dhcp_packet(2, xid, "192.168.50.101", "0.0.0.0", mac, offer_opts)
d_offer = unpack_dhcp_packet(offer)
# 3. Request
req_opts = (
pack_tlv(53, bytes([MSG_REQUEST]))
+ pack_tlv(50, ipaddress.IPv4Address("192.168.50.101").packed)
+ pack_tlv(54, ipaddress.IPv4Address("192.168.50.1").packed)
)
req = pack_dhcp_packet(1, xid, "0.0.0.0", "0.0.0.0", mac, req_opts)
d_req = unpack_dhcp_packet(req)
states.append("REQUESTING")
# 4. Ack
ack_opts = (
pack_tlv(53, bytes([MSG_ACK]))
+ pack_tlv(1, ipaddress.IPv4Address("255.255.255.0").packed)
+ pack_tlv(3, ipaddress.IPv4Address("192.168.50.1").packed)
+ pack_tlv(6, ipaddress.IPv4Address("192.168.50.2").packed)
+ pack_tlv(51, struct.pack("!I", 86400))
+ pack_tlv(54, ipaddress.IPv4Address("192.168.50.1").packed)
)
ack = pack_dhcp_packet(2, xid, "192.168.50.101", "0.0.0.0", mac, ack_opts)
d_ack = unpack_dhcp_packet(ack)
states.append("BOUND")
expected = {
"dora_types": [1, 2, 3, 5],
"states": ["INIT", "SELECTING", "REQUESTING", "BOUND"],
"assigned_ip": "192.168.50.101",
"subnet_mask": "255.255.255.0",
"router": "192.168.50.1",
"dns": "192.168.50.2",
"lease_seconds": 86400,
}
actual = {
"dora_types": [
d_disc["options"][53][0],
d_offer["options"][53][0],
d_req["options"][53][0],
d_ack["options"][53][0],
],
"states": states,
"assigned_ip": d_ack["yiaddr"],
"subnet_mask": str(ipaddress.IPv4Address(d_ack["options"][1])),
"router": str(ipaddress.IPv4Address(d_ack["options"][3])),
"dns": str(ipaddress.IPv4Address(d_ack["options"][6])),
"lease_seconds": struct.unpack("!I", d_ack["options"][51])[0],
}
return {
"name": "dhcp_dora_state_machine_and_tlv",
"summary": "完整封装并解析 RFC 2131 DHCP DORA 四步报文、魔数 Cookie(0x63825363)与 TLV 选项字段",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dhcp_lease_t1_t2_timers():
lease = 86400
t1_renew = int(lease * 0.5) # 50% unicast renew
t2_rebind = int(lease * 0.875) # 87.5% broadcast rebind
def client_phase(elapsed: int) -> str:
if elapsed < t1_renew:
return "BOUND"
if elapsed < t2_rebind:
return "RENEWING_UNICAST"
if elapsed < lease:
return "REBINDING_BROADCAST"
return "EXPIRED_INIT"
expected = {
"t1_seconds": 43200,
"t2_seconds": 75600,
"phase_at_10000": "BOUND",
"phase_at_50000": "RENEWING_UNICAST",
"phase_at_80000": "REBINDING_BROADCAST",
"phase_at_90000": "EXPIRED_INIT",
}
actual = {
"t1_seconds": t1_renew,
"t2_seconds": t2_rebind,
"phase_at_10000": client_phase(10000),
"phase_at_50000": client_phase(50000),
"phase_at_80000": client_phase(80000),
"phase_at_90000": client_phase(90000),
}
return {
"name": "dhcp_lease_t1_t2_timers",
"summary": "校验 DHCP 租期 T1(50% 单播续租)、T2(87.5% 广播重绑)与到期回收状态迁移",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dhcp_relay_agent_giaddr_selection():
# Relay agent stamps giaddr=10.20.0.1 so central DHCP server chooses pool 10.20.0.0/24
mac = bytes.fromhex("001122334455")
relayed = pack_dhcp_packet(1, 0x12345678, "0.0.0.0", "10.20.0.1", mac, pack_tlv(53, bytes([MSG_DISCOVER])))
parsed = unpack_dhcp_packet(relayed)
pools = {
ipaddress.IPv4Network("10.10.0.0/24"): "10.10.0.50",
ipaddress.IPv4Network("10.20.0.0/24"): "10.20.0.50",
}
gi = ipaddress.IPv4Address(parsed["giaddr"])
chosen = next(ip for net, ip in pools.items() if gi in net)
expected = {"hops": 1, "giaddr": "10.20.0.1", "selected_pool_ip": "10.20.0.50"}
actual = {"hops": parsed["hops"], "giaddr": parsed["giaddr"], "selected_pool_ip": chosen}
return {
"name": "dhcp_relay_agent_giaddr_selection",
"summary": "验证跨子网 DHCP 中继代理写入 giaddr 与 hops 字段后服务器按子网池选址的机制",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dhcp_snooping_port_policy():
trusted_ports = {"Gi0/1"}
events = [
("Gi0/1", MSG_OFFER), # legitimate DHCP server on trusted uplink
("Gi0/12", MSG_OFFER), # rogue DHCP server on untrusted access port
("Gi0/12", MSG_DISCOVER), # normal client discover on untrusted port
]
decisions = []
for port, mtype in events:
is_server_msg = mtype in (MSG_OFFER, MSG_ACK)
allowed = (not is_server_msg) or (port in trusted_ports)
decisions.append(allowed)
expected = {"trusted_offer_allowed": True, "rogue_offer_blocked": True, "client_discover_allowed": True}
actual = {
"trusted_offer_allowed": decisions[0],
"rogue_offer_blocked": not decisions[1],
"client_discover_allowed": decisions[2],
}
return {
"name": "dhcp_snooping_port_policy",
"summary": "验证交换机 DHCP Snooping 信任/非信任端口策略拦截伪造 DHCP Offer 欺骗攻击",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_dhcp_dora_state_machine_and_tlv(),
case_dhcp_lease_t1_t2_timers(),
case_dhcp_relay_agent_giaddr_selection(),
case_dhcp_snooping_port_policy(),
]
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-dhcp-protocol-lab/explore-dhcp-protocol.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-dhcp-protocol.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2722.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2723.zip