<figure><img src="image_1.png" /></figure>

HAL
open science

# Leveraging gem5 for Hardware Trojan Research: Simulation for Machine-Learning-Based Detection

Alessandro Palumbo, Ruben Salvador

<figure><img src="image_2.png" /></figure>

## To cite this version:

Alessandro Palumbo, Ruben Salvador. Leveraging gem5 for Hardware Trojan Research: Simulation for Machine-Learning-Based Detection. 10th International Workshop on Malicious Software and Hardware in the Internet of Things (MAL-IoT) 2025 - Proceedings of the 22nd ACM International Conference on Computing Frontiers: Workshops and Special Sessions, May 2025, Cagliari, Italy. pp.9-16, 10.1145/3706594.3728869. hal-05044677

HAL Id: hal-05044677

https://hal.science/hal-05044677v1

Submitted on 23 Apr 2025

HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.

L'archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d'enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.

<figure><img src="image_3.png" /></figure>

Distributed under a Creative Commons Attribution 4.0 International License
# Leveraging gem5 for Hardware Trojan Research: Simulation for Machine-Learning-Based Detection

Alessandro Palumbo

CentraleSupélec, Inria, CNRS, IRISA

Rennes, France

alessandro.palumbo@inria.fr

Ruben Salvador

CentraleSupélec, Inria, CNRS, IRISA

Rennes, France

ruben.salvador@inria.fr

## Abstract

Hardware Trojans (HTs) consist of malicious modifications intentionally embedded in hardware designs, capable of bypassing security measures, leaking sensitive information, or disrupting system operations. This work proposes a methodology for introducing and simulating HTs on microprocessor-based systems within the gem5 simulator, focusing on RISC-V architectures. By leveraging the gem5 System Emulation (SE) mode, we generate comprehensive datasets encompassing both benign and attack scenarios, automating the collection of 866 features from Hardware Performance Counters (HPC) dumped by gem5 after every program run. The dataset consists of 10,000 samples, evenly split into 5,000 benign and 5,000 attacked instances on different runs across 8 benchmarks. Contrary to previous work using processors with a very limited number of HPCs, we demonstrate how simulation provides access to a much larger number of HPCs and can, hence, enable new research on effective detection mechanisms. In particular, we show preliminary results for one HT and improve previous work on detection mechanisms using Machine Learning (ML). Using a Random Forest (RF) classifier and taking inspiration from the PIC16F84-T100 HT from the Trust-Hub platform as a case study, we achieve 100% attack detection. Our approach facilitates the security evaluation of microprocessors under HT attacks and provides a framework for experimenting with and analyzing ML-based detection strategies.

## CCS Concepts

* Security and privacy → Hardware security implementation;

* Computing methodologies → Machine learning; Model development and analysis; • Computer systems organization → Trusted computing; Embedded and cyber-physical systems.

## Keywords

Hardware Trojans, Gem5 Simulator, Microprocessor Security, Machine Learning-Based Anomaly Detection

## ACM Reference Format:

Alessandro Palumbo and Ruben Salvador. 2025. Leveraging gem5 for Hardware Trojan Research: Simulation for Machine-Learning-Based Detection. In *22nd ACM International Conference on Computing Frontiers (CF Companion '25), May 28–30, 2025, Cagliari, Italy*. ACM, New York, NY, USA, 8 pages. https://doi.org/10.1145/3706594.3728869

<figure><img src="image_4.png" /></figure>

This work is licensed under a Creative Commons Attribution 4.0 International License. CF Companion '25, Cagliari, Italy

© 2025 Copyright held by the owner/author(s).

ACM ISBN 979-8-4007-1393-4/25/05

https://doi.org/10.1145/3706594.3728869

## 1 Introduction

The risk of malicious modifications in Integrated Circuits (ICs) is a pressing concern in today's globalized economy, where the design, manufacturing, and distribution of complex electronic devices—such as commercial CPUs—are often carried out by different entities across various countries [13]. The Computer-Aided Design (CAD) tools used in the design cycle are typically developed by independent companies disconnected from the design and manufacturing processes. Intellectual property (IP) building blocks integrated into these devices are also frequently sourced from third-party vendors [36, 40]. With so many actors involved in the production chain, numerous opportunities exist to introduce malicious hardware modifications known as Hardware Trojans (HTs) [39].

Ensuring the integrity of ICs is a significant challenge. Even minor hardware alterations can have severe consequences, such as granting attackers supervisor privileges, exposing cryptographic keys, or enabling the execution of malicious software, as demonstrated in prior works [24, 48, 50]. One alarming example is the *Rosenbridge backdoor*, discovered in a commercial VIA Technologies C3 processor, which allowed unauthorized supervisor mode access [14]. These findings underscore the vulnerability of modern systems and highlight the urgent need for reliable and efficient methods to detect compromised CPUs and ICs [9, 31].

In this context, probabilistic approaches and Machine Learning (ML) seem good candidates for the detection and classification of threats in ICs [25] like HTs [1–3]. By analyzing subtle patterns and anomalies in circuit behaviour, ML models can significantly enhance the ability to detect hidden threats like HTs [22, 28, 32, 37].

Gem5 is a widely used, open-source platform for computer architecture research, enabling cycle-level simulation of various processor architectures [7, 30], including RISC-V [30, 38, 46]. It provides a flexible environment for modelling and analyzing different system-level architectural and microarchitectural choices. Although its use in the security domain is far less extended for the moment, we believe it can be an ideal tool for studying security threats emerging from different layers of the computing stack and their interactions. As a cycle-level simulator defined by event-driven models, it provides statistics at the cycle level and strikes an accuracy tradeoff with cycle-accurate simulation. However, this fact might be a limiting factor in simulating models described and capturing behaviours at the lowest levels of hardware description. As a result, its use as a simulation tool for hardware-level security vulnerabilities is almost nonexistent.

In this manuscript, we present a hands-on methodological approach to reproducing HTs on the gem5 simulator. To showcase its benefits, we introduce an ML-based methodology leveraging
HPCs to detect HTs in RISC-V processors using the proposed framework. We validate our approach across a diverse set of workloads, including cryptographic and computational applications. Our main contributions are as follows:

* **Comprehensive HT simulation framework:** We show how to precisely implement and evaluate HTs within the gem5 simulator, enabling realistic attack scenario modelling for hardware security analysis.

* **Extensive HPC analysis:** We systematically extract and analyze 866 HPCs from simulated RISC-V processors in gem5, identifying the most relevant features for the detection of (one) HT.

* **ML-driven detection approach:** We demonstrate the effectiveness of a supervised learning approach using a Random Forest (RF) classifier, and for the first time, to the best of our knowledge, we detect HTs only from HPC data with 100% accuracy and no false or undetected alarms.

While prior works have suggested that HPC values are not relevant for HT detection and classification, their conclusions were based on features obtained from a limited set of HPCs. In contrast, our approach leverages 866 features, enabling us to achieve 100% accuracy. We acknowledge that accessing so many HPCs is impractical in real-world scenarios. However, we want to highlight how **having access to an extended set of HPCs for offline study, and a subset of them at runtime, can dramatically improve HT detection accuracy** compared to previous works [32, 37].

The primary goal of this manuscript is to present a methodology for simulating HTs in gem5, selecting adequate HPCs, and evaluating one ML-based approach for runtime detection as a demonstration. We believe our approach can enable further research on microprocessor security and assist computer architects in selecting appropriate HPCs for HT runtime detection.

The remaining of the manuscript first provides, in Section 2, an overview of related work on attack detection and simulation techniques. Section 3 describes the methodology to model and simulate HTs in gem5 and the ML-based detection framework. Section 4 discusses the experimental setup and presents the evaluation results. Section 5 explores the practical implications and applications of our findings. Finally, Section 6 concludes the paper.

## 2 Related Work

Existing research on HTs is broad, covering all the layers from circuits to the system level. System-level methodologies focus on enabling the building of trusted systems, even when they include untrusted components [6, 43, 49]. A common approach involves running secure software on systems that rely on potentially untrustworthy CPUs [8, 16, 25].

Over the past two decades, numerous techniques have been developed to mitigate the impact of HTs by detecting them before system deployment. These methods are primarily circuit-level approaches that focus on identifying HTs during the design phase. They include techniques such as logic testing [11], formal property verification [51], side-channel analysis [29], structural and behavioral analysis [1, 33, 34], and ML [15, 23].

When considering possible attack vectors, CAD tools emerged as a significant threat to the security of FPGA-based systems [17, 45,

52]. Specifically, these tools can manipulate FPGA configurations by introducing HTs into the generated bitstreams [18, 44]. However, limited research has explored methods for detecting HTs embedded by malicious CAD tools in otherwise trusted IP cores.

To address this issue, a security rule-checking framework has recently been proposed, aiming to encourage using CAD tools designed to ensure system trustworthiness and security throughout the design process [26]. Additionally, ML-based approaches for detecting [32] and classifying [37] HTs within FPGA bitstreams, can offer a promising direction for verifying the reliability of CAD tools. These works [32, 37] studied using processor runtime features like HPCs for detection and classification. However, the available HPCs did not seem to significantly contribute to good detection/classification. The lack of relevance in their findings was likely due to the limited number of actual counters considered and possibly not selecting the most suitable ones for HT detection. In contrast, by utilizing gem5, we can access a much broader set of HPCs, eventually providing access to more relevant HPCs for HT detection without requiring access to hardware-specific features. These include several microprocessor behaviours and runtime characteristics, such as #data cache hits/misses, #branch mispredictions, #instruction cache hits/misses, and #data cache writebacks.

The gem5 simulator has been widely adopted in computer architecture research. It was introduced by Binkert et al. [7] as a flexible simulation environment for modelling CPUs, caches, and interconnects at both full-system and microarchitectural levels. After different extensions, it now supports multiple ISAs, including x86, ARM, MIPS, Power, and SPARC.

A community paper gathered some of the key advancements and major improvements throughout the years up to version 20.0+ [30], including improved cycle-level accuracy, system call emulation, and RISC-V support. Their work highlights the increasing adoption of gem5 for modern CPU and SoC research. Several studies have focused on extending gem5 to support the RISC-V architecture. Roelke and Stan [38] implemented RISC5, the first integration of RISC-V in gem5, enabling ISA-level simulations. Ta et al. [46] expanded this work by adding support for multi-core RISC-V simulations, validating synchronization mechanisms, and thread management. To improve simulation accuracy, Ganjehloo et al. [21] integrated gem5 with Chisel models, achieving cycle-accurate simulation at the microarchitectural level. This approach enables high-fidelity timing analysis for hardware components.

Gem5 simulation for security-focused research has seen increased adoption in recent years, e.g., for microarchitecture-related vulnerabilities. Ayoub and Maurice [5] have been the first to port Spectre on a x86 ISA on gem5. Forcioli et al. [19] proposed a virtual platform based on gem5 to analyze security vulnerabilities in CPUs and SoCs. Their study focused on transient execution attacks (Spectre, Meltdown), Side-Channel (Flush+Reload, Prime+Probe) and Fault Injection (Rowhammer) attacks, as well as hardware-level security issues such as TrustZone exploits. Similarly, Forcioli et al. [20] extended the analysis by investigating attacks against Trusted Execution Environments (TEE) using gem5, covering side-channel and transient execution threats in ARM, RISC-V, and x86 architectures. Awais et al. [4] analyzed patterns in instruction-based attacks using gem5, focusing on transient execution attacks such as Spectre and cache-based side-channel
<table><caption>Table 1: Related works based on security evaluations via gem5</caption><thead><tr><th rowspan="2">References</th><th colspan="8">Considered vulnerabilities</th><th colspan="3">Targeted ISA</th><th rowspan="2">M</th><th rowspan="2">D</th></tr><tr><th>Spectre</th><th>Meltdown</th><th>Flush+Reload</th><th>Prime+Probe</th><th>Rowhammer</th><th>ARM TrustZone</th><th>HTs</th><th>x86</th><th>ARM</th><th>RISC-V</th></tr></thead><tbody><tr><td>Ayoub et al. [5]</td><td>✓</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✓</td><td>✓</td><td></td><td></td><td></td></tr><tr><td>Forcioli et al. [19]</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td><td></td><td></td><td>✓</td><td>✓</td><td></td><td></td></tr><tr><td>Forcioli et al. [20]</td><td>✓</td><td>✓</td><td>✓</td><td>✓</td><td></td><td>✓</td><td></td><td>✓</td><td>✓</td><td>✓</td><td></td><td></td></tr><tr><td>Awais et al. [4]</td><td>✓</td><td></td><td>✓</td><td>✓</td><td></td><td></td><td></td><td>✓</td><td>✓</td><td></td><td></td><td>✓</td></tr><tr><td>De et al. [12]</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✓</td><td>✓</td><td></td><td>✓</td><td></td></tr><tr><td>Khan et al. [27]</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✓</td><td>✓</td><td></td><td>✓</td><td></td></tr><tr><td>Choudhari et al. [10]</td><td>✓</td><td></td><td>✓</td><td></td><td></td><td></td><td></td><td>✓</td><td></td><td></td><td>✓</td><td>✓</td></tr><tr><td>Peters et al. [35]</td><td></td><td></td><td>✓</td><td>✓</td><td></td><td></td><td></td><td></td><td></td><td>✓</td><td>✓</td><td>✓</td></tr><tr><td>This work</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✓</td><td></td><td>✓</td><td></td><td>✓</td></tr></tbody></table>

attacks like Flush+Reload and Prime+Probe. Their work provides valuable insights into attack behaviour and its impact on modern microarchitecture.

Gem5-emulated defensive mechanisms against transient execution attacks have been another major research focus. Choudhari et al. [10] proposed *SpecDefender*, a defence mechanism that leverages HPCs to detect Spectre-style transient execution attacks in real-time. Their work, implemented in gem5, demonstrates how speculative execution behaviour can be mitigated efficiently. Peters et al. [35] studied the impact of cache replacement policies on the security of randomized cache architectures. Their work, using a RISC-V core gem5, evaluates the resistance of randomized caching mechanisms to side-channel threats such as Prime+Probe, and Flush+Reload.

**At the confluence of HTs and gem5 simulation,** we can find some recent work. De et al. [12] introduced *HarTBleed*, an attack to exfiltrate sensitive data from a process's memory. The authors propose an HT into the microprocessor Translation Lookaside Buffer (TLB) that is triggered by repeated accesses to a specific L1 cache line. The HT's payload modifies an entry in the TLB to remap a virtual address controlled by the attacker with the goal of mapping a memory page containing sensitive data. Similarly, Khan et al. [27] demonstrated the *Cache-Out* attack that exploits an HT embedded in the CPU to leak cache memory data. The proposed attack assumes an HT implemented in the L1 data cache that is activated when a specific cache address is accessed repeatedly with a predefined data pattern. Once triggered, the HT manipulates SRAM peripherals such as word line underdrive and negative bit line mechanisms to induce read/write failures or leak data by exploiting column multiplexing. In this manuscript, we proposed a way to emulate and simulate the behaviour of an HT interfering with the processor fetch phase. Once a particular program memory line is addressed, the HT forces access to another particular memory location that could potentially contain a malicious instruction. Changing the value of the Program Counter (PC), this HT could also perform a Denial-of-Service attack. We also demonstrate the possibility of detecting such an HT using a simple ML model on the HPCs.

Table 1 summarizes related works on gem5-based microarchitectural security research. The columns M and D denote whether each work includes mitigation strategies or detection techniques, respectively.

# 3 Methodology

## 3.1 HT Simulation Framework In gem5

In gem5, the core and its components are defined through .cc source files, where users can specify the modules to be included in the simulated architecture. Once the simulator is built, configuration scripts—typically written in Python—allow users to set up and customize benchmark execution.

We utilized the gem5 simulator in System Emulation (SE) mode to create an environment for benign and attack scenarios. The SE mode allows user-space applications to run without needing a full operating system. Our simulation setup involved a RISC-V ISA model, specifically using the Riscv03CPU() core (available in gem5 as an out-of-order RISC-V processor model), with a set of benchmark applications designed to generate realistic execution patterns. 866 HPCs were extracted to capture execution behaviours.

To simulate the presence of an HT, we modify the required modules from the RISC-V processor built within gem5. In particular, for this work, we were inspired by the PIC16F84-T100 HT proposed on the Trust-Hub platform [41, 42, 47], which, in essence, manipulates the PC.

The particular description of the HT is as follows [47]: "The Trojan trigger, a state machine, observes the number of execution of specific instructions. Above a certain number of executions, the Trojan is triggered, and it changes the address to program memory." Its taxonomy according to TrustHub [47] is:

* Insertion phase: Design

* Abstraction level: Register Transfer

* Activation mechanism: Internally time-based triggered

* Effects: Denial-of-Service

* Location: Processor

* Physical characteristics: Functional

From a purely functional point of view, this description presents an HT whose payload manipulates the program memory by forcing access to a given address. To implement this behaviour, there are different points in gem5 where this can be done. Please note that we did not implement this HT; instead, we got inspiration from it. So, for this work, and without loss of generality, we took inspiration from this behaviour and emulated an HT that modifies the content of the PC when the program reaches a given address. This behaviour inherently sets a **threat model** that compromises the execution flow of a program by forcing the fetch of a specific instruction from memory, which could have been itself previously compromised.
Please note that with the provided HT description, other options are possible, e.g., considering the payload is activated during a data load instruction rather than during the instruction fetch phase. The specific modifications to model this behaviour are described in Section 4.

Once the modifications have been completed, by injecting this behaviour at runtime in a gem5 simulation, we can gather extensive runtime statistics to understand its impact on HPC values and devise an algorithm to detect its activation and possibly the HT type by leveraging embedded ML models.

## 3.2 Data Collection and Processing

We systematically collected HPC data from multiple simulation runs to build a comprehensive dataset for ML estimations. Our approach involved executing workloads (i.e., benchmarks) under both normal and attack conditions. We executed the different program runs in SE mode several times, for different random durations as described below, for both benign and compromised cores to simulate normal and attack conditions. For the workloads used, shown in Table 2, gem5 generated over 866 performance metrics per execution. Once the SE simulation is initialized and executed, gem5 dumps a statistics file at the end of each simulation containing an extensive set of performance statistics from HPCs, on which we relied for further analysis and ML-based detection. We used the default dump rate in gem5.

The benchmark programs used in this work are reported in Table 2. We built a dataset consisting of 10,000 samples, each of them containing the same 866 HPCs obtained through 5,000 executions on both the benign and compromised cores, respectively. Each of these 10,000 executions corresponds to one sample in the dataset, obtained by executing each benchmark program 625 times, each of them for a random time duration between 1 and 6 seconds of simulation time. Specifically, at the beginning of each execution, a random termination time within this interval was selected, and the processor simulation in gem5 was halted accordingly. On the emulated compromised core, the HT was triggered once per program execution.

## 3.3 ML Pipeline for HT Detection

Figure 1 shows the workflow of the proposed approach. The process begins with the gem5 simulator to model the behaviour of the benign and the compromised RISC-V core. Once the processor type is selected, it executes a set of benchmark programs, which generate execution patterns that allow for analysing processor behaviour under controlled conditions. After running the benchmarks, HPCs are extracted. If not enough data has been collected, the process loops back to execute additional benchmark runs until the dataset reaches the required size. Once the datasets for both the benign and attacked CPU are obtained as described in Section 3.2, we fed it to an ML pipeline.

In this work, we use an RF classifier as an exemplary use case to process the collected data and determine whether an HT is present and has been triggered. Please note how the framework can certainly accommodate any other ML model. The objective of this work is not to study different ML models but to prove how studying the impact of HT activation on HPCs can help computer

<table><caption>Table 2: Considered benchmarks</caption><thead><tr><td>Benchmark</td><td>Description</td></tr></thead><tbody><tr><td>AES</td><td>A symmetric encryption algorithm using the Rijndael cypher.</td></tr><tr><td>BlowFish</td><td>A fast symmetric-key block cypher designed for security and performance.</td></tr><tr><td>CRC</td><td>The Cyclic Redundancy Check, used for error detection in data transmission.</td></tr><tr><td>Dijkstra</td><td>An algorithm for finding the shortest path in a graph.</td></tr><tr><td>FFT</td><td>The Fast Fourier Transform, used for signal and image processing.</td></tr><tr><td>Idea</td><td>A block cipher used for secure data encryption.</td></tr><tr><td>QSORT</td><td>A sorting method that uses a recursive approach to sort data.</td></tr><tr><td>RSA</td><td>An asymmetric encryption algorithm based on prime factorization.</td></tr></tbody></table>

architects make informed decisions on which HPCs to include in a core to protect against a particular threat model.

The RF classifier pipeline consists of the following steps:

(1) **Feature Selection:** Extract the core HPCs that enhance accuracy.

(2) **Dataset Splitting:** Divide the dataset into training (80%) and testing (20%) sets to evaluate generalization.

(3) **Model Training:** Train our RF model as a proof of concept.

(4) **Evaluation:** Assess the model's performance.

The next section presents our experimental setup and provides the obtained results.

# 4 Evaluation

## 4.1 Experimental Set up

Our experiments were conducted on Ubuntu 22.04 OS running gem5 simulations on RISC-V SE mode. We used Python 3.8 with Scikit-learn, Pandas, NumPy, Seaborn, and Matplotlib libraries for data processing and ML. Several dependencies must be installed to set up the gem5 environment for RISC-V, including essential development tools and libraries. The required steps to set up the environment, clone gem5 and build the required RISC-V processor are included in Listing 1.

The command in line 9 of Listing 1 builds gem5 with the RISC-V ISA. The process is based on the .cc files present in the source directory, which define the hardware components of the processor to be built. These files describe the behaviour and structure of different architectural elements, such as cores, caches, and memory controllers, effectively enabling the emulation of a custom processor design. In particular, we built a RISC-V processor for our experiments, as shown in Figure 2.

Once the microprocessor has been successfully built, the gem5.opt executable should be generated. At this point, the environment is ready to run programs and collect statistical data. The Python script simple-riscv.py, available by default in the configs/learning_
<figure><img src="image_5.png" /><figcaption>Figure 1: The workflow of the proposed methodology.</figcaption></figure>

<figure><img src="image_6.png" /><figcaption>Figure 2: Basic architecture of the RISC-V simulated micro-processor.</figcaption></figure>

gem5/part1 path and reported in Listing 2 serves as the configuration file for the program run(s). This script allows for the specification of various core parameters, such as In-Order/Out-of-Order

execution, cache levels, memory size, and clock frequency. In particular, our configuration is as reported in Listing 2.

### Listing 1: Setup of gem5 Environment for RISC-V

```bash
# Install required dependencies
sudo apt install git zlib1g zlib1g-dev m4 build-essential
scons python3-dev libprotobuf-dev protbuf-compiler
libgoogle-perftools-dev libboost-all-dev device-tree
-compiler

# Clone the Gem5 repository
git clone https://github.com/gem5/gem5

# Enter the directory and build for RISC-V
cd gem5
python3 `which scons` build/RISCV/gem5.opt -j9
```

### Listing 2: RISC-V system configuration in gem5

```bash
# Clock Domain Configuration
system.clk_domain = SrcClockDomain()
system.clk_domain.clock = "1GHz"
system.clk_domain.voltage_domain = VoltageDomain()

# Memory Configuration
system.mem_mode = "timing" #timing-based simulation
system.mem Ranges = [AddrRange("512MB")]

# RISC-V CPU: Out-of-Order
system.cpu = Riscv03CPU()

# Create System Bus
system.membus = SystemXBar()

# Connect CPU Caches to System Bus
system.cpu.icache_port = system.membus.cpu_sideRALes
system.cpu.dcache_port = system.membus.cpu_sideRALes

# Setup Interrupt Controller
system.cpu.createInterruptController()

# Configure Main Memory (RAM)
system.memCtrl = MemCtrl()
system.memCtrl.dram = DDR3_1600_8x8()
system.memCtrl.dram. range = system.mem Ranges[0]
system.memCtrl.port = system.membus.mem_sideRALes

# Connect CPU to System Bus
system.system_port = system.membus.cpu_sideRALes

# Load Executable Binary
binary = os.path.join("tests/test-progs/hello/hello.o")
```

This Python script references a compiled binary file that the configured RISC-V processor will execute. The command to run the simulation on the built RISC-V is reported in Listing 3.

We precompiled the benchmark object files listed in Table 2 using the RISC-V toolchain for our experiments. These precompiled object files were then linked into the configuration file to facilitate program simulations. Upon completing each benchmark, the gem5 simulator generates the m5out/stats.txt file containing extensive runtime performance metrics. We executed multiple benchmark simulations as described previously and collected performance statistics from the HPCs dumped by gem5 for each run. These data points were subsequently used to build our dataset for further ML analysis.

### Listing 3: Gem5 Simulation Run

```bash
build/RISCV/gem5.opt configs/learning_gem5/part1/simple-riscv.py
```
4.1.1 Modelling PIC16F84-T100 in gem5. The HT considered as a case study in this work takes inspiration from the PIC16F84-T100 [47]. As described previously, this HT is located inside the processor, and its payload manipulates the address of the PC. As described earlier, our reinterpretation for this work, and without loss of generality, is that the HT effectively changes the value of the PC to address a different memory location with a potentially harmful instruction that would alter the execution flow. Figure 3 shows the idea of the HT action. To minimize the impact of the HT on the HPCs, we trigger the HT right after the PC reaches a specific location. The HT operates only once per program run.

<figure><img src="image_7.png" /><figcaption>Figure 3: The considered attack model action</figcaption></figure>

We first modified the base.cc file to implement our compromised core, altering the BaseSimpleCPU::setupFetchRequest function by inserting the code shown in Listing 4. This modification introduces an HT that manipulates the PC under specific conditions. Once the modification is applied, the compromised microprocessor model must be rebuilt. To do so, the command in line 9 of Listing 1 must be executed again.

Listing 4: Hardware Trojan Activation Code

```c
if (fetchPC == 0x017b48 && !flagBol) {
    fetchPC = 0x10656; // Malicious instruction redirect
    instAddr = 0x10656; // Update instruction address
    flagBol = true;}
```

1
2
3
4

We reproduced the MitM HT model considered in previous works [32, 37]. It operates by intercepting communication between the microprocessor and the instruction memory. It remains dormant until a specific trigger event occurs. The HT observes the value of fetchPC, which represents the PC of the CPU during instruction fetching. The trigger occurs when fetchPC reaches 0x017b48, indicating that a specific number of instructions have been executed. The condition !flagBol ensures that the attack is triggered only once per program run. Once the HT is triggered, fetchPC is modified to point to address 0x10656. This forces the program to deviate from its normal execution path and potentially execute malicious code. Additionally, the instruction address instAddr is updated to 0x10656, ensuring that the processor executes the instruction at the malicious address instead of continuing the expected control flow. After the injection, the PC resumes the execution of the legitimate and HT-free program.

## 4.2 Results

We evaluated our approach using an RF-based classification model, achieving 100% precision in HT detection. After running the models,

our analysis identified the most critical performance counters for this particular HT. The rank of the first fifty performance counters given by the RF from scikit-learn library is reported in Figure 4, where we include a basic description of the purpose of each HPC.

Previous works [32, 37] determined that HPCs were not suitable for detecting HTs. Their finding was based on a limited subset of performance counters, which may not have been the most relevant for effective detection. In this work, we pinpoint those with the highest discriminative power by considering a much broader set of 866 performance counters, significantly improving classification accuracy. Importantly, we observe how none of the HPCs used in those previous works are included in the 50 most important features found and reported here.

While our model achieves high accuracy, we acknowledge that we are, on one side, only detecting one HT and that accessing such a vast number of performance counters in real-world microprocessor applications may not always be feasible. However, our primary goal is to present a methodology for mapping HTs in the gem5 simulator and experiment with a simple ML model for detection to serve as a proof-of-concept to demonstrate its feasibility. Under more complex scenarios with other potential HTs, further work is certainly needed to identify good candidate HPCs and adequate ML models. Moreover, future work should also tackle an in-depth analysis of the reported HPCs useful for detecting each potential HT under study and how they are related to different CPU runtime behaviors.

# 5 Hardware Security Impact

The increasing complexity of modern microprocessors introduces new attack surfaces, making HT detection a crucial challenge. Our methodology enhances hardware security by systematically mapping and detecting HTs using the gem5 simulator. Our study leverages 866 performance counters, identifying those most relevant for HT detection. This approach improves the visibility into microprocessor behaviour, enabling a more precise and effective security analysis. Additionally, our ability to simulate and analyze HTs without requiring access to physical hardware allows security researchers to explore attack scenarios in a controlled environment, fostering a deeper understanding of microarchitectural vulnerabilities. The proposed framework offers several real-world applications in industrial and academic settings:

* **Security Verification in Microprocessor Design:** Hardware vendors can use our approach to assess the resilience of new microprocessor designs against HT threats during pre-silicon verification.

* **Threat Modeling for Secure Architectures:** Researchers can leverage our methodology to model attack scenarios and evaluate countermeasures, aiding in the design of more secure processors.

* **Hardware-Assisted Intrusion Detection:** Security teams in critical sectors (e.g., defence, finance, and telecommunications) can integrate performance counter-based anomaly detection systems to monitor real-time hardware execution and detect potential HTs.

* **Security Testing for Microprocessors:** Our framework can support security audits of microprocessor designs by
<figure><img src="image_8.png" /><figcaption>Figure 4: The most important 50 features to detect the considered HT.</figcaption></figure>

simulating malicious modifications and assessing their impact.

## 6 Conclusion

In this work, we proposed a methodology for introducing and simulating HTs within the gem5 simulator. Unlike previous studies focusing on FPGA-based detection, our approach enables a flexible and detailed microarchitectural analysis of HTs in a controlled simulation environment. By modifying the RISC-V processor model within gem5, we successfully mapped the execution of malicious modifications at the instruction-fetch level, providing a structured way to study their impact on microprocessor behaviour. This framework offers a reproducible way for ISA-independent analysis of HTs without requiring access to physical hardware, making it a valuable tool for security research. As a use case to complete the proposed methodology, we leveraged an ML-based detection approach, analyzing an extensive dataset of 866 performance counters extracted from simulated executions. Using an RF classifier, we achieved 100% precision in distinguishing between benign and compromised microprocessors. The methodology presented in this work assumes full access to performance counters, which may not always be

feasible on commercial hardware due to system constraints. However, our primary goal was establishing a structured approach for modelling and detecting HTs in gem5.

By establishing a methodology for introducing HTs into the gem5 simulator and demonstrating its feasibility through ML-based detection, this study provides a foundation for advancing microprocessor security research. As hardware-based threats continue to evolve, the need for robust, simulation-driven security analysis becomes increasingly critical. Our work contributes to this effort by offering a structured and scalable approach for evaluating malicious hardware modifications, paving the way for future innovations in HT detection and mitigation.

## References

[1] A. Palumbo et al. 2021. A Lightweight Security Checking Module to Protect Microprocessors against Hardware Trojan Horses. In *2021 IEEE International Symposium on Defect and Fault Tolerance in VLSI and Nanotechnology Systems (DFT)*. 1–6. doi:10.1109/DFT52944.2021.9568291

[2] A. Palumbo et al. 2023. Built-in Software Obfuscation for Protecting Microprocessors against Hardware Trojan Horses. In *2023 IEEE International Symposium on Defect and Fault Tolerance in VLSI and Nanotechnology Systems (DFT)*. 1–6. doi:10.1109/DFT59622.2023.10313534

[3] A. Palumbo et al. 2023. Improving the Detection of Hardware Trojan Horses in Microprocessors via Hamming Codes. In *2023 IEEE International Symposium on Defect and Fault Tolerance in VLSI and Nanotechnology Systems (DFT)*. 1–6.
doi:10.1109/DFT59622.2023.10313563

[4] Muhammad Awais et al. 2024. Decoding Attack Behaviors by Analyzing Patterns in Instruction-Based Attacks Using Gem5. In *2024 International Workshop on Rapid System Prototyping (RSP)*. 1–6. doi:10.1109/RSP64122.2024.10871078

[5] Pierre Ayoub and Clémentine Maurice. 2021. Reproducing Spectre Attack with Gem5: How to Do It Right?. In *Proceedings of the 14th European Workshop on Systems Security (EuroSec '21)*. Association for Computing Machinery, New York, NY, USA, 15–20. doi:10.1145/3447852.3548715

[6] A. Basak et al. 2017. Security Assurance for System-on-Chip Designs With Untrusted IPs. *IEEE Transactions on Information Forensics and Security* 12, 7 (2017), 1515–1528.

[7] Nathan Binkert et al. 2011. The Gem5 Simulator. *SIGARCH Comput. Archit. News* 39, 2 (Aug. 2011), 1–7. doi:10.1145/2024716.2024718

[8] G. Bloom et al. 2009. OS support for detecting Trojan circuit attacks. In *2009 IEEE International Workshop on Hardware-Oriented Security and Trust*. 100–103.

[9] Luca Cassano et al. 2022. Is RISC-V ready for Space? A Security Perspective. In *2022 IEEE International Symposium on Defect and Fault Tolerance in VLSI and Nanotechnology Systems (DFT)*. 1–6. doi:10.1109/DFT56152.2022.9962352

[10] Amit Choudhari et al. 2022. SpecDEFender: Transient Execution Attack Defender Using Performance Counters. In *Proceedings of the 2022 Workshop on Attacks and Solutions in Hardware Security (ASHES '22)*. Association for Computing Machinery, New York, NY, USA, 15–24. doi:10.1145/3560834.3563830

[11] X. Chuan et al. 2017. An efficient triggering method of hardware Trojan in AES cryptographic circuit. In *Proc. Int. Conf. Integrated Circuits and Microsystems*. 91–95.

[12] Asmit De et al. 2020. HarTBleed: Using Hardware Trojans for Data Leakage Exploits. *IEEE Transactions on Very Large Scale Integration (VLSI) Systems* 28, 4 (April 2020), 968–979. doi:10.1109/TVLSI.2019.2961358

[13] DIGITIMES. 2012. Trends in the global IC design service market. http://www.digitimes.com/news/a20120313RS400.html?chid=2

[14] Christopher Domas. 2018. Hardware Backdoors in x86 CPUs. https://i.blackhat.com/us-18/Thu-August-9/us-18-Domas-God-Mode-Unlocked-Hardware-Backdoors-In-x86-CPUS-wp.pdf.

[15] Chen Dong, Jinghui Chen, Wenzhong Guo, and Jian Zou. 2019. A machine-learning-based hardware-Trojan detection approach for chips in the Internet of Things. *International Journal of Distributed Sensor Networks* 15, 12 (2019), 1550147719888098.

[16] J. Dubeuf et al. 2013. Run-time detection of hardware Trojans: The processor protection unit. In *2013 18th IEEE European Test Symposium (ETS)*. 1–6.

[17] Adam Duncan et al. 2019. FPGA Bitstream Security: A Day in the Life. In *2019 IEEE International Test Conference (ITC)*. 1–10.

[18] Maik Ender et al. 2019. Insights into the mind of a trojan designer: the challenge to integrate a trojan into the bitstream. In *Proceedings of the 24th Asia and South Pacific Design Automation Conference*. 112–119.

[19] Quentin Forcioli et al. 2021. Virtual Platform to Analyze the Security of a System on Chip at Microarchitectural Level. In *2021 IEEE European Symposium on Security and Privacy Workshops (EuroS&PW)*. 96–102. doi:10.1109/EuroSPW54576.2021.00017

[20] Quentin Forcioli et al. 2023. A Gem5 Based Platform for Micro-Architectural Security Analysis. In *Proceedings of the 12th International Workshop on Hardware and Architectural Support for Security and Privacy (HASP '23)*. Association for Computing Machinery, New York, NY, USA, 91–99. doi:10.1145/3623652.3623674

[21] Nima Ganjehloo et al. 2018. Integrating Cycle-Accurate Chisel Models with Gem5's System Simulation. In *Chisel Community Conference*.

[22] Kevin Immanuel Gubbi et al. 2023. Hardware Trojan Detection Using Machine Learning: A Tutorial. *ACM Trans. Embed. Comput. Syst.* 22, 3, Article 46 (April 2023), 26 pages. doi:10.1145/3579823

[23] Zhao Huang et al. 2020. A Survey on Machine Learning Against Hardware Trojan Attacks: Recent Advances and Challenges. *IEEE Access* 8 (2020), 10796–10826.

[24] Y. Jin et al. 2012. Exposing vulnerabilities of untrusted computing platforms. In *Proc. Int. Conf. Computer Design*. 131–134.

[25] K. Arrikan et al. 2022. Processor Security: Detecting Microarchitectural Attacks via Count-Min Sketches. *IEEE Transactions on Very Large Scale Integration (VLSI) Systems* 30, 7 (2022), 938–951. doi:10.1109/TVLSI.2022.3171810

[26] K. Xiao et al. 2016. Security Rule Checking in IC Design. *Computer* 49, 8 (2016), 54–61.

[27] Mohammad Nasim Imtaiz Khan et al. 2020. Cache-Out: Leaking Cache Memory Using Hardware Trojan. *IEEE Transactions on Very Large Scale Integration (VLSI) Systems* 28, 6 (June 2020), 1461–1470. doi:10.1109/TVLSI.2020.2982188

[28] Konstantinos G others Liakos. 2019. Machine Learning for Hardware Trojan Detection: A Review. In *2019 Panhellenic Conference on Electronics & Telecommunications (PACET)*. 1–6. doi:10.1109/PACET48583.2019.8956251

[29] Y. Liu et al. 2017. SCCA: Side-channel correlation analysis for detecting hardware Trojan. In *Proc. Int. Conf. Anti-counterfeiting, Security, and Identification*. 196–200.

[30] Lowe-Power et al. 2020. The Gem5 Simulator: Version 20.0+. arXiv:2007.03152 [cs] (Sept. 2020). arXiv:2007.03152 [cs]

[31] Pegdwende Romaric Nikiema et al. 2023. Towards Dependable RISC-V Cores for Edge Computing Devices. In *2023 IEEE 29th International Symposium on On-Line Testing and Robust System Design (IOLTS)*. 1–7. doi:10.1109/IOLTS59296.2023.10224862

[32] Alessandro Palumbo et al. 2022. Is your FPGA bitstream Hardware Trojan-free? Machine learning can provide an answer. *Journal of Systems Architecture* 128 (2022), 102543. doi:10.1016/j.sysarc.2022.102543

[33] Alessandro Palumbo et al. 2023. Built-in Software Obfuscation for Protecting Microprocessors against Hardware Trojan Horses. In *2023 IEEE International Symposium on Defect and Fault Tolerance in VLSI and Nanotechnology Systems (DFT)*. IEEE, 1–6.

[34] Alessandro Palumbo et al. 2023. Improving the Detection of Hardware Trojan Horses in Microprocessors via Hamming Codes. In *2023 IEEE International Symposium on Defect and Fault Tolerance in VLSI and Nanotechnology Systems (DFT)*. IEEE, 1–6.

[35] Moritz Peters et al. 2024. On The Effect of Replacement Policies on The Security of Randomized Cache Architectures. In *Proceedings of the 19th ACM Asia Conference on Computer and Communications Security (ASIA CCS '24)*. Association for Computing Machinery, New York, NY, USA, 483–497. doi:10.1145/3634737.3637677

[36] Miodrag Potkonjak. 2010. Synthesis of trustable ICs using untrusted CAD tools. In *Proceedings of the 47th Design Automation Conference*. 633–634.

[37] Stefano Ribes et al. 2024. Machine Learning-Based Classification of Hardware Trojans in FPGAs Implementing RISC-V Cores.. In *ICISSP*. 717–724.

[38] Alec Roelke and Mircea R Stan. 2017. RISC5: Implementing the RISC-V ISA in Gem5. In *First Workshop on Computer Architecture Research with RISC-V (CARRV)*, Vol. 7.

[39] M. Rostami, F. Koushanfar, J. Rajendran, and R. Karri. 2013. Hardware Security: Threat Models and Metrics. In *Proc. Int. Conf. Computer-Aided Design*. 819–823.

[40] J. A. Roy et al. 2008. Extended abstract: Circuit CAD tools as a security threat. In *2008 IEEE International Workshop on Hardware-Oriented Security and Trust*.

[41] Hassan Salmani, Mohammad Tehranipoor, and Ramesh Karri. 2013. On Design Vulnerability Analysis and Trust Benchmarks Development. In *2013 IEEE 31st International Conference on Computer Design (ICCD)*, 471–474. doi:10.1109/ICCD.2013.6657085

[42] Bicky Shakya, Tony He, Hassan Salmani, Domenic Forte, Swarup Bhunia, and Mark Tehranipoor. 2017. Benchmarking of Hardware Trojans and Maliciously Affected Circuits. *Journal of Hardware and Systems Security* 1, 1 (March 2017), 85–102. doi:10.1007/s41635-017-0001-6

[43] D. M. Shila et al. 2015. FIDES: Enhancing trust in reconfigurable based hardware systems. In *2015 IEEE High Performance Extreme Computing Conference (HPEC)*. 1–7.

[44] Sandeep Sunkavilli et al. 2021. Analysis of Attack Surfaces and Practical Attack Examples in Open Source FPGA CAD Tools. In *2021 22nd International Symposium on Quality Electronic Design (ISQED)*. 504–509.

[45] Sandeep Sunkavilli et al. 2021. New Security Threats on FPGAs: From FPGA Design Tools Perspective. In *2021 IEEE Computer Society Annual Symposium on VLSI (ISVLSI)*. 278–283.

[46] Tuan Ta et al. 2018. Simulating Multi-Core RISC-V Systems in Gem5. In *Workshop on Computer Architecture Research with RISC-V*.

[47] Trust-Hub. 2024. Trust-Hub: A Community Platform for Hardware Security Research. https://trust-hub.org.

[48] N. G. Tsoutsos and M. Maniatakos. 2014. Fabrication Attacks: Zero-Overhead Malicious Modifications Enabling Modern Microprocessor Privilege Escalation. *IEEE Trans. Emerging Topics in Computing* 2, 1 (2014), 81–93.

[49] Dominik Šišeković et al. 2019. Control-Lock: Securing Processor Cores Against Software-Controlled Hardware Trojans. In *Proceedings of the 2019 on Great Lakes Symposium on VLSI (GLSVLSI '19)*. 27–32.

[50] Xinmu Wang et al. 2012. Software exploitable hardware Trojans in embedded processor. In *2012 IEEE International Symposium on Defect and Fault Tolerance in VLSI and Nanotechnology Systems (DFT)*. IEEE, 55–58.

[51] J. Zhang et al. 2015. VeriTrust: Verification for Hardware Trust. *IEEE Trans. Computer-Aided Design of Integrated Circuits and Systems* 34, 7 (2015), 1148–1161.

[52] Jiliang Zhang and Gang Qu. 2019. Recent attacks and defenses on FPGA-based systems. *ACM Transactions on Reconfigurable Technology and Systems (TRETS)* 12, 3 (2019), 1–24.