Abstract
The increasing reliance on smart grid communication systems has significantly raised the demand for robust cybersecurity measures to defend against advanced threats. This paper proposes a two-tier classification framework to enhance the detection and diagnosis of man-in-the-middle attacks within smart grid communication protocols. Initially, the model detects the presence of an attack and then identifies the specific type of man-in-the-middle attack through subsequent inferences. To achieve this, the “Man-in-the-Middle Attacks Targeting Modbus TCP/IP and MMS Protocols in the Smart Grid” dataset was carefully preprocessed and analyzed to better understand the underlying hidden characteristics. This understanding, coupled with existing works on fault detection and diagnosis, facilitated the engineering of new features from the original dataset. Four classifiers were employed in each tier: Random Forest, XGBoost, LightGBM, and CatBoost. The first tier exhibited exceptional performance, with the CatBoost framework achieving 99.6% accuracy. The second tier also demonstrated strong results, with the same model achieving 99.1% accuracy. Systematic model explainability was conducted using SHapley Additive exPlanations for both tiers and revealed that the highest accuracy was achieved using five features for the first and six for the second. The average inference time was approximately 4.76 milliseconds. The proposed framework is accurate, fast, interpretable, lightweight, and well-optimized for direct implementation in smart grid systems to detect and diagnose man-in-the-middle attacks.
1. Introduction
Man-in-the-middle (MITM) attacks are a critical threat in smart grid environments because they allow an adversary to silently intercept, modify, or spoof communications between devices. In an MITM attack, the intruder positions itself between two communicating entities (e.g., a sensor and a control center) and masquerades as a legitimate intermediary. This enables eavesdropping on confidential data exchanges or injection of falsified commands/data while the exchange still appears normal to each endpoint [1]. In power systems, such stealthy interference can facilitate false data injection (FDI) or false command injection (FCI) attacks that disrupt operations. For example, an attacker could alter measurement data or control signals, corrupting state estimation and grid control processes. This can have severe consequences for grid stability and reliability, e.g., by misleading automatic generation control or causing incorrect load dispatch decisions [2].
Modern smart grids are particularly susceptible to MITM attacks due to their extensive use of interconnected communication networks. Traditional power grids were relatively isolated, but today’s Advanced Metering Infrastructure (AMI), Supervisory Control and Data Acquisition (SCADA) systems, and other Industrial Control System (ICS) components are networked for real-time monitoring and control. AMI, for instance, relies on wireless links to transmit smart meter data and control commands, making those channels prime targets for interception and spoofing [3]. Likewise, many ICS protocols in substations and control centers (e.g., Modbus, DNP3) lack strong security; they often transmit data without encryption or authentication, leaving them open to packet sniffing and manipulation. These inherent vulnerabilities mean that an attacker with network access can impersonate devices or alter messages with relative ease. Furthermore, the convergence of Operational Technology (OT) with enterprise IT networks has expanded the attack surface. Formerly isolated control networks are now frequently connected to corporate networks or the Internet for remote management and data analytics, exposing critical grid control systems to external threats [4]. As smart grids become more digitally interconnected, their cyber-attack surface grows. The very communication technologies that enable efficiency and automation in smart grids also introduce new entry points for adversaries. Cybersecurity researchers recognize that the increasingly sophisticated and pervasive networking in smart grids makes them prime targets for attacks, with potentially catastrophic consequences for power reliability and national security if those attacks succeed. This urgent context underscores the need for robust defense mechanisms against MITM and related intrusions in power infrastructures.
To defend against such complex threats, the cybersecurity community has turned to Machine Learning (ML) techniques for advanced intrusion detection and prevention. ML-based Intrusion Detection Systems (IDS) can analyze vast streams of grid telemetry and network traffic in real or near-real time, learning to distinguish between normal patterns and malicious activity [5]. Unlike fixed rules or signature-based security tools, ML models can automatically learn system behaviors and adapt to new attack tactics. For example, data-driven models have been used to learn the normal dynamics of ICS processes (e.g., load frequency control, substation operations) directly from sensor and command data [6]. This ability to capture the legitimate patterns of device communications and power system states enables anomaly-based detection, flagging any significant deviation as a potential intrusion. A major advantage of ML-based approaches is their ability to identify previously unknown or zero-day attack patterns; they can detect novel MITM behaviors by detecting abnormal communication sequences or data inconsistencies that have not been observed during normal training [7]. This dramatically improves coverage against emerging threats. In addition, ML techniques enable adaptive learning. The models can be retrained or fine-tuned with new data, allowing the IDS to evolve in response to changing attacker strategies or grid configuration changes. In practice, researchers have demonstrated that incorporating ML algorithms into IDSs can markedly enhance detection capabilities. For instance, pattern recognition methods (including deep learning) have been shown to swiftly identify subtle signals of network compromise that might be overlooked by human operators [8]. ML-based IDS can also correlate multiple data features simultaneously (such as timing, protocol commands, and device responses), something difficult to achieve with manually crafted rules. The result is more automated and intelligent anomaly detection, reducing the burden on cybersecurity analysts.
A variety of ML methodologies have been explored to detect MITM attacks in smart grid and ICS contexts. Supervised learning approaches train on labeled examples of normal and attack traffic, producing classifiers that can recognize MITM patterns. Techniques such as Support Vector Machines (SVM), decision trees, random forests, and neural networks have been applied to classify network flows or power system measurements as benign or malicious. For example, the authors in [9] applied several supervised classifiers (enhanced with feature selection and boosting) to detect false data injection attacks in a simulated smart grid, achieving high accuracy in distinguishing attack traces. In the specific case of MITM detection, decision-tree-based ensembles have shown promise. One study reported that bagged tree models could reliably identify MITM anomalies in an oil-and-gas process control network with high precision [4]. A robust ML-based IDS system was developed in [10] using the Random Forest (RF) algorithm, which outperformed other algorithms in detecting MITM attacks in real-time infrastructure. The RF algorithm was further optimized with a hybrid bat algorithm to improve performance. Another IDS incorporating a random disturbance algorithm was designed in [11] to improve the performance of ML models. The system was validated in a testbed for both offline training and online real-time simulation. In [12], intricate MITM attacks were effectively detected and classified by a blended ensemble learning model utilizing tree-based algorithms. The model enhanced performance, minimized overfitting, and reduced latency, demonstrating superior accuracy in classifying attacks compared to traditional tree-based algorithms.
Similarly, researchers have developed unsupervised learning and semi-supervised anomaly detectors that do not rely on labeled attack data. These detectors learn a profile of normal smart grid behavior (using clustering, one-class SVM, autoencoders, etc.) and then raise alerts when current data deviate significantly from the norm [6]. An anomaly-based approach was used in [13] to detect MITM in ICS networks by modeling legitimate traffic and identifying out-of-bound variations. In [14], the authors identified vulnerabilities in Bluetooth Low Energy (BLE) devices that enable MITM attacks, which can easily compromise these devices due to their limited security features. They employed a combination of unsupervised and supervised ML techniques, specifically using model reconstruction to identify abnormal data patterns and a Text-CNN classification method to classify packets as normal or attack. The proposed approach achieved high accuracy (approximately 0.99) and a low false positive rate (approximately 0.03) in detecting and classifying BLE packets.
More recently, deep learning techniques have become prevalent. Complex neural network architectures (e.g., CNNs, LSTMs, graph neural networks) can automatically extract features from raw data and capture temporal or spatial correlations indicative of an attack. An approach based on a graph recurrent neural network was proposed in [15] for detecting eavesdropping attacks in smart grid wireless communication systems. This method effectively learned the topological structure and edge features of wireless sensor networks, achieving a detection accuracy of over 95%.
Despite encouraging progress, several gaps persist in existing research on ML-driven MITM detection for smart grids:
- Lack of ML Model Interpretability and Trust: A recurring concern in the literature is that ML-based IDS for smart grids operate as “black boxes,” making their decisions hard to trust in critical settings.
- Limited Attack Classification vs. Binary Detection: Many prior approaches detect the presence of an attack but do not precisely diagnose the attack type. In other words, earlier studies often treated all attacks similarly or focused on binary classification (normal vs. attack), leaving a gap in fine-grained classification.
- Insufficient Feature Representation of Attacks: The feature sets used in previous research may not fully capture the distinguishing characteristics of different MitM attacks. Earlier works did not engineer specialized features to better expose MitM behavior. By proposing new features, the lack of sufficiently informative features may be addressed.
- Balancing Detection Accuracy and Efficiency: Previous research often trades off accuracy for speed or vice versa. The authors note that the effectiveness of ML models depends on factors such as feature selection and the trade-off between detection accuracy and computational efficiency. This implies that prior works may not have achieved both high accuracy and low latency in a single solution.
- Handling of Unknown Attack Variants: An often underexplored issue is how IDS deals with novel or unseen attack types. Indeed, there is a need for detection systems to handle zero-day or previously unclassified attacks—a capability seldom discussed in earlier works that typically focus only on known attack classes.
This paper advances existing research by proposing a novel tiered-classification framework that leverages the strengths of multiple detection methodologies. The framework systematically addresses the problem in two tiers: the first distinguishes between malicious and normal samples, while the second identifies the specific type of MITM attack from among four distinct classes provided during the training phase. A key innovation, absent in previous studies, lies in the engineered features incorporated into the framework and their significant impact, as demonstrated by applying explainable artificial intelligence (XAI) to elucidate prediction outcomes. The contributions of this work are summarized in the following points:
- Implementation of a highly accurate CatBoost framework, achieving an accuracy exceeding 99.6% in detecting MITM attacks and 99.1% in attack type diagnosis.
- Development of novel engineered features accompanied by a comprehensive model selection process.
- Integration of XAI techniques for model optimization and control of feature complexity.
- Robust benchmarking through comparison of framework decisions against baseline models, demonstrating superior performance.
The remainder of the paper is structured as follows. Section 2 details the proposed solution, encompassing the framework, dataset description, models, evaluation metrics, exploratory data analysis, and the feature engineering process. Section 3 focuses on the results and discussion, covering the performance of both classification tiers, interpretation of the outputs, and post-processing steps. Finally, Section 4 concludes this work with a summary of the findings and their implications.
2. Proposed Tiered Classification Framework
The proposed solution in this work builds upon our prior research on fault detection and diagnosis in energy systems. Specifically, it draws on the foundational principles established in our earlier studies [16,17,18]. A baseline approach, often considered naive, involves training a general classifier directly on the dataset to distinguish between normal behavior and specific attack types, such as MITM attacks. While commonly employed in fault detection systems, this approach has notable limitations. The primary drawback of a generalized classifier is its sensitivity to the number and complexity of the classes used during training. As the number of classes increases, the classifier’s accuracy may decrease due to greater complexity and class overlap, leading to small but significant deviations from exact classification. Our prior work demonstrated that a more effective strategy is to adopt a “divide-and-conquer” methodology, where the problem is partitioned into smaller, more manageable subproblems, yielding improved classification performance. Building on this insight, the proposed solution incorporates a two-tiered classification framework, as shown in Figure 1. In the first tier, a model is trained to determine whether a given sample represents normal system behavior or an attack. In the second tier, samples identified as attacks are further classified into one of four specific MITM attack types. This hierarchical approach not only simplifies the classification task but also enhances the overall accuracy and efficiency of the detection system. The subsequent sections provide a detailed description of the four attack types and an overview of the dataset features used in this study. This comprehensive framework aims to address the limitations of traditional methods while leveraging the strengths of advanced machine-learning techniques for robust fault detection and diagnosis in smart grid systems. The proposed system is specifically trained to detect MITM attacks, though it can be adapted for other attack types. Once deployed in real-world or cyber-physical environments, the model continuously monitors network traffic, analyzes patterns, and reliably signals the presence of attacks. Its primary function is detection, but it also classifies MITM attacks into four categories based on the point of compromise: controller, router, bidirectional/two-way, or unknown. This detailed classification helps identify the attack origin and informs the appropriate mitigation strategy. As a result, the framework improves situational awareness and supports security management by enabling targeted and efficient interventions.
Figure 1.
The proposed framework.
2.1. Dataset Description
The datasets titled “Datasets of Man-in-the-middle Attacks Targeting Modbus TCP/IP and MMS Protocols in the Smart Grid” and available at Zenodo [19] serve as a resource for evaluating the detection and classification of MITM attacks within the Private Area Network (PAN) of smart grids. The datasets address critical cybersecurity vulnerabilities in smart grid communication protocols, namely Modbus TCP/IP and IEC 61850-8-1 [20] Manufacturing Message Specification (MMS). These protocols, commonly used for communication between local controllers at Distributed Energy Resource (DER) sites and grid-level centralized applications, often lack adequate confidentiality and integrity mechanisms, making them susceptible to MITM attacks. The datasets focus on eavesdropping attacks and provide flow-based features, including IRTT, TTOC, MITR, MATR, NROC, and an additional ARP-poisoning indicator feature. They support researchers in developing robust IDS and offer valuable insights to enhance the security of smart grid systems. The datasets are divided into two primary categories based on their creation method:
- Simulation Experiments (D1–D8) with 5604 rows and 7 features:
- –
- Datasets D1–D4 were generated using the MMS protocol.
- –
- Datasets D5–D8 were generated using the Modbus protocol.
- Real-Life Laboratory Experiments (A–H) with 5583 rows and 7 features. Datasets A–H were created using the TCP/IP Modbus communication protocol.
The datasets comprise the features given in Table 1.
Table 1.
Dataset features and descriptions.
In the datasets, a labeled variable is assigned to facilitate supervised learning. This variable assumes one of the following five values: {1, 50, 500, 1000, 2000}, each corresponding to a distinct class defined by the data provider and representing the set of normal and observed MITM attack types as follows:
- 1: Normal behavior;
- 50: Unknown MITM attack;
- 500: MITM two-way attack;
- 1000: MITM attacking controller;
- 2000: MITM attacking router.
This classification enables the training of ML models and helps build intuition for the variation in features across the labeled categories. A detailed description of these attack types, their associated risks, and the smart grid components where they are likely to occur is provided in Table 2.
Table 2.
Types of MITM attacks in the datasets.
2.2. ML Models and Metrics
The proposed framework for attack detection and diagnosis leverages ML classification models, particularly tree-based algorithms. This choice is inspired by our earlier research, which demonstrated their effectiveness in addressing similar issues, such as fault detection and diagnosis. Given the analogous nature of the problem, the following models were identified as baseline candidates for this framework: Random Forest (RF), Extreme Gradient Boosting (XGB), Light Gradient Boosting Machine (LGBM), and CatBoost. These models have consistently exhibited high performance in our prior works. A brief description of these models is provided below:
- Random Forest (RF): An ensemble learning method that builds multiple decision trees and aggregates their outputs to improve accuracy and reduce overfitting [21].
- Extreme Gradient Boosting (XGB): A powerful gradient-boosting algorithm optimized for speed and accuracy, which incorporates regularization to prevent overfitting [22].
- Light Gradient Boosting Machine (LGBM): A highly efficient gradient-boosting framework that uses histogram-based techniques to accelerate training on large datasets [23].
- CatBoost: A gradient-boosting model specifically designed to handle categorical features efficiently, reducing preprocessing requirements while maintaining robust performance [24].
The proposed classifiers were tested at both tiers of the framework, and the best-performing model at each tier was selected to construct the full pipeline for attack detection and MITM attack-type diagnosis. Performance evaluation was conducted using the classification metrics outlined in Table 3.
Table 3.
Classification metrics for multi-class evaluation.
2.3. Exploratory Data Analysis and Feature Engineering
Exploratory Data Analysis (EDA) is a critical component of this framework, as it facilitates a deeper understanding of the dataset’s features and potential underlying patterns that correlate with both normal and anomalous system behavior. This understanding provides valuable insights into possible new feature engineering opportunities, the identification of irrelevant features for removal, and the optimization of performance through techniques such as normalization. Moreover, it helps assess the presence of outliers and their potential impact on detection and diagnosis accuracy. The EDA was conducted with a focus on maintaining dataset integrity, particularly regarding the identification of normal behavior and various types of MITM attacks, and was driven by a series of investigative questions, which enabled the establishment of optimal results. These findings are summarized below.
- How are the data described? The statistical analysis in Figure 2a reveals that the dataset exhibits significant variability across its features. For example, the IRTT has a mean of 0.012 and ranges from 0.0026 to 0.91, indicating variability in connection setup times, though the low standard deviation (0.019) suggests most values are near the mean. The TTOC shows a mean of 0.2, a maximum of 2.8, and a median of 0.093, suggesting a right-skewed distribution with a few connections having significantly longer response times. Similarly, MITR has a very small mean (0.0069), indicating short request intervals, but variability remains low as reflected in its narrow range and standard deviation. These metrics highlight diverse patterns in connection timings, with some outliers influencing the ranges. In addition, the ARP poisoning indicator is binary (0 or 1), with its mean (0.19) suggesting that a small proportion of connections are affected by ARP poisoning, a crucial indicator for detecting potential cyber threats. On the other hand, the data are imbalanced between normal and attack samples as seen in Figure 2b, with normal samples accounting for 68.1% and attack samples for 31.9%. Nonetheless, it is noteworthy that three types of attacks—MITM Attacking Controller, MITM Attacking Router, and MITM Two-Way Attacks—have approximately similar representation, with an average presence ratio of 8.6%, whereas unknown attacks constitute 5.3% of the dataset. This distribution is promising for the proposed approach compared to the naive solution mentioned earlier. Training a model directly on this imbalanced dataset can lead it to favor the normal class, thereby compromising its generalizability. Therefore, adopting a tiered approach, where attacks are treated separately in a dedicated tier, appears to be a more effective and balanced solution.Figure 2. Statistical analysis and distribution of samples. (a) Statistical data analysis. (b) Distribution of attacks and normal samples.
- What can the outlier analysis reveal? Outliers, defined as values outside the normal range of a feature, can serve as critical indicators of abnormal behavior, particularly in cybersecurity and, more specifically, in the detection of MITM attacks. For instance, if time-related features exhibit outlier values in the context of data transmission and reception, it may signal external interference. This is evident in Figure 3a, where the original data reveal notable outliers in features such as IRTT, TTOC, and MATR, suggesting potential points of interest within the dataset. It can also be seen that MITR demonstrates minor deviations, highlighting the need for closer inspection of these variations.Figure 3. Feature analysis. (a) Outlier analysis. (b) Correlation analysis.
- What original correlations can be drawn? The mutual correlation analysis, based on Pearson correlation coefficients, presented in Figure 3b, provides valuable insights into the linear relationships among the features and between features and the target variable. Pearson correlation is particularly well-suited to this context because it captures linear dependencies in structured network traffic data, where variations induced by MITM attacks often manifest as measurable shifts in feature distributions and interactions. Notably, no feature pair exhibits a correlation higher than 82%, indicating limited multicollinearity and justifying the retention of all features. Regarding feature–target relationships, the ARP positioning indicator shows a strong positive correlation of 73%, followed by TTOC at 52%, while the remaining features exhibit correlations below 40%. An exception is RD, which presents a significant negative correlation with the target, reaching approximately −52%. This observation provides valuable insight for feature engineering, as RD, TTOC, and CD display complementary and, in some cases, symmetric correlation patterns with respect to the target variable. Such behavior suggests that these features capture different but interrelated aspects of the underlying network dynamics affected by the attack. In particular, the opposing correlation signs indicate that while some features increase in the presence of anomalous behavior, others decrease, thereby enhancing the separability of attack and normal classes. This complementary structure can be effectively leveraged to improve model discriminative power, support robust decision boundary formation, and reduce classification ambiguity, especially in the context of subtle and dynamic patterns characteristic of man-in-the-middle attack detection. These results highlight the strong discriminative power of specific network-level indicators, which is critical for accurately detecting and classifying MITM attacks. Hence, the use of Pearson correlation supports effective feature engineering by balancing redundancy reduction with the preservation of informative patterns, thereby contributing to robust model performance and enabling accuracy levels exceeding 90% in attack detection and classification tasks.
- What class separation level can we get given these correlations? Given the three most correlated features with the target, we assessed the separation levels in two dimensions by combining the best feature with one of the other two correlated features. Figure 4 highlights the results, demonstrating that combining ARP with TTOC achieves a primary level of separation between MITM attacking routers (MITM Two-Way attack from one side) and the other classes. A clearer separation is observed when combining MITR and TTOC features. This suggests that these features can help the model generalize better. However, they are still insufficient to provide optimal separation between four to five classes, as illustrated.Figure 4. Separation levels. (a) ARP vs. TTOC with labeled information. (b) MITR vs. TTOC with labeled information.
- Which features can be engineered? Based on the aforementioned observations, it is evident that attack detection can be achieved using the existing features. However, the distinction appears to be less decisive in identifying specific attack types. This limitation underscores the necessity of engineering new features that can enhance the diagnosis process for various attacks. To address this, we developed the following features:
- Request-to-Response Time Ratio (RRTR): represents the ratio of the request time to the response time, providing insights into the latency dynamics of communication exchanges.
- Inter-Request Variability (IRV): captures the variability between consecutive requests, which can indicate irregular patterns often linked to malicious activities.
- Request Density (RD): measures the density of requests relative to the overall connection duration, offering an indicator of abnormal communication behavior.
- Connection Duration (CD): represents the time difference between connection establishment and response, reflecting connection stability and potential delays.
These newly constructed features can significantly contribute to identifying MITM attacks, as they provide deeper insights into timing, variability, and density metrics, which are critical in detecting anomalous behaviors in network communication. This conclusion is supported by examining the correlation matrix with the target variable, as illustrated in Figure 5. In particular, two engineered features, RD and CD, exhibit correlations exceeding 50%, indicating their significant relevance to the target variable. The remaining engineered features demonstrate reasonable levels of correlation, further justifying their inclusion in the analysis.
Figure 5.
Correlation of the engineered features with the target.
The feature selection process was further guided by feature ranking analysis, a technique previously employed in our earlier work on fault detection and diagnosis systems. Leveraging principles of transfer learning, we assume a strong methodological similarity between fault detection and diagnosis frameworks and attack detection and diagnosis systems. The feature rankings reported in [16,17] enable the assessment of each feature’s contribution across a diverse set of models, which differ in computational complexity yet exhibit comparable decision boundary structures. This aspect is particularly critical in the context of attack detection, where robust and consistent decision-making is essential. Accordingly, we construct a consensus-based ranking by aggregating the most influential features identified across these models. This methodology demonstrates a significant positive impact on feature selection robustness and overall model performance.
3. Results and Analysis
The real and synthetic data were combined into a single DataFrame using Python 3.1’s merge functionality, resulting in a dataset size of 11,188 × 7. Subsequently, a custom function was developed to create the four newly engineered features, thus expanding the dataset to include 11 features in total. Another dedicated function was developed to prepare separate training sets: one for binary classification focused on detection and another for multi-class classification focused on attack diagnosis across the four classes. All training and testing processes were performed on the Google Colab platform, benefiting from its free resources under a CPU configuration. This highlights the simplicity and adaptability of the proposed framework to smart grid systems and IoT devices. The dataset was divided into training and testing subsets with an 80/20 split, respectively. The following sections present the results in detail, beginning with the detection results, followed by the diagnosis performance, and concluding with optimization efforts and the explainability of the results obtained.
3.1. Tier 1: Attack Detection Performance
The results in Table 4 show that the CatBoost classifier is the most accurate with 99.5%, followed by the three other classifiers with 99.4% and 99.3%.
Table 4.
Performance comparison of classifiers for tier 1 (attack detection).
Upon analyzing the confusion matrix in Figure 6a for the CatBoost classifier in the detection tier, it is evident that the model demonstrates high accuracy in distinguishing between normal and attack samples. The classifier achieves remarkably low false-positive (FP) and false-negative (FN) rates, with FP at 0.3% and FN at 0.5% for attack and normal cases, respectively, underscoring its strong performance. Examining the learning curve in Figure 6b shows that the model achieves 99% accuracy after processing only 1500 samples. This indicates rapid learning and efficiency, as the model quickly identifies patterns with minimal data. The curve further highlights that, as more data are introduced, the system’s generalizability improves significantly and converges rapidly. This is a crucial advantage from a modeling perspective, as timely and accurate detection of attacks is imperative for ensuring robust security in real-time applications.
Figure 6.
CatBoost confusion matrix and learning curve for tier 1 (attack detection). (a) Confusion matrix. (b) Learning curve.
3.2. Tier 2: Attack Diagnosis Performance
From a modeling perspective, the attack diagnosis system effectively identifies three main categories of MITM attacks: two-way, controller, and router attacks. A fourth category, labeled as unknown, is also present but holds less practical significance. The purpose of the diagnosis tier is to identify the exact type of attack; an unknown attack type offers no additional value beyond the general attack detection already provided by the first tier. However, for the sake of completeness, the unknown category is treated as distinct from the other three in the dataset. The results, summarized in Table 5, highlight CatBoost’s superior performance, achieving a remarkable 99.1% accuracy and outperforming all other models.
Table 5.
Performance comparison of classifiers for tier 2 (attack diagnosis).
The diagnosis tier demonstrates strong performance, as evidenced by the confusion matrix in Figure 7a and learning curve in Figure 7b. The FP rates are notably low across all classes, with the MITM Attacking Router class having an FP rate of approximately 2.6% and the Unknown MITM Attack and MITM Attacking Controller classes having 100% classification results with zero FP rates. This highlights the model’s capability to accurately distinguish between normal and attack samples. Moreover, the learning curve reveals rapid convergence, with the CatBoost achieving an accuracy of approximately 99.0% after processing only 1500 samples. This indicates that the model learns efficiently from relatively small datasets. Furthermore, the minimal gap between training and testing scores post-convergence demonstrates good generalization, as the model maintains consistent performance on unseen data. The absence of overfitting and the decreasing variance in the test scores with more data further reinforce the model’s reliability. Therefore, the diagnosis tier exhibits high accuracy, efficient convergence, and scalability, making it a robust and practical system for real-time attack detection and classification.
Figure 7.
CatBoost confusion matrix and learning curve for tier 2 (attack diagnosis). (a) Confusion matrix. (b) Learning curve.
3.3. Explainability and Interpretability
Establishing an interpretable model of ground truth is a critical factor in fostering human–model trust. In this regard, XAI plays a pivotal role by providing insights into model decisions across various dimensions. SHAP (SHapley Additive exPlanations) is adopted as the primary interpretability method due to its solid theoretical foundation based on Shapley values from cooperative game theory, which guarantees consistent and fair attribution of feature contributions. SHAP is particularly advantageous in the context of tree-based models, enabling efficient computation of both global and local explanations without requiring surrogate approximations. This dual capability is essential for security-oriented applications such as MITM detection, where understanding both the overall influence of features and the behavior of individual predictions is critical. While alternative XAI approaches, including LIME and gradient-based attribution methods, may provide complementary insights, SHAP offers a robust and theoretically grounded balance between interpretability, stability, and computational feasibility. For the detection tier in Figure 8a, the SHAP analysis reveals that the model heavily relies on MITR, ARP, and RD features. The RD feature, specifically engineered during the feature creation process, was designed to introduce additional descriptive power to the dataset. Other engineered features appear to have a lower impact in this tier, emphasizing the critical role of a select few features in distinguishing between normal and attack cases. For the diagnosis tier in Figure 8b, the SHAP analysis highlights IRTT, RD, and RRTR as the top three most influential features, with additional contributions from the fourth and fifth-ranked features. This finding underscores that these features enable the model to effectively construct decision boundaries between different attack classes. The SHAP analysis provides a clear understanding of how the model differentiates among various attack types, reinforcing the importance of feature engineering and interpretability in achieving robust and trustworthy decision-making across both tiers.
Figure 8.
SHAP analysis of the detection and diagnosis tiers. (a) Detection tier. (b) Diagnosis tier.
3.4. Performance Optimization and Benchmark Comparison
The performance optimization process was systematically conducted by leveraging the feature importance weights assigned by the SHAP XAI model. These weights were aggregated to determine the optimal feature rankings for both detection and diagnosis tasks. Each feature’s importance weight was multiplied by its corresponding feature value. Subsequently, a custom function was developed to incrementally add features to the dataset based on their importance rankings and compute the resulting accuracy. This iterative approach aimed to identify the optimal subset of features that maximized classification accuracy.
Figure 9 illustrates the accuracy evolution as features were incrementally added. For the detection task, the classifier achieved its peak performance with just five features, after which the accuracy stabilized. In contrast, the diagnosis task exhibited a progressive improvement beyond the five-feature threshold of its detection counterpart, ultimately stabilizing at six features. This iterative progression allowed the discovery of optimal feature sets for both tasks. The final set of selected features and their corresponding accuracies are summarized in Table 6.
Figure 9.
Accuracy evolution vs. the number of features for attack detection (blue) and diagnosis (red).
Table 6.
Optimal features and best accuracy for attack detection and diagnosis.
A baseline benchmark was conducted to evaluate model performance in the absence of the proposed feature engineering strategy. This evaluation included standard classifiers (MLP, DT, ET, and AdaBoost) and a Naive CatBoost model trained on the original feature space without engineered features, thereby isolating the impact of feature engineering. As shown in Figure 10, the CatBoost model with engineered features consistently outperformed all benchmark configurations in both detection and diagnosis tasks. For detection, benchmark models achieved accuracies between 98.39% (MLP) and 99.21% (Decision Tree), while the Naive CatBoost model reached 99.1%. This result indicates that CatBoost is competitive even without feature engineering. However, the CatBoost model with engineered features outperformed all baselines, achieving 99.6% accuracy and reducing misclassification to 0.4%. In the diagnosis task, benchmark models such as Decision Tree and AdaBoost achieved accuracies of 98.98% and 98.35%, respectively, while the Naive CatBoost model attained 97.83%. This performance gap underscores the importance of feature engineering, as the CatBoost model with engineered features achieved a significantly higher accuracy of 99.2%. Notably, it achieved perfect classification (100%) for critical attack categories, including MITM controller attacks and unknown MITM attacks. SHAP-based analysis further confirmed the efficiency of the proposed approach in feature selection and optimization, requiring only five features for detection and six for diagnosis while maintaining superior predictive performance. These results demonstrate that the observed performance gains are primarily attributable to the proposed feature engineering strategy, which substantially enhances the model’s discriminative capability.
Figure 10.
Model-free accuracy benchmark.
Finally, it is essential to highlight that the average testing time across both tiers is approximately 4.76 milliseconds, demonstrating the rapid identification of faults and simultaneous diagnosis of attack types. This swift response is critical to the development of cybersecurity frameworks and defense systems, as it ensures that intervention times are minimized. Such rapid detection capabilities are essential for mitigating threats effectively, reducing potential damage, and enhancing the system’s overall resilience against cyberattacks.
3.5. Insights and Implications
The results highlight the effectiveness of the tiered classification framework in detecting and diagnosing MITM attacks within smart grid communication protocols. The findings demonstrate that a multi-tiered approach not only improves detection accuracy but also ensures scalability and adaptability. Moreover, the engineered features significantly enhance the accuracy of the fault diagnosis tier, while the SHAP XAI model enabled the identification of the minimal number of features required to achieve optimal accuracy. These insights provide valuable guidance for the design and implementation of robust cybersecurity solutions in smart grid environments, offering a pathway to improved resilience and efficiency.
An additional consideration, particularly relevant to the diagnosis tier, is its implicit support for generalization to other attack types. Retaining the “unknown” MITM class during the diagnostic stage enhances the robustness and generalization capabilities of the proposed framework. Although this class does not correspond to a specific attack subtype, it encompasses anomalous behaviors that cannot be mapped to predefined categories within the dataset. Including this class increases the model’s decision boundary diversity and mitigates the risk of overfitting to a narrow set of attack patterns. Furthermore, despite representing only 5.3% of the dataset, it introduces valuable variability, strengthening the model’s ability to distinguish subtle and overlapping malicious behaviors. In practical deployment, this class may serve as a proxy for previously unseen or emerging attack behaviors, thereby improving the diagnostic module’s adaptability in heterogeneous realworld network environments.
4. Conclusions and Future Work
In this study, MITM attacks, a significant cybersecurity threat, were the focus of a comprehensive investigation. A publicly available dataset from Zenodo containing records of MITM attacks within smart grid communication protocols was carefully preprocessed and analyzed to evaluate the influence of various characteristics on the presence or absence of these attacks. The analyzed features included communication protocol parameters, such as the Initial Round-Trip Time, the Time to Obtain Completion, and other relevant metrics. Leveraging our expertise in fault detection and diagnosis, we engineered additional impactful features to enhance the model’s performance. The problem was addressed in two tiers of ML modeling: the first tier focused on attack detection (distinguishing normal traffic from attack traffic), while the second tier classified the specific attack type among four categories. ML models, including CatBoost, LGBM, XGBoost, and Random Forest, were trained for both tasks based on their suitability for the problem at hand. The results from the first tier showed that the CatBoost classifier achieved outstanding accuracy, classifying normal and attack samples with 99.6% accuracy and a misclassification rate of only 0.4%. For the diagnosis task, the CatBoost model also demonstrated strong performance, achieving 99.1% overall accuracy, including 100% accuracy against MITM controller attacks and unknown MITM attacks. To further optimize the framework, SHAP analysis was employed to minimize the number of required features while maintaining high accuracy. The analysis revealed that only five features were necessary for the detection model to achieve optimal accuracy, while six features were required for the diagnosis model. Additionally, SHAP analysis highlighted the importance of the engineered features, demonstrating their significant contribution to the models’ decision-making processes and reinforcing the success of the feature engineering strategy. This process also allowed us to achieve the shortest possible testing time, at 4.76 milliseconds. The reported high accuracy levels (99.6% for detection and 99.1% for classification) should be interpreted within the context of the dataset characteristics. Specifically, the structured nature of the dataset and the strong correlation between input features and target labels contribute to facilitating the learning task, potentially leading to optimistic performance estimates. While these results demonstrate the effectiveness of the proposed framework under controlled experimental conditions, they may not fully reflect performance in more complex and noisy real-world environments. Therefore, this study acknowledges that the dataset does not capture the full variability and uncertainty typically encountered in practical deployments. Future work will focus on validating the proposed approach using larger-scale, heterogeneous, and real-world datasets, incorporating diverse operating conditions and noise levels to further assess generalization capability and robustness. It can also explore the integration of additional mechanisms, such as ensemble techniques or deep learning models, to further enhance the diagnosis system. Another promising direction is to apply alternative XAI models to investigate the impact of additional features, building on the findings of this study.
Author Contributions
Conceptualization, H.N.N., Z.A., O.S. and K.C.; methodology, H.N.N. and Z.A.; software, H.N.N., Z.A., O.S. and K.C.; validation, H.N.N., Z.A., O.S. and K.C.; formal analysis, H.N.N., Z.A., O.S. and K.C.; writing—original draft preparation, H.N.N. and Z.A.; writing—review and editing, O.S. and K.C.; visualization, H.N.N. and Z.A.; supervision, H.N.N. and K.C.; project administration, H.N.N. All authors have read and agreed to the published version of the manuscript.
Funding
This research received no external funding.
Institutional Review Board Statement
Not applicable.
Informed Consent Statement
Not applicable.
Data Availability Statement
The dataset used in this study is publicly available on Zenodo at https://zenodo.org/record/8375657 (accessed on 6 March 2025).
Acknowledgments
We would like to express our sincere gratitude to Mohamed Faisal Elrawy, Lenos Hadjidemetriou, Christos Laoudias, and Maria K. Michael for generously making this dataset publicly available and enabling us to carry out and present this work.
Conflicts of Interest
Author Ola Salman was employed by DeepVu. The remaining authors declare that the research was conducted in the absence of any commercial or financial relationships that could be construed as a potential conflict of interest.
Abbreviations
The following abbreviations are used in this manuscript:
| MITM | Man-in-the-Middle |
| ML | Machine Learning |
| IDS | Intrusion Detection System |
| XAI | Explainable Artificial Intelligence |
| SHAP | SHapley Additive exPlanations |
| RF | Random Forest |
| XGB | Extreme Gradient Boosting |
| LGBM | Light Gradient-Boosting Machine |
| AMI | Advanced Metering Infrastructure |
| SCADA | Supervisory Control and Data Acquisition |
| ICS | Industrial Control System |
| DER | Distributed Energy Resource |
| MMS | Manufacturing Message Specification |
| EDA | Exploratory Data Analysis |
References
- Achaal, B.; Adda, M.; Berger, M.; Ibrahim, H.; Awde, A. Study of smart grid cyber-security, examining architectures, communication networks, cyber-attacks, countermeasure techniques, and challenges. Cybersecurity 2024, 7, 10. [Google Scholar] [CrossRef] [Scilit] [PubMed]
- Wlazlo, P.; Sahu, A.; Mao, Z.; Huang, H.; Goulart, A.; Davis, K.; Zonouz, S. Man-in-the-middle attacks and defence in a power system cyber-physical testbed. IET Cyber-Phys. Syst. Theory Appl. 2021, 6, 164–177. [Google Scholar] [CrossRef] [Scilit]
- Bendiab, G.; Grammatikakis, K.P.; Koufos, I.; Kolokotronis, N.; Shiaeles, S. Advanced metering infrastructures: Security risks and mitigation. In ARES ’20: Proceedings of the 15th International Conference on Availability, Reliability and Security; Association for Computing Machinery: New York, NY, USA, 2020. [Google Scholar] [CrossRef] [Scilit]
- Obonna, U.O.; Opara, F.K.; Mbaocha, C.C.; Obichere, J.K.C.; Akwukwaegbu, I.O.; Amaefule, M.M.; Nwakanma, C.I. Detection of Man-in-the-Middle (MitM) Cyber-Attacks in Oil and Gas Process Control Networks Using Machine Learning Algorithms. Future Internet 2023, 15, 280. [Google Scholar] [CrossRef] [Scilit]
- Sahani, N.; Zhu, R.; Cho, J.H.; Liu, C.C. Machine Learning-based Intrusion Detection for Smart Grid Computing: A Survey. ACM Trans. Cyber-Phys. Syst. 2023, 7, 1–31. [Google Scholar] [CrossRef] [Scilit]
- Raman, G.; Ahmed, C.M.; Mathur, A. Machine learning for intrusion detection in industrial control systems: Challenges and lessons from experimental evaluation. Cybersecurity 2021, 4, 27. [Google Scholar] [CrossRef] [Scilit]
- Liu, H.; Lang, B. Machine Learning and Deep Learning Methods for Intrusion Detection Systems: A Survey. Appl. Sci. 2019, 9, 4396. [Google Scholar] [CrossRef] [Scilit]
- Senthilkumar, S.P.; Arivarasan, A. Empirical Analysis of Machine Learning Models towards Adaptive Network Intrusion Detection Systems. In Proceedings of the 2022 4th International Conference on Smart Systems and Inventive Technology (ICSSIT); IEEE: Piscataway, NJ, USA, 2022; pp. 192–200. [Google Scholar] [CrossRef] [Scilit]
- Aziz, S.; Irshad, M.; Haider, S.A.; Wu, J.; Deng, D.N.; Ahmad, S. Protection of a smart grid with the detection of cyber-malware attacks using efficient and novel machine learning models. Front. Energy Res. 2022, 10, 964305. [Google Scholar] [CrossRef] [Scilit]
- Jim Solomon Raja, D.; Sriranjani, R.; Arulmozhi, P.; Hemavathi, N. Unified Random Forest and Hybrid Bat Optimization Based Man-in-the-Middle Attack Detection in Advanced Metering Infrastructure. IEEE Trans. Instrum. Meas. 2024, 73, 2523812. [Google Scholar] [CrossRef] [Scilit]
- Gao, Z.; Illindala, M.; Wang, J. Intrusion Detection System with Updated Structure and Feature Selection Algorithm for Man-In-The-Middle Attacks in the Smart Grid. In Proceedings of the 2023 IEEE Industry Applications Society Annual Meeting, IAS 2023; IEEE: Piscataway, NJ, USA, 2023. [Google Scholar] [CrossRef] [Scilit]
- Shafin, S.S.; Ashiqur Rahman, Q.; Gondal, I.; Karmakar, G.; Hossain Mondal, M.R. Blended Ensemble Learning for Robust MITM Attack Detection and Classification in Smart Grid. In Proceedings of the 2023 33rd Australasian Universities Power Engineering Conference, AUPEC 2023; IEEE: Piscataway, NJ, USA, 2023. [Google Scholar] [CrossRef] [Scilit]
- Eigner, O.; Kreimel, P.; Tavolato, P. Detection of Man-in-the-Middle Attacks on Industrial Control Networks. In Proceedings of the 2016 International Conference on Software Security and Assurance (ICSSA); IEEE: Piscataway, NJ, USA, 2016; pp. 64–69. [Google Scholar] [CrossRef] [Scilit]
- Lahmadi, A.; Duque, A.; Heraief, N.; Francq, J. MitM attack detection in BLE networks using reconstruction and classification machine learning techniques. In Proceedings of the Joint European Conference on Machine Learning and Knowledge Discovery in Databases; Springer: Cham, Switzerland, 2020; pp. 149–164. [Google Scholar]
- Jiang, W.; Wang, J.; Hsiung, K.L.; Chen, H.Y. GRNN-Based Detection of Eavesdropping Attacks in SWIPT-Enabled Smart Grid Wireless Sensor Networks. IEEE Internet Things J. 2024, 11, 37381–37393. [Google Scholar] [CrossRef] [Scilit]
- Allal, Z.; Noura, H.N.; Salman, O.; Chahine, K. Leveraging the power of machine learning and data balancing techniques to evaluate stability in smart grids. Eng. Appl. Artif. Intell. 2024, 133, 108304. [Google Scholar] [CrossRef] [Scilit]
- Allal, Z.; Noura, H.N.; Vernier, F.; Salman, O.; Chahine, K. Wind turbine fault detection and identification using a two-tier machine learning framework. Intell. Syst. Appl. 2024, 22, 200372. [Google Scholar] [CrossRef] [Scilit]
- Noura, H.N.; Allal, Z.; Salman, O.; Chahine, K. Explainable artificial intelligence of tree-based algorithms for fault detection and diagnosis in grid-connected photovoltaic systems. Eng. Appl. Artif. Intell. 2025, 139, 109503. [Google Scholar] [CrossRef] [Scilit]
- Elrawy, M.; Hadjidemetriou, L.; Laoudias, C.; Michael, M.K. Datasets of Man in the Middle Attacks Targeting Modbus TCPIP and MMS Protocols in the Smart Grid. Zenodo. 2023. Available online: https://zenodo.org/records/8375657 (accessed on 6 March 2025).
- IEC 61850-8-1; Communication Networks and Systems for Power Utility Automation—Part 8-1: Specific Communication Service Mapping (SCSM)—Mappings to MMS (ISO 9506-1 and ISO 9506-2) and to ISO/IEC 8802-3. International Electrotechnical Commission: Geneva, Switzerland, 2020.
- Scikit-Learn Developers. Scikit-Learn: Machine Learning in Python. 2023. Available online: https://scikit-learn.org/stable/ (accessed on 22 January 2023).
- XGBoost Developers. XGBoost: A Scalable Tree Boosting System. 2023. Available online: https://xgboost.readthedocs.io/en/release_3.2.0/ (accessed on 22 January 2023).
- LightGBM Developers. LightGBM: A Fast, Distributed, High-Performance Gradient Boosting (GBDT) Framework. 2023. Available online: https://lightgbm.readthedocs.io/en/stable/ (accessed on 22 January 2023).
- CatBoost Developers. CatBoost: High-Performance Gradient Boosting Library. 2023. Available online: https://catboost.ai/ (accessed on 22 January 2023).
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content. |
© 2026 by the authors. Licensee MDPI, Basel, Switzerland. This article is an open access article distributed under the terms and conditions of the Creative Commons Attribution (CC BY) license.









