Repository navigation
Expand file tree
/
Copy pathattack_simulator.py
More file actions
349 lines (285 loc) · 12.6 KB
/
Copy pathattack_simulator.py
File metadata and controls
349 lines (285 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
"""
attack_simulator.py - Three-Phase Attack Demonstration
Runs a theatrical attack sequence against the Grand Marina's defended
MQTT pipeline. All three attacks should be BLOCKED by the subscriber's
validation checks (HMAC, timestamp, sequence counter).
Phases:
1. Eavesdrop - subscribe to the topic and display intercepted messages
2. Inject - publish a message with a fake HMAC signature
3. Replay - re-send a captured message (stale timestamp + old sequence)
The dashboard will show each blocked attack in real time with red alerts.
Usage:
python attack_simulator.py
"""
import paho.mqtt.client as mqtt
import ssl
import json
import time
import hmac
import hashlib
import sys
import os
import copy
from datetime import datetime, timezone
# Fix Windows console encoding for Unicode / ANSI colors
if sys.platform == "win32":
os.system("") # enable ANSI escape codes on Windows
sys.stdout.reconfigure(encoding="utf-8")
# Handle paho-mqtt 2.0+ API change
try:
MQTT_CLIENT_ARGS = {"callback_api_version": mqtt.CallbackAPIVersion.VERSION1}
except AttributeError:
MQTT_CLIENT_ARGS = {}
# =============================================================================
# ANSI Colors
# =============================================================================
class C:
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
# =============================================================================
# Configuration
# =============================================================================
BROKER_HOST = "localhost"
BROKER_PORT = 8883
# mTLS certificates (attacker has valid credentials — insider threat)
CA_CERT = "certs/ca.pem"
CLIENT_CERT = "certs/device-001.pem"
CLIENT_KEY = "certs/device-001-key.pem"
TARGET_TOPIC = "hydroficient/grandmarina/device-001/sensors"
# =============================================================================
# Helpers
# =============================================================================
def type_effect(text, delay=0.03, color=C.GREEN):
"""Print text with a typewriter effect."""
for ch in text:
sys.stdout.write(f"{color}{ch}{C.RESET}")
sys.stdout.flush()
time.sleep(delay)
print()
def status(prefix, message, color=C.GREEN):
"""Print a bracketed status line."""
print(f"{color}[{prefix}]{C.RESET} {message}")
def section_header(title):
print(f"\n{C.CYAN}{'=' * 55}")
print(f" {title}")
print(f"{'=' * 55}{C.RESET}\n")
# =============================================================================
# Attack Simulator
# =============================================================================
class AttackSimulator:
def __init__(self):
self.client = None
self.intercepted = []
# --- connection ---
def connect(self):
self.client = mqtt.Client(
client_id="attack-simulator", **MQTT_CLIENT_ARGS
)
self.client.on_message = self._on_message
try:
self.client.tls_set(
ca_certs=CA_CERT,
certfile=CLIENT_CERT,
keyfile=CLIENT_KEY,
cert_reqs=ssl.CERT_REQUIRED,
tls_version=ssl.PROTOCOL_TLS,
)
except FileNotFoundError as e:
print(f"{C.RED}[ERROR] Certificate not found: {e}{C.RESET}")
print("[ERROR] Make sure your Project 5 certs/ directory is set up")
return False
status("*", "Scanning for MQTT broker...", C.YELLOW)
time.sleep(1)
try:
self.client.connect(BROKER_HOST, BROKER_PORT, keepalive=60)
self.client.loop_start()
except Exception as e:
status("-", f"Connection failed: {e}", C.RED)
return False
status("+", f"Connected to {BROKER_HOST}:{BROKER_PORT}", C.RED)
return True
def disconnect(self):
if self.client:
self.client.loop_stop()
self.client.disconnect()
def _on_message(self, client, userdata, msg):
try:
data = json.loads(msg.payload.decode())
self.intercepted.append({
"topic": msg.topic,
"payload": data,
"raw": msg.payload.decode(),
"time": datetime.now().strftime("%H:%M:%S"),
})
except Exception:
pass
# ------------------------------------------------------------------
# PHASE 1: Eavesdrop
# ------------------------------------------------------------------
def phase_eavesdrop(self, duration=8):
section_header("PHASE 1: EAVESDROPPING")
type_effect("Subscribing to hydroficient/grandmarina/#...", 0.02, C.YELLOW)
self.client.subscribe("hydroficient/grandmarina/#")
time.sleep(0.5)
status("+", "Now intercepting ALL hotel water system messages...", C.RED)
print()
start = time.time()
shown = 0
while time.time() - start < duration:
if len(self.intercepted) > shown:
msg = self.intercepted[shown]
self._display_intercepted(msg)
shown += 1
time.sleep(0.3)
if shown == 0:
status(
"!",
"No messages intercepted yet. Is publisher_defended.py running?",
C.YELLOW,
)
print(f"\n{C.DIM}Captured {len(self.intercepted)} messages.{C.RESET}\n")
def _display_intercepted(self, msg):
readings = msg["payload"].get("readings", msg["payload"])
pressure = readings.get("pressure_upstream",
readings.get("pressure_psi", "N/A"))
flow = readings.get("flow_rate",
readings.get("flow_rate_gpm", "N/A"))
print(f"{C.DIM}+------------- {C.RED}INTERCEPTED{C.DIM} --------------+{C.RESET}")
print(f"{C.DIM}|{C.RESET} Topic: {C.CYAN}{msg['topic']}{C.RESET}")
print(f"{C.DIM}|{C.RESET} Pressure: {C.YELLOW}{pressure} PSI{C.RESET}")
print(f"{C.DIM}|{C.RESET} Flow: {C.YELLOW}{flow} LPM{C.RESET}")
print(f"{C.DIM}|{C.RESET} Time: {C.WHITE}{msg['time']}{C.RESET}")
print(f"{C.DIM}+-------------------------------------------+{C.RESET}")
print()
# ------------------------------------------------------------------
# PHASE 2: Inject fake data (wrong HMAC)
# ------------------------------------------------------------------
def phase_inject(self):
section_header("PHASE 2: DATA INJECTION")
type_effect("Crafting fake sensor reading with bogus HMAC...", 0.02, C.YELLOW)
time.sleep(0.5)
fake_message = {
"device_id": "HYDROLOGIC-Device-001",
"timestamp": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"sequence": 99999,
"readings": {
"pressure_upstream": 250.0, # dangerously high
"pressure_downstream": 240.0,
"flow_rate": 0.0, # no flow
"gate_a_position": 100.0,
"gate_b_position": 100.0,
},
"status": "operational",
"hmac": "FAKE_HMAC_0000000000000000000000000000000000000000"
}
self.client.publish(TARGET_TOPIC, json.dumps(fake_message), qos=1)
status("!", "Sent: pressure = 250 PSI (DANGER ZONE!)", C.RED)
status("!", "HMAC is fake - subscriber should reject this", C.YELLOW)
print()
time.sleep(2)
# ------------------------------------------------------------------
# PHASE 3: Replay captured message
# ------------------------------------------------------------------
def phase_replay(self):
section_header("PHASE 3: REPLAY ATTACK")
if self.intercepted:
captured = self.intercepted[0]
type_effect("Re-sending previously captured message...", 0.02, C.YELLOW)
time.sleep(0.5)
status("!", "This message has an old timestamp and old sequence number", C.YELLOW)
self.client.publish(captured["topic"], captured["raw"], qos=1)
status("!", "Replayed captured message", C.RED)
status("!", "Subscriber should reject: stale timestamp OR duplicate sequence", C.YELLOW)
else:
type_effect("No captured messages - crafting stale replay...", 0.02, C.YELLOW)
time.sleep(0.5)
# Build a message with old timestamp and low sequence
stale_message = {
"device_id": "HYDROLOGIC-Device-001",
"timestamp": "2024-01-01T00:00:00Z", # obviously stale
"sequence": 1,
"readings": {
"pressure_upstream": 60.0,
"pressure_downstream": 55.0,
"flow_rate": 50.0,
"gate_a_position": 45.0,
"gate_b_position": 45.0,
},
"status": "operational",
"hmac": "stale_replay_no_valid_hmac_00000000000000000000"
}
self.client.publish(TARGET_TOPIC, json.dumps(stale_message), qos=1)
status("!", "Sent message with 2024 timestamp", C.RED)
status("!", "Subscriber should reject: stale timestamp", C.YELLOW)
print()
time.sleep(2)
# ------------------------------------------------------------------
# Summary
# ------------------------------------------------------------------
def summary(self):
print(f"\n{C.RED}{C.BOLD}")
print(" +===================================================+")
print(" | |")
print(" | ATTACK SEQUENCE COMPLETE |")
print(" | |")
print(" | Check the dashboard — were attacks blocked? |")
print(" | |")
print(" +===================================================+")
print(f"{C.RESET}")
print(f"{C.CYAN}Expected results:{C.RESET}")
print(f" Phase 1 (Eavesdrop): Messages visible — TLS protects the")
print(f" wire, but this attacker has mTLS certs.")
print(f" Phase 2 (Inject): {C.GREEN}BLOCKED{C.RESET} — HMAC mismatch")
print(f" Phase 3 (Replay): {C.GREEN}BLOCKED{C.RESET} — stale timestamp or duplicate sequence")
print()
print(f"{C.YELLOW}If the subscriber accepted any attacks, the defenses have a gap.{C.RESET}")
print(f"{C.YELLOW}If ALL were blocked, your pipeline is secure.{C.RESET}\n")
# =============================================================================
# Banner
# =============================================================================
def print_banner():
print(f"""
{C.RED}{C.BOLD}
+===========================================================+
| |
| A T T A C K S I M U L A T O R |
| |
| Target: Grand Marina Hotel |
| System: Water Monitoring Pipeline |
| Mode: Three-Phase Attack Sequence |
| |
+===========================================================+
{C.RESET}""")
time.sleep(1)
# =============================================================================
# Main
# =============================================================================
def main():
print_banner()
attacker = AttackSimulator()
if not attacker.connect():
print(f"{C.RED}Failed to connect. Is the mTLS broker running?{C.RESET}")
return
print()
time.sleep(1)
try:
# Phase 1: Eavesdrop
attacker.phase_eavesdrop(duration=8)
# Phase 2: Inject fake data
attacker.phase_inject()
# Phase 3: Replay
attacker.phase_replay()
# Summary
attacker.summary()
finally:
attacker.disconnect()
if __name__ == "__main__":
main()