Network flow generation and restoration method based on protocol constraint

By jointly modeling the continuous-time characteristics and discrete protocol fields of network traffic in a unified feature space and introducing protocol state constraints, the problem of difficulty in balancing protocol consistency and statistical characteristics in existing technologies is solved, achieving protocol consistency and integrity of generated or repaired results, and making it suitable for data completion in network traffic analysis and modeling.

CN121814685APending Publication Date: 2026-04-07NANJING TECH UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610048983.9
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-01-14
Publication Date
2026-04-07

AI Technical Summary

Technical Problem

Existing network traffic generation and repair methods struggle to collaboratively model continuous features and discrete protocol fields in a unified feature space, and the generated results often violate communication protocol specifications, resulting in insufficient usability of the generated results in real network environments.

Method used

By mapping the continuous-time characteristics of network traffic to the same feature space and introducing protocol state constraints during the generation and repair process, a hierarchical diffusion-type network traffic generation model is constructed to ensure that the generated trajectory conforms to the legal state transition relationship of the protocol state machine.

Benefits of technology

It achieves reliability in terms of protocol consistency and structural integrity of the generated or repaired results while maintaining the characteristics of network traffic statistics. It can repair missing or masked traffic segments and meet the data completion requirements of network traffic analysis and modeling.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121814685A_ABST
    Figure CN121814685A_ABST
Patent Text Reader

Abstract

The invention discloses a network flow generating and repairing method based on protocol constraint. The method comprises the following steps: analyzing an original traffic capture file, extracting basic features through stream-level recombination and session segmentation, and mapping a continuous time sequence and a discrete protocol field to a uniform feature space; and on the basis, constructing a diffusion type network flow generation model to capture a statistical attribute and time sequence dependency relationship of the network flow. In the generating or repairing process, a protocol state machine is constructed, protocol constraint is introduced in the reverse denoising stage, the sampling process is constrained through a legality guiding mechanism, and protocol logic violation in the generating process is avoided. And finally, through feature inverse mapping and virtual protocol stack state maintenance, reconstructing to obtain network flow data which meets a communication protocol specification and can be correctly analyzed by a real protocol stack. According to the method, the generation and repair of the network traffic can be realized under a unified framework, and the correctness of a result in protocol semantics is ensured.
Need to check novelty before this filing date? Find Prior Art

Description

Technical fields:

[0001] This invention relates to network traffic modeling and processing technology, specifically to a method for generating and repairing network traffic based on protocol constraints, belonging to the field of network security and data processing technology. Background technology:

[0002] With the widespread deployment of technologies such as cloud computing, the Internet of Things (IoT), and the Industrial Internet, the types of services carried in network environments are becoming increasingly diverse, and encrypted or semi-encrypted communications such as HTTPS, Virtual Private Networks (VPNs), and industrial control private network tunnels are emerging in large numbers. In such network environments, security devices and traffic analysis models rely heavily on high-quality network traffic data during the training and validation phases. However, real network traffic typically contains user privacy information, sensitive business data, and content related to the operation of critical infrastructure, making it difficult to share directly between different organizations or application scenarios. Simultaneously, attack traffic accounts for a relatively low proportion in real networks, and obtaining new attack samples is challenging, resulting in limited training data scale and an uneven distribution of categories, thus restricting the improvement of the effectiveness of related detection and analysis models.

[0003] To address the aforementioned issues, existing technologies primarily employ two types of methods to generate or supplement network traffic data: one type simulates traffic based on rules or scripts, generating virtual traffic data through preset protocol templates and behavioral scripts. While relatively simple to implement, this method generates traffic that differs significantly from real-world networks in terms of statistical characteristics and temporal structure, making it difficult to cover complex business scenarios. The other type utilizes data-driven models such as generative adversarial networks, variational autoencoders, and temporal neural networks to represent network traffic as a time-series sequence or matrix for modeling and generation. This method can fit existing data distributions to some extent, but it often ignores the explicit semantics and strict logical constraints of protocol header fields, easily leading to results that do not conform to communication protocol specifications, thus affecting its usability in real-world network environments.

[0004] Furthermore, network traffic contains continuous features such as inter-packet time intervals and payload lengths, as well as discrete features such as protocol type, port number, flags, and session direction. Existing models typically require processing these different types of features separately or concatenating them through simple encoding, making it difficult to achieve collaborative modeling of continuous features and discrete protocol fields in a unified feature space. Simultaneously, network traffic exhibits both local temporal characteristics at the packet level and long-range dependencies across multiple data packets and round-trip processes, making it difficult for single-scale modeling methods to simultaneously consider both local structure and overall evolution.

[0005] Therefore, a new network traffic generation and repair technology is needed that can jointly model continuous features and discrete protocol fields in a unified feature space, and introduce protocol state constraints in the traffic generation and repair process, so that the generation trajectory is restricted to the legal state transition relationship described by the protocol state machine, thereby improving the reliability of generated or repaired traffic in terms of protocol consistency and structural integrity. Summary of the Invention:

[0006] To address the problems in existing network traffic generation and repair methods, such as the difficulty in simultaneously considering statistical characteristics and protocol consistency, the difficulty in coordinating continuous features and discrete protocol fields in a unified space, and the tendency for generated results to violate protocol logic, the present invention aims to propose a network traffic generation and repair method based on protocol constraints.

[0007] This invention achieves joint modeling of multiple feature types by mapping continuous-time features and discrete protocol fields in network traffic to the same feature space. Furthermore, it introduces protocol state constraints during traffic generation and repair, ensuring that the generation trajectory is limited by the legal state transition relationships described by a predefined protocol state machine. This maintains the statistical characteristics of network traffic while ensuring consistency in protocol semantics and structure of the generated or repaired results. In addition, this invention supports the repair of missing or masked traffic segments to meet the data completion requirements in network traffic analysis and modeling.

[0008] The present invention achieves the above-mentioned technical objectives through the following technical means.

[0009] A method for generating and repairing network traffic based on protocol constraints includes the following steps:

[0010] Step 1: Parse the original network traffic capture file, sort the data packets by timestamp, perform flow-level aggregation, and segment the data packet sequence into sessions based on preset session identifier information and session timeout thresholds to obtain a set consisting of multiple data streams; within each data stream, calculate the inter-packet time interval between adjacent data packets, and extract the payload length and protocol fields to form an intra-flow packet-level feature sequence.

[0011] Step 2: Map the packet-level feature sequence to a unified feature space, wherein: the continuous features, including at least the inter-packet time interval and the payload length, are normalized; the discrete protocol fields, including at least the protocol type, port number, and protocol flags, are symbolically represented and converted into real-valued feature vectors through mapping; the continuous features are concatenated with the real-valued discrete features to obtain a unified packet-level feature representation for diffusion modeling.

[0012] Step 3: Construct a hierarchical diffusion network traffic generation model in the unified feature space. The generation model includes: a packet-level sub-network for modeling packet-level temporal relationships within a single data stream, and a flow-level sub-network for modeling global statistical features across data streams. During the training phase, the model is jointly trained by forward noise addition and backward noise prediction, so that the model learns the generation distribution of network traffic in the unified feature space.

[0013] Step 4: During the backdiffusion sampling process, protocol state constraints are introduced to guide the generated trajectory step by step. Specifically, this includes: constructing a protocol state machine that includes the transport layer state, application layer observation state, and default absorption state, and defining a set of discrete protocol fields corresponding to the generation action; at each backdiffusion time step, generating corresponding legality constraint information based on the current protocol state to limit the legal value range of each discrete protocol field in the current state; and guiding the backdiffusion process based on the legality constraint information, causing the generated trajectory to evolve in a direction that satisfies the protocol state machine constraints, thereby generating a protocol-compliant feature sequence.

[0014] Step 5: Perform inverse mapping on the feature sequences generated or repaired by protocol constraints, restore the continuous and discrete features in the unified feature space to standard network packet fields, and output network traffic data files that meet the protocol specifications by combining the protocol state maintenance and verification mechanism.

[0015] Furthermore, the specific process of step 1 is as follows:

[0016] Step 1.1: Parse the raw network traffic capture file, extracting each data packet into a structured record with a timestamp and protocol field. For the i-th data packet, denoted as...

[0017] p i =(t i src i dst i , spt i dpt i ,proto i len i )

[0018] Among them, t i For the arrival timestamp of the data packet, src i dst i These are the source address and destination address, respectively. i dpt i These are the source and destination ports, respectively, proto i For transport layer protocol type, len iThis represents the payload length of the data packets. All data packets are sorted in ascending order of their timestamps to obtain an ordered sequence of data packets:

[0019] P sorted ={p1, p2, ..., p N}

[0020] Step 1.2, to achieve unified modeling of bidirectional sessions, a "normalized quintuple" is defined as the unique identifier key K(p) of the stream. i For any data packet p i The direction-independent key value is determined by comparing the sizes of the sockets (IP and port combinations) at both ends of the communication:

[0021]

[0022] And additionally record the direction markers.

[0023]

[0024] Will have the same K(p) i Data packets are grouped into the same candidate data stream set.

[0025] Step 1.3, introduce a session timeout threshold T out The candidate set is segmented to distinguish different sessions that reuse the same quintuple. For the candidate set... The ordered data packet index sequence {i1, i2, ..., i... L If the time interval between adjacent data packets satisfies the segmentation condition: Then, truncation is performed at position r, dividing the original sequence into different final data streams. Let the m-th data stream contain L... m A sequence of data packets:

[0026]

[0027] And renumber the data packets within the stream in ascending order of time.

[0028] Step 1.4, in each data stream Internally, the time interval between packets is calculated and discrete features are extracted to construct a normalized feature vector sequence. For the t-th packet in the m-th stream (1≤t≤L)... m Define the time interval between packages (IAT). m,t for:

[0029]

[0030] Extract the corresponding payload length Len m,t =len(pm,t ) and other protocol fields, which together form the basic feature vector v at that moment. m,t :

[0031] v m,t =[IAT m,t Len m,t flag m,t ,proto m,t port m,t d m,t ]

[0032] Among them, flag m,t For data packet p m,t The transport layer protocol flag bit vector, proto m,t For transport layer protocol type, port m,t d is the destination port number. m,t This is a defined flow direction flag. Finally, the output is a set of all processed data streams. This serves as input data for unified feature mapping and model training in subsequent steps.

[0033] Furthermore, step 2 includes the following sub-steps:

[0034] Step 2.1: Perform normalization processing on the obtained continuous features (including inter-cabin time interval and payload length); specifically, the inter-cabin time interval (IAT) is processed using logarithmic normalization to obtain...

[0035]

[0036] The effective payload length Len is processed in the same way to obtain...

[0037]

[0038] Where ε is a small positive number to prevent numerical instability in logarithmic operations, and μ IAT , σ IAT μ Len , σ Len These are the mean and standard deviation of the corresponding features, calculated on the training set.

[0039] Step 2.2: Deconstruct the discrete features (including protocol flags, network layer or transport layer protocol type, and port number) obtained in Step 1). Convert each discrete value v into a fixed-length binary symbol vector. For a discrete field with a value range of [0, M-1), where M is the total number of possible values ​​for the field, determine its binary bit length n: And represent the discrete values ​​as a binary vector of length n:

[0040] b = (b1, b2, ..., b) n ), b i ∈{0,1}

[0041] Step 2.3: To enable the discrete binary vector to participate in the continuous modeling process of the diffusion model, a continuous embedding mapping method is used to process the discrete protocol field. Through a linear mapping function, the binary vector b is converted into a real-valued feature vector z: ε PDFCE (v) = Wb + u. Where W is the learnable mapping matrix and u is the bias vector. Finally, the real-valued feature vectors corresponding to all discrete protocol fields are concatenated to form a discrete feature subset z. d and the continuous feature subset obtained in step 2.1).

[0042] Furthermore, step 3 includes the following sub-steps:

[0043] Step 3.1: Construct a hierarchical diffusion generation model based on a unified feature space, comprising packet-level and flow-level sub-networks. For each data flow... Constructing flow-level eigenvectors

[0044] in, This represents the stream-level statistical characteristics obtained based on the stream's duration, total number of packets, uplink / downlink packet ratio, total number of bytes, and average packet length. m This is the encoded vector representing the category, business scenario, and security label of the stream.

[0045] f m Input the stream-level Mamba-encoded subnetwork to obtain the stream-level global control vector h. flow :

[0046] h flow Mamba flow (f m ,k,θ flow )

[0047] Where k is the current diffusion time step, θ flow These are the parameters for the stream-level Mamba subnetwork. Simultaneously, the packet-level feature sequences obtained in step 2) under the unified feature space are... Input a packet-level Mamba subnet and perform a state update: h m,t =Mamba pkt (h m,t-1 x m,t h flow ,k,θ pkt Obtain the packet-level hidden state sequence Where θ pkt For packet-level Mamba subnetwork parameters, h flowThis information is injected into the packet-level subnetwork as conditional information.

[0048] Based on this, the packet-level hidden state sequence and the stream-level global control vector are fused through the noise prediction head to output the corresponding noise prediction result: Where x m,k Let θ be the noisy feature sequence of the m-th data stream at time step k, where θ = {θ} flow θ pkt θ head} represents the set of trainable parameters for the generative model.

[0049] Step 3.2: Define the forward noise addition process of the diffusion model in the unified feature space. Let x be the noise-free feature sequence of the m-th data stream. m,0 According to the preset noise scheduling sequence Add forward noise to it.

[0050] Calculate the noisy features x at each time step m,k :

[0051] in Standard Gaussian noise, Let be the cumulative noise coefficient at the k-th time step. The training objective is to make ε the output of the noise prediction head. θ (x m,k ,k,f m To approximate the true noise ε, and thus, during the back diffusion process, based on ε... θ (·) Stepwise reconstruction of noise-free feature sequence x m,0 .

[0052] Step 3.3: Optimize the model parameters based on a hybrid loss function that combines continuous and discrete features:

[0053] For a continuous feature subset in a unified feature vector, the mean square error of noise prediction is used as the continuous feature loss.

[0054] For a discrete feature subset obtained through continuous embedding of discrete fields in a protocol, let its target continuous representation be d. i (i∈D), the corresponding predicted value is Define weighted discrete consistency loss

[0055]

[0056] Where D is the set of discrete feature dimensions, λ disc,i Let be the weight coefficient of the i-th discrete dimension, σ(·) be the activation function, and CE(·) be the cross-entropy loss, thus obtaining the overall training loss function:

[0057]

[0058] On the training dataset in a unified feature space, for θ flow θ pkt and noise prediction head parameter θ head Iterative optimization is performed by continuously updating the model parameters through backpropagation until the loss function is reached. The training of the two-branch Mamba diffusion generative model has converged and is complete.

[0059] Furthermore, step 4 includes the following sub-steps:

[0060] Step 4.1: Construct a protocol state machine based on both rule-based and statistical constraints.

[0061] To ensure that the generated traffic is logically complete and conforms to the protocol specifications, a five-tuple protocol state machine P = (S, A, δ, s0, T) is constructed.

[0062] Define the state space S as the transport layer state set S trans With the application layer observed state set S app Cartesian product and default absorbing state set {s ⊥ The union of} is S = (S trans ×S app )∪{s ⊥}

[0063] The transport layer state set S trans Includes the standard TCP states defined in RFC 793 and the connectionless UDP state NO_STATE. Application layer observed state set S app For the quantized historical record of discrete features, any s app ∈S app Includes the effective payload length range and normalized time interval range of the preceding message. Default absorption state s ⊥ This is a special termination state used to capture all illegal transitions. Once the system enters this state, it indicates that the current traffic sequence has seriously violated the protocol, and no further legitimate state transitions will be performed.

[0064] Define the action space A as the set of discrete feature vectors output by the generative model. To ensure that the space is finite and computationally achievable, any action a∈A is defined as a quintuple:

[0065] a = (dir, Flag) vec Proto id Port bucket Len bucket )

[0066] Where dir∈{+1, -1}: specifies the direction of data packet flow (from client to server or vice versa), thus distinguishing between TCP "send" and "receive" events. (Flag) vec ∈{0,1} 8 TCP flag vector The set of transport layer protocol numbers, whose values ​​belong to a finite subset of protocols appearing in the training dataset. Port bucket ∈{0, ..., N p -1}: A finite range index of port numbers obtained through clustering or hash mapping, Len bucket ∈{0, ..., N l -1}: Quantization bucket index of payload length.

[0067] Define the state transition function δ: S × A → S is a total function. For the current state s cur And generate action a:

[0068] Among them, rule constraint transfer (T) rule If (s) cur a) Conforms to TCP protocol specifications (e.g., when the current state is SYN_RCVD and dir is in the sending direction, the flag for action a) vec If SYN+ACK is included, then the process transitions to a valid next state s. next Statistical constraint transition (T) stat If (s) cur a) It conforms to the high-frequency business logic obtained from historical data statistics (i.e., the transition probability P(s)). next |s cur If a) ≥ η), then the transition to the legal next state s is possible. next Abnormal transition: For all cases not belonging to T rule And does not belong to T stat The combination of δ(s) is defined. cur , a) = s ⊥ .

[0069] To avoid dimensional explosion caused by the action space, validity constraints are decomposed into independent field masks. Define the query function. Output a set of independent mask vectors:

[0070]

[0071] Where M flag : Flag enable mask, indicating the valid TCP flag combinations in the current state, M proto : Protocol type allow mask, indicating the valid transport layer protocol types, M port: Port class allow mask, indicating the index of the legal target port class (e.g., only HTTP ports or dynamic ports allowed), M len : Load length range allowable mask, indicating the legal effective load length range. In the above mask, the dimension value corresponding to illegal actions is 0, and the dimension value corresponding to legal actions is 1.

[0072] Step 4.2, Initialize the initial state of back diffusion.

[0073] Let K be the total number of time steps for backdiffusion. For the traffic generation task, from the standard Gaussian distribution... The initial noise vector x is obtained by sampling at the Kth step. k For the traffic repair task, features of the known data are preserved, and Gaussian noise is applied only to the missing parts. These are then combined to obtain the initial state x. K .

[0074] Step 4.3: Perform unconstrained noise prediction and feature estimation.

[0075] At each time step k (decreasing from K to 1) of the reverse denoising process, the current noisy feature vector x is... k The input is fed into the generative model trained in step 3) to obtain the noise value ε predicted by the model. θ (x k (k, y).

[0076] Using the inverse formula of the diffusion model, calculate the estimated value x0 of the noise-free eigenvector at the current time:

[0077]

[0078] Extract the feature subset corresponding to the discrete action space A, denoted as .

[0079] Step 4.4, Hybrid Relaxation Gradient Guidance and State Update Based on Factorization Mask

[0080] First, state determination and factorization mask acquisition: Based on continuous features (such as timestamps) in x0 and the discrete state fixed in the previous time step, the current protocol state s is determined. t Using the validity query function defined in step 4.1), obtain the factorization mask group for this state: {M flag M proto M port M len}

[0081] Where M flag : Flag enable mask, indicating the valid TCP flag combinations in the current state, M proto: Protocol type allow mask, indicating the valid transport layer protocol types, M port : Port class allow mask, indicating the index of the legal target port class (e.g., only HTTP ports or dynamic ports allowed), M len : Load length range allowable mask, indicating the legal effective load length range. In the above mask, the dimension value corresponding to illegal actions is 0, and the dimension value corresponding to legal actions is 1.

[0082] For independent binary classification fields (multi-label attributes): For TCP flags (such as SYN, ACK, FIN, etc., which can appear simultaneously), a bit-by-bit relaxation is performed using a Sigmoid function with a temperature coefficient τ to obtain the flag probability vector.

[0083]

[0084] For protocol type, port category index, and payload length range, a Softmax function with a temperature coefficient τ is used for normalization relaxation to ensure that the probability sum of each category is 1. The port category index is calculated as follows: Protocol type probability Probability of load length interval Calculate similarly.

[0085] Secondly, a default energy function is constructed and its gradient is calculated. The protocol default energy E is defined as the weighted sum of the "illegal probability quality" of each field. The lower the energy, the more the generated probability distribution conforms to the mask constraint.

[0086]

[0087] Where ⊙ represents element-wise multiplication, 1-M represents the invalidity mask (valid positions are 0, invalid positions are 1), and λ f , λ c This represents the energy penalty weighting coefficient for each field, used to balance the importance of constraints across different fields. This represents the predicted probability vector of the corresponding discrete field c (i.e., protocol type, port, or payload length) in the summation term at the current time step.

[0088] Calculate the total energy function E with respect to the noisy input x at the current time step. k gradient vector

[0089] The calculated gradient is used as a guiding force to "reject illegal states" and correct the original noise predictions of the generative model:

[0090]

[0091] Where s is the guiding strength scalar. Finally, substituting into the reverse state update formula of DDPM, the state x of the previous time step is calculated. k-1 :

[0092]

[0093] The process is repeated until k=1, and the output is a feature sequence that strictly satisfies the constraints of the protocol state machine.

[0094] Furthermore, step 5 includes the following sub-steps:

[0095] Step 5.1: For continuous features, based on the statistical parameters recorded during the training phase, perform inverse normalization operations on the packet time interval and payload length corresponding to the feature mapping process to restore their original numerical scale. For discrete protocol fields, determine the corresponding discrete values ​​according to the probability distribution of the model output, and restore them to the standard representation of the protocol field through a preset mapping relationship. The protocol field includes at least the protocol type, port category, and transport layer flag.

[0096] Step 5.2, Protocol State Maintenance and Header Reconstruction. During packet-by-packet reconstruction, the protocol state information is maintained in accordance with that in Step 4), and the network packet header is reconstructed based on the recovered feature fields. By accumulating the recovered inter-packet time intervals, the absolute arrival time order of each data packet is determined; based on this, the corresponding source address, destination address, and related protocol fields are generated according to the data packet direction information and the current protocol state. For connection-oriented transport layer protocols, the sequence-related fields are updated consistently based on the current session state to ensure that the reconstructed data packet sequence meets the timing and state transition requirements in the protocol specification.

[0097] Step 5.3, Consistency Verification and Traffic File Output. After reconstructing the packet fields, a protocol consistency verification operation is performed on the generated packet sequence to ensure the integrity and validity of the packet header fields. The network traffic data file is output according to the task type: when performing a traffic generation task, the reconstructed packet sequence is written to the target traffic file in chronological order; when performing a traffic repair task, the generated complete packet and the remaining data segments in the original traffic file are merged in chronological order to output a complete network traffic data file with consistent timing.

[0098] Compared with existing technologies, this invention has the following main advantages: It jointly models continuous-time features and discrete protocol fields in a unified feature space, avoiding information fragmentation caused by processing different types of features separately or simply splicing them together, thus facilitating the characterization of the overall structural features of network traffic. By introducing protocol state constraints during the generation and repair process, the generation trajectory always conforms to the legal transition relationships defined by the protocol state machine, thereby reducing the possibility of illegal protocol field combinations or incomplete session processes in the generation results. Simultaneously, this invention achieves network traffic generation and repair within the same framework, enabling the completion of missing, abnormal, or masked traffic segments, reconstructing complete traffic data while ensuring protocol consistency. The generated or repaired network traffic data meets communication protocol specifications and can be parsed and processed by real protocol stacks, exhibiting good applicability. Attached Figure Description

[0099] To more clearly illustrate the technical solutions of the embodiments of the present invention, the drawings used in the following description of the embodiments will be briefly introduced. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0100] Figure 1 Overall flowchart of the method

[0101] Figure 2 Schematic diagram of the two-layer Mamba diffusion generation model structure

[0102] Figure 3 Diagram of constructing a polymorphic protocol machine Detailed implementation method:

[0103] The present invention will be further described in detail below with reference to the accompanying drawings and specific embodiments:

[0104] It will be understood by those skilled in the art that, unless otherwise defined, all terms used herein (including technical and scientific terms) have the same meaning as commonly understood by one of ordinary skill in the art to which this invention pertains. It should also be understood that terms such as those defined in general dictionaries should be understood to have the meaning consistent with their meaning in the context of the prior art, and should not be interpreted in an idealized or overly formal sense unless defined as herein.

[0105] like Figure 1 As shown, this invention proposes a network traffic generation and repair method based on protocol constraints. The method mainly includes five steps: data preprocessing, unified feature mapping, Mamba diffusion model training, generation / repair under protocol constraints, and inverse mapping and traffic reconstruction.

[0106] Step 1: Parse the raw network traffic capture file

[0107] Step 1.1: Parse the original network traffic capture file, extracting each data packet into a structured record with a timestamp and protocol field; for the i-th data packet, denoted as...

[0108] p i =(t i src i dst i , spt i dpt i ,proto i len i )

[0109] Among them, t i For the arrival timestamp, src i dst i These are the source address and destination address, respectively. i dpt i These are the source and destination ports, respectively, proto i For transport layer protocol type, len i The payload length is given; all data packets are rearranged in ascending order of timestamp to obtain an ordered data packet sequence P. sorted ={p1, p2, ..., p N}

[0110] Step 1.2, to achieve unified modeling of bidirectional sessions, a "normalized quintuple" is defined as the unique identifier key K(p) of the stream. i For any data packet p i The direction-independent key value is determined by comparing the sizes of the sockets (IP and port combinations) at both ends of the communication:

[0111]

[0112] And additionally record the direction markers.

[0113]

[0114] Will have the same K(p) i Data packets are grouped into the same candidate data stream set.

[0115] Step 1.3, introduce a session timeout threshold T out The candidate set is segmented to distinguish different sessions that reuse the same quintuple. For the candidate set... The ordered data packet index sequence {i1, i2, ..., i...L If the time interval between adjacent data packets satisfies the segmentation condition: Then, truncation is performed at position r, dividing the original sequence into different final data streams. Let the m-th data stream contain L... m A sequence of data packets:

[0116]

[0117] And renumber the data packets within the stream in ascending order of time.

[0118] Step 1.4, in each data stream Internally, the time interval between packets is calculated and discrete features are extracted to construct a normalized feature vector sequence. For the t-th packet in the m-th stream (1≤t≤L)... m Define the time interval between packages (IAT). m,t for:

[0119]

[0120] Extract the corresponding payload length Len m,t =len(p m,t ) and other protocol fields, which together form the basic feature vector v at that moment. m,t :

[0121] v m,t =[IAT m,t Len m,t flag m,t ,proto m,t port m,t d m,t ]

[0122] Among them, flag m,t For data packet p m,t The transport layer protocol flag bit vector, proto m,t For transport layer protocol type, port m,t d is the destination port number. m,t This is a defined flow direction flag. Finally, the output is a set of all processed data streams. This serves as input data for unified feature mapping and model training in subsequent steps.

[0123] Step 2, unified mapping after data preprocessing, such as... Figure 1 As shown in step 2.

[0124] Step 2.1: Perform normalization processing on the obtained continuous features (including inter-cabin time interval and payload length); specifically, the inter-cabin time interval (IAT) is processed using logarithmic normalization to obtain...

[0125]

[0126] The effective payload length Len is processed in the same way to obtain...

[0127]

[0128] Where ε is a small positive number to prevent numerical instability in logarithmic operations, and μ IAT , σ IAT μ Len , σ Len These are the mean and standard deviation of the corresponding features, calculated on the training set.

[0129] Step 2.2: Deconstruct the discrete features (including protocol flags, network layer or transport layer protocol type, and port number) obtained in Step 1). Convert each discrete value v into a fixed-length binary symbol vector. For a discrete field with a value range of [0, M-1), where M is the total number of possible values ​​for the field, determine its binary bit length n: And represent the discrete values ​​as a binary vector of length n:

[0130] b = (b1, b2, ..., b) n ), b i ∈{0,1}

[0131] Step 2.3: To enable the discrete binary vector to participate in the continuous modeling process of the diffusion model, a continuous embedding mapping method is used to process the discrete protocol field. Through a linear mapping function, the binary vector b is converted into a real-valued feature vector z: ε PDFCE (v) = Wb + u. Where W is the learnable mapping matrix and u is the bias vector. Finally, the real-valued feature vectors corresponding to all discrete protocol fields are concatenated to form a discrete feature subset z. d And the continuous feature subset obtained in step 2.1).

[0132] Step 3: Construct and train the diffusion backbone model, such as... Figure 2 As shown.

[0133] Step 3.1: Construct a hierarchical diffusion generation model based on a unified feature space, comprising packet-level and flow-level sub-networks. For each data flow... Constructing flow-level eigenvectors

[0134] in, This represents the stream-level statistical characteristics obtained based on the stream's duration, total number of packets, uplink / downlink packet ratio, total number of bytes, and average packet length. mThis is the encoded vector representing the category, business scenario, and security label of the stream.

[0135] f m Input the stream-level Mamba-encoded subnetwork to obtain the stream-level global control vector h. flow :

[0136] h flow =Mamba flow (f m ,k,θ flow )

[0137] Where k is the current diffusion time step, θ flow These are the parameters for the stream-level Mamba subnetwork. Simultaneously, the packet-level feature sequences obtained in step 2) under the unified feature space are... Input a packet-level Mamba subnet and perform a state update: h m,t =Mamba pkt (h m,t-1 x m,t h flow ,k,θ pkt Obtain the packet-level hidden state sequence Where θ pkt For packet-level Mamba subnetwork parameters, h flow This information is injected into the packet-level subnetwork as conditional information.

[0138] Based on this, the packet-level hidden state sequence and the stream-level global control vector are fused through the noise prediction head to output the corresponding noise prediction result: Where x m,k Let θ be the noisy feature sequence of the m-th data stream at time step k, where θ = {θ} flow θ pkt θ head} represents the set of trainable parameters for the generative model.

[0139] Step 3.2: Define the forward noise addition process of the diffusion model in the unified feature space. Let x be the noise-free feature sequence of the m-th data stream. m,0 According to the preset noise scheduling sequence Add forward noise to it.

[0140] Calculate the noisy features x at each time step m,k :

[0141] in Standard Gaussian noise, Let be the cumulative noise coefficient at the k-th time step. The training objective is to make ε the output of the noise prediction head. θ (x m,k ,k,fm To approximate the true noise ε, and thus, during the back diffusion process, according to ∈ θ (·) Stepwise reconstruction of noise-free feature sequence x m,0 .

[0142] Step 3.3: Optimize the model parameters based on a hybrid loss function that combines continuous and discrete features:

[0143] For a continuous feature subset in a unified feature vector, the mean square error of noise prediction is used as the continuous feature loss.

[0144] For a discrete feature subset obtained through continuous embedding of discrete fields in a protocol, let its target continuous representation be d. i (i∈D), the corresponding predicted value is Define weighted discrete consistency loss

[0145]

[0146] Where D is the set of discrete feature dimensions, λ disc,i Let be the weight coefficient of the i-th discrete dimension, σ(·) be the activation function, and CE(·) be the cross-entropy loss, thus obtaining the overall training loss function:

[0147]

[0148] On the training dataset in a unified feature space, for θ flow θ pkt and noise prediction head parameter θ head Iterative optimization is performed by continuously updating the model parameters through backpropagation until the loss function is reached. The training of the two-branch Mamba diffusion generative model has converged and is complete.

[0149] Step 4: Protocol Constraint Generation and Repair

[0150] Step 4.1, construct a protocol state machine based on both rule-based and statistical constraints, such as... Figure 3 As shown in the diagram on the right.

[0151] To ensure that the generated traffic is logically complete and conforms to the protocol specifications, a five-tuple protocol state machine P = (S, A, δ, s0, T) is constructed.

[0152] Define the state space S as the transport layer state set S trans With the application layer observed state set S app Cartesian product and default absorbing state set {s ⊥ The union of} is S = (S trans×S app )∪{s ⊥}

[0153] The transport layer state set S trans Includes the standard TCP states defined in RFC 793 and the connectionless UDP state NO_STATE. Application layer observed state set S app For the quantized historical record of discrete features, any s app ∈S app Includes the effective payload length range and normalized time interval range of the preceding message. Default absorption state s ⊥ This is a special termination state used to capture all illegal transitions. Once the system enters this state, it indicates that the current traffic sequence has seriously violated the protocol, and no further legitimate state transitions will be performed.

[0154] Define the action space A as the set of discrete feature vectors output by the generative model. To ensure that the space is finite and computationally achievable, any action a∈A is defined as a quintuple:

[0155] a = (dir, Flag) vec Proto id Port bucket Len bucket )

[0156] Where dir∈{+1, -1}: specifies the direction of data packet flow (from client to server or vice versa), thus distinguishing between TCP "send" and "receive" events. (Flag) vec ∈{0,1} 8 TCP flag vector The set of transport layer protocol numbers, whose values ​​belong to a finite subset of protocols appearing in the training dataset. Port bucket ∈{0, ..., N p -1}: A finite range index of port numbers obtained through clustering or hash mapping, Len bucket ∈{0, ..., N l -1}: Quantization bucket index of payload length.

[0157] Define the state transition function δ: S × A → S is a total function. For the current state s cur And generate action a:

[0158] Among them, rule constraint transfer (T) rule If (s) cur a) Conforms to TCP protocol specifications (e.g., when the current state is SYN_RCVD and dir is in the sending direction, the flag for action a) vecIf SYN+ACK is included, then the process transitions to a valid next state s. next Statistical constraint transition (T) stat If (s) cur a) It conforms to the high-frequency business logic obtained from historical data statistics (i.e., the transition probability P(s)). next |s cur If a) ≥ η), then the transition to the legal next state s is possible. next Abnormal transition: For all cases not belonging to T rule And does not belong to T stat The combination of δ(s) is defined. cur , a) = s ⊥ .

[0159] To avoid dimensional explosion caused by the action space, validity constraints are decomposed into independent field masks. Define the query function. Output a set of independent mask vectors:

[0160]

[0161] Where M flag : Flag enable mask, indicating the valid TCP flag combinations in the current state, M proto : Protocol type allow mask, indicating the valid transport layer protocol types, M port : Port class allow mask, indicating the index of the legal target port class (e.g., only HTTP ports or dynamic ports allowed), M len : Load length range allowable mask, indicating the legal effective load length range. In the above mask, the dimension value corresponding to illegal actions is 0, and the dimension value corresponding to legal actions is 1.

[0162] Step 4.2, Initialize the initial state of back diffusion.

[0163] Let K be the total number of time steps for backdiffusion. For the traffic generation task, from the standard Gaussian distribution... The initial noise vector x is obtained by sampling at the Kth step. K For the traffic repair task, features of the known data are preserved, and Gaussian noise is applied only to the missing parts. These are then combined to obtain the initial state x. K .

[0164] Step 4.3, perform unconstrained noise prediction and feature estimation, such as... Figure 3 The intermediate process is shown below.

[0165] At each time step k (decreasing from K to 1) of the reverse denoising process, the current noisy feature vector x is... k The input is fed into the generative model trained in step 3) to obtain the noise value ε predicted by the model. θ (xk (k, y).

[0166] Using the inverse formula of the diffusion model, calculate the estimated value x0 of the noise-free eigenvector at the current time:

[0167]

[0168] Extract the feature subset corresponding to the discrete action space A, denoted as .

[0169] Step 4.4, Hybrid Relaxation Gradient Guidance and State Update Based on Factorization Mask

[0170] First, state determination and factorization mask acquisition: Based on continuous features (such as timestamps) in x0 and the discrete state fixed in the previous time step, the current protocol state s is determined. t Using the validity query function defined in step 4.1), obtain the factorization mask group for this state: {M flag M proto M port M len}

[0171] Where M flag : Flag enable mask, indicating the valid TCP flag combinations in the current state, M proto : Protocol type allow mask, indicating the valid transport layer protocol types, M port : Port class allow mask, indicating the index of the legal target port class (e.g., only HTTP ports or dynamic ports allowed), M len : Load length range allowable mask, indicating the legal effective load length range. In the above mask, the dimension value corresponding to illegal actions is 0, and the dimension value corresponding to legal actions is 1.

[0172] For independent binary classification fields (multi-label attributes): For TCP flags (such as SYN, ACK, FIN, etc., which can appear simultaneously), a bit-by-bit relaxation is performed using a Sigmoid function with a temperature coefficient τ to obtain the flag probability vector.

[0173]

[0174] For protocol type, port category index, and payload length range, a Softmax function with a temperature coefficient τ is used for normalization relaxation to ensure that the probability sum of each category is 1. The port category index is calculated as follows: Protocol type probability Probability of load length interval Calculate similarly.

[0175] Secondly, a default energy function is constructed and its gradient is calculated. The protocol default energy E is defined as the weighted sum of the "illegal probability quality" of each field. The lower the energy, the more the generated probability distribution conforms to the mask constraint.

[0176]

[0177] Where ⊙ represents element-wise multiplication, 1-M represents the invalidity mask (valid positions are 0, invalid positions are 1), and λ f , λ c This represents the energy penalty weighting coefficient for each field, used to balance the importance of constraints across different fields. This represents the predicted probability vector of the corresponding discrete field c (i.e., protocol type, port, or payload length) in the summation term at the current time step.

[0178] Calculate the total energy function E with respect to the noisy input x at the current time step. k gradient vector

[0179] The calculated gradient is used as a guiding force to "reject illegal states" and correct the original noise predictions of the generative model:

[0180]

[0181] Where s is the guiding strength scalar. Finally, substituting into the reverse state update formula of DDPM, the state x of the previous time step is calculated. k-1 :

[0182]

[0183] The process is repeated until k=1, and the output is a feature sequence that strictly satisfies the constraints of the protocol state machine.

[0184] Step 5: Inverse Mapping and Reconstruction

[0185] Step 5.1: For continuous features, based on the statistical parameters recorded during the training phase, perform inverse normalization operations on the packet time interval and payload length corresponding to the feature mapping process to restore their original numerical scale. For discrete protocol fields, determine the corresponding discrete values ​​according to the probability distribution of the model output, and restore them to the standard representation of the protocol field through a preset mapping relationship. The protocol field includes at least the protocol type, port category, and transport layer flag.

[0186] Step 5.2, Protocol State Maintenance and Header Reconstruction. During packet-by-packet reconstruction, the protocol state information is maintained in accordance with that in Step 4), and the network packet header is reconstructed based on the recovered feature fields. By accumulating the recovered inter-packet time intervals, the absolute arrival time order of each data packet is determined; based on this, the corresponding source address, destination address, and related protocol fields are generated according to the data packet direction information and the current protocol state. For connection-oriented transport layer protocols, the sequence-related fields are updated consistently based on the current session state to ensure that the reconstructed data packet sequence meets the timing and state transition requirements in the protocol specification.

[0187] Step 5.3, Consistency Verification and Traffic File Output. After reconstructing the packet fields, a protocol consistency verification operation is performed on the generated packet sequence to ensure the integrity and validity of the packet header fields. The network traffic data file is output according to the task type: when performing a traffic generation task, the reconstructed packet sequence is written to the target traffic file in chronological order; when performing a traffic repair task, the generated complete packet and the remaining data segments in the original traffic file are merged in chronological order to output a complete network traffic data file with consistent timing.

[0188] The technical solution of the present invention has been described above with reference to the preferred embodiments shown in the accompanying drawings. However, it will be readily understood by those skilled in the art that the scope of protection of the present invention is obviously not limited to these specific embodiments. Without departing from the principles of the present invention, those skilled in the art can make equivalent changes or substitutions to the relevant technical features, and the technical solutions after these changes or substitutions will all fall within the scope of protection of the present invention.

Claims

1. A method for generating and repairing network traffic based on protocol constraints, characterized in that, Includes the following steps: Step 1) Parse the original network traffic capture file, sort the data packets by timestamp, perform flow-level aggregation, and perform session segmentation on the data packet sequence based on the normalized 5-tuple and the preset session timeout threshold to obtain a set consisting of multiple data streams; within each data stream, calculate the inter-packet time interval between adjacent data packets, and extract the payload length and protocol fields to form an intra-flow packet-level feature sequence. Step 2) Map the packet-level feature sequence to a unified feature space, wherein: for continuous features, at least the inter-packet time interval and payload length are normalized; for discrete protocol fields, at least the protocol type, port number, and protocol flag bits are first symbolically decomposed and represented as binary vectors, and then converted into real-valued feature vectors through linear mapping; the continuous features are concatenated with the real-valued discrete features to obtain a unified packet-level feature representation for diffusion modeling. Step 3) Construct a hierarchical diffusion network traffic generation model in the unified feature space. The generation model includes at least: a packet-level Mamba sub-network for modeling packet-level temporal relationships within a single data stream, and a flow-level Mamba sub-network for modeling global statistical features across data streams. During the training phase, the model is jointly trained by forward noise addition and backward noise prediction, so that the model learns the generation distribution of network traffic in the unified feature space. Step 4) During the backdiffusion sampling process, protocol state constraints are introduced to guide the generation trajectory step by step. Specifically, this includes: constructing a protocol state machine that includes the transport layer state, application layer observation state, and default absorption state, and defining a set of discrete protocol fields corresponding to the generation action; at each backdiffusion time step, generating a corresponding factorized legality mask based on the current protocol state to limit the legal value range of each discrete protocol field in the current state; performing hybrid relaxation on the discrete protocol fields using Softmax or Sigmoid functions to construct a protocol default energy function reflecting the probability of illegal values, and calculating the gradient of this energy function relative to the current noisy features; using the gradient to correct the noise predicted by the diffusion model, so that the backdiffusion process evolves in the direction that satisfies the protocol state machine constraints, thereby generating a protocol-compliant feature sequence. Step 5) Perform inverse mapping on the feature sequences generated or repaired by protocol constraints, restore the continuous and discrete features in the unified feature space to standard network data packet fields, and output network traffic data files that meet the protocol specifications by combining the protocol state maintenance and verification mechanism.

2. The method for generating and repairing network traffic based on protocol constraints according to claim 1, characterized in that, Step 1) includes the following sub-steps: Step 1.1) Parse the raw network traffic capture file, extracting each data packet into a structured record with a timestamp and protocol field. For the i-th data packet, denoted as... p i =(t i ,src i ,dst i ,spt i ,dpt i ,proto i ,len i ) Among them, t i For the arrival timestamp of the data packet, src i dst i These are the source address and destination address, respectively. i dpt i These are the source and destination ports, respectively, proto i For transport layer protocol type, len i This represents the payload length of the data packets. All data packets are sorted in ascending order of their timestamps to obtain an ordered sequence of data packets: P sorted ={p1,p2,...,p N } Step 1.2) To achieve unified modeling of bidirectional sessions, a "normalized quintuple" is defined as the unique identifier key K(p) for the data stream. i For any data packet p i By comparing the size relationship between the sockets (IP address and port combination) at both ends of the communication, a direction-independent normalized 5-tuple key is constructed: And additionally record the direction markers. The same normalized quintuple bond K(p) i Data packets are grouped into the same candidate data stream set. Step 1.3) Introduce a session timeout threshold T out Each candidate data stream set is split to distinguish different sessions that reuse the same normalized quintuple. Let the candidate set be... The data packet index sequence sorted by time is {i1, i2, ..., i...} L If adjacent data packets satisfy the time interval condition: Then, session segmentation is performed at position r, dividing the original sequence into different final data streams. Let the m-th final data stream contain L. m A sequence of data packets: And renumber the data packets within the stream in ascending order of timestamps. Step 1.4) In each data stream Internally, the inter-packet time interval is calculated and protocol-related features are extracted to construct a normalized sequence of packet-level feature vectors. For the t-th data packet p in the m-th data stream... m,t (1≤t≤L m Define the time interval between packages (IAT). m,t for: And extract the corresponding effective payload length Len m,t =len(p m,t ) and other discrete protocol fields, which together form the basic feature vector v at that moment. m,t : v m,t =[IAT m,t ,Len m,t ,flag m,t ,proto m,t ,port m,t ,d m,t ] Among them, flag m,t For data packet p m,t The transport layer protocol flag bit vector, proto m,t For data packet p m,t Transport layer protocol type, port m,t For data packet p m,t Destination port number, d m,t For data packet p m,t The flow direction indicator. Finally, output the set of all processed data streams. This serves as input data for unified feature mapping and model training in subsequent steps.

3. The method for generating and repairing network traffic based on protocol constraints according to claim 1, characterized in that, Step 2) includes the following sub-steps: Step 2.1) Perform normalization processing on the obtained continuous features (including inter-cabin time interval and payload length); wherein, the inter-cabin time interval (IAT) is processed using logarithmic normalization to obtain The effective payload length Len is processed in the same way to obtain... Where ∈ is a preset small positive number to prevent numerical instability in logarithmic operations, and μ IAT , σ IAT μ Len , σ Len These are the mean and standard deviation of the corresponding features, calculated on the training dataset. Step 2.2) Deconstruct the discrete features (including protocol flags, network layer or transport layer protocol type, and port number) obtained in Step 1). Convert each discrete value v into a fixed-length binary symbol vector. For a discrete field with a value range of [0, M-1), where M is the total number of possible values ​​for the field, determine its binary bit length n: And represent the discrete values ​​as a binary vector of length n: b=(b1,b2,...,b n ),b i ∈{0,1} Step 2.3) To enable discrete binary vectors to participate in the continuous modeling process of the diffusion model, a continuous embedding mapping method is used to process the discrete protocol fields. Through a linear mapping function, the binary vector b with discrete values ​​v is transformed into a real-valued feature vector z: ε PDFCE (v) = Wb + u. Where W is the learnable mapping matrix and u is the bias vector. Finally, the real-valued feature vectors corresponding to all discrete protocol fields are concatenated to form a discrete feature subset z. d And with the continuous feature subset z obtained in step 2.1). c = [IAT′,Len′] are concatenated to form the packet-level unified feature vector x of the t-th data packet in the m-th data stream. m,t This serves as the input basis for subsequent diffusion-based network traffic generation models.

4. The method for generating and repairing network traffic based on protocol constraints according to claim 1, characterized in that, Step 3) includes the following sub-steps: Step 3.1) Based on the unified feature space obtained in Step 2), construct a hierarchical diffusion network traffic generation model that includes packet-level sub-networks and flow-level sub-networks. For each data flow... Construct the corresponding flow level feature vector in, This represents the stream-level statistical feature vector obtained based on the data stream's duration, total number of packets, uplink / downlink packet ratio, total number of bytes, and average packet length. m This is the encoding vector for the category, business scenario, and security label of the data stream. The flow level feature vector f m The current diffusion time step k is used as input and fed into the stream-level Mamba coding sub-network to obtain the stream-level global control vector h. flow : h flow Mamba flow (f m,k ,θ flow ) Where, θ flow These are the trainable parameters for the stream-level Mamba subnetwork. Simultaneously, the packet-level feature sequences obtained in step 2) within the unified feature space are... Input the packet-level Mamba subnetwork and the flow-level global control vector h flow This conditional information is injected into the packet-level subnetwork to update the state and obtain the packet-level hidden state sequence. h m,t =Mamba pkt (h m,t-1 x m,t h flow ,k,θ pkt ), where θ pkt These are the trainable parameters for the packet-level Mamba subnetwork. Based on this, the packet-level hidden state sequence and the stream-level global control vector are fused through the noise prediction head to output the corresponding noise prediction result: Where x m,k Let θ be the noisy feature sequence of the m-th data stream at time step k, where θ = {θ} flow θ pkt θ head } represents the set of trainable parameters for the generative model. Step 3.2) Define the forward noise addition process of the diffusion model in the unified feature space. Let x be the noise-free feature sequence of the m-th data stream. m,0 According to the preset noise scheduling sequence Forward noise is applied to the feature sequence. Calculate the noisy features x at each time step m,k : in Standard Gaussian noise, Let be the cumulative noise coefficient at the k-th time step. The training objective is to let ∈ in step 3.1) be the noise prediction head output. θ (x m,k ,k,f m This approximates the true noise ε, allowing the model to accurately reflect the predicted noise ε during backdiffusion. θ (·) Stepwise reconstruction of noise-free feature sequence x m,0 . Step 3.3) Jointly optimize the parameters of the hierarchical diffusion generation model based on a hybrid loss function of continuous and discrete features: For a continuous feature subset in a unified feature vector, the mean square error of noise prediction is used as the continuous feature loss. For a discrete feature subset obtained through continuous embedding of discrete fields in a protocol, let its target continuous representation be d. i (i∈D), the corresponding predicted value is Define weighted discrete consistency loss Where D is the set of discrete feature dimensions, λ disc,i Let be the weight coefficient of the i-th discrete dimension, σ(·) be the activation function, and CE(·) be the cross-entropy loss. Combining the continuous feature loss and the discrete feature loss, we obtain the overall training loss function: On the training dataset in a unified feature space, the parameters θ of the convection-level subnetwork flow Packet-level subnetwork parameters θ pkt and noise prediction head parameter θ head Iterative optimization is performed by continuously updating the model parameters through backpropagation until the loss function is reached. The training of the two-branch Mamba diffusion generative model has converged and is complete.

5. The method for generating and repairing network traffic based on protocol constraints according to claim 1, characterized in that, Step 4) includes the following sub-steps: Step 4.1) Construct a protocol state machine based on a combination of rule constraints and statistical constraints to constrain the legality of the generated trajectory during the back diffusion process. To ensure that the generated traffic is logically complete and conforms to the protocol specifications, a five-tuple protocol state machine P = (S, A, δ, s0, T) is constructed. Define the state space S as the transport layer state set S trans With the application layer observed state set S app Cartesian product and default absorbing state set {s ⊥ The union of} is S = (S trans ×S app )∪{s ⊥ } The transport layer state set S trans It contains a set of standard states defined according to transport layer protocol specifications, including at least the connection establishment, data transmission, and connection release states as defined in RFC 793 for TCP; and the connectionless state NO_STATE for UDP. The application layer observe state set S app To quantify the discrete characteristics of historical messages, any application layer observation state s app ∈S app Includes the payload length range and normalized time interval range of preceding data packets. Default absorption state s ⊥ This is a special termination state used to capture all illegal transitions. Once the system enters this state, it indicates that the current traffic sequence has seriously violated the protocol, and no further legitimate state transitions will be performed. Let the action space A be the set of discrete feature vectors output by the generative model at each time step. To ensure that the space is finite and computationally achievable, any action a∈A is defined as a quintuple: a=(dir,Flag vec ,Proto id ,Port bucket ,Len bucket ) Where dir∈{+1, -1}: specifies the direction of data packet flow (from client to server or vice versa), thus distinguishing between TCP "send" and "receive" events. (Flag) vec ∈{0,1} 8 Represents the transport layer flag bit vector. This indicates the transport layer protocol type, and its value belongs to a finite subset of protocols appearing in the training dataset. Port bucket ∈{0, ..., N p `-1}` represents a finite range index of port numbers obtained through clustering or hash mapping. Len bucket ∈{0, ..., N l-1 } represents the quantization interval index of the payload length. Define the state transition function δ: S × A → S is a total function. For the current state s cur And the transition rules for generating action 'a' include: Rule constraint transfer (T) rule If (s) cur A) Conforms to TCP protocol specifications (e.g., when the current state is SYN_RCVD and dir is in the sending direction, the Flag for action a). vec If SYN+ACK is included, then the process transitions to a valid next state s. next Statistical constraint transition (T) stat If (s) cur a) It conforms to the high-frequency business logic obtained from historical data statistics (i.e., the transition probability P(s)). next |s cur If a) ≥ η), where η is the preset statistical probability threshold for determining high-frequency business logic (with a value range of 0 < η < 1), then the process transitions to the legal next state s. next Abnormal transition: For all cases not belonging to T rule And does not belong to T stat The action combination defines the state transition to the default absorption state, i.e., δ(s). cur , a) = s ⊥ . To avoid dimensionality explosion caused by the action space, validity constraints are decomposed into a set of field-level factorized masks. Define the query function. Output a set of independent mask vectors: Where M flag This represents the flag allow mask, indicating the valid TCP flag combinations in the current state. M proto The protocol type allow mask indicates the valid transport layer protocol type, M. port For port class allow mask, indicate the index of the legal target port class (e.g., allow only HTIP ports or dynamic ports), M len This is a mask indicating the legal payload length range. In the mask, illegal actions correspond to a dimension value of 0, while legal actions correspond to a dimension value of 1. Step 4.2) Initialize the initial state of the back diffusion Let K be the total number of time steps for backdiffusion. For the traffic generation task, from the standard Gaussian distribution... The initial noise vector x is obtained by sampling at the Kth step. K For the traffic repair task, features of the known data are preserved, and Gaussian noise is applied only to the missing parts. These are then combined to obtain the initial state x. K . Step 4.3) Perform unconstrained noise prediction and feature estimation during the back diffusion process. At each time step k (decreasing from K to 1) of the reverse denoising process, the current noisy feature vector x is... k The input is fed into the diffusion generation model trained in step 3) to obtain the noise value predicted by the model. θ (x k (k, y). Using the inverse update formula of the diffusion model, calculate the estimated value x0 of the noise-free eigenvector at the current time step. Extract the feature subset corresponding to the discrete action space A, denoted as . Step 4.4) Hybrid relaxation gradient guidance and protocol state update based on factorization mask. First, state determination and factorization mask acquisition: Based on the currently generated continuous features (such as timestamps) and the discrete state determined in the previous time step, the current protocol state s is determined. t Using the validity query function defined in step 4.1), obtain the set of field-level factorization masks for this state: {M flag M proto M port M len } For independent binary classification fields (multi-label attributes): For TCP flags (such as SYN, ACK, FIN, etc., which can appear simultaneously), a bit-by-bit relaxation is performed using a Sigmoid function with a temperature coefficient τ to obtain the flag probability vector. For protocol type, port category index, and payload length range, a Softmax function with a temperature coefficient τ is used for normalization relaxation to ensure that the probability sum of each category is 1. The port category index is calculated as follows: Protocol type probability Probability of load length interval The same calculation applies. Secondly, based on the above probability distribution, a protocol default energy function is constructed and its gradient is calculated. The protocol default energy E is defined as the weighted sum of the "illegal probability quality" of each field. The lower the energy, the smaller its value indicates that the generation distribution conforms more to the protocol constraints. Where ⊙ represents element-wise multiplication, 1-M represents the illegality mask (valid positions are 0, invalid positions are 1), and λ f , λ c These represent the energy penalty weight coefficients for each field, used to balance the importance of constraints across different fields. This represents the predicted probability vector of the corresponding discrete field c (i.e., protocol type, port, or payload length) in the summation term at the current time step. Calculate the default energy E with respect to the noisy feature x at the current time step. k gradient vector The calculated gradient is then used as a guiding term to correct the noisy predictions in the generator model output, thereby suppressing illegal state transitions during the reverse denoising process. Where s is the guiding intensity scalar. Finally, substituting the corrected noise prediction value into the backdiffusion update formula, we obtain the state x of the previous time step. k-1 : It also updates the protocol state synchronously, and executes the cycle until all back diffusion steps are completed, outputting a feature sequence that strictly satisfies the protocol state machine constraints.

6. The method for generating and repairing network traffic based on protocol constraints according to claim 1, characterized in that, Step 5) includes the following sub-steps: Step 5.1) For continuous features, based on the statistical parameters recorded during the training phase, perform inverse normalization operations on the inter-packet time interval and payload length corresponding to the feature mapping process to restore their original numerical scale. For discrete protocol fields, determine the corresponding discrete values ​​according to the probability distribution of the model output, and restore them to the standard representation of the protocol field through a preset mapping relationship. The protocol field includes at least the protocol type, port category, and transport layer flag. Step 5.2) Protocol State Maintenance and Header Reconstruction. During packet-by-packet reconstruction, the protocol state information is maintained in accordance with that in Step 4), and the network packet header is reconstructed based on the recovered feature fields. The absolute arrival time order of each data packet is determined by accumulating the recovered inter-packet time intervals. Based on this, the corresponding source address, destination address, and related protocol fields are generated according to the data packet direction information and the current protocol state. For connection-oriented transport layer protocols, the sequence-related fields are updated consistently according to the current session state to ensure that the reconstructed data packet sequence meets the timing and state transition requirements in the protocol specification. Step 5.3) Consistency Verification and Traffic File Output. After reconstructing the packet fields, perform a protocol consistency verification operation on the generated packet sequence to ensure the integrity and validity of the packet header fields. Output network traffic data files according to the task type: when performing a traffic generation task, write the reconstructed packet sequence into the target traffic file in chronological order; when performing a traffic repair task, merge the generated complete packet with the missing data segments in the original traffic file in chronological order, and output a complete network traffic data file with monotonic timing.