A smart, real-time security system that protects smart buildings from hackers trying to tamper with temperature and humidity sensors (like the DHT11) to hijack heating and cooling systems.
In this project, we performed an ARP Spoofing attack [ARP Spoofing: An attack where a hacker links their computer to the network gateway to intercept and modify sensor readings] to hijack and manipulate live sensor data. We then used this hijacked data to train our Machine Learning models, and we developed Snort Rules [Snort Rules: Network security rules used to detect and drop malicious traffic packets] to identify and block these spoofing attempts in real time.
π‘οΈ Enterprise Alignment & Relevance (BACnet/SC, ISA/IEC 62443, and Research Validation)
Today's modern building automation (Operational Technology, or OT) security relies on two primary layers:
- The Network Layer (BACnet Secure Connect - BACnet/SC): Standardized under ASHRAE 135, it uses TLS 1.3 encryption and X.509 digital certificates to secure communications. However, BACnet/SC only secures the "pipe." If a sensor is physically tampered with (e.g., heating it with a lighter) or a gateway is compromised, BACnet/SC will happily encrypt and deliver the fake readings.
- The Compliance Layer (ISA/IEC 62443): This global industrial standard mandates continuous behavioral monitoring and anomaly detection for control systems.
[vanilla-css-tip] Our system acts as the "brain" looking inside the encrypted BACnet/SC pipe. By analyzing data payloads at the application layer with our 3-tier hybrid engine, we detect semantic anomalies (fake drift, frozen drops, and data replays) that encryption cannot see. This directly satisfies the security logging and behavioral monitoring requirements of ISA/IEC 62443-4-2.
Our hybrid approach and next-gen roadmap are validated by three recent research publications:
- AI-Based Sensor Defense: Cybersecure Intelligent Sensor Framework for Smart Buildings (Sensors, Dec 2025)
- Validates: The industry standard of using hybrid ML (Random Forest/Ensembles) paired with rules to monitor sensor data integrity in smart buildings.
- Physics-Informed Diagnostics: Physics-Informed LLMs/Models for HVAC Anomaly Detection (NeurIPS 2025 Workshop on UrbanAI)
- Validates: The integration of thermodynamic and physical boundary constraints to improve model transparency and drastically reduce false alarm rates.
- Real-Time Adaptive Thresholds: Real-Time Adaptive Anomaly Detection in IIoT Environments (IEEE TNSM, 2024/2026)
- Validates: The necessity of dynamic drift adaptation and continuous feedback loops to handle fluctuating sensor data streams.
- 78.10% Overall Accuracy on multi-sensor streams.
- Interactive Web UI Dashboard built with Streamlit and Plotly.
- Human-in-the-Loop Feedback Engine for continuous adaptive learning.
As smart buildings automate climate control using IoT sensors, they introduce a critical vulnerability: the physical-digital overlap. If a hacker tampers with room temperature sensors, they can trick the central HVAC [Heating, Ventilation, and Air Conditioning] system into overheating or running continuously. This causes massive energy bills, physical equipment wear, and occupant discomfort.
While enterprise cloud security solutions exist, they are limited and slow. Uploading millions of sensor readings to the cloud creates latency [delay] and relies on constant internet connectivity. If the connection drops, the security drops.
To solve this, our project implements a real-time hybrid Intrusion Detection System (IDS) that runs directly at the smart building edge [Edge: Local processors in the building, rather than remote cloud servers]. This provides low-latency, resilient protection that works even if the building loses internet access.
Our framework uses a lightweight, highly efficient stack optimized for real-time edge processing:
- Deep Learning (PyTorch): We use an LSTM Autoencoder
[LSTM: Long Short-Term Memory model]configured with64 β 32units. Unlike heavy Transformer models, LSTMs are lightweight and designed for sequential temporal data (time-series), establishing a normal behavioral baseline[normal temperature profile]of the building and flagging zero-day[previously unseen]attacks purely based on elevated reconstruction error. - Machine Learning (Scikit-Learn): Runs Random Forest and Isolation Forest classifiers in parallel to classify specific attack signatures when anomalies are flagged.
- Sensor Simulation (DHT11): The DHT11 temperature and humidity sensor is the industry standard for climate control. We simulate DHT11 compromises because they model real-world attacks on HVAC systems, showing how fake readings can trigger physical utility failures.
- Web Dashboard (Streamlit & Plotly): A lightweight dashboard for live visualization of sensor streams and detection flags.
- Data Pipeline (Pandas & Numpy): Optimizes sliding temporal windows and feature extraction.
- Protocols (MQTT): Supports asynchronous event-driven streaming from physical edge devices.
In December 2023 (Ireland), cyber attackers targeted European water utility infrastructure, accessing internal supervisory systems via exposed IoT gateways. By tampering with sensor streams, the attackers attempted to manipulate water levels, flow meters, and chemical dosing values to trigger physical utility failures.
Traditional signature-based firewalls cannot detect these stealthy, low-and-slow manipulations. This project secures smart buildings against similar attacks in real time by continuously monitoring a sliding window of sensor readings (size = 30) and extracting key statistical features to block compromises at the edge:
temp_slope(Trend): Captures gradual shifts over time to block Drift Attacks.temp_std(Variance): Differentiates between flat stuck values (Drop Attacks) and high-frequency fluctuations (Noise Attacks).temp_range(Spread): Measures full peak-to-peak swings to identify Injection Attacks.temp_entropy(Shannon Entropy): Detects elevated randomness and high-frequency noise profiles.temp_max_jump&temp_spike: Identifies sudden absolute value deviations (spikes) indicative of malicious data injections.
No single detection technique is sufficient for advanced attacks. This system fuses three independent layers to achieve robust resilience:
graph TD
A[IoT Sensor Stream] --> B[Sliding Window Feature Extraction]
B --> C[3-Tier Detection Engine]
subgraph C [3-Tier Hybrid Engine]
C1[Tier 1: LSTM Autoencoder <br> Unsupervised Anomaly Flagging]
C2[Tier 2: ML Ensembles <br> Random Forest & Gradient Boosting]
C3[Tier 3: Statistical Rule Engine <br> Deterministic Boundary Checks]
end
C1 --> D[Anomaly Flag]
C2 --> E[Pattern Classification]
C3 --> F[Deterministic Bounds Check]
D & E & F --> G[Hybrid Decision Engine]
G --> H[Predict Attack Type]
H --> I[Human-in-the-Loop Override]
I --> J[(feedbackmemory.json)]
J -->|Continuous Adaptation| G
-
Tier 1: Unsupervised LSTM Autoencoder (Anomaly Detection)
- Trained exclusively on normal sensor data to establish a baseline of healthy building behavior.
- Compresses sequences (
LSTM 64 β LSTM 32) and reconstructs them. - Anomalies are flagged when the Mean Squared Error (MSE) reconstruction error exceeds a dynamic
3-sigmathreshold (Mean + 3 * Std).
-
Tier 2: Supervised ML Ensembles (Pattern Classification)
- Random Forest: Acts as the primary pattern learner, mapping sequence features (slope, std, range, entropy, spikes, jumps) to attack classes.
- Gradient Boosting (Currently Unused): Trained during offline setup, but its predictions are currently bypassed in the final online decision chain. We plan to integrate it using a voting ensemble.
- Isolation Forest: Operates in parallel to flag novel, unseen anomaly distributions.
-
Tier 3: Deterministic Rule Engine (Edge Case Defense)
- Runs alongside ML to catch clear physical limits.
- Injection Attack Rule: Triggered if
max_jump > 5.0Β°Corzscore_max > 5.0. - Replay Attack Rule: Compares the incoming data window to historical signatures in the buffer to catch repeated signals.
- Drift Attack Rule: Triggered when
abs(slope) > drift_threshold(0.05). - Drop Attack Rule: Triggered if
std < 0.1andrange < 0.4(freeze detection) orslope < -0.15(step drop). - Noise Attack Rule: Triggered if
std > 2.0andentropy > 1.5.
To prevent AI hallucinations and adapt to seasonal building operations, the framework incorporates a Continuous Feedback Learning Loop:
- System Prediction: The model analyzes a sensor window and outputs a prediction (e.g.,
Noise Attack | Confidence: Medium). - User Review: The administrator reviews the prediction via the Streamlit dashboard and overrides the label if it is a false positive.
- Memory Storage: Corrected feature vectors and their target labels are stored in
feedbackmemory.json. - Instant Matching: For subsequent inferences, the classification engine checks the feedback database for similar historical patterns, bypassing model errors and automatically correcting similar alerts in the future.
To bridge the remaining detection gaps and transition this prototype into a commercial-grade, rock-solid smart building security product, we are launching an aggressive technical upgrade roadmap divided into three core pillars:
- MCU Deployment [ESP32 / ARM Cortex-M]: We are quantizing
[shrinking model size and math precision]our PyTorch LSTM models so they can run directly on low-power, $5 microcontrollers inside wall-mounted thermostat sensors. - ONNX Gateway Acceleration: Deploying on edge gateway boxes (like Raspberry Pi 5 or NVIDIA Jetson Orin Nano). Exporting models to ONNX Runtime enables sub-millisecond hardware-accelerated predictions for thousands of rooms simultaneously.
- C++/Rust Feature Engineering: Rewriting the sliding-window feature calculations in C++ or Rust as a Python extension, dropping latency from milliseconds to microseconds.
- Multi-Modal Sensor Fusion: Temperature alone is easy to spoof. We are integrating CO2, air quality (VOCs), motion detectors (PIR), and HVAC power logs. If temperature spikes but the room is empty and the heater is off, the system automatically shuts down the spoofed stream.
- Physics-Informed Thermal Modeling: Connecting our dataset generator to building energy simulators like EnergyPlus to generate highly realistic normal baselines that factor in sunlight, windows, and insulation.
-
Constant-Time Replay Search via LSH: Instead of a limited sliding 100-window history, we are implementing Locality-Sensitive Hashing (LSH). LSH converts window waves into short signatures, allowing the detector to query a database of 10,000+ past windows in constant
$O(1)$ time to catch replays from days ago instantly. - Seasonal & Diurnal Adaptive Baselines: Temperature baselines naturally drift between day and night, and summer and winter. We are deploying an online adaptive baseline threshold that self-adjusts based on weather forecasts and time-of-day.
- Temporal Convolutional Networks (TCNs): Upgrading from recurrent LSTM models to 1D Temporal CNNs with dilated convolutions. CNNs process time-series windows in parallel, dramatically speeding up training and edge inference.
Resilient-IoT-Intrusion_Detection_System_for_Smart-Buildings/
βββ README.md # Main Project Documentation
βββ SECURITY.md # Security reporting guidelines
βββ .gitignore # Git ignore file
β
βββ IDS_Codebase/ # π Patched Production Codebase
β βββ app.py # Streamlit UI dashboard
β βββ hybrid_iot_ids.py # Core decision engine
β βββ feedback_engine.py # Feedback database manager
β βββ run_hybrid_demo.py # Automated demo pipeline
β βββ test_hybrid_iot_ids.py # Unit test suite
β βββ enhanced_iot_dataset_3sensors.csv # Multi-sensor active dataset
β βββ feedbackmemory.json # Pre-seeded feedback overrides
β βββ IMPLEMENTATION_SUMMARY.md # Enhanced metrics summary
β βββ detection/ # Replay and config submodules
β βββ features/ # Feature extraction submodules
β βββ DataSet Gen/ # Dataset generator scripts
β
βββ Snort_Rules/ # π‘οΈ Snort Rules & Cyber Scripts
β βββ detect.py # Original rules script
β βββ attacks.py # Original attacks simulator
β βββ cyber_output.pages # Research documentation
β
βββ Project_Documentation/ # π Combined Documentation & Resources
β βββ Minor Project Presentation.pptx.pptx # Semester-End PowerPoint Presentation
β βββ Cybersecure Intelligent Sensor Framework Smart Buildings.pdf # Academic PDF
β βββ Physics_Informed_LLM_HVAC_Anomaly_Detection.pdf # Academic PDF
β βββ RealTime_Adaptive_Anomaly_Detection_IIoT.pdf # Academic PDF
β βββ Resilient_Smart_Building_Cybersecurity.pdf # Academic PDF
β βββ IDS_MQTT_Report.docx # NIDS Snort Report
β βββ ... (other administration reports/forms)
β
βββ Datasets/ # π Combined Datasets & Database
β βββ dht11_dataset_10000.csv # Original 10k single-sensor dataset
β βββ log_temp.csv # Temperature log data
β βββ data_cleaner.py # Data preprocessing script
β βββ multi_sensor_cleaned_balanced.csv # Cleaned multi-sensor dataset
β
βββ hardware/ # π ESP8266 IoT Device Firmware Code
β βββ Device_01.ino # Device 1 (DHT11)
β βββ Device_02.ino # Device 2 (DHT11)
β βββ Device_03.ino # Device 3 (DHT22)
β
βββ plots_and_diagrams/ # Diagrams for README.md
β βββ ...
β
βββ archive/ # Exploratory work
βββ dht11-anomaly-detection-lstm-ae-replay-attack.ipynb # Jupyter notebook
π Live IoT Data Generation Layer (ESP8266 & DHT11/22 Firmware)
To test our Intrusion Detection System against live, real-time data, we deployed three physical microcontrollers to stream temperature and humidity telemetry over WiFi.
[Device_01: ESP8266 + DHT11] --(MQTT/WiFi)-->
[Device_02: ESP8266 + DHT11] --(MQTT/WiFi)--> [MQTT Broker: 192.168.1.8 (Port 1883)]
[Device_03: ESP8266 + DHT22] --(MQTT/WiFi)-->
- Device 01: ESP8266 connected to a DHT11 sensor at pin D4 (GPIO4).
- Device 02: ESP8266 connected to a DHT11 sensor at pin D4 (GPIO4).
- Device 03: ESP8266 connected to a DHT22 (high precision) sensor at pin D4 (GPIO4).
This C++ code keeps the MQTT connection alive, syncs time via NTP, and publishes JSON payloads to sensor/Device_XX every 5 seconds. The files are located in hardware/.
π‘οΈ Network Intrusion Detection (Snort 3 / Snort++ Rule Engine)
While our machine learning layers handle semantic attacks, we deploy Snort 3 to passively monitor network-level traffic (MQTT on port 1883 and ICMP probes) on our gateway interface (eth0).
βοΈ Execution Command
sudo snort -i eth0 -A alert_fast -c /etc/snort/snort.luaπ Custom Snort Rules
We developed custom rule definitions to detect MQTT scans, traffic flooding, and reconnaissance sweep events:
| Rule Name | Snort 3 Rule Definition | Purpose |
|---|---|---|
| MQTT Connection Attempt | alert tcp any any -> any 1883 (msg:"[IoT] MQTT Connection Attempt"; sid:2000001; rev:1;) |
Monitors active client connections to the broker. |
| SYN Packet Scan | alert tcp any any -> any 1883 (flags:S; msg:"[IoT] MQTT SYN Packet (Possible Scan)"; sid:2000002; rev:1;) |
Flags TCP SYN port scans targeting the MQTT port (e.g., Nmap). |
| High MQTT Traffic (DoS) | alert tcp any any -> any 1883 (msg:"[IoT] High MQTT Traffic"; detection_filter:track by_src, count 20, seconds 5; sid:2000003; rev:1;) |
Triggers if a source IP floods the broker with |
| Reconnaissance Ping | alert icmp any any -> any any (msg:"[IoT] Ping Detected"; sid:2000004; rev:1;) |
Flags ICMP echo sweep requests identifying active nodes on the network. |
π οΈ Simulated Attack Scenarios Tested
-
Reconnaissance Sweep: Attacker runs
ping 192.168.1.8. Snort raises[IoT] Ping Detectedalerts. -
Port Scan Detection: Attacker runs
nmap -p 1883 192.168.1.8. Snort raises[IoT] MQTT SYN Packet (Possible Scan). -
Denial of Service (DoS): Attacker runs an MQTT message flood.
Snort flags the anomalous traffic burst and generates
for i in {1..30}; do mosquitto_pub -h 192.168.1.8 -t test -m "attack"; done
[IoT] High MQTT Trafficalerts.
[!TIP] For the full screenshots, network logs, and rule stats, see the IDS_MQTT_Report.docx inside the
Project_Documentation/folder.
Recommended: Python 3.13 (Stable Release)
Note
Python 3.13 is recommended for maximum compatibility.
Newer pre-release versions (such as Python 3.14) may not yet have stable builds of TensorFlow or PyTorch available for Windows.
pip install pandas numpy scikit-learn tensorflow streamlit plotly matplotlibAlternatively, if a requirements.txt file is available:
pip install -r requirements.txtcd IDS_CodebaseStart the Streamlit web application:
streamlit run app.pyAfter execution, open your browser and visit:
http://localhost:8501
Execute the automated demonstration pipeline:
python run_hybrid_demo.pyRun the complete test suite to verify functionality:
python -m unittest test_hybrid_iot_ids.py| Component | Technology |
|---|---|
| Language | Python 3.13 |
| Dashboard | Streamlit |
| Machine Learning | TensorFlow |
| Data Processing | Pandas, NumPy |
| Visualization | Plotly, Matplotlib |
| Testing | unittest |
| Algorithms | Scikit-learn |
Install Dependencies
β
Launch Dashboard
β
Run Hybrid Demo
β
Execute Tests
β
Analyze Results