Conceptio › Archive › arXiv CS
arXiv CS open access

SEMPRE: Semantic-Aware Protocol Reverse Engineering via Consistency-Driven Joint Optimization

Yihua Xu et al. · arxiv_cs
arXiv CS · Papers
Open Source ↗Direct PDF ↓
cryptographycybersecurityprivacysecurity
Protocol reverse engineering (PRE) is essential for understanding undocumented or proprietary communication formats, enabling security-critical tasks such as vulnerability discovery, malware C2 analysis, and IDS signature generation. However, existing PRE techniques rely on brittle hand-written rule
Conceptio Open Archive

Analyze & explore related research in Conceptio

Connect this record directly into your research workflow or AI agent. Explore citations across open repositories, query full text, and export structured proof bundles.

Yihua Xu

Weijie Huang

Xiaofeng Wang

Hang Zhang

Illinois Institute of Technology yxu131@hawk.illinoistech.edu

Indiana University wh25@iu.edu

Nanyang Technological University xiaofeng.wang@ntu.edu.sg

Indiana University hz64@iu.edu

Binghui Wang

Yue Duan

Illinois Institute of Technology bwang70@illinoistech.edu

Singapore Management University yueduan@smu.edu.sg

I. I NTRODUCTION Protocol reverse engineering (PRE) is the process of analyzing communication flows to deduce the message structures, semantics, or state machines of network protocols, typically when official specifications are unavailable, incomplete, or proprietary [1], [2]. When only protocol messages and the program binaries that implement the protocol are available, PRE becomes particularly challenging. Analysts often have to rely on captured network traffic and the behavior of related (often closed-source) software to infer how systems exchange information. Figure 1 illustrates the expected output of PRE on a real-world Modbus message [3]. Given a 12-byte message (byte [0] to byte [11]), PRE aims to: (1) accurately identify the boundaries of all fields within the message (field detection),

Network and Distributed System Security (NDSS) Symposium 2027 22–26 March 2027, Seoul, Republic of Korea ISBN 978-1-970672-09-1 https://dx.doi.org/10.14722/ndss.2027.242825 www.ndss-symposium.org

00 00

00 06

04

00 30

00 28

Message

[6] [7]

[ 8, 9 ]

[ 10, 11 ]

Fields

Integer

25 CC

Integer

and (2) infer each field’s type and role (semantic inference). PRE is a key enabler for security applications, including analyzing malware command-and-control (C2) communications [4], [5], discovering vulnerabilities in undocumented or proprietary protocols [6], and generating intrusion detection system (IDS) signatures for previously unknown threats [7]. Input

Types

FF

CMD

Integer

Static

[ 4, 5 ]

Group

[ 2, 3 ]

Length

[ 0, 1 ]

Static

PRE

Integer

Abstract—Protocol reverse engineering (PRE) is essential for understanding undocumented or proprietary communication formats, enabling security-critical tasks such as vulnerability discovery, malware C2 analysis, and IDS signature generation. However, existing PRE techniques rely on brittle hand-written rules, under-model contextual dependencies among neighboring fields, and often fail on messages with nested sub-protocols. We present S EM PRE, a fully automated PRE framework that replaces adhoc heuristics with recursive LLM reasoning grounded in finegrained dynamic program analysis. S EM PRE uses taint-flow and loop traces to guide an LLM-driven tree-of-thought search that slices messages into fields while detecting nested sub-payloads, producing a hierarchical layout. It then infers each field’s type and role and iteratively refines boundaries by freezing highconfidence segments and re-running detection under semantic constraints, yielding an EM-style procedure that monotonically improves structure and semantics until convergence. Evaluated on a broad corpus of mainstream protocols against six stateof-the-art PRE systems, S EM PRE achieves an average F1 of 0.76 for field detection (vs. <0.40 for all baselines) and 0.72 for semantic inference (vs. 0.14 for BinPRE). Ablations confirm the contribution of each component, and a case study on a prolific real-world botnet demonstrates practical utility.

Results

arXiv:2610.31844v1 [cs.CR] 22 Oct 2026

S EM PRE: Semantic-Aware Protocol Reverse Engineering via Consistency-Driven Joint Optimization

Functions

Fig. 1: Protocol Reverse Engineering Due to the importance of PRE, a substantial body of research has emerged. Existing studies generally fall into two categories: network-traffic-based approaches and binaryanalysis-based approaches. Network-traffic-based methods, such as BinaryInferno [8], NEMESYS [9], DynPRE [10], and NetPlier [11], take captured network traces as input and apply statistical techniques to extract recurring format patterns. However, their effectiveness depends heavily on access to high-quality and diverse traffic that captures many protocol message instances—an assumption that is often difficult to satisfy in practice. In contrast, binary-analysis-based approaches, including Dispatcher [12], PolyGlot [13], Tupni [14], and BinPRE [2], leverage dynamic program analysis to recover detailed runtime semantics by observing how the protocol implementation parses and consumes message bytes. For example, if the binary consistently loads bytes [0–1] together, applies endian-aware integer operations (e.g., shifting/combining), and uses the resulting value in conditional branches or length calculations, this provides strong evidence that [0–1] forms a multi-byte integer field rather than unrelated bytes. As a result, binary-based approaches are often more practical in realworld settings where high-quality traffic traces are unavailable. Despite significant progress, we identify three fundamental

limitations of state-of-the-art (SOTA) binary-analysis-based techniques, as elaborated below. First, SOTA approaches rely heavily on hand-crafted heuristics or rule sets that are tuned to specific byte patterns or protocol families. This rule-driven design limits generalizability and makes it difficult to keep pace with the diversity of real-world encodings. A representative example is BinPRE [2], which uses multiple rules to label a field as a filename only when the byte sequence ends with a known extension (e.g., “.txt” or “.jpg”). Consequently, filenames that are length-prefixed, UTF16 encoded, or extensionless can be missed or mislabeled. Second, existing techniques often model fields in isolation, without explicitly capturing semantic relationships among neighboring fields. In practice, many protocols exhibit strong contextual dependencies that are crucial for semantic inference. For instance, a tag immediately followed by a length field strongly suggests the canonical Type–Length–Value (TLV) pattern, and checksum fields typically appear after the data they protect. The Dynamic Host Configuration Protocol (DHCP) [15], for example, encodes options as a sequence of TLV triples. Reliably identifying the Tag–Length prefix is essential for delineating the corresponding value fields and inferring their types. Prior work, such as BinaryInferno [8], can leverage serialization patterns to detect certain LV/TLVlike structures, but it does not reason about why fields depend on one another or how upstream boundary errors propagate to downstream semantic inference. As a result, failing to model such dependencies can lead to inaccuracies that may cascade into subsequent analyses, such as vulnerability discovery. Third, these PRE techniques struggle to robustly handle a special yet prevalent case – nested protocols, where a message embeds a sub-payload that follows a different protocol specification. While dynamic binary-analysis–based approaches (e.g., Polyglot [13], Tupni [14], and BinPRE [2]) can expose certain field semantics by observing runtime parsing behavior or can infer repeated or nested layouts from control-flow regularities, these methods primarily recover syntactic structure rather than an explicit hierarchical semantic representation. In practice, inferred fields are often flattened into a single sequence, obscuring protocol-layer boundaries. However, nested payloads typically induce stronger dependencies within a subprotocol than across protocol boundaries. Existing systems do not explicitly represent or reason about this distinction, and approaches with limited semantic cues (e.g., BinaryInferno) still assign roles largely at the level of individual fields, without modeling hierarchical relationships or distinguishing intra-payload dependencies from inter-layer transitions. Consequently, nested protocols may be only partially recovered, and inferred layouts can become brittle for multi-layer designs such as EtherNet/IP (EIP) [16] encapsulating Common Industrial Protocol (CIP) [17] payloads. Recent studies [18], [19], [20] suggest that large language models (LLMs) can outperform rigid, heuristic-based pipelines in reverse-engineering tasks such as disassembly [20] and decompilation [19], [18]. Trained on large corpora, LLMs can internalize recurring structural regularities and, importantly,

capture relationships among distant components, enabling more flexible inference under uncertainty. Motivated by these advances, we first examined whether an off-the-shelf LLM could perform protocol reverse engineering (PRE) without additional structure. In a pilot study, we asked GPT-o3 (the same backbone model used in our approach) to perform field detection on 179 messages from four representative protocols (50 Modbus, 41 S7, 38 FTP, and 50 DNS). The results exposed the limitations of naı̈ve prompting: the model achieved an F1 of 0.69 on Modbus (the simplest format in our set) and remained below 0.50 on S7, FTP, and DNS. These outcomes indicate that dependable PRE requires more than a single, unconstrained pass through an LLM. A qualitative inspection suggests that naı̈ve prompts often trigger hallucinated fields, incorrect semantic assumptions, and inconsistent labeling across messages, especially for formats with optional fields, variable-length encodings, or layered structure. We attribute this behavior to the difficulty of reliably grounding generation on long, noisy inputs (e.g., dynamic traces) and maintaining global consistency when many interacting constraints must be satisfied simultaneously. To effectively tackle the PRE problem, our key insight is that field detection and semantic inference are tightly coupled: accurate boundaries make semantics easier to infer, while semantic constraints (e.g., TLV relationships, checksums, length fields, nested payload headers) can in turn validate and refine boundaries. With this, we develop S EM PRE, a fully automated PRE framework, which integrates fine-grained dynamic program analysis with a recursive LLM-driven reasoning procedure that performs joint optimizations over field detection and semantic inference, rather than treating them as two independent stages as in prior work. S EM PRE first performs fine-grained dynamic taint analysis and loop detection while executing the protocol binary on a given input message. These traces provide low-level evidence about how individual bytes are consumed (e.g., grouped loads, comparisons, arithmetic, and repeated parsing behavior), which we encode as structured hints for downstream reasoning. Next, in the field detection step, S EM PRE uses an LLM-based tree-of-thought search to propose candidate segmentations that are consistent with the collected taint/loop evidence. To address nested protocols, S EM PRE exploits the LLM’s capability to recognize subpayload boundaries and recursively applies the same detection procedure to any inferred nested regions, yielding an initial hierarchical message layout. Given this layout, our system performs semantic inference to predict the type and role of each field. The inferred semantics are then fed back into a subsequent detection round: high-confidence boundaries are frozen, and ambiguous regions are re-segmented under stronger semantic constraints. Then, S EM PRE alternates between field detection and semantic inference, using the output of each step to constrain the other until a fixed point is reached. If the process fails to converge within a preset budget, S EM PRE restarts with alternative hypotheses to escape poor local optima. Inspired by the Expectation–Maximization (EM) algorithm [21], we formalize this procedure as an iterative

2

where J(m, s) scores structural plausibility (e.g., boundary quality and cross-field constraints).

optimization process and prove that each update is monotonic and that the procedure converges to a local optimum. The end result is a heuristic-free, effective PRE solution that improves both accuracy and stability compared to state-ofthe-art techniques. We implemented a prototype of S EM PRE and evaluated it against six state-of-the-art PRE tools. The results demonstrate that S EM PRE achieves the best overall performance across a diverse set of popular protocols. In field detection, S EM PRE attains the highest average F1 score of 0.76, demonstrating a 90%+ improvement with no other tools exceeding 0.4. In semantic inference, S EM PRE achieves an average F1 score of 0.72, substantially outperforming the 0.14 of BinPRE, the state-of-the-art PRE tool. Our further ablation study confirms and quantifies the contribution of each design component. In addition, we demonstrate S EM PRE’s practicality for security tasks by using it to analyze the protocol of a real-world, widely distributed botnet malware sample.

Semantic inference. Let Ycommon be a vocabulary of semantic labels (field types/functions), and let Y = Ycommon ∪ {⊥}, where ⊥ denotes “unknown / none of the above.” Given a message m and a detected segmentation s with K fields, semantic inference assigns one label per field by maximizing a global semantic objective: fsem (m, s) = arg max G(m, s, y), y∈Y K

where y = (y1 , . . . , yK ) and G(m, s, y) evaluates semantic consistency across fields and with the observed bytes. For each field k, yk ∈ Ycommon indicates an assigned semantic type/function, while yk = ⊥ indicates that no suitable label is assigned. In this study, we reuse Ycommon defined in BinPRE [2] (i.e., five common types: static, integer, group, bytes, and string, and six common semantic functions: command, length, delim, checksum, filename, and aligned, detailed in Table XI) for fair comparisons in our evaluation. Note that adding new types or functions is straightforward and requires minimal configuration in S EM PRE, since it is built on an LLM that retains extensive knowledge of types and functions.

Contributions. Our contributions are summarized as follows: • We designed a fully automated PRE framework, which integrates fine-grained dynamic program analysis with a recursive LLM-driven reasoning procedure that performs joint optimizations over field detection and semantic inference. • We formally proved that our algorithm converges to a local optimum. • We implemented a prototype of S EM PRE and opensourced our implementation 1 to facilitate future research in this field. We further evaluated its efficacy. Our experiments demonstrate that S EM PRE significantly outperforms prior PRE mechanisms and excels in analyzing real-world malware protocols (§IV).

B. Motivation To better understand the limitations of current PRE techniques, we examine several representative scenarios drawn from real-world network protocols and highlight the core challenges that existing tools struggle to address. Inflexible Heuristics-Based Rules. Recent PRE mechanisms (e.g., BinPRE [2]) rely heavily on hand-crafted inference rules, typically designed by experts based on well-documented protocols and prior knowledge, to identify and label protocol fields. These rules inevitably introduce bias and limit the potential for generalization. For instance, Figure 2 shows a real-world TFTP message containing a filename field (Byte[217]). The file name here (“pxelinux.cfg/C0”) includes a special slash character that is explicitly excluded by BinPRE’s filename identification heuristic, but permitted by TFTP’s specification [22]. Consequently, BinPRE fails to correctly recognize field semantics because of its rigid rules. In contrast, S EM PRE avoids such brittle, protocol-specific heuristics by grounding an LLM’s semantic hypotheses in dynamic execution evidence (e.g., tainting information and parsing behavior), enabling it to generalize to unseen but speccompliant field values rather than rejecting them due to hardcoded pattern rules.

II. P ROBLEM S TATEMENT & M OTIVATION A. Problem Statement We formally define the PRE problem as follows. Let M denote the space of protocol messages. Each message m ∈ M is a finite byte sequence m = (b0 , b1 , . . . , b|m|−1 ), bi ∈ {0, 1}8 . Field detection. A (flat) segmentation of m is an ordered list of K byte intervals  s = (l1 , r1 ), (l2 , r2 ), . . . , (lK , rK ) such that (i) each interval is contiguous with 0 ≤ lk ≤ rk ≤ |m|−1, (ii) intervals are non-overlapping and ordered, i.e., rk + 1 = lk+1 for all k ∈ {1, . . . , K − 1}, and (iii) they cover the entire message, i.e., l1 = 0 and rK = |m|−1. Let S(m) denote the set of all valid segmentations of m. Field detection seeks a segmentation that maximizes a global structural objective:

Ignorance of Semantic Relationships. Protocol fields rarely occur in isolation; instead, they are tied together by structural and semantic dependencies that govern correct parsing and interpretation. A common example is the Length–Value (LV) construct, in which a length field specifies the size of a subse-

fdet (m) = arg max J(m, s), s∈S(m)

1 https://anonymous.4open.science/r/SemPRE-F9F8

3

Message:

00 01

70 78 … 2F 43 30 00

6F … 00

74 … 00

Fields:

[ 0, 1 ]

[ 2, …, 17 ]

[ 18, …, 23 ]

[ 24, …, 44 ]

Semantics:

Opcode

File Name = pxelinux.cfg/C0

Mode

Options

Header

Message:

Fields:

03

00

00 19

02

F0

80

32 01 … 01 E0

Fields:

[0]

[1]

[ 2, 3 ]

[4]

[5]

[6]

[ 7, …, 24 ]

Semantics:

Version

Reserved

Length

Length

Type

Credit

S7 Protocol Message

[ 0, …, 23 ]

[ 24, …, 45 ]

[ 46, …, 81 ]

III. S YSTEM D ESIGN AND I MPLEMENTATION A. Overview As depicted in Figure 5, S EM PRE comprises three principal phases, namely pre-processing, field detection, and semantic inference, of which the latter two are coupled through a joint optimization process.

Fig. 5: S EM PRE Overview Given a raw message from an undocumented protocol and its corresponding binary, preprocessing runs the binary on the message under dynamic taint analysis. We record perbyte dataflow and detect parsing loops along the executed path, exposing where the program repeatedly consumes input. These taint/loop cues reliably indicate variable-length arrays and length-prefixed regions, helping localize field boundaries and size dependencies. The taint map, loop inventory, and raw message are then used to construct an initial segmentation by aligning taint boundaries with loop patterns and other structural cues. Next, semantic inference assigns each segment a data type and functional role (e.g., length, command, string) using evidence extracted from the binary and statistical priors. High-confidence semantic predictions are fed back as constraints to refine segmentation (e.g., enforcing length–payload consistency). Field detection and semantic inference alternate until the joint objective stops improving; if needed, we restart with a different initialization up to a fixed budget. The final output is a stable, semantically annotated message layout. Notably, we operate on each message independently and avoid cross-message semantic alignment or majority-vote reconciliation. Without ground truth, global alignment can amplify noisy predictions and propagate errors across messages; instead,

S7COMM

Message:

0A 02 … 01 00

Current techniques implicitly assume a single, homogeneous message format. Hence, they either stop at the outerlayer header/payload boundary (leaving the embedded protocol unanalyzed) or flatten the entire byte stream into a single structure, which often leads to missegmentation and incorrect semantic labels for the inner protocol. S EM PRE explicitly targets nested protocols via recursive inference.

quent variable-length field, allowing the receiver to precisely delimit the payload. Figure 3 shows such dependencies in an S7 communication message [23]. In this example, byte[4] encodes a length that indicates the next 2 bytes form a payload segment. Likewise, byte[2–3] encodes the total message length, constraining the maximum extent of all subsequent fields. These length declarations create explicit cross-field constraints that, if modeled, can substantially reduce ambiguity in both field boundary detection and semantic labeling. Existing PRE techniques do not reason about these interfield dependencies, which makes them prone to cascading errors. For instance, a boundary mistake around a length field can distort the inferred layout of all downstream fields, and semantic mislabeling can remove key constraints needed for correct segmentation. For instance, BinPRE infers semantics at the byte (or local) level and labels byte[4] as a fixed-width numeric field without linking it to the following payload, and it even misinterprets byte[2–3] as two independent “Length” fields rather than a single two-byte length value. S EM PRE addresses this limitation by jointly optimizing field boundaries and semantic labels in an iterative loop, allowing inferred LV constraints (e.g., a length field governing a following payload) to validate and refine segmentation decisions rather than treating each field in isolation. COTP

00 00 … E4 6A

Fig. 4: Insufficient Handling of Nested Protocols

Fig. 2: Inflexible Heuristics-Based Rules

TPKT

CIP

70 00 … 00 00

Fig. 3: Ignorance of Semantic Relationships Insufficient Handling of Nested Protocols. Nested protocol structures are pervasive in real-world communication stacks, especially in industrial settings. A representative example is EtherNet/IP (EIP) [16], which commonly encapsulates Common Industrial Protocol (CIP) [17] payloads. In practice, a single EIP message may contain one or more embedded CIP messages, each with its own internal field layout and semantics. As shown in Figure 4, the example EIP message includes a CIP sub-payload spanning byte[46–81], accounting for nearly half of the message.

4

S EM PRE emphasizes per-message internal consistency guided by execution evidence. This process mirrors the workflow of a human analyst: an initial coarse segmentation and semantic assignment is iteratively refined by identifying high-confidence labels and using them to revise earlier boundary and type hypotheses, repeating until the message description becomes coherent and self-consistent. In S EM PRE, the analyst’s evaluative role is delegated to an LLM. Recent studies [24], [25], [26], [27] show that state-of-the-art models (e.g., GPT-4) can perform self-critique and error correction when provided access to intermediate reasoning artifacts, and prior work [28], [29], [30] finds their judgments often track human preferences, making them effective automated evaluators in iterative pipelines [31]. Accordingly, after each iteration, the LLM reviews the current hypotheses, flags outputs it deems reliable, and feeds these constraints into the next cycle to progressively improve both segmentation and semantic interpretation.

Message

ToT-based Field Detection

LLM

Identified Fields

Taint & Loop Info

Field Detection Result

Inferred Semantics Recursive Field Detection

Sub-payload Detection

Fig. 6: Field Detection detection enables the LLM to cross-validate multiple candidate segmentations against taint, loop, and semantic cues, thereby pruning inconsistent branches and curbing hallucinations while arriving at a globally coherent field layout, which effectively improves accuracy.

Tree-of-Thoughts (ToT) in Field Detection. ToT is a prompting framework that extends chain-of-thought prompting and B. Pre-processing self-consistency [35], [36]. Instead of committing to a sinIn the pre-processing stage, given a message and a binary gle linear reasoning trace, ToT explores multiple candidate that consumes the message, our system performs a byte-level reasoning trajectories in parallel, organized as branches of dynamic taint analysis [32] that taints the given message as a tree. Each node corresponds to a thought: a short textual the data source and keeps track of how the binary processes intermediate step that is sufficiently concise to enable dithe given message during the execution by recording how verse generation, yet informative enough to support reliable the binary’s instructions access, propagate, and transform the evaluation. A typical ToT workflow comprises four steps: tainted data from the input message. By doing so, S EM PRE (1) thought decomposition, which defines the intermediate can produce a set of taint information that contains details on steps appropriate for the task; (2) thought generation, which which instructions read from, write to, or otherwise depend proposes k candidate thoughts for the current state (e.g., via on each part of the input message during execution, which sampling); (3) state evaluation, which scores candidates by is essential for further segmenting the message into multihow much progress they make toward a solution and selects ple fields. This information provides execution-level evidence the most promising states to retain; and (4) search, which for subsequent field segmentation. Since S EM PRE performs expands the tree using a strategy such as breadth-first or depthsemantic reasoning on a per-message basis, its effectiveness first search, iterating until a satisfactory solution is found. does not primarily depend on the number of execution traces 1/31/26, 6:06 PM collected for the same message. To further facilitate field Thought Message detection, we perform loop detection [33] to recognize loops Indexes decomposition [ 0, 1, ..., 38, 39 ] during the execution and record the memory addresses of Len=40 Field 1 [ 0, 1 ] the loops in order to correlate repetitive processing patterns Though Start from 0 Field 2 k=5 Generation observed in the execution trace with the specific message [ 2, ..., 12 ] [ 0, ..., 3 ] Searching Field 3 [ 0, 1 ] bytes being handled. Identifying loops will highlight code [ 13, ..., 18 ] [ 0, 1 ] [2] that iterates over portions of the input, revealing variable... [ 2, ..., 9 ] [ 2, ..., 12 ] [2] Field 4 State [ 2, ..., 9 ] [ 0, ..., 3 ] [ 19, ..., 26 ] length fields or length-prefixed blocks. Such iteration patterns ... ... [ 13, ..., 39 ] [ 13, ..., 18 ] ... Evaluation [ 2, ..., 12 ] [ 13, ..., 18 ] offer clear markers for field boundaries and size relationships, Field x ... thereby sharpening the accuracy. [ 19, ..., 26 ] [ 19, ..., 26 ] ... https://whimsical.com/field-Bphd3DcewHSypvMfJEtxU7

...

C. Field Detection As depicted in Figure 6, our field detection takes as input the message, the taint and loop information from the preprocessing, and the inferred semantics from semantic inference (will be empty in the first iteration, more details in Section III-D), and eventually outputs the field detection result. To achieve this, S EM PRE leverages a novel prompting technique, Tree-of-Thoughts (ToT) [34], which enables LLMs to explore multiple reasoning paths through thoughts, leading to more accurate problem-solving. Specifically, ToT in field

Fig. 7: Tree-of-Thoughts Process To use ToT effectively in the context of S EM PRE, we instantiate it as a structured search procedure for message segmentation that explicitly captures semantic dependencies between adjacent fields. We treat field boundaries as the ToT search space: a ToT state represents a partial segmentation of the message prefix, and each expansion hypothesizes the next contiguous field starting at the first unassigned byte. Given

5

1/1

a raw protocol message of length L, the initial state spans indices [0, 1, . . . , L − 1] and the search begins at index i = 0. Because protocol fields are contiguous and sequential, we map one “thought” to one complete field. Concretely, at position i, a thought proposes the next field as a contiguous byte range [i, j] (with j ≥ i). Selecting j uniquely determines the next start position i ← j + 1, so later boundary decisions are naturally conditioned on earlier ones. In the thought generation phase, starting from the current index i, S EM PRE proposes up to k (we empirically set to 5) end positions j, yielding k alternative field hypotheses [i, j]. These candidates are not arbitrary: they are generated by jointly leveraging dynamic taint cues (e.g., grouping bytes consumed by the same semantic operation) and LLM-derived protocol cues (e.g., delimiter patterns, length constraints, and value formats). Figure 7 illustrates this process on a message of length L = 40 (indices [0, . . . , 39]): at i = 0, the model may propose candidate boundaries such as [0, 1] and [0, . . . , 3]; after choosing [0, 1], the next step begins at i = 2 and may generate candidates including [2, 2], [2, . . . , 9], and [2, . . . , 12]. In the state evaluation phase, each candidate field induces a successor state (i.e., a longer prefix segmentation), which the LLM scores using a cost-based function, which reflects: (1) whether tainted bytes used in semantic operations are consistently covered by the proposed fields, (2) whether boundaries violate inferred structural/semantic constraints (e.g., length– payload consistency), and (3) whether the partial layout is plausible under common protocol patterns. The cost value C lies in [0, 1] for every path, with C = 0 denoting a perfectly consistent segmentation and C = 1 denoting one that violates every constraint on every field. S EM PRE retains only low-cost states, pruning implausible segmentations early while preserving diverse, high-quality boundary hypotheses. Finally, in the search phase, S EM PRE performs a tree search over these states. Starting at i = 0, we apply depth-first search to enumerate complete segmentations and select the lowestcost root-to-leaf path that reaches the end of the message. In Figure 7, the final field-detection result is the concatenation of the fields along this best path (i.e., Field 1: [0, 1], Field 2: [2, . . . , 12], Field 3: [13, . . . , 18], Field 4: [19, . . . , 26]).

Algorithm 1: Field Detection FieldDetection(M, T aint, Loop, SemLabels); Input : M - A message of an unknown protocol; T aint - Taint information; Loop - Loop information; SemLabels - High-confident semantic labels; T oT - ToT parameters. Output: F ields - Detected fields of the message; 2 P romptf ield ← Create a field detection prompt using (M sg, T aint, Loop, SemLabels, T oT ) ; 3 Response ← LLMQuery(P romptf ield ) ; 4 F ields ← Responce; 5 Log ← P romptf ield ; 6 while i ≤ MaxIterTimes do 7 P romptf ield ← Log + F ields + Psubpayload ; 8 Response ← LLMQuery(P romptf ield ); 9 F ields, SubP ayloadF lag ← Response; 10 if SubPayloadFlag == True then 11 Log ← P romptf ield ; 12 i + +; 13 continue; 14 else 15 break; 16 end if 17 end while 18 return F ields 1

using the given parameters (Ln. 2) and query the LLM to obtain Response, which contains the initial field set F ields. Next, we build a sub-payload detection prompt by combining contextual information Log+F ields with sub-payload prompt template Psubpayload (Ln.7) and query LLM to get Response (Ln. 8), which provides updated fields of the message and an indicator showing whether additional sub-payload detection is required. Taint information in the context informs LLM which bytes are fixed, allowing it to reason only over untainted regions. If another iteration is needed, then we update Log and repeat; otherwise, the fields are the results.

Recursive Sub-payload Detection. We leverage the LLM to perform sub-payload detection, shown in Figure 6. When the LLM identifies a potential sub-payload region inside a protocol data unit (PDU), we recursively invoke the ToT-based field detection procedure described earlier on that sub-region, providing the same inputs (e.g., taint-flow and loop evidence, as well as any currently inferred semantics). This recursive process continues until the LLM reports that no further subpayloads remain. As illustrated in Algorithm 1, it takes as input a message M , the taint and loop information T aint and Loop from preprocessing, and high-confident semantic labels SemLabels from semantic inference (which will be empty in the first iteration), and outputs F ields as detection results. Specifically, we first create a field-detection prompt P romptf ield

D. Semantic Inference Following field detection, S EM PRE proceeds to semantic inference depicted in Figure 8. The inference stage is initialized with two resources: (i) a diverse exemplar set covering various protocol categories (e.g., binary, textual, or mixed messages), and (ii) the catalog of candidate type–function pairs defined by BinPRE [2]. Because a field’s interpretation depends on neighboring fields and message-level constraints, semantic inference cannot be performed as an independent label assignment. For instance, a single field often admits several plausible type–function hypotheses whose validity is contingent on adjacent semantics (e.g., a putative length indicator dictates how the succeeding payload must be parsed).

6

refinement process continues until semantic convergence is achieved or no further improvements can be made. Algorithm 2: Joint Optimization F ields = {}, SemLabels = {}; while i ≤ MaxIterationTimes do 3 F ields ← FieldDetection(M, T aint, Loop, SemLabels); 4 SemLabels ← SemanticInference(M, F ewShots, F ields); 5 F ieldsh , SemLabelsh , N eedF urtherOp ← LLMQuery (F ields, SemLabels); 6 update (T ypeh , F nh ); 7 if N eedF urtherOp == T rue then 8 F ields = F ieldsh ; 9 SemLabels = SemLabelsh ; 10 i + +; 11 Go to the next iteration ; 12 else 13 return F ields, SemLabels; 14 end if 15 end while 16 if i > M axIterationT imes then 17 Restart the whole process ; 18 end if 1 2

Fig. 8: Semantic Inference and Joint Optimization

To this end, we formulate semantic inference as a structured search and realize it with another Tree-of-Thoughts (ToT) prompting scheme. Each field produced by the field-detection phase constitutes one “thought” step: at that node, the LLM generates candidate type–function pairs by analyzing byte patterns, taint-/loop-derived behavior, and higher-level protocol cues. Successive steps branch to form alternative semantic paths over the message. Every path is cost-scored according to constraint consistency and corpus priors; a branch-andbound mechanism then prunes incoherent paths, retaining only those with minimal cost. Exploration proceeds in sliding windows of 5 fields, iterating until all segments have been evaluated. During the process, the LLM also serves as an internal evaluator. Paths whose cost falls below a calibrated threshold are marked as high-confidence, and their labels are fixed as additional constraints for the next iteration. Through this iterative coupling of field detection and semantic inference, S EM PRE progressively converges on a globally coherent structural and semantic interpretation of the message. Complete prompt templates are included in Appendix A.

Optimization Algorithm. The optimization procedure is summarized in Algorithm 2. We initialize the field detection results, denoted by F ields, and the semantic inference results, denoted by SemLabels, as empty sets. The algorithm then proceeds iteratively through the following stages: (1) invoke Algorithm 1 to obtain a provisional set of fields (Ln.3); (2) apply few-shot exemplars, constraint rules, and the interim fields to infer semantic labels (Ln.4); and (3) query the LLM to select high-confidence predictions and determine whether additional joint optimization is needed (Ln.5). If further optimization is required, the high-confidence predictions are fixed, and the next iteration is executed (Ln.7–11). Otherwise, the algorithm returns F ields and SemLabels as the final outputs (Ln.13). Moreover, if the current solution has not converged, S EM PRE restarts the entire process and repeats the optimization until a predefined limit is reached (Ln.16–17).

E. Joint Optimization Based on our unique insight that field detection and semantic inference are strongly correlated and can complement each other, S EM PRE performs an iterative process between the two to jointly optimize results and reach a local optimum, as shown in Figure 8. This component is inspired by the Expectation–Maximization (EM) algorithm [21], which addresses problems involving partially observed data. In particular, after the initial inference round, S EM PRE has identified message fields and predicted their types and functions. Among these, some predictions can be marked as high-confidence (evaluated by the LLM) and serve as partially observed labels that guide the next iteration. This process is also inspired by how human analysts approach reverse engineering tasks. Analysts often begin with uncertain or approximate field interpretations, refine their understanding as more structural or semantic cues emerge, and use confident insights to correct earlier errors. S EM PRE mimics this behavior by using the LLM to evaluate its own intermediate outputs and determine whether further refinement is warranted. Through this feedback loop, S EM PRE incrementally improves its predictions, correcting earlier mistakes and reinforcing accurate interpretations. The

F. Analysis of Iterative Refinement S EM PRE alternates between field detection and semantic inference, using high-confidence predictions from one iteration as constraints for the next. Because both stages involve stochastic LLM inference, we do not claim unconditional convergence for arbitrary executions. Instead, we analyze the refinement process under a structural property of the PRE problem and two practical behavioral assumptions. The analysis characterizes when the iterative process is expected to stabilize.

7

State and Objective. Given a message B and its dynamic analysis information T , let St and Lt denote the field segmentation and semantic labels at iteration t, respectively. Let Ht denote the set of high-confidence predictions retained as constraints. We use J(S, L | B, T ) to denote the consistency of a candidate interpretation with runtime evidence and cross-field constraints, where a larger value indicates a more consistent interpretation.

consistent with these assumptions across iterations by tracking the accumulation of high-confidence predictions and changes in the predicted field boundaries and semantic labels. S EM PRE also bounds the number of refinement iterations and restarts the process when it does not stabilize within the predefined budget. Thus, the analysis characterizes when S EM PRE’s refinement process reaches a stable fixed point, rather than claiming convergence to a local or global optimum.

Finite Candidate Space. For a finite message, the number of possible contiguous segmentations is finite. Since S EM PRE assigns each field a label from a finite semantic vocabulary, the joint candidate space of (S, L) is also finite. Likewise, Ht can contain only finitely many constraints. This property follows directly from the discrete formulation of field segmentation and semantic labeling.

IV. E VALUATION We evaluate our system with respect to its general effectiveness and its efficacy in handling real-world cases. Specifically, we aim to conduct a series of experiments to answer the following research questions. RQ1: How effective is S EM PRE for field detection? RQ2: How effective is S EM PRE for semantic inference? • RQ3: Can S EM PRE maintain its effectiveness without potential prior knowledge from the LLM or with a different backbone LLM? • RQ4: Does each component of S EM PRE contribute uniquely in protocol reverse engineering? • RQ5: Can S EM PRE effectively handle real-world malware protocols? •

Assumption 1: Reliable High-Confidence Constraints. Following prior findings on the reliability of high-confidence LLM predictions, we assume that predictions retained in Ht are sufficiently reliable to serve as constraints in subsequent iterations. In particular, we assume that fixing these predictions does not introduce erroneous constraints that prevent refinement toward an interpretation more consistent with the available runtime evidence. The retained constraints therefore accumulate as Ht ⊆ Ht+1 . (1)

•

A. Experimental Setup

Assumption 2: Consistency-Preserving Refinement. We further assume that an accepted refinement does not decrease the consistency objective: J(St+1 , Lt+1 | B, T ) ≥ J(St , Lt | B, T ).

Baseline Techniques. To evaluate the effectiveness of S EM PRE, we compare its performance against six stateof-the-art PRE techniques, including both network-trafficbased and binary-analysis-based approaches. Specifically, we compare S EM PRE with PolyGlot [13], Tupni [14], AutoFormat [37], BinPRE [2], BinaryInferno [8], and DynPRE [10]. Note that we directly reuse the code released by the original authors for BinPRE, PolyGlot, AutoFormat, and Tupni, and re-implement BinaryInferno and DynPRE ourselves based on their papers since their code is unavailable.

(2)

This condition captures S EM PRE’s intended behavior: newly identified semantic constraints, such as a reliable length– payload relationship, reduce ambiguity in subsequent field detection, while refined field boundaries constrain semantic inference. Under Eq. 2, the sequence

Dataset. We constructed the dataset as follows.

Jt = J(St , Lt | B, T )

Protocols. We collect three protocol datasets for evaluation: D1) the dataset in BinPRE [2], which includes eight widely used protocols covering textual, binary, and mixed formats across the industrial control and network communication domains; D2) a real-world undocumented dataset from GitHub, which contains three real-world undocumented protocols (KTP [38], CCN [39] and Xfer [40]); D3) we use Mirai [41], which is a botnet malware protocol, as a case study. Further information is listed in Table XV. • Messages. Detailed in Table I in Appendix, we collect two message datasets: (1) open-source message datasets and (2) datasets built by ourselves when open-source datasets are unavailable. Concretely, we build the datasets for DNP3.0, HTTP, Mirai, KTP, CCN, and Xfer using their clients and the tcpdump tool. The other messages are from opensource datasets. The number of messages varies across protocols, as the sources of messages differ by protocol. •

is non-decreasing. Because the candidate space is finite, Jt cannot strictly increase indefinitely. Moreover, if an iteration does not improve Jt but adds new reliable constraints, Ht can strictly grow only finitely many times. Therefore, if S EM PRE continues refinement only when either Jt+1 > Jt

or

Ht ⊂ Ht+1 ,

(3)

The process eventually reaches a state in which neither condition holds. We call this a stable fixed point of the refinement procedure. Practical Interpretation. The above result is conditional, not a formal guarantee of local or global optimality. In practice, an LLM may generate an inconsistent hypothesis or incorrectly mark a prediction as high-confidence, violating the behavioral assumptions above. We can observe behavior

8

Additionally, the network-based PRE methods, BinaryInferno and DynPRE, are designed to handle small input messages. Please note: although BinPRE reports results, its public repository does not release the corresponding messages (except Modbus), so we evaluated them using our own captured ones.

a flaw because it significantly reduces the impact of incorrect boundaries. For example, BinPRE outputs [-1,2,3,5,6] (5 offsets but 4 fields) against a ground truth [-1,1,5,6]. Based on BinPRE’s calculation, 3 of 5 offsets match (-1, 5, 6), giving precision 0.6 even though only 1 field is correctly identified (5, 6). Thus, our metrics directly work at the field level. We check whether predicted field boundaries are correct, which is simpler and more direct than BinPRE.

TABLE I: Groud Truth Details.

396

7149

5911

2455 0.82 0.35

R.T. - ratio of labeled types; R.F. - ratio of labeled functions

1.0

Ground Truth Collection. The primary source of groundtruth annotations is the official protocol documentation. For Mirai, whose protocol lacks a formal specification, we instead derive the annotations through a manual audit of the publicly available source code. The resulting corpus records, for every message, the byte-level field boundaries together with a single type and a single function label for each field. All annotations are cross-validated against Wireshark packet dissections, yielding a data set we regard as error-free. Type and function labels are absent for a small subset of fields when the available taxonomy proves insufficient or when discrepancies arise between the written specification and the Wireshark interpretation.

0.8

0.7591

F1 Score

0.6 0.3928 0.3284

0.4

0.3669

0.3491

0.3306

0.2

0.0904

Se

m

PR

E

0.0

E

1 1 0.33

o

26

yn PR

80

rn

80

fe

D4

D

1 0.35

i

45

pn

127

In

127

5 5 5

ry

10

na

Mirai Ethernet/IP BAC OPC

Bi

D3

at

9 1 0.17 24 1 0.38 24 0.93 0.27

Tu

54 64 84

m

54 64 90

To evaluate field detection, we compute precision, recall, and F1 score for S EM PRE on each protocol and aggregate the results across all messages. We compare against baseline methods using the D1 dataset, which includes eight widely used protocols spanning all three protocol categories. Overall, as shown in Figure 9, S EM PRE substantially outperforms all baselines. Compared to the strongest competitor, BinPRE, S EM PRE achieves a whopping 95% improvement (0.76 v.s. 0.39). Averaged across all baselines, the F1 gain is 0.45, and remains 0.41 when excluding the weakest baseline, BinaryInferno. In absolute terms, S EM PRE correctly identifies 4,822 of 6,465 ground-truth fields, exceeding the runner-up by 933 correct detections.

ot

9 8 9

B. RQ1: Effectiveness on Field Detection

0.26 0.47 0.37 0.31 0.46 0.82 0.29 0.18

gl

KTP CCN Xfer

1 0.66 0.84 0.65 1 1 0.86 0.82

oF or

D2

100 372 1046 212 206 137 32 248

A ut

378 526 2346 452 450 168 96 1166

E

378 798 2802 692 450 168 112 1414

ly

50 41 50 53 50 38 16 62

Po

D1

Modbus S7comm Ethernet/IP DNP3 DNS FTP TFTP HTTP

Summary

# Messages # Fields # Types # Fn.s R.T. R.F.

nP R

Protocol

Bi

Dataset

Fig. 9: Average F1 Score in Field Detection For individual protocols, S EM PRE outperforms all baselines in nearly all cases (Table II), with two minor exceptions. For Modbus, BinPRE achieves a perfect F1 score (1.00), while S EM PRE attains 0.99, a negligible difference. For DNP3, AutoFormat achieves higher precision due to protocol-specific constraints. DNP3 produces the longest taint- and loopanalysis traces because its implementation validates nearly every byte, which limits S EM PRE to using less than 10% of the analysis data under OpenAI API input-length constraints. AutoFormat, by contrast, can leverage the full analysis. Even so, S EM PRE attains an F1 score of approximately 0.80 (about 90% of AutoFormat’s performance), demonstrating strong robustness despite the reduced data.

Evaluation Metrics. Field detection produces a set of byte offsets that mark the field boundaries. Each predicted offset is classified as either a true positive or a false positive with respect to the reference annotations, enabling the computation of precision (the proportion of predicted boundaries that are correct), recall (the proportion of actual boundaries that are recovered), and their harmonic mean, the F1 score. Semantic inference, likewise, is evaluated through these three measures: although the task is nominally multi-class, each type or function assignment can be viewed as a binary decision (correct vs. incorrect) relative to the ground truth. Accordingly, we aggregate the per-field outcomes to obtain precision, recall, and F1 for type labels and function labels. Throughout the study, these three metrics (precision, recall, and F1) serve as the basis for our performance assessment. Please note that BinPRE uses offset-level metrics for field detection, considering all bytes in a given message, but this is

Answer to RQ1: S EM PRE identifies fields with a solid F1 score of 0.76 on all protocol messages and can beat all state-of-the-art techniques.

9

TABLE II: Field Detection Results. S EM PRE

Protocols

BinPRE

Polyglot

AutoFormat

Tupni

Binaryinferno

DynPRE

Pre.

Rec.

F1

Pre.

Rec.

F1

Pre.

Rec.

F1

Pre.

Rec.

F1

Pre.

Rec.

F1

Pre.

Rec.

F1

Pre.

Rec.

F1

Modbus S7comm Ethernet/IP DNP3 DNS FTP TFTP HTTP

0.98 0.81 0.86 0.84 0.56 0.57 1.00 0.63

1.00 0.81 0.75 0.76 1.00 0.79 1.00 0.57

0.99 0.81 0.80 0.80 0.72 0.66 1.00 0.60

0.99 0.82 1.00 0.88 0.39 0.36 0.46 0.27

1.00 0.02 0.15 0.58 0.97 0.38 0.66 0.36

1.00 0.05 0.25 0.70 0.56 0.37 0.54 0.31

0.60 0.47 0.36 0.59 0.23 0.20 0.14 0.07

0.98 0.16 0.61 1.00 1.00 0.58 1.00 0.40

0.75 0.23 0.45 0.74 0.38 0.30 0.24 0.12

0.85 0.43 0.37 0.83 0.22 0.17 0.11 0.10

1.00 0.13 0.60 1.00 0.91 0.44 0.83 0.40

0.92 0.19 0.46 0.91 0.36 0.25 0.20 0.16

0.60 0.47 0.36 0.69 0.23 0.20 0.14 0.07

0.98 0.16 0.61 1.00 1.00 0.58 1.00 0.40

0.75 0.23 0.45 0.81 0.38 0.30 0.24 0.12

0.25 0.00 0.03 0.98 0.00 0.00 0.50 0.02

0.15 0.00 0.01 0.41 0.00 0.00 0.17 0.00

0.19 0.00 0.01 0.58 0.00 0.00 0.25 0.00

0.81 0.841 0.86 N/A 0.212 N/A N/A N/A

0.37 0.511 0.11 N/A 0.802 N/A N/A N/A

0.51 0.641 0.19 N/A 0.342 N/A N/A N/A

Average

0.77

0.75

0.76

0.49

0.33

0.39

0.23

0.60

0.33

0.27

0.58

0.37

0.23

0.60

0.33

0.28

0.05

0.09

0.63

0.24

0.35

1 - / 2 - DynPRE only accepts part of the messages 1 - Counting based on the first 31 messages; 2 - Counting based on the first 16 messages.

90% improvement over the runner-up (BinPRE). Performance on S7comm, EIP, and HTTP is comparatively lower (0.64, 0.67, and 0.70, respectively), which we attribute primarily to boundary errors introduced during field detection. Notably, the precision for EIP and HTTP is close to 1.00, indicating that when field boundaries are correctly identified, the inferred function labels are highly reliable. S7Comm is particularly challenging because messages over TCP/IP are encapsulated by multiple headers, creating a deeply nested structure in which semantic errors at outer layers can propagate to inner sub-payloads.

C. RQ2: Effectiveness on Semantic Inference To evaluate semantic inference, we assess type inference and function inference separately, comparing only against baselines that support the corresponding task. For type inference, we compare exclusively with BinPRE, the only baseline that predicts field types, using the same type categories for fairness. For function inference, we include all baselines except AutoFormat, which does not perform semantic labeling. Overall, S EM PRE correctly infers 3,441 of 5,582 reference types and 1,431 of 2,353 reference functions. For type inference (Table III), S EM PRE consistently outperforms BinPRE across all evaluated protocols. Its F1 score on TFTP is comparatively lower (0.3542), but it still exceeds all baselines. This gap is primarily caused by semantic ambiguity: several TFTP fields are encoded as byte strings, yet they semantically represent numeric parameters or composite values, making type assignment difficult even for experienced analysts. BinPRE’s weak results on S7comm, FTP, and HTTP largely stem from inaccurate field detection: when boundaries are wrong, semantic inference is inherently inaccurate. While BinPRE reaches an F1 of 0.70 on DNP3, it often assigns multiple type labels to the same field. We count such multilabel outputs as incorrect (even if one label matches the ground truth), because this behavior amounts to guessing and can artificially inflate precision (by up to 20%) without providing genuine semantic understanding. TABLE III: Type Inference Results. Protocols

S EM PRE

BinPRE

Precision Recall

F1 Precision Recall

Answer to RQ2: S EM PRE identifies both field type and function with high accuracy, significantly outperforming all the state-of-the-art PRE techniques. D. RQ3: Robustness and Generalization

S EM PRE uses GPT-o3 model as its backbone LLM, which raises the concern that the model may have been exposed to protocol specifications during pre-training, potentially introducing bias into our evaluation. To decouple S EM PRE’s performance from any latent prior knowledge, we construct a zero-prior-knowledge setting. Concretely, our prompt explicitly forbids the use of any background knowledge about Modbus, S7Comm, Ethernet/IP, DNP3, DNS, FTP, TFTP, and HTTP, and requires field extraction to be derived solely from the provided message content and auxiliary traces. We validate that this constraint is effective by observing a clear performance degradation when running vanilla GPT-o3 under the zero-knowledge prompt (Table V). We then evaluate three configurations on the D1 dataset: S EM PRE, S EM PRE-zero, and BinPRE. As shown in Table IV, S EM PRE indeed benefits from background knowledge. However, even without it, S EM PRE-zero still significantly outperforms BinPRE on most protocols. The only exception is DNP3, where API inputlength limits force us to truncate the taint context, reducing the amount of usable dynamic evidence and thereby weakening the method’s effectiveness.

F1

Modbus S7comm Ethernet/IP DNP3 DNS FTP TFTP HTTP

0.82 0.83 0.90 0.92 0.75 0.95 0.35 0.90

0.79 0.81 0.78 0.80 0.60 0.72 0.75 0.82 0.67 0.71 0.58 0.72 0.35 0.35 0.48 0.62

0.41 0.00 0.33 0.00 0.58 0.00 1.00 0.00

0.40 0.41 0.00 0.00 0.04 0.08 0.00 0.00 0.42 0.49 0.00 0.00 0.16 0.27 0.00 0.00

Average

0.86

0.62 0.72

0.45

0.08 0.14

For function inference (Table XIX in Appendix), S EM PRE again outperforms all baselines on every protocol, yielding a

10

TABLE IV: Effectiveness w/wo Prior Knowledge. Protocols Modbus S7comm Ethernet/IP DNP3 DNS FTP TFTP HTTP

S EM PRE-zero1

S EM PRE Field Type

Fn.

Fields Type

Fn.

Fields Type

Fn.

0.81 0.80 0.69 0.82 0.71 0.72 0.35 0.62

1.00 0.64 1.00 0.90 0.93 0.77 1.00 0.70

0.99 0.82 0.62 0.64 0.65 0.63 1.00 0.85

0.73 0.59 0.62 0.34 0.55 0.68 0.41 0.55

0.99 0.35 0.99 0.31 0.72 0.74 1.00 0.54

1.00 0.05 0.25 0.70 0.56 0.37 0.54 0.31

0.41 0.00 0.22 0.00 0.49 0.00 0.27 0.00

1.00 0.00 1.00 0.86 0.75 0.00 0.64 0.00

0.72 0.74

0.72

0.45 0.43

0.39

0.14 0.35

0.99 0.81 0.80 0.80 0.72 0.66 1.00 0.60

Average 0.76

Answer to RQ3: S EM PRE maintains strong performance without prior LLM knowledge or with a different backbone LLM, consistently outperforming SOTA techniques.

BinPRE

E. RQ4: Ablation Study In this study, we explore the effectiveness of two core components of S EM PRE: recursive sub-payload detection (Figure 6) and iterative optimization (Figure 8). To conduct this ablation study cost-efficiently, we use a small-scale dataset derived from RQ1 by selecting the first 10 messages from each protocol. We evaluate the following configurations of S EM PRE: • S EM PRE-norec-noop: remove both the recursive subpayload detection and the iterative optimization • S EM PRE-noop: remove the iterative optimization • S EM PRE-ToT: remove the ToT • S EM PRE-norec: remove the recursive sub-payload detection • S EM PRE: full-fledged S EM PRE Recursive sub-payload detection addresses the challenge of field detection in the presence of nested payloads. As shown in Table VII in Appendix, adding this component increases the average F1 score from 0.58 to 0.76 compared to S EM PREnorec-noop. Although DNS sees a decrease (1.00 to 0.77), substantial gains are achieved for Ethernet/IP (0.37 → 0.71) and HTTP (0.39 → 0.62). A similar performance shift between S EM PRE-norec-noop and S EM PRE further confirms the effectiveness of recursive detection.

1 - S EM PRE-zero: S EM PRE in the zero-prior-knowledge setting.

We further evaluate on undocumented protocols (D2 dataset), whose specifications are unlikely to be memorized by LLMs. As shown in Table XVIII in Appendix, S EM PRE consistently outperforms both BinPRE and vanilla GPT-o3. Although S EM PRE and BinPRE rely on the same taint information, BinPRE groups bytes using the Needleman–Wunsch algorithm, which lacks instruction-level semantic awareness and often produces incorrect merges. In contrast, S EM PRE leverages LLM-guided consistency between field detection and semantic inference to interpret taint outputs and delineate boundaries more accurately. An exception applies to KTP, where performance is comparable between S EM PRE and vanilla GPT-o3, because half of the fields are firmly associated with the sending end, while the other fields work for the receiving end, and taint information affects only fields related to the sending end.

TABLE VI: Ablation Study Results - Semantic Inference.

Finally, we replace GPT-o3 with DeepSeek-v3.1-terminus to examine whether S EM PRE’s effectiveness changes substantially under a different backbone LLM. The results remain comparable and consistently outperform BinPRE (Table XVII), suggesting that S EM PRE’s gains are not tied to any single model, but stem primarily from its overall design.

Protocols

TABLE V: GPT-o3 Performance.

Protocols

w Knowledge

0.67 0.80 0.38 0.27 0.70 0.48 1.00 0.48

Average 0.53

0.63 0.77 0.38 0.36 0.84 0.79 0.69 0.64

0.45 0.40 0.12 0.27 0.39 0.85 1.00 0.21

S EM PRE

Fn. F1

Type F1 Fn. F1 Type F1 Fn. F1

Modbus S7comm Ethernet/IP DNP3 DNS FTP TFTP HTTP

0.79 0.68 0.28 0.75 0.71 0.68 0.50 0.31

1.00 0.53 0.25 0.82 0.87 0.71 0.97 0.18

0.78 0.86 0.31 0.84 0.72 0.68 0.40 0.65

1.00 0.70 0.24 0.97 1.00 0.71 0.95 0.49

0.78 0.91 0.47 0.80 0.70 0.67 0.40 0.68

1.00 0.77 0.62 0.90 0.96 0.71 1.00 0.71

Average

0.48

0.51

0.56

0.58

0.62

0.74

w/o Knowledge Improved field detection should also enhance semantic inference, as intended. S EM PRE-noop outperforms S EM PREnorec-noop on semantic tasks, raising average F1 0.48 → 0.56, for type inference and 0.51 → 0.58 for function inference (Table VI). Adding iterative optimization further boosts performance, raising F1 scores to 0.62 for type inference and 0.74 for function inference. While some protocols show minor drops, the gains on Ethernet/IP and HTTP are substantial, as shown in Table VI. From these results, we observe that recursive sub-payload detection is effective: the total correct fields are 176 without sub-payload detection (vs. 483 in SemPRE) for the nested

Fields Types Fn. Fields Types Fn. Modbus S7comm Ethernet/IP DNP3 DNS FTP TFTP HTTP

S EM PRE-norec-noop S EM PRE-noop Type F1

0.62 0.18 0.32 0.36 0.87 0.38 0.77 0.50

0.58 0.34 0.44

0.62 0.19 0.23 0.54 0.89 0.67 0.62 0.66

0.57 0.06 0.06 0.33 0.51 0.74 0.91 0.24

0.46 0.29

11

TABLE VII: Ablation Study Results - Field Detection. Protocols

S EM PRE-norec-noop S EM PRE-noop

a persistent threat in the cybersecurity landscape. We simulate a realistic analysis scenario in which only the Mirai binary and captured network traffic are available. We analyze 10 messages exchanged between the command-and-control (C&C) server and an infected device, reflecting an early-stage reverseengineering setting in which no protocol documentation is assumed. We evaluate both S EM PRE and BinPRE against a manually constructed ground truth derived from the source code. Across the ten messages, the ground truth contains 117 fields, 127 type instances, and 45 function labels. BinPRE assumes that a program consumes each message buffer in a single pass. The Mirai binary, however, reuses the same buffer and parses it a second time, breaking BinPRE’s offset arithmetic and leading to almost zero accuracy. In contrast, although S EM PRE and BinPRE rely on the same taint outputs, S EM PRE does not impose a single-pass assumption. Instead, it uses LLM-based reasoning over the collected evidence and can therefore accommodate repeated buffer accesses. To isolate this effect, we run an additional experiment in which both tools are explicitly informed that the Mirai binary traverses the message buffer twice. With this hint, BinPRE achieves an F1 score of 0.55 for field detection. By comparison, S EM PRE attains a stable 0.83 F1 for field detection with or without the hint. At the per-message level, S EM PRE recovers perfectly accurate boundaries for 9 out of 10 messages, whereas BinPRE does so for only 2. The remaining gap largely stems from BinPRE’s dependence on the Needleman–Wunsch (NW) algorithm for aligning instruction sequences, as it captures primarily instruction-level correspondences and often misses deeper semantic relations needed to correctly merge and split tainted regions.

S EM PRE

Pre. Rec.

F1

Pre. Rec.

F1 Pre. Rec.

F1

Modbus 1.00 1.00 S7comm 0.98 0.69 Ethernet/IP 0.96 0.23 DNP3 0.95 0.58 DNS 1.00 1.00 FTP 0.34 0.78 TFTP 1.00 1.00 HTTP 0.53 0.31

1.00 0.81 0.37 0.72 1.00 0.47 1.00 0.39

1.00 1.00 1.00 1.00 0.84 0.91 0.90 0.95 0.93 0.89 0.94 0.92 0.81 0.63 0.71 0.87 0.61 0.72 0.91 0.94 0.92 0.90 0.78 0.84 0.63 1.00 0.77 0.58 1.00 0.73 0.34 0.78 0.47 0.23 0.53 0.32 0.91 1.00 0.95 1.00 1.00 1.00 0.61 0.62 0.62 0.81 0.68 0.74

Average 0.84 0.45

0.58

0.77 0.75 0.76 0.81 0.72 0.76

TABLE VIII: Ablation Study Results - Sub-payload Detection. SemPRE-norec

Protocols

SemPRE

BinPRE

bnd F1

type F1

fn F1

bnd F1

type F1

fn F1

bnd F1

type F1

fn F1

Ethernet/IP BAC OPC

0.55 0.92 0.78

0.12 0.80 0.72

0.13 0.96 0.95

0.72 0.84 0.73

0.47 0.80 0.70

0.62 0.90 0.96

0.19 0.79 0.36

0.00 0.21 0.00

0.13 0.15 0.00

Avg.

0.71

0.50

0.56

0.76

0.62

0.74

0.29

0.06

0.12

protocol Ethernet/IP. To strengthen the component’s contribution, we build a small nested dataset D4 and evaluate S EM PRE-norec and S EM PRE on that. The results are shown in Table VIII. S EM PRE-ToT degrades F1 from 0.76/0.62/0.74 to 0.71/0.50/0.56 (Table IX, compared to S EM PRE, indicating that ToT alone cannot improve performance but plays a key role in S EM PRE. Overall, these results demonstrate that both recursive subpayload detection and iterative optimization significantly enhance S EM PRE ’s ability to extract fields and infer semantics.

TABLE X: Case Study - F1 Scores.

Answer to RQ4: S EM PRE ’s recursive sub-payload detection and iterative optimization are essential for high performance.

S EM PRE BinPRE

Field

Type

Function

0.83 0.55

0.69 0.27

0.74 0.19

F. RQ5: Case Study Answer to RQ5: The S EM PRE can effectively support real-world security analysis, particularly in scenarios where protocols are undocumented and malicious.

Finally, we evaluate S EM PRE’s efficacy using a case study on a variant of the Mirai botnet [41], a well-known malware family that targets Internet-of-Things (IoT) devices and poses

V. R ELATED W ORK

TABLE IX: Ablation Study Results - ToT Affect. SemPRE-ToT

Protocols

A. Protocol Reverse Engineering

SemPRE

bnd F1

type F1

fn F1

bnd F1

type F1

fn F1

modbus s7 eip dnp3 dns ftp tftp http

1.00 0.89 0.55 0.92 0.78 0.45 1.00 0.72

0.78 0.85 0.12 0.80 0.72 0.61 0.40 0.66

1.00 0.71 0.13 0.96 0.95 0.67 1.00 0.62

0.91 0.92 0.72 0.84 0.73 0.32 1.00 0.74

0.78 0.91 0.47 0.80 0.70 0.67 0.40 0.68

1.00 0.77 0.62 0.90 0.96 0.71 1.00 0.71

Avg.

0.71

0.50

0.56

0.76

0.62

0.74

Automated protocol reverse engineering (PRE) techniques broadly fall into two categories: network-traffic-based and binary-analysis-based approaches. Traffic-based systems infer message layouts by identifying recurring byte patterns across packet traces, whereas binary-analysis methods reconstruct formats and semantics by examining how a program processes its inputs. Early binary-analysis tools (e.g., Polyglot [13], AutoFormat [37], and Tupni [14]) use taint tracking and execution context analysis to extract field boundaries but provide limited semantic information. In parallel, traffic-based methods have evolved from largely heuristic systems such as NEMESYS [9]

12

to more structured approaches like NetPlier [11], which leverage sequence alignment and probabilistic inference to identify type-indicating fields and reconstruct protocol state machines. Recent work has improved both semantic depth and robustness. BinaryInferno [8] combines multiple heuristics in an entropy-guided ensemble to improve precision and completeness, while DynPRE [10] adopts an active-learning strategy that generates probe messages to explore protocol states and reveal richer semantics. BinPRE [2] represents the state of the art in binary-analysis-based PRE. It aligns instruction sequences, employs atomic field detectors for common datahandling idioms, and iteratively clusters and refines candidate fields. Evaluated on eight real-world protocols, BinPRE surpasses prior systems, including Polyglot, AutoFormat, Tupni, BinaryInferno, and DynPRE, in both precision and recall.

when the required knowledge is insufficiently represented in their pre-training data [47], [48]. Furthermore, LLMs often lack grounding in external knowledge and can struggle with consistency across long or complex reasoning chains [31]. Although we apply Tree-of-Thoughts and iterative refinement to improve the LLM’s effectiveness, the LLM’s limitations are hard to eliminate entirely. Byte-Level v.s Bit-Level Semantics. Our current implementation supports only six semantic function labels for fair comparison with BinPRE, far fewer than those found in realworld protocols. In addition, S EM PRE performs semantic annotation at byte granularity. This design follows directly from our reuse of BinPRE’s taint-analysis backend, which tracks data dependencies at the byte level. While byte-level tainting integrates cleanly with dynamic program analysis and remains efficient in practice, it limits S EM PRE’s ability to recover finer-grained semantics. This limitation is particularly salient for embedded and low-level protocols, where meaning is often encoded at the bit level rather than the byte level. For example, in the Controller Area Network (CAN) protocol, individual bits within a byte frequently represent distinct flags or sensor states (e.g., fault indicators and enable/disable toggles) [49]. Such semantics cannot be fully captured with bytelevel inference alone, which constrains S EM PRE’s precision in these settings. Extending S EM PRE to support bit-level taint tracking, bit-level semantic inference, and a richer taxonomy of semantic functions is an important direction for future work.

B. LLM Reasoning Techniques Early progress in LLM reasoning stemmed solely from prompt engineering. Chain-of-Thought [36] (CoT) prompting revealed that inserting a few worked examples elicits multistep reasoning, boosting accuracy on math and commonsense tasks. Self-Consistency [35] improves CoT by sampling diverse reasoning paths and selecting the majority answer, yielding double-digit gains across several benchmarks. ActivePrompt [42] further adapts the exemplar set on-the-fly, choosing those that best suit a new task. Despite these advances, all three methods rely on a single linear trace of text tokens and quickly degrade when the input interleaves structured bytes with noisy instrumentation—precisely the scenario in protocol reverse engineering (PRE). To avoid the myopia of linear CoT, Tree-of-Thoughts [34] (ToT) treats reasoning as an explicit tree search, allowing the model to branch, backtrack, and evaluate partial solutions before committing; GPT-4 accuracy on the “24 Game” rises from 4% to 74% under this scheme. Yet ToT still assumes that each “thought” is a clean natural-language fragment, leaving open how to segment—and reason over—raw byte streams mixed with taint-trace noise. S EM PRE tackles exactly this gap by anchoring tree exploration in execution evidence. LLMs can also grade and revise their own work. A recent study [43] shows that introducing a reflection loop—generate, critique, then refine—mainly lifts performance on multiplechoice QA and planning benchmarks. S EM PRE borrows this idea but grounds the critique in concrete taint maps and loop inventories, rather than in free-form textual judgment.

Robustness to Adversarial Settings. Obfuscation techniques that randomize field access order or copy data into temporary scratch buffers can blur taint signals and defeat ToT search. This problem involves defeating obfuscation, which is fundamentally orthogonal to the protocol reverse engineering task. We will leave this for future research. VII. C ONCLUSION Protocol reverse engineering (PRE) reconstructs message structures and field semantics, yet existing tools rely on fragile heuristics and struggle with nested payloads and semantic dependencies. We present S EM PRE, a fully automated PRE framework that couples fine-grained dynamic analysis with a recursive LLM reasoning loop. Using taint-flow and loop traces, it segments messages, detects nested payloads, and iteratively refines structure and semantics through a monotonic EM-style process. On eight mainstream protocols, S EM PRE attains an F1 score of 0.76 for field detection—over twice the prior best—and raises semantic-inference accuracy to 0.72. It also proves effective on Mirai botnet traffic, accurately recovering undocumented fields and semantics. These results show that LLM-based reasoning can replace brittle heuristics and set a new state of the art in PRE.

VI. D ISCUSSION LLM Limitations. Despite their impressive performance across a wide range of tasks, large language models (LLMs) are subject to several important limitations, particularly in terms of reliability and factual accuracy. One of the most critical issues is hallucination, where the model generates fluent but factually incorrect or fabricated outputs. Studies have shown that LLMs may confidently generate incorrect or hallucinatory answers [44], [45], produce inaccurate or fabricated sources [46], and exhibit reduced factual reliability

13

A PPENDIX

O PEN S CIENCE Our code is available https://anonymous.4open.science/r/SemPRE-F9F8.

E THICAL C ONSIDERATIONS Stakeholder Identification and Impacts. The research process and outcomes affect multiple stakeholders: Research Team. Benefits from academic advancement and technical validation; bears responsibility for guiding ethical use. Security Researchers/Analysts. Gains a high-precision tool for vulnerability discovery, malware analysis, and IDS signature generation, improving work efficiency. Enterprises/Organizations. Can leverage S EM PRE to identify protocol vulnerabilities, but faces potential risks of legitimate protocol reverse-engineering by third parties. General Users. Indirectly benefits from enhanced system security but may face privacy/property risks if the tool is misused. Open Source Community. Obtains open-source resources to advance PRE research, promoting field development. Security Community and Society Beneficence. S EM PRE addresses limitations of heuristic-based PRE tools, doubling field detection F1 score (0.76 vs. ¡0.40) and improving semantic inference accuracy (0.72 vs. 0.14), advancing network security defense capabilities. Respect for Persons. All experimental datasets are from opensource repositories or legally captured traffic, with sensitive information (IP addresses, device IDs) anonymized to protect user privacy. Justice. The S EM PRE prototype is open-sourced to ensure fair access to technical resources, with transparent experimental design for community verification. Respect for Law and Public Interest. The research and publication comply with network security regulations; we explicitly oppose misuse of the tool for illegal activities. Potential Harms Analysis. We acknowledge that the protocols may create negative impacts if used by illicit actors to reveal private protocols. For example, an attacker may reconstruct the syntactic and semantic information of a private protocol using S EM PRE and then send spurious messages to attack normal users. Ethical Rationale for Research and Publication Research Justification. Traditional PRE tools rely on brittle heuristics, failing to handle nested protocols and semantic dependencies. S EM PRE fills this technical gap with LLM-driven joint optimization, critical for improving security defense. Publication Justification. Open-sourcing and publishing enable academic exchange, allowing the community to refine the tool. Ethical guidelines and positive application scenario descriptions minimize misuse risks, ensuring alignment with public interest.

14

at

R EFERENCES

[21] X.-L. Meng and D. Van Dyk, “The em algorithm—an old folk-song sung to a fast new tune,” Journal of the Royal Statistical Society: Series B (Methodological), vol. 59, no. 3, pp. 511–567, 01 2002. [Online]. Available: https://doi.org/10.1111/1467-9868.00082 [22] “Rfc 1350: The tftp protocol (revision 2),” https://www.rfc-editor.org/ rfc/rfc1350, 2025. [23] “What properties, advantages and special features does the s7 protocol offer - siemens industry online support,” https://support.industry.siemens.com/cs/document/26483647/ what-properties-advantages-and-special-features-does-the-s7-protocol-offer-? dti=0&lc=en-WW, 2025. [24] A. Madaan, N. Tandon, P. Gupta, S. Hallinan, L. Gao, S. Wiegreffe, U. Alon, N. Dziri, S. Prabhumoye, Y. Yang et al., “Self-refine: Iterative refinement with self-feedback,” Advances in Neural Information Processing Systems, vol. 36, pp. 46 534–46 594, 2023. [25] C. Hu, Y. Hu, H. Cao, T. Xiao, and J. Zhu, “Teaching language models to self-improve by learning from language feedback,” arXiv preprint arXiv:2406.07168, 2024. [26] J. Lu, W. Zhong, W. Huang, Y. Wang, F. Mi, B. Wang, W. Wang, L. Shang, and Q. Liu, “SELF: Language-driven selfevolution for large language model,” 2024. [Online]. Available: https://openreview.net/forum?id=XD0PHQ5ry4 [27] X. Liang, S. Song, Z. Zheng, H. Wang, Q. Yu, X. Li, R.-H. Li, Y. Wang, Z. Wang, F. Xiong et al., “Internal consistency and self-feedback in large language models: A survey,” arXiv preprint arXiv:2407.14507, 2024. [28] C.-H. Chiang and H.-y. Lee, “Can large language models be an alternative to human evaluations?” arXiv preprint arXiv:2305.01937, 2023. [29] Z. Sun, Y. Shen, Q. Zhou, H. Zhang, Z. Chen, D. Cox, Y. Yang, and C. Gan, “Principle-driven self-alignment of language models from scratch with minimal human supervision,” Advances in Neural Information Processing Systems, vol. 36, pp. 2511–2565, 2023. [30] J. Fu, S.-K. Ng, Z. Jiang, and P. Liu, “Gptscore: Evaluate as you desire,” arXiv preprint arXiv:2302.04166, 2023. [31] J. Achiam, S. Adler, S. Agarwal, L. Ahmad, I. Akkaya, F. L. Aleman, D. Almeida, J. Altenschmidt, S. Altman, S. Anadkat et al., “Gpt-4 technical report,” arXiv preprint arXiv:2303.08774, 2023. [32] E. J. Schwartz, T. Avgerinos, and D. Brumley, “All you ever wanted to know about dynamic taint analysis and forward symbolic execution (but might have been afraid to ask),” in 2010 IEEE symposium on Security and privacy. IEEE, 2010, pp. 317–331. [33] T. Moseley, D. Grunwald, D. A. Connors, R. Ramanujam, V. Tovinkere, and R. Peri, “Loopprof: Dynamic techniques for loop detection and profiling,” in Proceedings of the 2006 Workshop on Binary Instrumentation and Applications (WBIA), 2006. [34] S. Yao, D. Yu, J. Zhao, I. Shafran, T. Griffiths, Y. Cao, and K. Narasimhan, “Tree of thoughts: Deliberate problem solving with large language models,” Advances in neural information processing systems, vol. 36, pp. 11 809–11 822, 2023. [35] X. Wang, J. Wei, D. Schuurmans, Q. Le, E. Chi, S. Narang, A. Chowdhery, and D. Zhou, “Self-consistency improves chain of thought reasoning in language models,” arXiv preprint arXiv:2203.11171, 2022. [36] J. Wei, X. Wang, D. Schuurmans, M. Bosma, F. Xia, E. Chi, Q. V. Le, D. Zhou et al., “Chain-of-thought prompting elicits reasoning in large language models,” Advances in neural information processing systems, vol. 35, pp. 24 824–24 837, 2022. [37] Z. Lin, X. Jiang, D. Xu, and X. Zhang, “Automatic protocol format reverse engineering through context-aware monitored execution,” 01 2008. [38] “KTP,” https://github.com/laksh0820/Custom-Transport-Protocol-Socket, 2025. [39] “CCN,” https://github.com/BenjaminWang236/ Custom-Protocol-for-Client-Server-Communication, 2025. [40] “Xfer,” https://github.com/ZAK3IR/xfer, 2022. [41] “Mirai,” https://github.com/jgamblin/Mirai-Source-Code, 2025. [42] S. Diao, P. Wang, Y. Lin, R. Pan, X. Liu, and T. Zhang, “Active prompting with chain-of-thought for large language models,” arXiv preprint arXiv:2302.12246, 2023. [43] M. Renze and E. Guven, “Self-reflection in llm agents: Effects on problem-solving performance, 2024,” URL https://arxiv. org/abs/2405.06682, 2024. [44] A. Slobodkin, O. Goldman, A. Caciularu, I. Dagan, and S. Ravfogel, “The curious case of hallucinatory (un) answerability: Finding truths in the hidden states of over-confident large language models,” in

[1] J. Narayan, S. K. Shukla, and T. C. Clancy, “A survey of automatic protocol reverse engineering tools,” ACM Computing Surveys (CSUR), vol. 48, no. 3, pp. 1–26, 2015. [2] J. Jiang, X. Zhang, C. Wan, H. Chen, H. Sun, and T. Su, “Binpre: Enhancing field inference in binary analysis based protocol reverse engineering,” in Proceedings of the 2024 on ACM SIGSAC Conference on Computer and Communications Security, 2024, pp. 3689–3703. [3] “Modbus protocol,” https://www.modbustools.com/modbus.html, 2025. [4] J. Wang, Q. Liu, C. Liu, and J. Yin, “Gan-based adversarial patch for malware c2 traffic to bypass dl detector,” in Information and Communications Security: 23rd International Conference, ICICS 2021, Chongqing, China, November 19-21, 2021, Proceedings, Part I. Berlin, Heidelberg: Springer-Verlag, 2021, p. 78–96. [Online]. Available: https://doi.org/10.1007/978-3-030-86890-1 5 [5] C. Fu, Q. Li, M. Shen, and K. Xu, “Detecting tunneled flooding traffic via deep semantic analysis of packet length patterns,” in Proceedings of the 2024 on ACM SIGSAC Conference on Computer and Communications Security, ser. CCS ’24. New York, NY, USA: Association for Computing Machinery, 2024, p. 3659–3673. [Online]. Available: https://doi.org/10.1145/3658644.3670353 [6] D. Brumley, J. Caballero, Z. Liang, J. Newsome, and D. Song, “Towards automatic discovery of deviations in binary implementations with applications to error detection and fingerprint generation.” in USENIX Security Symposium, vol. 15, 2007. [7] H. Dreger, A. Feldmann, M. Mai, V. Paxson, and R. Sommer, “Dynamic application-layer protocol analysis for network intrusion detection,” in 15th USENIX security symposium. USENIX Association, 2006, pp. 257–272. [8] J. Chandler, A. Wick, and K. Fisher, “Binaryinferno: A semantic-driven approach to field inference for binary message formats.” in NDSS, 2023. [9] S. Kleber, H. Kopp, and F. Kargl, “{NEMESYS}: Network message syntax reverse engineering by analysis of the intrinsic structure of individual messages,” in 12th USENIX Workshop on Offensive Technologies (WOOT 18), 2018. [10] Z. Luo, K. Liang, Y. Zhao, F. Wu, J. Yu, H. Shi, and Y. Jiang, “Dynpre: Protocol reverse engineering via dynamic inference,” in Proc. NDSS, 2024, pp. 1–18. [11] Y. Ye, Z. Zhang, F. Wang, X. Zhang, and D. Xu, “Netplier: Probabilistic network protocol reverse engineering from message traces.” in NDSS, 2021. [12] J. Caballero, P. Poosankam, C. Kreibich, and D. Song, “Dispatcher: Enabling active botnet infiltration using automatic protocol reverseengineering,” in Proceedings of the 16th ACM conference on Computer and communications security, 2009, pp. 621–634. [13] J. Caballero, H. Yin, Z. Liang, and D. Song, “Polyglot: Automatic extraction of protocol message format using dynamic binary analysis,” in Proceedings of the 14th ACM conference on Computer and communications security, 2007, pp. 317–329. [14] W. Cui, M. Peinado, K. Chen, H. J. Wang, and L. Irun-Briz, “Tupni: Automatic reverse engineering of input formats,” in Proceedings of the 15th ACM conference on Computer and communications security, 2008, pp. 391–402. [15] R. Droms, “Dynamic host configuration protocol,” RFC 2131, March 1997. [Online]. Available: https://www.rfc-editor.org/info/rfc2131 [16] P. Brooks, “Ethernet/ip-industrial protocol,” in ETFA 2001. 8th International Conference on Emerging Technologies and Factory Automation. Proceedings (Cat. No. 01TH8597), vol. 2. IEEE, 2001, pp. 505–514. [17] S. Viktor, D. Vangompel, and R. Voss, “The common industrial protocol (cip) and the family of cip networks,” Milwaukee, Wisconsin, USA, ODVA, 2016. [18] W. K. Wong, D. Wu, H. Wang, Z. Li, Z. Liu, S. Wang, Q. Tang, S. Nie, and S. Wu, “Decllm: Llm-augmented recompilable decompilation for enabling programmatic use of decompiled code,” Proceedings of the ACM on Software Engineering, vol. 2, no. ISSTA, pp. 1841–1864, 2025. [19] P. Hu, R. Liang, and K. Chen, “Degpt: Optimizing decompiler output with llm,” in Proceedings 2024 Network and Distributed System Security Symposium, vol. 267622140, 2024. [20] X. She, Y. Zhao, and H. Wang, “Wadec: Decompiling webassembly using large language model,” in Proceedings of the 39th IEEE/ACM International Conference on Automated Software Engineering, 2024, pp. 481–492.

15

Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing, 2023, pp. 3607–3625. [45] M. Xiong, Z. Hu, X. Lu, Y. Li, J. Fu, J. He, and B. Hooi, “Can llms express their uncertainty? an empirical evaluation of confidence elicitation in llms,” in International Conference on Learning Representations, vol. 2024, 2024, pp. 23 650–23 678. [46] W. H. Walters and E. I. Wilder, “Fabrication and errors in the bibliographic citations generated by chatgpt,” Scientific reports, vol. 13, no. 1, p. 14045, 2023. [47] N. Kandpal, H. Deng, A. Roberts, E. Wallace, and C. Raffel, “Large language models struggle to learn long-tail knowledge,” in International conference on machine learning. PMLR, 2023, pp. 15 696–15 707. [48] S. Lin, J. Hilton, and O. Evans, “Truthfulqa: Measuring how models mimic human falsehoods,” in Proceedings of the 60th annual meeting of the association for computational linguistics (volume 1: long papers), 2022, pp. 3214–3252. [49] Robert Bosch GmbH, CAN Specification Version 2.0, 1991, http://esd. cs.ucr.edu/webres/can20.pdf. [50] “freemodbus,” https://github.com/cwalter-at/freemodbus, 2025. [51] “Open real-world traces for Modbus and DNS,” https://www.netresec. com/?page=PcapFiles, 2025. [52] “snap7,” https://sourceforge.net/projects/snap7, 2025. [53] “Open real-world traces for S7Comm,” https://wiki.wireshark.org/ SampleCaptures#s7comm-s7-communication, 2025. [54] “OpENer,” https://github.com/EIPStackGroup/OpENer, 2025. [55] “Open real-world traces for Ethernet/IP,” https://github.com/ITI/ ICS-Security-Tools/blob/master/pcaps/EthernetIP/EthernetIP-CIP.pcap, 2025. [56] “opendnp3,” https://github.com/dnp3/opendnp3, 2025. [57] “LightFTP,” https://github.com/hfiref0x/LightFTP, 2025. [58] “Open real-world traces for FTP,” ftp://ita.ee.lbl.gov/new/lbnl.anon-ftp. 03-01-10.tcpdump.gz, 2025. [59] “tftp-hpa,” https://git.kernel.org/pub/scm/network/tftp/tftp-hpa, 2025. [60] “Open real-world traces for TFTP,” https://www.cloudshark.org/ captures/07ebe14c792b, 2025. [61] “dnsmasq,” https://github.com/infinet/dnsmasq, 2025. [62] “miniweb,” https://github.com/avih/miniweb, 2025.

A PPENDIX

16

11/11/25, 5:47 PM A. Prompt Design

{The prompt of field detection of a message}

Prompting. We use structured prompt templates to guide the LLM through field detection, sub-payload identification, and semantic inference. Beyond a fixed introduction, each prompt includes (i) taint and loop analysis outputs, (ii) the raw message, (iii) high-confidence semantic cues, and (iv) explicit reasoning instructions. This structure constrains the model to task-specific context, reducing hallucinations and improving consistency across runs. At initialization, we instruct the LLM to act as an expert in protocol reverse engineering. 1) The Prompt Template: Field Detection : The prompt template for the task of field detection comprises by five parts, shown in Figure 10, which are titled in italic font. We set Tree-of-Thoughts (ToT) parameters in the ‘step-by-step instructions’ section 11/14/25, 9:03 AM to guide LLM reasoning.

<Final_Fields> ... </Final_Fields> If any sub-payload field in the above message is a protocol in the previously formatted output, keep parsing the sub-payload field by using the same steps in the above analysis. If no sub-payload field exists in the previous output, then you should give out a message that is wrapped by “<sub_payload></sub_payload>”

11/14/25, 4:40 PM

<Final_Fields> Known ... information </Final_Fields> <Sub_payload>No sub-payload </Sub_payload>

Fig. 11: LLM Interaction: Field Detection Process

download

Fixed the introduction

Fixed the introduction

We need to identify the types and functions of all fields in a given message. There are 5 types and 6 functions in total. Types are 'static', 'integer', 'group', 'bytes', and 'string'. Functions are 'command', 'length', 'delim', 'checksum', 'filename', and 'aligned' We got the fields of the message from its tainted test information. Now, please predict the type and function of each field whose type and function are unknown.

We use the taint testing information of a given message and the types and functions of some fields of a given message to predict the fields of the given message. The format rules of the taint testing information are as follows. For the following rules, we define <txt> as a string, <asm_code> as an x86 assemble code with its address, <offset_x> as offset of the tainted memory address, <src_x> as the memory address of the <offset_x>, and <value_x> as the value of the corresponding <offset_x>. Rule 1: when <txt> is 'Instruction' and <asm_code> including an immediate number is for logic and arithmetic operators, the pattern of the line is '<txt> <asm_code> <thread_id> <offset_0> <value_0>'; ... Rule 9: ,,,

We give attributes of types as follows. 'static' denotes a fixed value across messages. 'integer' represents a number of variable length. 'group' comprises a list of available values. 'bytes' denotes a sequence of binary bytes of arbitrary length. 'string' denotes a sequence of text characters. We give attributes of functions as follows. 'command' denotes message type. 'length' indicates the length of a message or data. 'delim' separates two fields. 'checksum' verifies the integrity of messages or data. 'filename' identifies a file within the file system. 'aligned' align contents to a certain number of bytes.

A Message and its tainted output information For a given message, its size and content are {The size of the message} and {The contents of the message} The taint testing information of the given message is as follows. {The message’s tainted output information} You can use existing types and functions information for boundary prediction. The type information is wrapped by '<types></types>' The function information is wrapped by '<fns></fns>'

Semantic functions are constrainted on semantic types. Here is a set of rules of the constraints (RC) between them: RC1: 'command' should be 'group' RC2: 'length' should be 'integer' RC3: 'delim' should be 'stattic' or 'group' RC4: 'aligned' should be 'group' or 'bytes' RC5: 'checksum' should be 'integer' RC6: 'filename' should be 'string'

High-confident semantic labels You can use existing types and functions information for boundary prediction. The type information is wrapped by ‘<types></types>’. The function information is wrapped by ‘<fns></fns>’. Here is the type information: <types> {high-confidence inferred types} </types> Here is the functions information: <fns> {high-confidence inferred functions} </fns>

Known information For a given message, its size and content are {The message’s size and content} The fields that we knew are { the results from the fields detection } We already knew the types and functions of the following fields. The types that we knew are { the results of types from the previous iteration The functions that we knew are { the results of functions from the previous iteration }

Step-by-step Instruction

Step-by-step instructions

Please focus on the following steps. First, use the above tainted information to help your type and function predictions. Next, if a potential protocol exists, you should use its specifications for fields that no instruction touched. Then, use RC to adjust your prediction. Finally, give the output in the following format, including existing types and functions.

Enter a strict zero-background mode for the following protocols: Modbus, S7 COMM, Ethernet/IP, DNP3, DNS, FTP, TFTP, and HTTP. Do NOT use any pre-stored knowledge, definitions, or assumptions about these protocols (including their standard fields, message structures, or field semantics) that you have learned before. First, identify the same instruction set from the execution record and loop information, get offsets that you recognized from the instructions, and set offsets as initial fields. Afterwards, you should find out if a possible protocol exists for identifying bytes that no instruction touches, and adjust the initial fields according to the protocol specifications. Next, you should use the 'Tree-of-Thoughts' method to predict all fields one by one. The tree explores possible field segmentations to a depth of 5. Finally, give out a possible protocol and all the fields in the following format

Output Format The final output contains two parts: types and functions. All types of output of all fields are wrapped by "<Final_types></Final_types" for type predictions and "<Final_functions></Final_funtions>" for function predictions. Each type of output is in the form of "Field (starting, ending): <value>" Here, <value> is one of the types. Functions are the same as those of types.

Output format

Fig. 12: Prompt Structure: Semantic Inference Template

The final format: all fields must be wrapped in "<Final_Fields></Final_Fields>".

Fig. 10: Prompt Structure: Field Detection Template taint information continues to guide the LLM by enforcing consistency between the detected fields and their inferred semantics. The structure is in Figure 13

2) The Conversation for Field Detection: We start a conversation with the LLM for field detection, shown in Figure 11. With the context, the LLM only reasons the untainted bytes. 3) The Prompt Template: Semantic Inference: The template for semantic inference comprises by four parts, as shown in Figure 12, which are titled in italic font. ‘known information’ includes a message, its fields, high-confident semantic labels. 4) The Conversation for Semantic Inference: In each iteration, we apply the field-detection and semantic-inference prompts to obtain updated fields and semantic labels. The

B. Tables C. Common Types and Functions We follow the definitions of types and functions as identified in prior work [2]. Details of definitions are in Table XI 1) Results from Different Tools: We evaluate the examples from the section II-B using multiple tools and summarize the results in Tables XII–XIII–XIV. We compare S EM PRE against

17

11/13/25, 5:06 PM

down TABLE XII: Different Results on the Filename Field of TFTP from Different Tools

{The conversation log of field detection of the message}

Tools

Field

Function

BinPRE Polyglot Tupni S EM PRE

[2], [3, 17] [2], [3], [4], ..., [16], [17] [2], [3, 17] [2, 17]

None, Aligned Filename

GroundTruth

[2, 17]

Filename

{The prompt of the semantic infernece of the message <Final_Types> ... </Final_Types> <Final_Functions> ... </Final_Functions> <Selected_Types> ... </Selected_Types> <Selected_Functions> ... </Selected_Functions> <Stop_Iter> ... </Stop_Iter>

TABLE XIII: Different Results on Two Length Fields of S7 from Different Tools

Group Bytes String Command Length Delim Checksum Filename Aligned

Function

BinPRE Polyglot Tupni S EM PRE

△ △ △ [2, 3], [4]

None, None None, None None, None Length, Length

GroundTruth

[2, 3], [4]

Length, Length

TABLE XIV: Different Results on Nested Protocol of EIP from Different Tools

TABLE XI: Semantic types and functions

Integer

Field

△: incorrect field detection; None: the lack of prediction

Fig. 13: LLM Interaction: Semantic Inference Process

Static

Tools

Semantic Types Fixed values across messages, usually protocol-specific flags Numeric metadata (e.g., sizes), in either bigor little-endian Enumerated static values for actions, message types, etc. Protocol data in raw binary format Text character sequences (e.g., file names) Semantic Functions Denotes message types Indicates the length of messages or data Separates two fields Verifies message or data integrity Identifies a file within the file system Aligns contents to a specified byte boundary

Tools

Field

Nested Protocol

BinPRE Polyglot Tupni S EM PRE

[30, 81] △ △ [46, 81]

D.

GroundTruth

[46, 81]

CIP

△: incorrect field detection: -: not support; D.: detect a nested sub-payload; TABLE XV: Protocol Datasets for Evaluation. Dataset Protocol Format

D1

BinPRE, Polyglot, and Tupni (BPT) to highlight both the strengths of S EM PRE and the limitations of BPT. As shown in Table XII, the results illustrate the shortcomings of BPT’s inflexible, heuristic-based rules. Next, we observe the effects of the ignorance of semantic relationships in BPT. However, S EM PRE can correctly rebuild them in Table XIII. Finally, we spot the power of S EM PRE about detecting subpayload but BPT can’t in Table XIV 2) Details for Protocol in Datasets: Table XV shows the details of the protocols in the datasets. Format colomn indicates the categories of the content of procotol messages: binary, text, or mixed. Project colomn shows the resources of the protocol binary file.

Modbus binary S7comm binary Ethernet/IP binary DNP3.0 binary FTP text TFTP mixed DNS mixed HTTP text

Project

Message Source

freemodbus [50] snap7 [52] OpENer [54] opendnp3 [56] LightFTP [57] tftpd-hpa [59] dnsmasq [61] miniweb [62]

Open-source [51] Open-source [53] Open-source [55] tcpdump Open-source [58] Open-source [60] Open-source [51] tcpdump

D2

KTP CCN Xfer

binary KTP-Source-Code [38] binary CCN-Source-Code [39] mixed Xfer-Source-Code [40]

tcpdump tcpdump tcpdump

D3

Mirai

mixed Mirai-Source-Code [41]

tcpdump

3) Semantic Capabilities of the Baselines: We summarize the semantic modeling capabilities of representative prior protocol reverse engineering (PRE) systems. We compare these approaches along three dimensions: (1) the analysis paradigm they adopt, (2) the kinds of semantic types for protocol fields they infer, and (3) the kinds of semantic functions they are

18

able to identify. Details are in Table XVI. TABLE XVI: Capability of baselines and S EM PRE Protocols

Approaches

Types

Functions

PolyGlot Tupni AutoFormat BinPRE S EM PRE

binary-analysis-based binary-analysis-based binary-analysis-based binary-analysis-based binary-analysis-based

COM MT ypes COM MT ypes

BinaryInferno DynPRE

network-traffic-based network-traffic-based

-

CMD; LEN; DELIM LEN; CHS COM MF ns COM MF ns LEN CMD, LEN

-: not support; CMD: command; LEN: length; DELIM: delimitor; CHS: checksum; COM M T ypes: common types; COM M F ns: common functions.

4) Tables Related to RQ3: Table XVII shows the results for S EM PRE with different backbones. Results show that the performance of S EM PRE does not depend on a specific LLM model. TABLE XVII: Performance with Different Backbones. S EM PRE-o3

Protocols

S EM PRE-ds

S EM PRE-hy

Field Type Fn. Fields Type Fn. Fields Type Fn. Modbus S7comm Ethernet/IP DNP3 DNS FTP TFTP HTTP

0.99 0.81 0.80 0.80 0.72 0.66 1.00 0.60

0.81 0.80 0.69 0.82 0.71 0.72 0.35 0.62

1.00 0.64 1.00 0.90 0.93 0.77 1.00 0.70

0.98 0.64 0.42 0.65 0.75 0.63 0.71 0.60

Average 0.76 0.72 0.74 0.58

0.74 0.39 0.64 0.47 0.64 0.53 0.53 0.62

0.98 0.26 0.97 0.42 0.73 0.66 0.95 0.70

0.93 0.76 0.46 0.61 0.71 0.64 0.68 0.11

0.59 0.62 0.49

0.61 0.49 0.65 0.37 0.46 0.32 0.56 0.01

0.81 0.31 1.00 0.25 0.58 0.59 0.81 0.03

0.39 0.46

S EM PRE-o3: the backbone of S EM PRE is GPT-o3; S EM PRE-ds: the backbone of S EM PRE is DeepSeek-v3.1-terminus S EM PRE-hy: the backbone of S EM PRE is Hy3

Table XVIII shows the results on undocumented protocols under different approaches. TABLE XVIII: Effectiveness on Undocumented Protocols. Protocols

S EM PRE Field Type

BinPRE Fn.

Fields Type

Vanilla GPT-o3 Fn.

Fields Type

Fn.

KTP 0.50 CCN 1.00 Xfer 0.73

0.22 0.44 0.72 0.92 0.49 0.93

0.44 0.53 0.22

0.00 0.00 0.50 0.00 0.18 0.29

0.57 0.48 0.47

0.24 0.13 0.38 0.67 0.38 0.40

Avg. 0.71

0.43 0.77

0.41

0.19 0.11

0.52

0.31 0.43

5) Tables Related to RQ2: Table XIX show the details of metrics from S EM PRE and baselines. DynPRE receives and responds to a subset of messages for S7comm and DNS, so the results depend on the messages it responds to.

19

TABLE XIX: Function Inference Results. SemPRE

Protocols

BinPRE

Polyglot

Tupni

Binaryinferno

DynPRE

Pre.

Rec.

F1

Pre.

Rec.

F1

Pre.

Rec.

F1

Pre.

Rec.

F1

Pre.

Rec.

F1

Pre.

Rec.

F1

Modbus S7comm Ethernet/IP DNP3 DNS FTP TFTP HTTP

1.00 0.78 1.00 0.99 1.00 1.00 1.00 0.99

1.00 0.55 0.50 0.83 0.86 0.63 1.00 0.54

1.00 0.64 0.67 0.90 0.93 0.77 1.00 0.70

1.00 0.00 1.00 1.00 0.80 0.00 1.00 0.00

1.00 0.00 0.10 0.75 0.71 0.00 0.47 0.00

1.00 0.00 0.17 0.86 0.75 0.00 0.64 0.00

0.64 0.00 0.00 0.25 0.00 0.00 0.00 0.003

1.00 0.00 0.00 0.25 0.00 0.00 0.00 0.24

0.78 0.00 0.00 0.25 0.00 0.00 0.00 0.004

1.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00

0.50 0.00 0.00 0.25 0.00 0.00 0.00 0.00

0.67 0.00 0.00 0.40 0.00 0.00 0.00 0.00

0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00

0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00

0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00

0.00 0.001 N/A N/A 0.002 N/A N/A N/A

0.00 0.001 N/A N/A 0.002 N/A N/A N/A

0.00 0.001 N/A N/A 0.002 N/A N/A N/A

Average

0.96

0.61

0.74

0.82

0.22

0.35

0.01

0.09

0.01

0.005

0.04

0.006

0.00

0.00

0.00

0.00

0.00

0.00

Average - The performance on all protocols; Bold numbers indicate the best results 1. counting based on the first 31 messages; 2 - counting based on the first 16 messages;

20

3 - 0.0015;

4 - 0.0030;

5 - 0.0026;

6 - 0.0050

Related documents

Record · ID 1442308 · SHA-256 788161c23ee5da57
Retrieved via Conceptio: every document is proof-bundled with source, license, and retrieval metadata.
Bring this data into your agent: Connect via MCP or API · 20 free credits to start · no card required
Read the Docs → · View CLI source on GitHub · Conceptio Open Knowledge Archive