如何注册 post-dissector 并追加列?
解读
在国内一线厂商的 Wireshark 二次开发面试中,这道题考察的是插件化扩展能力与UI 数据注入能力的综合掌握程度。
注册 post-dissector 属于“协议解析后处理”阶段,核心目标是在不破坏原有解析树的前提下追加自定义字段;而“追加列”则要求把字段同步到主界面的 Packet List 面板,实现零脚本、可固化、可过滤的列输出。
面试官通常通过追问“注册时机”“字段生命周期”“列过滤性能”来判别候选人是否真正做过工程级插件,而非跑过 Demo。
知识点
- post-dissector 注册入口:
register_postdissector()在wtap_encap为WTAP_ENCAP_PER_PACKET时生效,必须在proto_register_XXX阶段完成。 - 字段句柄:使用
proto_register_field_array注册hf_register_info,并标记HFILL中的BFI标志位BASE_ALLOW_ZERO,否则空值会被 UI 过滤掉。 - 列追加 API:
proto_set_custom_column仅对 3.6+ 生效;老版本需手动col_add_str并在prefs.columns里固化列名,国内多数政企场景仍跑 3.4 LTS,必须兼容。 - 性能陷阱:postdissector 每包都会回调,禁止在回调中做字符串拼接或正则解析;应预编译
wmem_map_t缓存,把耗时操作挪到init阶段。 - 安全合规:国内等保测评要求“解析插件必须可卸载”,因此需实现
plugin_version与plugin_can_unload,否则会被甲方安全团队打回。
答案
步骤如下(以 C 语言插件为例,Lua 思路相同但 API 名字差异不大):
-
头文件与全局句柄
#include <epan/packet.h> #include <epan/postdissector.h> static int proto_my_post = -1; static int hf_my_latency = -1; static dissector_handle_t my_post_handle; -
注册协议与字段
void proto_register_my_post(void) { static hf_register_info hf[] = { { &hf_my_latency, { "App Latency", "my_post.latency", FT_UINT32, BASE_DEC, NULL, 0x0, "Custom latency in us", HFILL }} }; proto_my_post = proto_register_protocol( "MyPost Dissector", "MyPost", "my_post"); proto_register_field_array(proto_my_post, hf, array_length(hf)); } -
注册 post-dissector
void proto_reg_handoff_my_post(void) { my_post_handle = create_dissector_handle(dissect_my_post, proto_my_post); register_postdissector(my_post_handle); } -
解析回调中写列
static int dissect_my_post(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree _U_, void *data _U_) { guint32 latency = 0; /* 从已有的解析树中拿字段,避免二次解析 */ latency = (guint32)g_tree_lookup(pinfo->private_table, "tcp.analysis.ack_rtt"); if (latency) { col_add_fstr(pinfo->cinfo, COL_CUSTOM, "%u us", latency); /* 把值也写进解析树,方便过滤 */ proto_tree_add_uint(tree, hf_my_latency, tvb, 0, 0, latency); } return tvb_captured_length(tvb); } -
追加列到 UI
在~/.config/wireshark/preferences里追加gui.column.format: "Latency", "%Cus:my_post.latency",或使用
epan/prefs.h提供的prefs_register_column在插件里固化,避免让用户手动改配置文件,这是国内交付的隐性要求。 -
卸载支持
gboolean plugin_can_unload(void) { return TRUE; }
编译后放 ~/.local/lib/wireshark/plugins/3.6/epan/(Linux)或 Wireshark\plugins\3.6\epan\(Windows),重启即可在 Packet List 看到“Latency”列,且可用 my_post.latency > 10000 过滤。
拓展思考
-
如果数据包经过 IPS 分片重组,post-dissector 会在每个重组片段都触发一次,如何避免重复写列?
答:在pinfo->fd->flags.visited为 0 时才写列,利用PINFO_FD_VISITED(pinfo)做短路。 -
国内云厂商常把 Wireshark 嵌入容器 sidecar,插件需热升级,但
register_postdissector不支持重复注册。
答:在plugin_can_unload里先deregister_postdissector,再proto_unregister_protocol,确保内存无泄漏,否则 k8s 健康检查会把 Pod 踢掉。 -
若列值需要中文显示,务必使用 UTF-8 无 BOM 编码,并在
col_add_str前加g_utf8_validate,否则 Windows 中文版会显示乱码,导致甲方验收失败。