A vehicle-mounted CAN bus intrusion detection method and system and a storage medium
Patent Information
- Application Number
- CN202610769123.4
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-05-31
- Publication Date
- 2026-10-16
AI Technical Summary
[0005]综上所述,现有车载CAN总线入侵检测方法普遍存在对非均匀时间间隔特征提取能力弱、多分类检测精度低以及计算资源消耗大的技术问题,目前尚未提出有效的解决方案
(1)高精度多分类检测能力:通过融合自编码器的空间特征提取与Transformer的全局时序建模,本申请不仅能够识别拒绝服务攻击等简单攻击类型,还能够精准检测伪装攻击、重放攻击等具有复杂时序依赖特征的攻击类型,实现了对车载CAN总线入侵行为的高精度多分类检测。
Smart Images

Figure CN122933047A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of information processing technology, and in particular to a method, system and storage medium for detecting intrusion into a vehicle CAN bus. Background Technology
[0002] With the rapid development of Intelligent Connected Vehicles (ICVs), the complexity and openness of in-vehicle networks are increasing, and attack entry points and methods are diversifying simultaneously, making cybersecurity issues for ICVs increasingly severe. The Controller Area Network (CAN) in vehicles is the standard for in-vehicle network bus systems. The CAN bus is an economical and reliable serial, synchronous, half-duplex bus built on differential signaling, enabling connections between various ECUs within the vehicle and providing efficient communication between them. However, due to the lack of authentication and encryption on the CAN bus, and security issues with its priority scheme, it is vulnerable to various network threats. Furthermore, because the CAN bus uses a broadcast communication method without authentication, CAN messages lack source and destination addresses, allowing any node connected to the bus to obtain messages during transmission. Therefore, attackers can easily sniff out information on the bus by infiltrating a node on the bus. Attackers can intrude into or even control vehicles by injecting malicious information into the data fields of CAN messages, such as denial-of-service (DoS) attacks, fuzzy attacks, spoofing attacks, replay attacks, and masquerade attacks, which can damage nodes and vehicles and cause serious security risks.
[0003] Attacks targeting vehicle networks and controls ultimately involve attacks on communication between onboard ECUs, manifesting as abnormal traffic on the CAN bus. To address network threats on the CAN bus, the industry widely employs intrusion detection methods, utilizing Intrusion Detection Systems (IDS) to promptly detect abnormal traffic, thereby protecting the CAN bus and ensuring vehicle safety. Compared to traditional rule-based and feature-matching-based intrusion detection methods and machine learning-based methods, deep learning-based intrusion detection methods can autonomously identify complex behavioral patterns from massive amounts of raw packet data without extensive feature engineering. Furthermore, they can quickly adapt to new attack patterns and learn from them, providing more intelligent protection for onboard networks.
[0004] However, existing automotive CAN bus intrusion detection technologies still face numerous challenges in practical applications. First, there's the conflict between detection accuracy and real-time performance: while deep learning methods excel in detection accuracy, the limited computing power of automotive ECUs struggles to support the high computational demands of complex models like BERT and GPT. Second, there's the contradiction between increasingly complex attacks and limited detection dimensions: existing detection systems are mostly confined to binary classification tasks, simply categorizing detection results as "normal" or "abnormal," failing to effectively address the increasingly diverse and combined attack scenarios in automotive networks and lacking detailed information for subsequent defense. Third, there's the contradiction between the diversification of attack dimensions and the fragmentation of feature analysis: most studies analyze CAN message features such as ID, payload, and timestamps in isolation, with the utilization of CAN message timestamps limited to simple difference calculations, lacking in-depth modeling and analysis of nonlinear time interval characteristics.
[0005] In summary, existing vehicle CAN bus intrusion detection methods generally suffer from technical problems such as weak ability to extract features from non-uniform time intervals, low accuracy of multi-class detection, and high consumption of computational resources. No effective solution has yet been proposed. Summary of the Invention
[0006] The embodiments of this disclosure provide a method, system and storage medium for detecting intrusion on a vehicle CAN bus. By integrating spatial feature extraction of an autoencoder with temporal dependency modeling of a Transformer, and introducing a time smoothing algorithm and a timestamp encoding mechanism, high-precision multi-class real-time detection of intrusion behavior on a vehicle CAN bus is achieved.
[0007] According to one aspect of the present disclosure, a method for detecting intrusion into a vehicle CAN bus is provided, comprising: preprocessing acquired raw message data of a vehicle CAN bus to generate multiple message sequences; each message in each message sequence includes at least a timestamp, a CAN identifier, and a data payload; for each message in each message sequence, inputting the corresponding CAN identifier and data payload into the encoding part of an autoencoder, and extracting the spatial features of the message after dimensionality reduction and compression; performing a nonlinear mapping on the timestamp of the message using a time smoothing algorithm including logarithmic transformation to extract the time features of the message; and for each message sequence, processing the message... The spatial features of each message within the sequence are fused with the temporal location embedding vector generated based on the temporal features of each message to construct a spatiotemporal feature sequence of the message sequence. For each message sequence, the corresponding spatiotemporal feature sequence is input into a multi-head attention Transformer encoder to extract the long-distance dependencies between messages within the message sequence and generate a context feature vector for the message sequence. For each message sequence, the corresponding context feature vector is input into a classifier to output the detection result for each message sequence. The detection result is used to indicate the category of the message sequence, which includes a normal state or one of several preset attack types.
[0008] According to another aspect of the present disclosure, a storage medium is also provided, the storage medium including a stored program, wherein, when the program is executed, a processor performs any of the methods described above.
[0009] According to another aspect of the present disclosure, an in-vehicle CAN bus intrusion detection system is also provided, comprising: a preprocessing module, configured to preprocess the acquired raw message data of the in-vehicle CAN bus to generate multiple message sequences; each message in each message sequence includes at least a timestamp, a CAN identifier, and a data payload; a first feature extraction module, configured to, for each message in each message sequence, input the corresponding CAN identifier and data payload into the encoding part of an autoencoder, and extract the spatial features of the message after dimensionality reduction and compression; and extract the temporal features of the message by performing a nonlinear mapping on the timestamp of the message using a time smoothing algorithm including logarithmic transformation; and a feature fusion module, configured to, for each message sequence... The system employs a first feature extraction module, which fuses the spatial features of each message within the message sequence with a time position embedding vector generated based on the time features of each message to construct a spatiotemporal feature sequence of the message sequence. A second feature extraction module, for each message sequence, inputs the corresponding spatiotemporal feature sequence into a multi-head attention Transformer encoder to extract long-distance dependencies between messages within the message sequence, generating a context feature vector for the message sequence. A classification module, for each message sequence, inputs the corresponding context feature vector into a classifier and outputs a detection result for each message sequence. The detection result indicates the category of the message sequence, which includes a normal state or one of several preset attack types.
[0010] According to another aspect of the present disclosure, an in-vehicle CAN bus intrusion detection system is also provided, comprising: a processor; and a memory connected to the processor, configured to provide the processor with instructions for processing the following steps: preprocessing acquired raw message data of the in-vehicle CAN bus to generate multiple message sequences; each message in each message sequence includes at least a timestamp, a CAN identifier, and a data payload; for each message in each message sequence, inputting the corresponding CAN identifier and data payload into the encoding part of an autoencoder, and extracting the spatial features of the message after dimensionality reduction and compression; and nonlinearly mapping the timestamp of the message using a time smoothing algorithm including logarithmic transformation to extract the time of the message. Features: For each message sequence, the spatial features of each message within the message sequence are fused with a time position embedding vector generated based on the time features of each message to construct a spatiotemporal feature sequence of the message sequence; for each message sequence, the corresponding spatiotemporal feature sequence is input into a multi-head attention Transformer encoder to extract the long-distance dependencies between messages within the message sequence and generate a context feature vector of the message sequence; for each message sequence, the corresponding context feature vector is input into a classifier to output the detection result of each message sequence, the detection result being used to indicate the category of the message sequence, the category including a normal state or one of multiple preset attack types.
[0011] In the scenario of intrusion detection on an in-vehicle CAN bus, this application first preprocesses the original message data to generate multiple message sequences, providing a standardized input basis for subsequent feature extraction. Then, for each message in each message sequence, on the one hand, the CAN identifier and data payload are compressed using an autoencoder to extract compact spatial features, effectively reducing the computational resource consumption of the subsequent Transformer module; on the other hand, a time smoothing algorithm including logarithmic transformation is used to perform nonlinear mapping on the timestamps to extract time features, enhancing sensitivity to microsecond-level non-uniform time intervals. Next, for each message sequence, the spatial features of each message within the sequence are fused with a time position embedding vector generated based on the time features of each message to construct a spatiotemporal feature sequence, achieving unified modeling of spatiotemporal features and further strengthening the ability to extract features from non-uniform time intervals. Finally, for each message sequence, the corresponding spatiotemporal feature sequence is input into the multi-head attention Transformer encoder to extract the long-distance dependencies between messages in the sequence, generate a context feature vector, and output the detection result of each message sequence through the classifier. The detection result is used to indicate whether the sequence is in a normal state or one of a variety of preset attack types, thus achieving high-precision multi-classification detection.
[0012] Therefore, this application reduces the computational load and resource consumption of the model through dimensionality reduction compression using an autoencoder; enhances the extraction capability of non-uniform time interval features through a collaborative mechanism of time smoothing and timestamp encoding; and achieves high-precision multi-class detection through global modeling using a multi-head attention Transformer encoder. This solves the technical problems commonly found in existing automotive CAN bus intrusion detection methods, such as weak extraction capability of non-uniform time interval features, low multi-class detection accuracy, and high computational resource consumption. Attached Figure Description
[0013] The accompanying drawings, which are included to provide a further understanding of this disclosure and form part of this application, illustrate exemplary embodiments of the present disclosure and are used to explain the disclosure, but do not constitute an undue limitation thereof. In the drawings: Figure 1 This is a hardware structure block diagram of a computing device for implementing the method described in Embodiment 1 of this disclosure; Figure 2 This is a flowchart illustrating the intrusion detection method for the vehicle CAN bus according to Embodiment 1 of this disclosure; Figure 3 This is an overall architecture diagram of the vehicle CAN bus intrusion detection model based on Transformer and AE architecture as described in Embodiment 1 of this disclosure; Figure 4 This is the overall functional architecture diagram of the vehicle CAN bus intrusion detection platform according to Embodiment 1 of this disclosure; Figure 5 This is a flowchart of the detection process during platform operation according to Embodiment 1 of this disclosure; Figure 6 This is a schematic diagram of the processing flow of the data preprocessing component according to Embodiment 1 of this disclosure; Figure 7 This is a detailed structural diagram of the autoencoder AE, a single-message feature extraction component, according to Embodiment 1 of this disclosure; Figure 8 This is a schematic diagram of the internal structure and calculation process of the time-embedded Transformer (including the TSE module) according to Embodiment 1 of this disclosure; Figure 9 This is a schematic diagram illustrating the principle of the multi-head attention mechanism according to Embodiment 1 of this disclosure; Figure 10 This is a schematic diagram of the structure of an in-vehicle CAN bus intrusion detection system according to Embodiment 2 of this disclosure; and Figure 11 This is a schematic diagram of the structure of an in-vehicle CAN bus intrusion detection system according to Embodiment 3 of this disclosure. Detailed Implementation
[0014] To enable those skilled in the art to better understand the technical solutions of this disclosure, the technical solutions of the embodiments of this disclosure will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are merely some embodiments of this disclosure, and not all embodiments. Based on the embodiments of this disclosure, all other embodiments obtained by those skilled in the art without creative effort should fall within the scope of protection of this disclosure.
[0015] It should be noted that the terms "first," "second," etc., in the specification, claims, and accompanying drawings of this disclosure are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments of this disclosure described herein can be implemented in orders other than those illustrated or described herein. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion; for example, a process, method, system, product, or apparatus that comprises a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.
[0016] Example 1
[0017] According to this embodiment, a method embodiment for vehicle CAN bus intrusion detection is provided. It should be noted that the steps shown in the flowchart in the accompanying drawings can be executed in a computer system such as a set of computer-executable instructions. Although a logical order is shown in the flowchart, in some cases, the steps shown or described may be executed in a different order than that shown here.
[0018] The method embodiments provided in this example can be executed on mobile terminals, computer terminals, servers, or similar computing devices. Figure 1 A hardware block diagram of a computing device for implementing an intrusion detection method, system, and storage medium for an in-vehicle CAN bus is shown. Figure 1 As shown, a computing device may include one or more processors (processors may include, but are not limited to, microprocessors such as MCUs or programmable logic devices such as FPGAs), a memory for storing data, a transmission device for communication functions, and an input / output interface. The memory, transmission device, and input / output interface are connected to the processor via a bus. In addition, it may also include a display, keyboard, and cursor control device connected to the input / output interface. Those skilled in the art will understand that... Figure 1The structure shown is for illustrative purposes only and does not limit the structure of the aforementioned electronic device. For example, a computing device may also include... Figure 1 The more or fewer components shown, or having the same Figure 1 The different configurations shown.
[0019] It should be noted that the aforementioned one or more processors and / or other data processing circuits are generally referred to herein as "data processing circuits". These data processing circuits may be embodied, in whole or in part, in software, hardware, firmware, or any other combination thereof. Furthermore, the data processing circuits may be a single, independent processing module, or may be integrated, in whole or in part, into any other element in a computing device. As involved in the embodiments of this disclosure, the data processing circuits serve as processor control (e.g., selection of a variable resistor termination path connected to an interface).
[0020] The memory can be used to store software programs and modules of application software, such as the program instruction / data storage device corresponding to the vehicle CAN bus intrusion detection method in this embodiment of the present disclosure. The processor executes various functional applications and data processing by running the software programs and modules stored in the memory, thereby implementing the aforementioned vehicle CAN bus intrusion detection method. The memory may include high-speed random access memory, and may also include non-volatile memory, such as one or more magnetic storage devices, flash memory, or other non-volatile solid-state memory. In some instances, the memory may further include memory remotely located relative to the processor, and these remote memories can be connected to computing devices via a network. Examples of such networks include, but are not limited to, the Internet, corporate intranets, local area networks, mobile communication networks, and combinations thereof.
[0021] The transmission device is used to receive or send data via a network. Specific examples of the network described above may include a wireless network provided by the computing device's communication provider. In one example, the transmission device includes a Network Interface Controller (NIC), which can connect to other network devices via a base station to communicate with the Internet. In another example, the transmission device may be a Radio Frequency (RF) module used for wireless communication with the Internet.
[0022] The display can be, for example, a touchscreen liquid crystal display (LCD), which allows users to interact with the user interface of the computing device.
[0023] It should be noted here that, in some optional embodiments, the above... Figure 1The computing device shown may include hardware elements (including circuitry), software elements (including computer code stored on a computer-readable medium), or a combination of both hardware and software elements. It should be noted that... Figure 1 This is only one instance of a specific particular instance, and is intended to illustrate the types of components that may exist in the aforementioned computing devices.
[0024] Under the aforementioned operating environment, according to the first aspect of this embodiment, a method for detecting intrusion into an in-vehicle CAN bus is provided. This method comprises... Figure 1 The processor implementation shown. Figure 2 A flowchart illustrating the method is shown below. (Refer to...) Figure 2 As shown, the method includes: S202: Preprocess the acquired raw message data of the vehicle CAN bus to generate multiple message sequences; each message in each message sequence includes at least a timestamp, a CAN identifier, and a data payload; S204: For each message in each message sequence, the corresponding CAN identifier and data payload are input into the encoding part of the autoencoder, and the spatial features of the message are extracted after dimensionality reduction and compression; the timestamp of the message is nonlinearly mapped by a time smoothing algorithm including logarithmic transformation to extract the time features of the message; S206: For each of the message sequences, the spatial features of each message in the message sequence are fused with the time position embedding vector generated based on the time features of each message to construct the spatiotemporal feature sequence of the message sequence; S208: For each message sequence, the corresponding spatiotemporal feature sequence is input into a multi-head attention Transformer encoder to extract the long-distance dependency between messages in the message sequence and generate the context feature vector of the message sequence. S210: For each of the message sequences, the corresponding context feature vector is input to the classifier, and the detection result of each message sequence is output. The detection result is used to indicate the category of the message sequence, which includes a normal state or one of a variety of preset attack types.
[0025] Specifically, in vehicle driving or onboard system operation scenarios, when real-time safety monitoring of the vehicle CAN bus is required, the raw message data on the CAN bus is first collected in real time through the vehicle gateway interface or OBD interface, or the stored CAN log file is read. Figure 3 This diagram illustrates the overall architecture of the vehicle CAN bus intrusion detection model based on the Transformer and AE architecture described in this embodiment. Figure 3As shown, the acquired raw message data of the vehicle CAN bus is preprocessed to generate multiple message sequences. Each message in each sequence includes at least a timestamp, a CAN identifier, and a data payload (corresponding to step S202). Specifically, the continuous vehicle CAN bus message stream is divided according to a preset sliding window to generate multiple message sequences, each containing a fixed number of continuous messages. Each message in each sequence is parsed to extract the timestamp, CAN identifier (which is the arbitration domain ID, i.e., CAN ID), and data payload (i.e., the data field), which serve as the basic input for subsequent feature extraction. Through the above preprocessing, the original continuous message stream is converted into a structured message sequence, providing standardized input data for subsequent message-level feature extraction and ensuring the standardization and consistency of the model processing.
[0026] Then, for each message in each message sequence, the corresponding CAN identifier and data payload are input into the encoding part of the autoencoder, and the spatial features of the message are extracted after dimensionality reduction and compression (corresponding to the first half of step S204). Specifically, Figure 7 A detailed structural diagram of the self-encoder is shown. Combined with... Figure 7 As shown, the autoencoder includes an encoding part and a decoding part, where the encoding part maps high-dimensional input to low-dimensional latent vectors. During the intrusion detection phase, only the encoding part is used. The CAN identifier and data payload of each message are concatenated into a high-dimensional input vector, which is then input to the encoding part. After dimensionality reduction and compression, a low-dimensional latent vector is output as the spatial feature of the message. Through the dimensionality reduction and compression processing of the autoencoder, redundant information in the original message data is effectively removed, significantly reducing the input dimension and computational load of the subsequent Transformer module, thus resolving the contradiction between limited computing power and the high computational requirements of complex models in an automotive environment.
[0027] Simultaneously, for each message in each message sequence, a time smoothing algorithm incorporating logarithmic transformation is used to nonlinearly map the timestamp of the message, extracting the message's temporal features (corresponding to the latter half of step S204). Specifically, considering the extremely small and unevenly distributed arrival intervals of CAN messages, this application uses logarithmic transformation to process the normalized timestamps, amplifying minute time interval differences while suppressing the impact of abnormally large time intervals on the model. Through the nonlinear mapping of the time smoothing algorithm, the originally minimal microsecond-level time intervals are mapped to a numerical range more easily processed by neural networks, effectively solving the gradient vanishing or numerical insensitivity problems, significantly enhancing the model's sensitivity to temporal anomalies (such as dense messages caused by injection attacks), and laying the foundation for subsequent identification of time-based attack behaviors.
[0028] Secondly, for each message sequence, the spatial features of each message within the message sequence are fused with the time position embedding vector generated based on the time features of each message to construct the spatiotemporal feature sequence of the message sequence (corresponding to step S206). Specifically, Figure 8 A schematic diagram illustrating the internal structure and computational flow of a time-embedded Transformer is shown. Figure 8 As shown, for each message sequence, a time-location embedding vector is generated using a timestamp encoding (TSE) mechanism based on the temporal features of each message within the sequence and the message's position index within the sequence. This timestamp encoding mechanism encodes both the temporal features and the position index, dynamically reflecting the absolute and relative positions of the messages on the timeline. The generated time-location embedding vector is then fused with the spatial feature vectors of each message to form a fused feature vector, which is then arranged in message order to construct the spatiotemporal feature sequence of the message sequence. The time-location embedding vector generated by the timestamp encoding mechanism replaces the traditional position index encoding, solving the problem of non-uniform sampling, achieving unified modeling of spatiotemporal features, further enhancing the ability to extract features from non-uniform time intervals, and providing high-quality feature input for subsequent global dependency modeling.
[0029] Next, for each message sequence, the corresponding spatiotemporal feature sequence is input into a Multi-Head Attention Transformer Encoder to extract the long-distance dependencies between messages within the message sequence, generating the context feature vector of the message sequence (corresponding to step S208). Specifically, Figure 9 A schematic diagram illustrating the principle of multi-head attention mechanisms is shown. Combined with... Figure 8 and Figure 9 As shown, the constructed spatiotemporal feature sequence is input into a multi-head attention Transformer encoder. Multiple attention heads compute the attention weights between the feature vectors in the sequence in parallel, utilizing a multi-head self-attention mechanism to capture long-distance dependencies and global contextual information between messages within the sequence. After processing by multiple encoder layers, the output sequence's contextual feature vector (typically the average pooling of the sequence or the output of a specific token) is obtained. This vector integrates the temporal and spatial information of all messages within the sequence. Through the multi-head attention mechanism, the model can simultaneously focus on feature patterns in different subspaces of the sequence. For example, one attention head focuses on the periodic changes of a specific CAN identifier, while another attention head focuses on the changing patterns of the data payload. This enables multi-angle capture of complex attack patterns, ensuring the comprehensiveness and accuracy of sequence feature extraction.
[0030] Finally, for each message sequence, the corresponding context feature vector is input to the classifier, which outputs the detection result for each message sequence. The detection result indicates the category of the message sequence, which includes a normal state or one of several preset attack types (corresponding to step S210). Specifically, the context feature vector output by the Transformer encoder is input to the classifier. The classifier maps the feature vector to a probability distribution for each category through linear transformation and the Softmax activation function, and outputs the category with the highest probability as the detection result for that message sequence. Several preset attack types include DoS attacks, fuzzing attacks, RPM spoofing attacks, gear spoofing attacks, replay attacks, and masquerade attacks. In practical applications, when the detection result is a normal state, the system continues monitoring without triggering any alarms. When the detection result is a preset attack type, the system triggers corresponding alarms and defensive measures based on the specific attack type. For example, when a denial-of-service attack is detected, it indicates a large number of high-priority packets appearing in a short period of time. The system can record the attack log and trigger an alarm. When an ambiguity attack is detected, it indicates that random IDs and random data exist in the packets. The system can block the forwarding of abnormal packets. When a spoofing attack is detected, it indicates that the attacker is imitating the ID of a normal electronic control unit to send malicious packets. Since the attacker's hardware clock crystal oscillator has a slight deviation from the original, this method can keenly perceive this micro-time difference through a collaborative mechanism of time smoothing and timestamp encoding, thereby achieving accurate identification and triggering an alarm. Through the above multi-classification detection capabilities, the system can not only determine whether there are anomalies in the packet sequence, but also output the specific attack type, providing fine-grained attack type information for subsequent differentiated defense, thereby adopting targeted defense strategies and effectively dealing with increasingly diverse and combined attack scenarios.
[0031] Through steps S202 to S210 above, this embodiment combines spatial feature extraction from an autoencoder, spatiotemporal feature fusion of time smoothing and timestamp encoding, global dependency modeling of a multi-head attention Transformer encoder, and multi-class detection to form a lightweight, high-precision, multi-class supported vehicle CAN bus intrusion detection method. This method can effectively solve the problems of weak feature extraction capability for non-uniform time intervals, low multi-class detection accuracy, and high computational resource consumption in existing technologies.
[0032] To support the practical application of the above method, this embodiment also provides an in-vehicle CAN bus intrusion detection platform, the software architecture of which is as follows: Figure 4 As shown, the detection flowchart during platform operation is as follows: Figure 5 As shown. Combined with Figure 4 and Figure 5 As shown, the platform adopts a B / S architecture, which includes a data layer, a logic layer, and a presentation layer.
[0033] The data layer is used to store various data resources, including: log files, which store historically collected CAN message files (such as .trc files in PCAN format or .log files in Linux CAN format); model repository, which stores trained PyTorch model files (.pth format), which contain the weights of the autoencoder's encoding part and the Transformer encoder's weights; and a MySQL database, which stores user information (such as username, hash-encrypted password) and detection records.
[0034] The logic layer (server-side), serving as the backend service, is developed based on the Python Flask framework and includes the following core sub-modules: a CAN acquisition sub-module, which calls the python-can library, configures the baud rate (e.g., 500kbps), establishes a connection with the CAN interface, and reads CAN message frames in real time; a preprocessing sub-module, which implements preprocessing logic such as data cleaning, normalization, and serialization; and an inference sub-module, which loads a pre-trained PyTorch model, inputs the preprocessed message sequence tensor into the model, and obtains the detection results for each sequence. In actual testing, the platform's single-sequence inference time can be optimized to the millisecond level (approximately 1.37ms), meeting the real-time detection requirements of high-speed communication on the vehicle CAN bus. The logic layer provides API interfaces through the Flask framework for data interaction with the presentation layer.
[0035] The presentation layer, serving as the front-end interface, is developed based on the Vue.js 3 framework and provides the following functions: visualization of detection results, supporting log file upload and graphical operation for real-time detection; real-time display of the detection results (normal or specific attack type) of the currently read CAN data frames during the detection process, and summary display of the detection results after the detection is completed; log backtracking, allowing users to view historical detection records on the history page and data dashboard to analyze the time point of attack, attack type, etc.; and a historical detection log download entry, facilitating users to export detection results for offline analysis.
[0036] The data layer and the logic layer interact through file access and database access, while the logic layer and the presentation layer interact through API requests and data access.
[0037] This platform supports two working modes: real-time detection and file upload detection. Users can choose according to their actual needs. Figure 5 The flowchart of the detection process during platform operation is shown, and the specific workflow is as follows.
[0038] (1) Real-time detection mode.
[0039] After logging into the system, the user selects the "Real-time Detection" mode and clicks the "Start Detection" button. The system backend initializes the CAN interface and begins capturing raw message data from the CAN bus. Captured messages enter a sliding window buffer. Whenever the number of messages in the buffer reaches the preset window size n (i.e., the length of a message sequence), the system immediately triggers a model inference. The model detects the current message sequence and outputs the detection result: if normal, "Normal" is displayed on the front-end interface; if an attack is detected, the specific attack type is displayed (e.g., "fuzzing_attack" or "DoS_attack"). The user can manually click the "Stop Detection" button at any time to end the detection task. After detection stops, the system summarizes the detection results of all message sequences within the detection period and outputs a final detection report (statistical information on normal or various attack types). Simultaneously, all detection results and detection logs are uploaded to the database and log files for subsequent forensic analysis and auditing.
[0040] (2) File upload detection mode.
[0041] After logging into the system, the user selects the "File Upload Detection" mode and uploads a CAN message log file (e.g., a .trc file in PCAN format or a .log file in Linux CAN format). The system backend reads the messages from the file and segments them into multiple sequences according to a preset window size n. Each sequence is then subjected to model inference. For each sequence, the model outputs a detection result: if normal, it displays "Normal"; if an attack occurs, it displays the specific attack type (e.g., "DoS_attack"). After all messages have been processed, the system summarizes the detection results for all message sequences and outputs a final detection report (statistical information on normal status and various attack types). All detection results and detection logs are synchronously uploaded to the database and log files for subsequent forensic analysis.
[0042] Through these two working modes, the platform supports both online real-time monitoring in real vehicle environments and batch analysis of offline data, demonstrating good flexibility and applicability.
[0043] In addition, to achieve the physical deployment of the above software architecture, this embodiment also provides a corresponding hardware architecture. This hardware architecture includes an in-vehicle access terminal and a computing unit. The in-vehicle access terminal is used to physically connect to the vehicle's CAN bus, providing the underlying message capture capability for the data acquisition layer. Specifically, the in-vehicle access terminal can use a USB-CAN adapter supporting the SocketCAN protocol (e.g., PEAK PCAN-USB) or an embedded CAN controller (e.g., a development board based on STM32 or NXP chips). The terminal connects directly to the CAN High / CAN Low twisted-pair cable behind the vehicle gateway via a pierced wire clamp to achieve electrical connection with the CAN bus, ensuring real-time capture of the underlying CAN message data. The computing unit is used to deploy various functional modules of the logic layer, including CAN message acquisition, preprocessing, and model inference. The computing unit can be the in-vehicle infotainment system host, the autonomous driving domain controller, or a laptop computer used for testing. To meet the real-time inference requirements of the Transformer model in an in-vehicle environment, the computing unit should have a certain parallel computing capability and can be configured with an NVIDIA GPU to accelerate model inference, such as using a Jetson Orin embedded module or an RTX series discrete graphics card. Through the synergy of the aforementioned hardware and software architectures, the platform can capture CAN bus messages in real time and efficiently execute intrusion detection algorithms in the vehicle environment, meeting the engineering requirements for real-vehicle deployment.
[0044] As described in the background section above, existing automotive CAN bus intrusion detection technologies still face numerous challenges in practical applications. Firstly, there is a conflict between detection accuracy and real-time performance: while deep learning methods excel in detection accuracy, the limited computing power of automotive ECUs struggles to support the high computational load demands of complex models such as BERT and GPT. Secondly, there is a conflict between the increasing complexity of attacks and the limited scope of detection: existing detection systems are mostly limited to binary classification tasks, simply categorizing detection results as "normal" or "abnormal," which is insufficient to effectively address the increasingly diverse and combined attack scenarios in automotive networks and fails to provide more detailed information for subsequent defense. Thirdly, there is a conflict between the diversification of attack dimensions and the fragmentation of feature analysis: most studies analyze CAN message features such as ID, payload, and timestamps in isolation, and the utilization of CAN message timestamps is limited to simple difference calculations, lacking in-depth modeling and analysis of nonlinear time interval characteristics.
[0045] In view of this, this application first preprocesses the original message data to generate multiple message sequences, providing a standardized input basis for subsequent feature extraction. Then, for each message in each message sequence, on the one hand, the CAN identifier and data payload are compressed by the encoding part of the autoencoder to extract compact spatial features, effectively reducing the computational resource consumption of the subsequent Transformer module; on the other hand, a time smoothing algorithm including logarithmic transformation is used to perform nonlinear mapping on the timestamp to extract time features and enhance the sensitivity to microsecond-level non-uniform time intervals. Next, for each message sequence, the spatial features of each message in the sequence are fused with the time position embedding vector generated based on the time features of each message to construct the spatiotemporal feature sequence of the sequence, realizing unified modeling of spatiotemporal features and further enhancing the ability to extract features of non-uniform time intervals. Finally, for each message sequence, the corresponding spatiotemporal feature sequence is input into the multi-head attention Transformer encoder to extract the long-distance dependencies between messages in the sequence, generate a context feature vector, and output the detection result of each message sequence through the classifier. The detection result is used to indicate whether the sequence is in a normal state or one of a variety of preset attack types, thus achieving high-precision multi-classification detection.
[0046] Therefore, this application reduces the computational load and resource consumption of the model through dimensionality reduction compression using an autoencoder; enhances the extraction capability of non-uniform time interval features through a collaborative mechanism of time smoothing and timestamp encoding; and achieves high-precision multi-class detection through global modeling using a multi-head attention Transformer encoder. This solves the technical problems commonly found in existing automotive CAN bus intrusion detection methods, such as weak extraction capability of non-uniform time interval features, low multi-class detection accuracy, and high computational resource consumption.
[0047] Optionally, the original message data is a continuous vehicle CAN bus message stream; and the operation of preprocessing the acquired original vehicle CAN bus message data to generate multiple message sequences includes: dividing the vehicle CAN bus message stream according to a preset sliding window size to generate multiple message sequences; parsing each message in the message sequence to extract the timestamp, CAN identifier, and data payload; converting the CAN identifier and the data payload from hexadecimal format to decimal numerical vectors; padding data payloads that are less than a preset byte length with a specified value; filtering out messages whose CAN identifier value exceeds a preset threshold; and performing a normalization operation on the timestamp by subtracting the timestamp of the first message in the sequence or the global minimum timestamp.
[0048] Specifically, during the operation of the vehicle-mounted CAN bus, the raw message data is transmitted in the form of a continuous stream. In order to convert the raw message into a standardized input format acceptable to the model, this application designs a data preprocessing component to perform preprocessing operations such as message sequence segmentation, field parsing, format conversion, data cleaning and normalization. Figure 6 A schematic diagram of the processing flow of this data preprocessing component is shown.
[0049] like Figure 6 As shown, the data preprocessing component first divides the continuous vehicle CAN bus message stream into multiple message sequences according to a preset sliding window size. For example, the window size can be set to 29 for the Car Hacking dataset and 15 for the ROAD dataset. Each sequence contains a fixed number of consecutive messages, serving as the basic unit for a single inference operation of the model. The data preprocessing component parses each message in each message sequence, extracting three core fields: timestamp, CAN identifier, and data payload. The timestamp records the message's arrival time, the CAN identifier identifies the message's priority and source, and the data payload carries specific control commands or sensor data.
[0050] After parsing, the data preprocessing component formats each field. For the CAN identifier and data payload, they are converted from hexadecimal format to decimal numerical vectors so that the neural network model can process them directly. For the data payload, since the CAN data field supports a maximum of 8 bytes, messages shorter than 8 bytes are padded with specified values (e.g., 00) to ensure that the payload length of all messages is uniform, facilitating subsequent concatenation into a fixed-dimensional input vector. For the CAN identifier, messages with identifier values exceeding a preset threshold are filtered out. For example, diagnostic or network management messages with ID values greater than 0x700 are filtered out. These messages occur very infrequently under normal driving conditions and are prone to false alarms; filtering reduces the interference of noisy data on the detection model. For the timestamp, a normalization operation is performed, i.e., subtracting the timestamp of the first message in the sequence or the global minimum timestamp to obtain a relative time value, thereby eliminating the influence of excessively large absolute time values and allowing the model to focus more on the time interval changes between messages rather than absolute time.
[0051] Thus, through the aforementioned operations of the data preprocessing component, the continuous vehicle CAN bus message stream is converted into a structured, standardized message sequence. Each message in each sequence contains a normalized timestamp, a decimal CAN identifier, and a uniform-length decimal data payload. This provides a standardized input basis for subsequent message-level feature extraction, ensuring the consistency and standardization of the model's input data.
[0052] Optionally, the encoding part of the autoencoder includes an input layer, an encoding layer, and a latent layer; the autoencoder is pre-trained unsupervised by minimizing the mean square error between the input vector and the reconstructed vector; and, for each message in each message sequence, the operation of inputting the corresponding CAN identifier and data payload into the encoding part of the autoencoder, and extracting the spatial features of the message after dimensionality reduction and compression includes: for each message in each message sequence, concatenating the CAN identifier and data payload of the message into an input vector, inputting it into the encoding part of the autoencoder, and outputting the corresponding spatial vector as the spatial features of the message after mapping by the encoding layer.
[0053] Specifically, in order to extract the spatial features of a single message and reduce the data dimensionality to alleviate the computational burden of subsequent models, this application designs an autoencoder component for dimensionality reduction and compression of the CAN identifier and data payload in the message. Figure 7 A detailed structural diagram of the self-encoder component is shown. (For example...) Figure 7 As shown, the autoencoder component includes an encoding part and a decoding part, wherein the encoding part further includes an input layer, an encoding layer, and a latent layer.
[0054] During the training phase, the autoencoder component is pre-trained using unsupervised learning to learn the compressed representation of normal packets. Specifically, the continuously arriving packet stream is segmented into packet sequences. n is the number of messages in the sequence, and each sequence is associated with a tag. If the sequence contains at least one attack message, then Mark it as the corresponding attack type; otherwise mark it as normal.
[0055] message sequence Specifically, this involves: CAN ID ( The raw data is usually in hexadecimal (e.g., 0x160). During processing, it is converted to a decimal value. Each ID is then split into a 4-byte vector representation (padded with 0s at the highest bits if necessary), for example... (Byte splitting from a decimal perspective). Data payload ( The maximum length is 8 bytes. For messages shorter than 8 bytes, padding with 0x00 is used. Similarly, hexadecimal data is converted to a vector of 8 decimal values. For example, the data 00 00 00 00 00 00 00 00 is converted to [0, 0, 0, 0, 0, 0, 0, 0]. The original timestamp is usually a Unix timestamp (e.g., 1516183885.123456). To eliminate the impact of excessively large absolute time values, normalization is performed: ,in This could be the first timestamp of the current sequence or the start timestamp of the entire dataset. Additionally, packets with ID values greater than 0x700 are filtered out; these are typically diagnostic or network management packets, which occur very infrequently under normal driving conditions and are prone to false alarms.
[0056] Next, the CAN identifier and data payload of the message sample are concatenated into an input vector, which is then fed into the encoding part. After being mapped layer by layer by the encoding layer, a low-dimensional latent vector is output. The decoding part reconstructs this latent vector back to the original input dimension, and uses minimizing the mean squared error between the input vector and the reconstructed vector as the training objective, forcing the encoding part to learn the optimal compressed representation that retains key information. For example, in a practical implementation, a 4-byte CAN identifier and an 8-byte data payload can be concatenated into a 12-dimensional input vector, which is then compressed into a 10-dimensional latent vector by the encoding part, and finally reconstructed back into 12 dimensions by the decoding part. Furthermore, during the model pre-training stage, the mean squared error (MSE) is used as the loss function. ,in This is the output of the decoder. Through unsupervised learning, the encoder is forced to learn the optimal compressed representation of the message.
[0057] Furthermore, in actual CAN bus data collection, the number of normal messages is usually far greater than that of attack messages, with a ratio that can reach 1000:1. If such an imbalanced dataset is used directly for training, the model will tend to predict all samples as normal, leading to a significant drop in the detection rate of attack samples. To address this issue, this embodiment introduces the Synthetic Minority Over-sampling Technique (SMOTE) to resample the training dataset before model training. Specifically, for each minority class sample (i.e., the attack message sequence), its k nearest neighbors in the feature space are calculated, and then random interpolation is performed on the lines connecting the current sample and each nearest neighbor to generate a new synthetic sample. Through this operation, new attack samples are continuously generated until the number of samples in each class reaches a balanced state. Moreover, after SMOTE resampling, the number of normal samples and attack samples of each class in the training dataset tends to be balanced, thereby effectively avoiding the model's bias towards the majority class and significantly improving the detection capability of rare attack types.
[0058] During the intrusion detection phase, only the encoding part of the autoencoder component is used, and the weights of the trained encoding part are fixed. For each message in each message sequence, the CAN identifier and data payload of the message are concatenated into an input vector, which is then input to the encoding part of the autoencoder component. After being mapped layer by layer through the encoding layer, the corresponding spatial vector is output from the latent layer as the spatial feature of the message.
[0059] Thus, by using the dimensionality reduction and compression processing of the autoencoder component, the high-dimensional message input is mapped to a low-dimensional compact feature representation, effectively removing redundant information in the original message data, significantly reducing the input dimension and computational load of the subsequent Transformer module, and resolving the contradiction between limited computing power and the high computational requirements of complex models in the vehicle environment.
[0060] Optionally, the calculation formula for the time smoothing algorithm including logarithmic transformation is: ; Where i is the index of the message in the message sequence. To represent the normalized original timestamp of the i-th message, As a smoothing factor, This represents the time characteristics output after processing by the time smoothing algorithm.
[0061] Specifically, considering the extremely small (usually microseconds) and uneven distribution of CAN message arrival intervals, this application designs a time smoothing component to perform nonlinear mapping on the timestamps of messages in order to enhance the model's sensitivity to timing anomalies. Figure 8 A schematic diagram of the internal structure and computational process of a time-embedded Transformer is shown, including the processing flow of the time smoothing component.
[0062] like Figure 8 As shown, the time smoothing component uses a time smoothing algorithm involving logarithmic transformation to process the normalized original timestamps. The calculation formula of this algorithm is shown above: for the first message in the message sequence (i.e., i=0), its time feature output is 0; for subsequent messages (i.e., i>0), the normalized original timestamps are processed by... Divide by smoothing factor Add 1, take the logarithm to the base 2, and then take the absolute value to obtain the output time feature. .
[0063] In practical applications, smoothing factor This is used to adjust the sensitivity of the time interval. Experiments show that for the CarHacking dataset (with a high sampling frequency), Pick The best results are achieved; for the ROAD dataset, Pick The best results were achieved. This transformation not only amplifies small time differences but also suppresses the impact of abnormally large time intervals (such as the first message after the bus goes to sleep) on the model through a logarithmic function.
[0064] This logarithmic transformation can amplify minute differences in time intervals: when the message interval is extremely small, The logarithmic transformation maps the larger intervals of data to a more sensitive region within the numerical range. When the message intervals are abnormally large, the logarithmic function can suppress the impact of these values on the model, preventing individual extreme time intervals from dominating the model's learning process. For example, for a 500kbps CAN bus, the interval between adjacent messages is typically several hundred microseconds. After the aforementioned logarithmic transformation, the originally very small microsecond-level time intervals are mapped to a numerical range that is easier for neural networks to process.
[0065] Thus, by using the nonlinear mapping processing of the time smoothing component, the problem of gradient vanishing or numerical insensitivity is effectively solved, and the model's sensitivity to time anomalies is significantly enhanced, laying the foundation for subsequent identification of time-based attack behaviors (such as dense packets caused by injection attacks, micro-time deviations caused by spoofing attacks, etc.).
[0066] Optionally, for each message sequence, the operation of fusing the spatial features of each message within the message sequence with a time-location embedding vector generated based on the time features of each message to construct a spatiotemporal feature sequence of the message sequence includes: for each message in the message sequence, generating a time-location embedding vector based on the time features of the message and the position index of the message in the message sequence using a timestamp encoding mechanism; for the feature dimension index... and The timestamp encoding mechanism calculates the time position embedding vector using the following formula. : ; ; Where p is the position index of the message in the message sequence. The time feature of the message is d, and the model embedding dimension is d (12 in this embodiment, i.e., 10 dimensions of AE output + original preserved features or padding dimension); this encoding method allows the model to know both "which message this is" and "when this message arrived".
[0067] Then, the spatial features of the message are added to the corresponding temporal position embedding vector to construct the fusion features of the message; the fusion features of each message in the message sequence are arranged in the message order to form the spatiotemporal feature sequence of the message sequence.
[0068] Specifically, in order to unify the modeling of spatial and temporal features and enable the model to simultaneously perceive the content information and timing information of the message, this application designs a feature fusion component to construct the spatiotemporal feature sequence of the message sequence. Figure 8 A schematic diagram of the internal structure and computational process of a time-embedded Transformer is shown, including the processing flow of the feature fusion component.
[0069] like Figure 8 As shown, the feature fusion component first performs a feature fusion analysis on each message in the message sequence based on the message's temporal features. The message's position index p in the sequence is used to generate a time-location embedding vector through a timestamp encoding mechanism. This timestamp encoding mechanism employs the aforementioned sine-cosine function formula, where d is the model embedding dimension and j is the dimension index. Unlike traditional index-based position encoding, this timestamp encoding mechanism incorporates physical time information. Combined with the sequence position information p, it dynamically reflects the absolute and relative position of the message on the time axis. When j takes different values, the sine and cosine functions have different wavelengths, enabling encoding in different dimensions to capture temporal variation patterns at different scales.
[0070] After generating the temporal location embedding vector, the feature fusion component adds and fuses the spatial features of the message with the corresponding temporal location embedding vector to construct the fused features of the message. Through the addition operation, spatial features and temporal location information are embedded into the same feature space, achieving a unified expression of spatiotemporal features. Subsequently, the feature fusion component arranges the fused features of each message in the message sequence according to the original order of the messages in the sequence, forming the spatiotemporal feature sequence of the message sequence.
[0071] Thus, through the aforementioned processing of the feature fusion component, spatial features are fused with temporal location embedding vectors generated based on temporal features, replacing the traditional positional encoding method based solely on indices. This fusion mechanism not only preserves the content information of the message but also introduces physical time information, solving the problem of non-uniform sampling and achieving unified modeling of spatiotemporal features. This provides high-quality feature input for subsequent global dependency modeling of the Transformer encoder.
[0072] Optionally, for each message sequence, the operation of inputting the corresponding spatiotemporal feature sequence into a multi-head attention Transformer encoder to extract the long-distance dependencies between messages within the message sequence and generate the context feature vector of the message sequence includes: inputting the spatiotemporal feature sequence into a multi-head attention Transformer encoder, the multi-head attention Transformer encoder comprising multiple encoder layers connected in sequence, each encoder layer comprising a multi-head attention sub-layer and a feedforward neural network sub-layer; calculating the attention weights between each feature vector in the spatiotemporal feature sequence in parallel through the multi-head attention sub-layer of the current encoder layer, and capturing the long-distance dependencies between messages based on the attention weights using a self-attention mechanism to obtain an attention output; inputting the attention output into the feedforward neural network sub-layer of the current encoder layer for nonlinear transformation, and adding the transformation result to the input of the encoder layer through a residual connection, and then performing layer normalization processing to obtain the output of the current encoder layer; using the output of the current encoder layer as the input of the next encoder layer, and after processing by each encoder layer in sequence, using the output of the last encoder layer as the context feature vector of the message sequence.
[0073] Specifically, in order to capture long-distance dependencies and global context information within the message sequence, this application designs a sequence feature extraction component, which adopts a multi-head attention Transformer encoder architecture. Figure 8 This diagram illustrates the internal structure and computational flow of a time-embedded Transformer. Figure 9 A schematic diagram illustrating the principle of multi-head attention mechanisms is shown. (For example...) Figure 8 and Figure 9 As shown, the sequence feature extraction component first inputs the constructed spatiotemporal feature sequence into a multi-head attention Transformer encoder. This encoder includes multiple encoder layers connected in sequence (several layers are shown exemplarily in the figure), and each encoder layer further includes a multi-head attention sub-layer and a feedforward neural network sub-layer.
[0074] The input to the multi-head attention Transformer encoder is the feature extracted by the AE. Position embedding with TSE generation Add them together. Among them, the settings are... A point of attention (e.g.) Each head is calculated independently. (Query) (Key) (Value) matrix.
[0075] ; Multi-head mechanisms allow models to focus on features in different subspaces of a sequence simultaneously. For example, one head can focus on the periodicity of a specific ID, while another head can focus on the changing patterns of the data payload.
[0076] In the multi-head attention sublayer, multiple parallel attention heads calculate the attention weights (i.e., relevance weights, or attention scores) between each feature vector in the spatiotemporal feature sequence. Each attention head independently generates a query matrix, a key matrix, and a value matrix, calculates the attention output using the scaled dot product attention formula, and then concatenates and linearly transforms the outputs of all attention heads. Based on the calculated attention weights, the self-attention mechanism can capture long-distance dependencies between messages within the sequence. That is, regardless of how far apart two messages are in the sequence, as long as they are related, the model can directly calculate their attention weights, thereby establishing a direct dependency. Through the multi-head mechanism, the model can simultaneously focus on feature patterns in different subspaces of the sequence. For example, one attention head can focus on the periodic changes of a specific CAN identifier, while another attention head can focus on the changing patterns of the data payload.
[0077] Subsequently, the output of the multi-head attention sub-layer is fed into a feed-forward network (FFN) sub-layer for nonlinear transformation. The feed-forward network sub-layer typically consists of two linear transformations and a nonlinear activation function (such as ReLU) to further extract deeper features from the attention output. After each sub-layer, residual connections and layer normalization are applied: the input and output of the current sub-layer are added, followed by layer normalization. Residual connections allow gradients to flow directly through the deep network, effectively preventing the vanishing gradient problem; layer normalization stabilizes the training process and accelerates model convergence.
[0078] The output of the current encoder layer (i.e., the result after layer normalization) serves as the input to the next encoder layer, and this process continues through all encoder layers in sequence. The output of the last encoder layer is the final output of the entire encoder, serving as the context feature vector for the message sequence. This context feature vector integrates the spatial and temporal features of all messages within the sequence and implies long-range dependencies between messages. In this embodiment, the number of encoder layers is set to 6.
[0079] Thus, through the multi-head attention Transformer encoder processing of the sequence feature extraction component, the model can compute the dependencies between all positions in the sequence in parallel, effectively capturing long-distance dependencies and global context information between messages. At the same time, the multi-head mechanism enables multi-angle capture of complex attack patterns, providing rich feature representations for subsequent classification decisions.
[0080] Optionally, the classifier includes a fully connected layer and a Softmax activation function; and, for each message sequence, the operation of inputting the corresponding context feature vector into the classifier and outputting the detection result of each message sequence includes: inputting the context feature vector into the fully connected layer for linear transformation to obtain an output value equal to the preset number of categories; converting the output value into a probability distribution through the Softmax activation function, and outputting the category with the highest probability as the detection result of the message sequence.
[0081] Specifically, to map the context feature vector output by the sequence feature extraction component to specific detection categories, this application designs a classification component. This classifier includes a fully connected layer and a Softmax activation function. The classification component first inputs the context feature vector output by the Transformer encoder into the fully connected layer. The fully connected layer performs a linear transformation on the context feature vector, mapping it to the category space and outputting a vector with a dimension equal to the preset number of categories, where each dimension corresponds to the original score of one category. The preset number of categories is set according to actual detection needs, including normal states and various preset attack types (e.g., denial-of-service attacks, fuzzy attacks, spoofing attacks, replay attacks, disguise attacks, etc.). Therefore, the number of output values equals "1 (normal) + number of attack types". Furthermore, during the training phase, the classification component uses the cross-entropy loss function for training.
[0082] Subsequently, the classification component transforms the raw score vector output by the fully connected layer into a probability distribution using the Softmax activation function. The Softmax function exponentially normalizes the raw score for each class, ensuring that the sum of the output probabilities for all classes is 1, and that the probability value for each class is between 0 and 1. The transformed probability distribution intuitively reflects the confidence level of the current message sequence belonging to each class.
[0083] Finally, the classification component outputs the category with the highest probability as the detection result for the packet sequence. For example, if the probability of the normal state is the highest, "normal" is output; if the probability of a certain attack type is the highest, the corresponding attack type label is output. In practical applications, when the detection result is a normal state, the system continues monitoring without triggering an alarm; when the detection result is a certain attack type, the system executes corresponding defense measures according to preset policies, such as recording attack logs, sending alarms to the cloud SOC, or blocking the forwarding of packets with specific IDs at the gateway.
[0084] Therefore, through the fully connected layer and Softmax activation function of the classification component, the context feature vector is transformed into a clear category determination result, realizing an end-to-end mapping from the message sequence to the specific detection category. This classifier supports multi-class output, providing fine-grained attack type information for subsequent differentiated defense, effectively solving the problem of existing technologies having a single detection dimension and only being able to distinguish between normal and abnormal. Furthermore, the detection principles of several representative attack types are explained below: (1) Denial-of-Service Attack Detection. A denial-of-service attack is characterized by a large number of high-priority CAN identifiers (e.g., 0x000) appearing in a short period of time. This dense message flow causes time intervals... It exhibits an extremely small numerical distribution, and the identifier space features extracted by the autoencoder are also locked onto specific values. The multi-head attention Transformer encoder can easily capture this extreme temporal anomaly pattern, thereby accurately identifying denial-of-service attacks.
[0085] (2) Detection of fuzzy attacks. In a fuzzy attack, the attacker injects random identifiers and random data payloads into the CAN bus. The compression mapping of the identifiers and data payloads by the autoencoder component generates a potential space vector that is completely different from the normal message. Combined with the global context modeling of the Transformer encoder, the system can quickly identify random sequences that do not conform to the normal communication protocol specifications, thus achieving accurate detection of fuzzy attacks.
[0086] (3) Detection of spoofing attacks. Spoofing attacks are the most difficult type of attack to detect. Attackers stop the normal transmission of electronic control units and impersonate their identifiers to send malicious data. Although the identifier is legitimate, the clock crystal of the attacker's hardware often has a slight deviation (clock offset) from the original electronic control unit, and the micro-timing of the message transmission (jitter) is different from the normal state. The time smoothing algorithm introduced in this application amplifies these microsecond-level time differences. Combined with the timestamp encoding mechanism, it enables the Transformer encoder to keenly perceive that "although the identifier is correct, the arrival time of the message does not conform to the normal pattern", thereby accurately identifying spoofing attacks.
[0087] Based on the above detection mechanism, this method can effectively address diverse and complex vehicle CAN bus attack scenarios, providing comprehensive protection for vehicle network security.
[0088] In summary, the beneficial effects of this application are as follows: (1) High-precision multi-class detection capability: By integrating the spatial feature extraction of the autoencoder and the global temporal modeling of the Transformer, this application can not only identify simple attack types such as denial-of-service attacks, but also accurately detect attack types with complex temporal dependence features such as spoofing attacks and replay attacks, thus realizing high-precision multi-class detection of intrusion behavior of vehicle CAN bus.
[0089] (2) Innovative time feature processing mechanism: This application introduces a time smoothing algorithm and a timestamp encoding mechanism. It performs nonlinear mapping on microsecond-level non-uniform time intervals through logarithmic transformation, and generates a position embedding vector that integrates physical time information based on the smoothed time features. This overcomes the shortcomings of traditional models in effectively handling non-uniform time intervals of CAN bus and significantly improves the sensitivity to time-based abnormal behavior.
[0090] (3) Lightweight and efficient model: This application uses an autoencoder to reduce the dimension of the input message data, effectively reducing the input dimension and model parameters of the Transformer module, and significantly reducing the computational load. The measured single-sequence inference time can reach the millisecond level (about 1.37ms), which can meet the real-time detection requirements of high-speed communication (such as 500kbps) of vehicle CAN bus.
[0091] (4) Data imbalance handling: This application introduces synthetic minority class oversampling technology during the training phase, and generates new attack samples through interpolation to balance the number of each class. This effectively solves the model bias problem caused by the fact that there are far more normal samples than attack samples, and improves the detection rate of rare attack types.
[0092] (5) The system is highly practical: This application adopts a B / S architecture design, which decouples the front-end display from the back-end calculation. It supports two working modes: offline log upload and analysis and online real-time detection. This is convenient for security researchers to conduct offline data analysis and model verification, and also convenient for automotive engineers to conduct real-time safety monitoring in the real vehicle environment. It has good engineering applicability and user-friendliness.
[0093] Furthermore, according to this embodiment, a storage medium is also provided. The storage medium includes a stored program, wherein, during program execution, a processor executes any of the methods described above.
[0094] It should be noted that, for the sake of simplicity, the foregoing method embodiments are all described as a series of actions. However, those skilled in the art should understand that this application is not limited to the described order of actions, as some steps may be performed in other orders or simultaneously according to this application. Furthermore, those skilled in the art should also understand that the embodiments described in the specification are preferred embodiments, and the actions and modules involved are not necessarily essential to this application.
[0095] Through the above description of the embodiments, those skilled in the art can clearly understand that the methods according to the above embodiments can be implemented by means of software plus necessary general-purpose hardware platforms. Of course, they can also be implemented by hardware, but in many cases the former is a better implementation method. Based on this understanding, the technical solution of this application, in essence, or the part that contributes to the prior art, can be embodied in the form of a software product. This computer software product is stored in a storage medium (such as ROM / RAM, magnetic disk, optical disk), and includes several instructions to cause a terminal device (which may be a mobile phone, computer, server, or network device, etc.) to execute the methods described in the various embodiments of this application.
[0096] Example 2
[0097] Figure 10 An in-vehicle CAN bus intrusion detection system according to this embodiment is shown, which corresponds to the method described according to Embodiment 1. Reference Figure 10 As shown, the system includes: a preprocessing module 1010, used to preprocess the acquired raw message data of the vehicle CAN bus to generate multiple message sequences; each message in each message sequence includes at least a timestamp, a CAN identifier, and a data payload; a first feature extraction module 1020, used to input the corresponding CAN identifier and data payload into the encoding part of the autoencoder for each message in each message sequence, and extract the spatial features of the message after dimensionality reduction and compression; and to extract the temporal features of the message by performing a nonlinear mapping on the timestamp of the message using a time smoothing algorithm including logarithmic transformation; and a feature fusion module 1030, used to fuse the features of each message in each message sequence. Spatial features are fused with temporal location embedding vectors generated based on the temporal features of each message to construct a spatiotemporal feature sequence of the message sequence; a second feature extraction module 1040 is used to input the corresponding spatiotemporal feature sequence to a multi-head attention Transformer encoder for each message sequence, extract the long-distance dependencies between messages in the message sequence, and generate a context feature vector of the message sequence; a classification module 1050 is used to input the corresponding context feature vector to a classifier for each message sequence, and output the detection result of each message sequence, wherein the detection result is used to indicate the category of the message sequence, and the category includes a normal state or one of a variety of preset attack types.
[0098] It should be noted that the vehicle CAN bus intrusion detection system provided in this embodiment can realize all the functions and steps in the above method embodiments, solve the same technical problems, and achieve the same technical effects. The similarities will not be repeated here.
[0099] Therefore, according to this embodiment, this application reduces the model's computational load and resource consumption through dimensionality reduction compression using an autoencoder; enhances the extraction capability of non-uniform time interval features through a collaborative mechanism of time smoothing and timestamp encoding; and achieves high-precision multi-class detection through global modeling using a multi-head attention Transformer encoder. This solves the technical problems commonly found in existing automotive CAN bus intrusion detection methods, such as weak extraction capability of non-uniform time interval features, low multi-class detection accuracy, and high computational resource consumption.
[0100] Example 3
[0101] Figure 11 An in-vehicle CAN bus intrusion detection system according to this embodiment is shown, which corresponds to the method described according to Embodiment 1. Reference Figure 11 As shown, the system includes: a processor 1110; and a memory 1120, connected to the processor 1110, for providing the processor 1110 with instructions to perform the following processing steps: preprocessing the acquired raw message data of the vehicle CAN bus to generate multiple message sequences; each message in each message sequence includes at least a timestamp, a CAN identifier, and a data payload; for each message in each message sequence, inputting the corresponding CAN identifier and data payload into the encoding part of the autoencoder, and extracting the spatial features of the message after dimensionality reduction and compression; performing a nonlinear mapping on the timestamp of the message using a time smoothing algorithm including logarithmic transformation to extract the time features of the message; for each For each message sequence, the spatial features of each message within the message sequence are fused with a time position embedding vector generated based on the time features of each message to construct a spatiotemporal feature sequence of the message sequence. For each message sequence, the corresponding spatiotemporal feature sequence is input into a multi-head attention Transformer encoder to extract the long-distance dependencies between messages within the message sequence and generate a context feature vector of the message sequence. For each message sequence, the corresponding context feature vector is input into a classifier to output a detection result for each message sequence. The detection result is used to indicate the category of the message sequence, which includes a normal state or one of several preset attack types.
[0102] It should be noted that the vehicle CAN bus intrusion detection system provided in this embodiment can realize all the functions and steps in the above method embodiments, solve the same technical problems, and achieve the same technical effects. The similarities will not be repeated here.
[0103] Therefore, according to this embodiment, this application reduces the model's computational load and resource consumption through dimensionality reduction compression using an autoencoder; enhances the extraction capability of non-uniform time interval features through a collaborative mechanism of time smoothing and timestamp encoding; and achieves high-precision multi-class detection through global modeling using a multi-head attention Transformer encoder. This solves the technical problems commonly found in existing automotive CAN bus intrusion detection methods, such as weak extraction capability of non-uniform time interval features, low multi-class detection accuracy, and high computational resource consumption.
[0104] The sequence numbers of the embodiments in this application are for descriptive purposes only and do not represent the superiority or inferiority of the embodiments.
[0105] In the above embodiments of this application, the descriptions of each embodiment have different focuses. For parts not described in detail in a certain embodiment, please refer to the relevant descriptions of other embodiments.
[0106] In the several embodiments provided in this application, it should be understood that the disclosed technical content can be implemented in other ways. The system embodiments described above are merely illustrative; for example, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be through some interfaces, or indirect coupling or communication connection between units or modules, and may be electrical or other forms.
[0107] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.
[0108] Furthermore, the functional units in the various embodiments of this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit.
[0109] If the integrated unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of this application, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of this application. The aforementioned storage medium includes various media capable of storing program code, such as a USB flash drive, read-only memory (ROM), random access memory (RAM), portable hard drive, magnetic disk, or optical disk.
[0110] The above description is only a preferred embodiment of this application. It should be noted that for those skilled in the art, several improvements and modifications can be made without departing from the principle of this application, and these improvements and modifications should also be considered within the scope of protection of this application.
Claims
1. A method for detecting intrusion into a vehicle-mounted CAN bus, characterized in that, include: The acquired raw message data from the vehicle CAN bus is preprocessed to generate multiple message sequences; Each message in each of the aforementioned message sequences includes at least a timestamp, a CAN identifier, and a data payload; For each message in each message sequence, the corresponding CAN identifier and data payload are input into the encoding part of the autoencoder, and the spatial features of the message are extracted after dimensionality reduction and compression. The time features of the message are extracted by nonlinearly mapping the timestamp of the message using a time smoothing algorithm that includes logarithmic transformation. For each message sequence, the spatial features of each message in the message sequence are fused with the time position embedding vector generated based on the time features of each message to construct the spatiotemporal feature sequence of the message sequence; For each message sequence, the corresponding spatiotemporal feature sequence is input into a multi-head attention Transformer encoder to extract the long-distance dependencies between messages in the message sequence and generate the context feature vector of the message sequence. For each message sequence, the corresponding context feature vector is input into the classifier, and the detection result of each message sequence is output. The detection result is used to indicate the category of the message sequence, which includes a normal state or one of a variety of preset attack types.
2. The method according to claim 1, characterized in that, The original message data is a continuous stream of vehicle CAN bus messages; Furthermore, the process of preprocessing the acquired raw message data from the vehicle's CAN bus to generate multiple message sequences includes: The vehicle CAN bus message stream is divided according to a preset sliding window size to generate multiple message sequences; Each message in the message sequence is parsed to extract the timestamp, CAN identifier, and data payload; Convert the CAN identifier and the data payload from hexadecimal format to a decimal numerical vector. Pad the data payload that is less than the preset byte length with a specified value; Filter out messages whose CAN identifier value exceeds a preset threshold; Normalization is performed on the timestamp by subtracting the timestamp of the first message in the sequence or the global minimum timestamp.
3. The method according to claim 1, characterized in that, The autoencoder's encoding part includes an input layer, an encoding layer, and a latent layer; the autoencoder is pre-trained unsupervised by minimizing the mean square error between the input vector and the reconstructed vector. Furthermore, for each message in each message sequence, the operation of inputting the corresponding CAN identifier and data payload into the encoding part of the autoencoder, and extracting the spatial features of the message after dimensionality reduction and compression includes: For each message in each message sequence, the CAN identifier and data payload of the message are concatenated into an input vector, which is then input to the encoding part of the autoencoder. After mapping by the encoding layer, the corresponding spatial vector is output as the spatial feature of the message.
4. The method according to claim 1, characterized in that, The calculation formula for the time smoothing algorithm that includes logarithmic transformation is as follows: ; Where i is the index of the message in the message sequence. To represent the normalized original timestamp of the i-th message, As a smoothing factor, This represents the time characteristics output after processing by the time smoothing algorithm.
5. The method according to claim 1, characterized in that, For each of the message sequences, the operation of fusing the spatial features of each message within the message sequence with the time position embedding vector generated based on the time features of each message to construct the spatiotemporal feature sequence of the message sequence includes: For each message in the message sequence, a time-location embedding vector is generated based on the message's time characteristics and its position index in the message sequence using a timestamp encoding mechanism. The timestamp encoding mechanism calculates the time-location embedding vector using the following formula: ; ; Where p is the position index of the message in the message sequence. Here, d represents the time feature of the message, j represents the model embedding dimension, and j represents the dimension index. The spatial features of the message are added to the corresponding temporal location embedding vector to construct the fusion features of the message; The fusion features of each message in the message sequence are arranged in the order of the messages to form the spatiotemporal feature sequence of the message sequence.
6. The method according to claim 1, characterized in that, For each of the aforementioned message sequences, the corresponding spatiotemporal feature sequence is input into a multi-head attention Transformer encoder to extract long-distance dependencies between messages within the message sequence and generate a context feature vector for the message sequence. This process includes: The spatiotemporal feature sequence is input into a multi-head attention Transformer encoder, which includes multiple encoder layers connected in sequence. Each encoder layer includes a multi-head attention sub-layer and a feedforward neural network sub-layer. Through the multi-head attention sublayer of the current encoder layer, the attention weights between each feature vector in the spatiotemporal feature sequence are calculated in parallel, and the long-distance dependencies between each message are captured by the self-attention mechanism based on the attention weights to obtain the attention output; The attention output is input to the feedforward neural network sublayer of the current encoder layer for nonlinear transformation. The transformation result is added to the input of the encoder layer through residual connection and then processed by layer normalization to obtain the output of the current encoder layer. The output of the current encoder layer is used as the input of the next encoder layer. After processing by each encoder layer in sequence, the output of the last encoder layer is used as the context feature vector of the message sequence.
7. The method according to claim 1, characterized in that, The classifier's fully connected layer and Softmax activation function; Furthermore, for each of the message sequences, the operation of inputting the corresponding context feature vector into the classifier and outputting the detection result for each message sequence includes: The context feature vector is input into the fully connected layer for linear transformation to obtain an output value equal to the preset number of categories; The output value is converted into a probability distribution using the Softmax activation function, and the category with the highest probability is output as the detection result of the message sequence.
8. A storage medium, characterized in that, The storage medium includes a stored program, wherein, when the program is executed, the method described in any one of claims 1 to 7 is performed by a processor.
9. A vehicle-mounted CAN bus intrusion detection system, characterized in that, include: The preprocessing module is used to preprocess the acquired raw message data of the vehicle CAN bus to generate multiple message sequences; each message in each message sequence includes at least a timestamp, a CAN identifier, and a data payload. The first feature extraction module is used to input the corresponding CAN identifier and data payload into the encoding part of the autoencoder for each message in each message sequence, and extract the spatial features of the message after dimensionality reduction and compression. The time features of the message are extracted by nonlinearly mapping the timestamp of the message using a time smoothing algorithm that includes logarithmic transformation. The feature fusion module is used to fuse the spatial features of each message in the message sequence with the time position embedding vector generated based on the time features of each message for each message sequence, so as to construct the spatiotemporal feature sequence of the message sequence. The second feature extraction module is used to input the corresponding spatiotemporal feature sequence into the multi-head attention Transformer encoder for each message sequence, extract the long-distance dependency relationship between messages in the message sequence, and generate the context feature vector of the message sequence. The classification module is used to input the corresponding context feature vector into the classifier for each packet sequence and output the detection result for each packet sequence. The detection result is used to indicate the category of the packet sequence, which includes a normal state or one of a variety of preset attack types.
10. A vehicle-mounted CAN bus intrusion detection system, characterized in that, include: processor; as well as A memory, connected to the processor, for providing the processor with instructions to perform the following processing steps: The acquired raw message data of the vehicle CAN bus is preprocessed to generate multiple message sequences; each message in each message sequence includes at least a timestamp, a CAN identifier, and a data payload. For each message in each message sequence, the corresponding CAN identifier and data payload are input into the encoding part of the autoencoder, and the spatial features of the message are extracted after dimensionality reduction and compression. The time features of the message are extracted by nonlinearly mapping the timestamp of the message using a time smoothing algorithm that includes logarithmic transformation. For each message sequence, the spatial features of each message in the message sequence are fused with the time position embedding vector generated based on the time features of each message to construct the spatiotemporal feature sequence of the message sequence; For each message sequence, the corresponding spatiotemporal feature sequence is input into a multi-head attention Transformer encoder to extract the long-distance dependencies between messages in the message sequence and generate the context feature vector of the message sequence. For each message sequence, the corresponding context feature vector is input into the classifier, and the detection result of each message sequence is output. The detection result is used to indicate the category of the message sequence, which includes a normal state or one of a variety of preset attack types.