Prateek-Pulastya/Hydroficient-Externship

GitHub: Prateek-Pulastya/Hydroficient-Externship

面向酒店水务监测场景的安全IoT MQTT管道项目,采用TLS/mTLS、HMAC签名与重放防御构建四层防护并通过攻击模拟验证。

Stars: 0 | Forks: 0


![Python](https://img.shields.io/badge/Python-3.10+-1B3A6B?style=for-the-badge&logo=python&logoColor=white) ![MQTT](https://img.shields.io/badge/MQTT-Mosquitto-2563A8?style=for-the-badge&logo=eclipse-mosquitto&logoColor=white) ![TLS](https://img.shields.io/badge/TLS%201.3-Enabled-166534?style=for-the-badge&logo=letsencrypt&logoColor=white) ![Streamlit](https://img.shields.io/badge/Streamlit-Dashboard-FF4B4B?style=for-the-badge&logo=streamlit&logoColor=white) ![Attacks Blocked](https://img.shields.io/badge/Attacks%20Blocked-100%25-166534?style=for-the-badge&logo=shield&logoColor=white) ![mTLS](https://img.shields.io/badge/mTLS-Device%20Auth-1B3A6B?style=for-the-badge&logo=openssl&logoColor=white) ![HMAC](https://img.shields.io/badge/HMAC-SHA256-2563A8?style=for-the-badge&logo=gnuprivacyguard&logoColor=white) ![Status](https://img.shields.io/badge/Status-Complete-166534?style=for-the-badge)
## 📌 项目背景 | 字段 | 详情 | |-------|---------| | **客户** | Grand Marina Hotel — HYDROLOGIC 水监测系统 | | **角色** | 安全工程师实习生 | | **周期** | 2026 年 2 月 – 4 月 \| 远程 | | **技术栈** | Python · Mosquitto MQTT · TLS/mTLS · HMAC-SHA256 · Streamlit | | **成果** | 在所有模拟威胁场景中实现了零次成功攻击 | ## 🎯 问题陈述 未受保护的 IoT pipeline 会将运营基础设施暴露于三种基本的攻击类型之下: ``` ┌─────────────────────────────────────────────────────────────────────┐ │ UNPROTECTED MQTT PIPELINE │ │ │ │ Sensor ──────────► Broker ──────────► Subscriber │ │ plaintext plaintext │ │ │ │ ❌ Eavesdrop → Attacker reads all sensor data in real time │ │ ❌ Inject → Attacker sends false readings into the system │ │ ❌ Replay → Attacker resends old messages as current data │ └─────────────────────────────────────────────────────────────────────┘ ``` ## 🏗️ 架构 ``` ┌─────────────────────────────────────────────────────────────────────────────┐ │ SECURED PIPELINE ARCHITECTURE │ │ │ │ ┌──────────────┐ TLS + mTLS ┌──────────────────┐ │ │ │ IoT Sensor │ ──────────────► │ MQTT Broker │ │ │ │ Publisher │ │ Mosquitto │◄─── ca.pem │ │ │ (Python) │ │ Port 8883 (TLS) │ server.pem │ │ └──────────────┘ └────────┬─────────┘ │ │ │ │ │ ┌──────────────┐ ┌────────▼─────────┐ │ │ │ Attacker │ ──── BLOCKED ──►│ Validation │ │ │ │ attack.py │ (no cert / │ Engine │ │ │ │ fake_pub() │ bad HMAC / │ HMAC + Timestamp │ │ │ │ replay() │ expired ts) │ + Sequence Check │ │ │ └──────────────┘ └────────┬─────────┘ │ │ │ │ │ ┌────────▼─────────┐ │ │ │ Streamlit │ │ │ │ Security │ │ │ │ Dashboard │ │ │ └──────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` **证书信任链:** ``` Certificate Authority (ca.pem) ├── Server Certificate (server.pem + key) → MQTT Broker identity └── Client Certificates (device-N.pem) → IoT device identity ``` ## 🛡️ 防御栈 — 四层防御 每一层都会消除一个特定的攻击向量。移除其中一层 —— 该攻击就会成功。 ### 第 1 层 — TLS 加密 ``` # Broker 配置 — 在端口 8883 上强制执行 TLS listener 8883 cafile /certs/ca.pem certfile /certs/server.pem keyfile /certs/server.key require_certificate true ``` | 启用 TLS 前 | 启用 TLS 后 | |-----------|----------| | ❌ 所有流量均可通过抓包读取 | ✅ 流量完全加密 — 没有私钥则无法读取 | | ❌ 传感器数据、压力、流量暴露 | ✅ 网络观察者对数据零可见性 | **性能:** 延迟增加 `< 1ms` — 可忽略不计。 ### 第 2 层 — 双向 TLS (mTLS) 设备身份 TLS 对流量进行加密。mTLS 则强制执行 **谁可以连接**。 ``` # Client 连接 — 必须提供 device certificate client.tls_set( ca_certs="certs/ca.pem", certfile="certs/device-001.pem", # unique per device keyfile="certs/device-001.key", tls_version=ssl.PROTOCOL_TLS ) ``` | 设备状态 | Broker 响应 | |-------------|----------------| | ✅ 有效的证书 | `CONNECTED` | | ❌ 无证书 | `Connection refused: TLS handshake failed` | | ❌ 错误的 CA | `Connection refused: certificate verify failed` | | ❌ 过期的证书 | `Connection refused: certificate has expired` | **连接开销:** `+2.1 ms` — 以 0.1% 的成本实现完整的设备身份强制执行。 ### 第 3 层 — HMAC 消息签名 mTLS 验证 **身份**。HMAC 验证 **完整性**。 被攻陷的授权设备仍然可以发送被篡改的数据 — HMAC 能够检测到这一点。 ``` import hmac, hashlib, json def sign_message(payload: dict, secret: str) -> dict: body = json.dumps(payload, sort_keys=True) signature = hmac.new( secret.encode(), body.encode(), hashlib.sha256 ).hexdigest() return {**payload, "hmac": signature} def verify_message(message: dict, secret: str) -> bool: received_hmac = message.pop("hmac", None) body = json.dumps(message, sort_keys=True) expected = hmac.new(secret.encode(), body.encode(), hashlib.sha256).hexdigest() return hmac.compare_digest(received_hmac, expected) ``` 对 payload 的任何修改 — 哪怕只有一个字符 — 都会使签名失效。 ### 第 4 层 — 重放攻击防御 即使是来自授权设备的合法、已签名消息也可能被重放。 该层强制执行 **新鲜度** 和 **唯一性**。 ``` def validate_replay_defenses(message: dict, seen_counters: set) -> tuple[bool, str]: # Freshness check — reject messages older than 10 seconds msg_time = message.get("timestamp") if abs(time.time() - msg_time) > 10: return False, "REJECTED: Message expired (timestamp)" # Uniqueness check — reject duplicate sequence numbers seq = message.get("seq") if seq in seen_counters: return False, "REJECTED: Duplicate message (replay)" seen_counters.add(seq) return True, "ACCEPTED" ``` ## 🧪 实验结果 ### 重放防御 — 隔离测试 | 防御配置 | 立即重放 | 延迟重放 (60s+) | 篡改重放 | |----------------------|:----------------:|:---------------------:|:---------------:| | 无防御 | ❌ 0% 拦截 | ❌ 0% 拦截 | ❌ 0% 拦截 | | 仅 Timestamp | ❌ 0% 拦截 | ✅ 100% 拦截 | ❌ 0% 拦截 | | 仅 Counter | ✅ 100% 拦截 | ✅ 100% 拦截 | ❌ 0% 拦截 | | **三者结合** | **✅ 100%** | **✅ 100%** | **✅ 100%** | ### 完整攻击模拟 — 最终结果 ``` ┌────────────────────┬──────────────────────────┬─────────────────────────┬──────────┐ │ Attack Phase │ What Attacker Tried │ Defense That Caught │ Result │ ├────────────────────┼──────────────────────────┼─────────────────────────┼──────────┤ │ Phase 1: Eavesdrop│ Read MQTT traffic │ TLS Encryption │ BLOCKED │ │ Phase 2: Inject │ Send fake device messages │ mTLS + HMAC │ BLOCKED │ │ Phase 3: Replay │ Resend captured messages │ Timestamp + Counter │ BLOCKED │ │ Phase 4: Tamper │ Modify payload and resend │ HMAC Signature │ BLOCKED │ └────────────────────┴──────────────────────────┴─────────────────────────┴──────────┘ ✅ Valid messages accepted: 70 🚫 Attacks blocked: 4 attack types, 100% rejection rate 📊 Total messages processed: 74 ``` ## 📊 安全仪表盘 使用 Streamlit 构建 — 将后端安全控制转化为实时的运营可见性。 **仪表盘功能:** - 实时传感器数据 — 所有酒店区域的压力 (PSI)、流量 (LPM)、闸门位置 - 带有时间戳的实时安全事件日志 - 攻击检测警报,包含攻击类型、源设备和拦截确认 - 安全状态指示器 — HMAC + timestamp + 序列验证状态 - 基于区域的监控 — 主楼、泳池与水疗中心、厨房与洗衣房 **仪表盘实时捕获攻击:** ``` [16:52:43] ✅ Main Building: pressure=60.71 PSI, flow=50.36 LPM [16:54:22] 🚨 ATTACK DETECTED Type: Message Tampering Source: HYDROLOGIC-Device-001 Target: Water System Status: BLOCKED BY SECURITY SYSTEM [16:54:23] ✅ Main Building: pressure=61.27 PSI, flow=51.19 LPM ``` ## 🔬 威胁模型 (STRIDE) | 攻击向量 | STRIDE 类别 | 防御手段 | |--------------|----------------|---------| | 窃听 — 读取传感器流量 | 信息泄露 | TLS 加密 | | 未经授权的发布 — 注入伪造数据 | 伪造 | mTLS 证书认证 | | 重放攻击 — 重发捕获的消息 | 重放 | Timestamp + Counter | | 设备冒充 — 伪造传感器身份 | 伪造 | mTLS + 证书 CA | | 消息篡改 — 修改 payload | 篡改 | HMAC-SHA256 签名 | ## 💡 关键工程洞察 **1. 身份 ≠ 完整性** mTLS 验证 *谁发送了* 数据。HMAC 验证 *数据未被更改*。这些是截然不同的安全属性 — 只有同时强制执行这两者,系统才是安全的。 **2. 重放攻击绕过了传统的安全假设** 如果没有新鲜度验证,即使完全加密和双向认证的系统也容易受到重放攻击。这是 IoT 部署中最容易被忽视的攻击向量之一。 **3. 纵深防御是不可妥协的** 每一层都有盲点: - mTLS 阻止外部攻击者 — 但无法阻止被攻陷的内部人员 - HMAC 阻止伪造 — 但无法阻止对有效签名消息的重放 - Timestamp 阻止延迟重放 — 但无法阻止即时重放 - Counter 阻止即时重放 — 但无法阻止被篡改的消息 只有将它们结合起来才能实现全面保护。 **4. 可见性是一项安全要求** 技术上安全但无法产生可观察输出的 pipeline 提供的运营价值为零。仪表盘将加密控制转化为可操作的情报。 ## 📁 项目结构 ``` hydrologic-security/ │ ├── certs/ # Certificate infrastructure │ ├── ca.pem # Certificate Authority │ ├── server.pem / server.key # Broker identity │ └── device-001.pem / .key # Device identity (per device) │ ├── publisher.py # Secure IoT sensor simulator ├── subscriber.py # Validation engine (HMAC + replay defense) ├── attack.py # Attack simulation suite │ ├── eavesdrop() # Packet capture simulation │ ├── fake_publish() # Unauthorized injection │ └── replay_attack() # Replay attack simulation │ ├── dashboard.py # Streamlit security dashboard ├── anomaly_detection.py # Isolation Forest AI layer (Week 8) │ ├── mosquitto.conf # Broker TLS + mTLS configuration ├── generate_certs.sh # Certificate generation script └── requirements.txt ``` ## ⚙️ 设置与运行 ``` # 1. Clone 并 install git clone https://github.com/[your-handle]/hydrologic-security cd hydrologic-security pip install -r requirements.txt # 2. 生成 certificates chmod +x generate_certs.sh ./generate_certs.sh # 3. 启动 MQTT broker mosquitto -c mosquitto.conf # 4. Terminal 1 — 启动 subscriber (validation engine) python subscriber.py # 5. Terminal 2 — 启动 publisher (sensor simulator) python publisher.py # 6. Terminal 3 — 启动 security dashboard streamlit run dashboard.py # 7. Terminal 4 — 运行 attack simulations (可选) python attack.py ``` ## 🎓 本项目展示的技能 | 技能 | 证明 | |-------|---------| | **威胁建模** | 在实施之前应用了 STRIDE 方法论 | | **安全系统设计** | 从不安全的基线开始逐步强化 | | **密码学实践** | TLS、mTLS、HMAC-SHA256 的实施与验证 | | **攻击模拟** | 带有文档记录的实时对抗性测试 | | **安全工程** | 具有可衡量结果的纵深防御架构 | | **技术沟通** | 结构化地记录发现与建议 | ## 🔮 后续步骤 - [ ] 证书生命周期自动化 — 大规模的配置、轮换和吊销 - [ ] 实时告警 pipeline — 被拒绝的消息触发事件通知 - [ ] 扩展 AI 异常检测 — 针对渐进式漂移和内部威胁的 Isolation Forest - [ ] 在生产环境中部署到所有 HYDROLOGIC 区域 - [ ] 添加 MQTT ACL (Access Control Lists) 以实现 topic 级别的授权
**Prateek Pulastya** — 安全工程师 德国柏林 · [LinkedIn](https://linkedin.com/in/prateekpulastya22) · [GitHub](https://github.com/[your-handle]) · pulastyaprateek02@gmail.com *于 Hydroficient 安全工程实习期间构建 — 2026 年 4 月*
标签:Kubernetes, Python, TLS/mTLS, 威胁建模, 无后门, 物联网, 逆向工具