CoolFace
Apppublic

mdghufran/iot-fingerprinting

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
App README

IoT Device Fingerprinting & Anomaly Detection Framework

![Python](https://www.python.org/) ![scikit-learn](https://scikit-learn.org/) ![FastAPI](https://fastapi.tiangolo.com/) ![Dash](https://dash.plotly.com/) ![License](LICENSE) ![Dataset](https://archive.ics.uci.edu/dataset/442) ![Accuracy]() ![HuggingFace](https://mdghufran-iot-fingerprinting.hf.space)

M.Tech Cyber Forensics โ€” Final Semester Thesis NIELIT Srinagar  |  Md Ghufran Alam  |  Roll No. NDU202400038

Live Deployment

URL
Live Dashboardhttps://mdghufran-iot-fingerprinting.hf.space
API Docshttps://mdghufran-iot-fingerprinting.hf.space/docs
API Healthhttps://mdghufran-iot-fingerprinting.hf.space/status
HuggingFace Spacehttps://huggingface.co/spaces/mdghufran/iot-fingerprinting
LinkedIn Posthttps://www.linkedin.com/feed/update/urn:li:activity:7460802322206650368/
Deployed on HuggingFace Spaces (Docker) โ€” fully live, no local setup required.

A production-grade machine learning system that fingerprints IoT devices by their network traffic signature and detects Mirai / BASHLITE botnet attacks in real time โ€” without installing anything on the devices themselves.

Trained on the real N-BaIoT dataset (UCI ML Repository #442) featuring 9 physical IoT devices and live attack traffic. Delivers results through a FastAPI REST interface and a live Plotly Dash dashboard, with full SHAP explainability on every prediction.


Table of Contents


Overview

Smart home devices โ€” cameras, thermostats, smart bulbs โ€” cannot run antivirus software. Yet they are the most common entry point for botnets. The Mirai botnet (2016) compromised over 600,000 IoT devices and took down Twitter, Netflix, and Reddit with a single DDoS attack. BASHLITE followed the same playbook.

Traditional network security tools cannot defend against this because they do not know what device they are looking at or what normal behaviour looks like for that device.

This framework solves both problems directly from network traffic โ€” no agent software, no device modification required:

QuestionAnswer
"Which device is this on my network?"Device Fingerprinting โ€” Random Forest on 37 flow features (100% accuracy)
"Is it behaving normally right now?"Anomaly Detection โ€” per-device Isolation Forest + One-Class SVM ensemble
"Why did the model flag this?"SHAP Explainability โ€” top-10 feature contributions per prediction

All three answers arrive in a single POST /analyze call, in under 40 ms.


Screenshots

Live Dashboard

[image] Main dashboard โ€” anomaly score timeline, detected device types, and real-time stats

[image] Alerts by severity (HIGH / CRITICAL) + anomaly score gauge + recent alert feed

SHAP Explainability

[image] Live SHAP panel โ€” top features that drove the model's last prediction (green = toward device, red = away)

FastAPI REST Interface

[image] Dark-themed Swagger UI at `http://localhost:8000/docs` โ€” all 8 endpoints

[image] `GET /health` response โ€” models loaded, SHAP ready, 36 ms latency


Key Results

Device Fingerprinting (8 IoT device types)

ModelTest AccuracyROC-AUC
Random Forest (primary)100.00%1.0000
Gradient Boosting100.00%1.0000
Voting Ensemble (RF+GB+SVM)100.00%1.0000
SVM (RBF)94.89%0.9967

Anomaly Detection (Real Mirai / BASHLITE attacks)

DeviceAUC-ROCF1
Smart Doorbell0.87730.4811
Smart Thermostat0.85900.3963
Motion Sensor0.79460.2206
Smart TV0.77320.2415
Smart Plug0.73410.2990
Smart Camera0.71250.2610
Note: Lower F1 on anomaly detection is expected and realistic โ€” Mirai/BASHLITE are engineered to blend with normal traffic. AUC-ROC is the threshold-independent metric used here.

Architecture

Network Flow (37 features)
         โ”‚
         โ–ผ
  RobustScaler (normalization)
         โ”‚
    โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
    โ”‚                         โ”‚
    โ–ผ                         โ–ผ
Device Fingerprinting    Anomaly Detection
(Random Forest)          (IF + OC-SVM ensemble)
    โ”‚                         โ”‚
    โ–ผ                         โ–ผ
Device Label             Anomaly Score
+ Confidence             + Severity
    โ”‚                         โ”‚
    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
               โ–ผ
         Alert Manager
               โ”‚
    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
    โ–ผ                     โ–ผ
FastAPI REST API     Plotly Dash
(port 8000)          (port 8050)

Features

#FeatureDetail
1Real N-BaIoT Dataset9 physical IoT devices, Mirai + BASHLITE attacks (UCI #442)
2100% Fingerprinting AccuracyRandom Forest on 37 network flow features
3Unsupervised Anomaly DetectionNo labeled attack data needed โ€” trains only on normal traffic
4Per-Device ModelsEach device type gets its own dedicated anomaly detector
5SHAP Explainability (XAI)Top-10 feature contributions shown for every prediction
6REST APIFastAPI + dark-themed Swagger UI on port 8000
7Live DashboardPlotly Dash with real-time alert feed and charts on port 8050
8SMOTE BalancingHandles class imbalance automatically during training
9Alert ManagementFour severity levels โ€” LOW / MEDIUM / HIGH / CRITICAL

Quick Start

1. Clone the repository

bash
git clone https://github.com/Ghufran2002/iot-fingerprinting-framework.git
cd iot-fingerprinting-framework

2. Create a virtual environment (recommended)

bash
python -m venv venv

# Windows
venv\Scripts\activate

# Linux / macOS
source venv/bin/activate

3. Install dependencies

bash
pip install -r requirements.txt

4. Download real dataset & train models

bash
python train.py --download

This will:

  • โ€”Download the N-BaIoT dataset (~1.7 GB, one-time) from UCI ML Repository
  • โ€”Train all fingerprinting + anomaly models
  • โ€”Generate 10 evaluation plots in plots/
Slow internet? Manually download from Kaggle N-BaIoT and extract to data/nbaiot/

5. Start the system

bash
python run.py
ServiceURL
REST API Docshttp://localhost:8000/docs
Live Dashboardhttp://localhost:8050

Training Modes

bash
python train.py --download   # Download N-BaIoT + train hybrid (recommended)
python train.py --hybrid     # Real N-BaIoT + synthetic fill-in
python train.py --real       # Real N-BaIoT only
python train.py              # Synthetic data only (no download needed)

Dataset

N-BaIoT โ€” Detection of IoT Botnet Attacks Source: UCI ML Repository #442

Real DeviceMapped Label
Danmini Doorbellsmart_doorbell
Ecobee Thermostatsmart_thermostat
Provision PT-737E Security Camerasmart_camera
Provision PT-838 Security Camerasmart_speaker
Samsung SNH-1011N Webcamsmart_tv
Philips B120N Baby Monitorsmart_bulb
SimpleHome XCS7-1002 Camerasmart_plug
Ennio Doorbellmotion_sensor

Attack types included: Mirai (ack, scan, syn, udp, udpplain) + BASHLITE/Gafgyt (combo, junk, scan, tcp, udp)


37 Network Flow Features

CategoryFeatures
Temporal (5)flowduration, meaniat, stdiat, miniat, max_iat
Volume (4)packetcount, bytecount, packetrate, byterate
Packet Size (4)meanpktsize, stdpktsize, minpktsize, maxpktsize
Protocol Flags (6)tcpratio, udpratio, synratio, finratio, rstratio, ackratio
Application Layer (8)ishttps, ismqtt, iscoap, ismdns, isntp, dnsquerycount, wellknownportratio, is_encrypted
Traffic Direction (3)uploadbytes, downloadbytes, uploaddownloadratio
Destination (7)uniquedestports, uniquedestips, portentropy, ipentropy, wellknownportscount, meandestport, stddest_port

Project Structure

iot-fingerprinting-framework/
โ”‚
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ data/
โ”‚   โ”‚   โ”œโ”€โ”€ generator.py        # Synthetic dataset generator
โ”‚   โ”‚   โ”œโ”€โ”€ preprocessor.py     # RobustScaler + SMOTE + train/val/test split
โ”‚   โ”‚   โ”œโ”€โ”€ real_loader.py      # N-BaIoT loader + 115โ†’37 feature mapping
โ”‚   โ”‚   โ””โ”€โ”€ download_real.py    # One-click N-BaIoT downloader
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ features/
โ”‚   โ”‚   โ””โ”€โ”€ extractor.py        # 37 feature names + 8 device type definitions
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ models/
โ”‚   โ”‚   โ”œโ”€โ”€ fingerprinter.py    # RF / GB / SVM / VotingEnsemble classifier
โ”‚   โ”‚   โ”œโ”€โ”€ anomaly_detector.py # Per-device IsolationForest + OneClassSVM
โ”‚   โ”‚   โ””โ”€โ”€ trainer.py          # End-to-end training pipeline + plots
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ api/
โ”‚   โ”‚   โ””โ”€โ”€ main.py             # FastAPI app with 8 endpoints + SHAP
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ dashboard/
โ”‚   โ”‚   โ””โ”€โ”€ app.py              # Plotly Dash live dashboard
โ”‚   โ”‚
โ”‚   โ””โ”€โ”€ utils/
โ”‚       โ”œโ”€โ”€ alert_manager.py    # Alert severity + deduplication
โ”‚       โ””โ”€โ”€ logger.py           # loguru logger setup
โ”‚
โ”œโ”€โ”€ data/
โ”‚   โ””โ”€โ”€ iot_flows.csv           # Synthetic dataset (fallback, 1600 rows)
โ”‚
โ”œโ”€โ”€ plots/                      # Auto-generated evaluation charts
โ”‚   โ”œโ”€โ”€ cm_random_forest.png
โ”‚   โ”œโ”€โ”€ roc_curves.png
โ”‚   โ”œโ”€โ”€ feature_importance.png
โ”‚   โ”œโ”€โ”€ anomaly_scores.png
โ”‚   โ””โ”€โ”€ ...
โ”‚
โ”œโ”€โ”€ models/                     # Saved .pkl files (git-ignored, regenerate via train.py)
โ”‚
โ”œโ”€โ”€ tests/
โ”‚   โ””โ”€โ”€ test_pipeline.py
โ”‚
โ”œโ”€โ”€ train.py                    # Training entry point
โ”œโ”€โ”€ run.py                      # Start API + Dashboard
โ”œโ”€โ”€ requirements.txt
โ””โ”€โ”€ README.md

API Reference

EndpointMethodDescription
/healthGETSystem status, uptime, models loaded
/devicesGETList all 8 supported device types
/fingerprintPOSTIdentify device type from network flow
/anomaly/scorePOSTGet anomaly score for a known device
/analyzePOSTCombined fingerprint + anomaly in one call
/explainPOSTSHAP top-10 feature contributions
/alerts/recentGETRecent anomaly alerts
/metricsGETAPI stats, alert counts

Example โ€” Analyze a flow

bash
curl -X POST http://localhost:8000/analyze \
  -H "Content-Type: application/json" \
  -d '{
    "features": {
      "flow_duration": 90,
      "mean_iat": 0.003,
      "packet_count": 28000,
      "byte_count": 42000000,
      "tcp_ratio": 0.95,
      "is_https": 1.0,
      "mean_dest_port": 443
    }
  }'

Response:

json
{
  "fingerprint": {
    "device_type": "smart_camera",
    "confidence": 0.9876,
    "is_known": true
  },
  "anomaly": {
    "anomaly_score": 0.21,
    "is_anomalous": false,
    "severity": null,
    "threshold": 0.75
  }
}

Plots

All plots are auto-saved to plots/ after running train.py:

PlotDescription
cm_random_forest.pngConfusion matrix โ€” Random Forest
roc_curves.pngROC curves per device (one-vs-rest)
feature_importance.pngTop 15 features by Gini importance
model_comparison.pngAccuracy comparison across 4 models
precision_recall_f1.pngMacro P/R/F1 for all models
anomaly_scores.pngNormal vs attack score distribution
device_distribution.pngDataset composition pie chart
shap_bar.pngGlobal SHAP feature importance
shap_per_device.pngPer-device SHAP summary

Tech Stack

LayerTechnology
LanguagePython 3.9+
MLscikit-learn 1.3+
Class Balancingimbalanced-learn (SMOTE)
ExplainabilitySHAP (TreeExplainer)
REST APIFastAPI + Pydantic + Uvicorn
DashboardPlotly Dash
Model Persistencejoblib
Loggingloguru
Visualizationmatplotlib + seaborn

Citation

If you use this framework or the N-BaIoT dataset, please cite:

bibtex
@dataset{nbaiot2018,
  author    = {Meidan, Yair and Bohadana, Michael and Mathov, Yael and
               Mirsky, Yisroel and Shabtai, Asaf and Breitenbacher, Dominik and Elovici, Yuval},
  title     = {N-BaIoT: Network-based Detection of IoT Botnet Attacks Using Deep Autoencoders},
  year      = {2018},
  publisher = {UCI Machine Learning Repository},
  url       = {https://archive.ics.uci.edu/dataset/442}
}

License

This project is released under the MIT License. You are free to use, modify, and distribute it with attribution.


<div align="center">

<sub>Designed and developed as part of M.Tech Cyber Forensics thesis work</sub>

Md Ghufran Alam Roll No. NDU202400038 &nbsp;|&nbsp; M.Tech Cyber Forensics &nbsp;|&nbsp; NIELIT Srinagar &nbsp;|&nbsp; 2026

<sub>If this project helped you, consider giving it a โญ on GitHub</sub>

</div>