Repository navigation
Expand file tree
/
Copy pathsimulate_attacks.py
More file actions
327 lines (279 loc) · 11.6 KB
/
Copy pathsimulate_attacks.py
File metadata and controls
327 lines (279 loc) · 11.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
"""Safe lab-only attack simulation & detection-gap testing suite for SentinelIDS.
SAFETY BOUNDARY: Refuses any non-loopback / non-RFC1918 external IP target.
Designed exclusively for testing your own machine or owned isolated lab VMs.
"""
from __future__ import annotations
import argparse
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import ipaddress
import socket
import struct
import subprocess
import threading
import time
from typing import Iterator
import urllib.error
import urllib.request
class UnsafeTargetError(ValueError):
"""Raised if target IP is outside loopback or RFC1918 private lab space."""
def validate_lab_target(target: str) -> str:
"""Verify target is strictly loopback or RFC1918 private IP; reject hostnames/public IPs."""
cleaned = target.strip()
try:
ip_obj = ipaddress.ip_address(cleaned)
except ValueError as exc:
raise UnsafeTargetError(
f"Target must be a literal loopback or RFC1918 IP address, got {target!r}"
) from exc
if ip_obj.is_loopback or ip_obj.is_private:
if ip_obj.is_unspecified or ip_obj.is_multicast:
raise UnsafeTargetError(f"Unsupported special address: {cleaned}")
return str(ip_obj)
raise UnsafeTargetError(
f"SAFETY BLOCK: Refusing external/public IP target {cleaned}. "
"SentinelIDS simulation scripts only target localhost or private lab hosts."
)
class _SinkHandler(BaseHTTPRequestHandler):
def do_GET(self) -> None: # noqa: N802
self.send_response(200)
self.end_headers()
self.wfile.write(b"OK\n")
def do_POST(self) -> None: # noqa: N802
length = int(self.headers.get("Content-Length", "0") or 0)
if length > 0:
self.rfile.read(min(length, 4096))
self.send_response(200)
self.end_headers()
self.wfile.write(b"Received\n")
def log_message(self, format: str, *args: object) -> None:
return
def _start_local_http_target(port: int = 8080) -> tuple[ThreadingHTTPServer, int]:
server = ThreadingHTTPServer(("127.0.0.1", port), _SinkHandler)
actual_port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
return server, actual_port
def _build_dns_query_packet(domain: str) -> bytes:
tx_id = b"\xab\xcd"
flags = b"\x01\x00" # Standard query, recursion desired
counts = struct.pack("!HHHH", 1, 0, 0, 0)
qname = b"".join(
bytes([len(label)]) + label.encode("ascii")
for label in domain.strip(".").split(".")
if label
) + b"\x00"
qtype_qclass = struct.pack("!HH", 1, 1) # A IN
return tx_id + flags + counts + qname + qtype_qclass
def sim_icmp_sweep(target: str) -> None:
"""Rule 1 (T1018): Send 6 ICMP echo packets (> Windows 4-ping baseline)."""
ip = validate_lab_target(target)
print(f"[T1018] Sending 6 ICMP echo requests to {ip}...")
subprocess.run(["ping", "-n", "6", ip], check=False)
def sim_port_scan(target: str, port_count: int = 25) -> None:
"""Rule 2 (T1046): Rapidly probe TCP ports to trigger threshold SYN scan alert."""
ip = validate_lab_target(target)
print(f"[T1046] Scanning {port_count} TCP ports on {ip}...")
for port in range(8000, 8000 + port_count):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.15)
try:
sock.connect_ex((ip, port))
finally:
sock.close()
def sim_brute_force(target: str, port: int = 2222, attempts: int = 7) -> None:
"""Rule 3 (T1110.001): Rapid repeated SSH connection attempts."""
ip = validate_lab_target(target)
print(f"[T1110.001] Sending {attempts} rapid TCP/SSH attempts to {ip}:{port}...")
for _ in range(attempts):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.25)
try:
sock.connect_ex((ip, port))
finally:
sock.close()
time.sleep(0.1)
@contextmanager
def _local_http_target(ip: str, port: int = 8080) -> Iterator[int]:
"""Spin up a disposable local sink HTTP server for localhost-only tests."""
if ip != "127.0.0.1":
yield port
return
server, actual_port = _start_local_http_target(port=port)
try:
yield actual_port
finally:
server.shutdown()
server.server_close()
def sim_scanner_user_agent(target: str, port: int = 8080) -> None:
"""Rule 4 (T1595): Send HTTP GET with flagged scanner User-Agent."""
ip = validate_lab_target(target)
with _local_http_target(ip, port) as actual_port:
url = f"http://{ip}:{actual_port}/"
print(f"[T1595] Sending flagged scanner User-Agent to {url}...")
req = urllib.request.Request(url, headers={"User-Agent": "SentinelScanner/1.0 (nikto)"})
try:
with urllib.request.urlopen(req, timeout=2.0) as resp:
resp.read()
except urllib.error.URLError as exc:
print(f"HTTP request info: {exc}")
def sim_plaintext_creds(target: str, port: int = 8080) -> None:
"""Rule 5 (T1040): Send plaintext dummy test credentials in HTTP POST body."""
ip = validate_lab_target(target)
with _local_http_target(ip, port) as actual_port:
url = f"http://{ip}:{actual_port}/login"
print(f"[T1040] Sending cleartext test POST credentials to {url}...")
body = b"username=lab_demo&password=DemoOnlyNotRealPassword"
req = urllib.request.Request(url, data=body, method="POST")
try:
with urllib.request.urlopen(req, timeout=2.0) as resp:
resp.read()
except urllib.error.URLError as exc:
print(f"HTTP request info: {exc}")
def sim_malicious_dns(target: str, domain: str = "c2-beacon.sentinel.invalid") -> None:
"""Rule 6 (T1071.004): Emit UDP DNS query for RFC-reserved .invalid lab domain."""
ip = validate_lab_target(target)
print(f"[T1071.004] Sending test DNS query for {domain} to {ip}:53...")
pkt = _build_dns_query_packet(domain)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.sendto(pkt, (ip, 53))
finally:
sock.close()
def sim_dos_burst(target: str, port: int = 8080, count: int = 120) -> None:
"""Rule 7 (T1498.001): Rapid TCP connection burst exceeding 100 SYNs/5s."""
ip = validate_lab_target(target)
print(f"[T1498.001] Sending {count} rapid TCP connection attempts to {ip}:{port}...")
for _ in range(count):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.05)
try:
sock.connect_ex((ip, port))
finally:
sock.close()
def sim_custom_traversal(target: str, port: int = 8080) -> None:
"""Rule 8 (T1190): Send HTTP probe for /.env and path traversal."""
ip = validate_lab_target(target)
with _local_http_target(ip, port) as actual_port:
for path in ("/.env", "/../../etc/passwd"):
url = f"http://{ip}:{actual_port}{path}"
print(f"[T1190] Requesting {url}...")
try:
with urllib.request.urlopen(url, timeout=2.0) as resp:
resp.read()
except urllib.error.URLError:
pass
def sim_honeypot_probe(target: str, ssh_port: int = 2222, http_port: int = 8088) -> None:
"""Probe local defensive SSH & HTTP honeypots."""
ip = validate_lab_target(target)
print(f"[Honeypot] Probing fake SSH ({ip}:{ssh_port}) and fake HTTP ({ip}:{http_port})...")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1.5)
try:
sock.connect((ip, ssh_port))
banner = sock.recv(256)
print(f" SSH banner received: {banner.decode('ascii', errors='replace').strip()}")
sock.sendall(b"SSH-2.0-LabProbe\r\n")
except OSError as exc:
print(f" SSH decoy unavailable: {exc}")
finally:
sock.close()
try:
req = urllib.request.Request(
f"http://{ip}:{http_port}/admin",
data=b"username=admin&password=labprobe",
headers={"User-Agent": "SentinelScanner/1.0"},
method="POST",
)
with urllib.request.urlopen(req, timeout=2.0) as resp:
resp.read()
except urllib.error.HTTPError as exc:
print(f" HTTP decoy returned expected {exc.code}")
except urllib.error.URLError as exc:
print(f" HTTP decoy unavailable: {exc}")
def sim_slow_scan_gap_test(
target: str,
port_count: int = 10,
delay_seconds: float = 6.0,
) -> None:
"""Detection-gap test: 1 port every delay_seconds (evades 15 ports/10s Suricata threshold)."""
ip = validate_lab_target(target)
print(
f"[GAP-TEST] Slow-scanning {port_count} ports on {ip} at 1 port/{delay_seconds:.1f}s..."
)
for idx in range(port_count):
port = 8100 + idx
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.2)
try:
sock.connect_ex((ip, port))
finally:
sock.close()
print(f" Probed {ip}:{port} ({idx + 1}/{port_count})")
if idx + 1 < port_count:
time.sleep(delay_seconds)
def sim_correlation_chain(target: str, ssh_port: int = 2222, http_port: int = 8088) -> None:
"""Multi-stage demo: Honeypot probe -> Port scan -> Brute-force -> Malicious DNS."""
ip = validate_lab_target(target)
print(f"[CORR-DEMO] Running multi-stage chain against {ip}...")
sim_honeypot_probe(ip, ssh_port=ssh_port, http_port=http_port)
time.sleep(1.0)
sim_port_scan(ip, port_count=20)
time.sleep(1.0)
sim_brute_force(ip, port=ssh_port, attempts=7)
time.sleep(1.0)
sim_malicious_dns(ip)
print("[CORR-DEMO] Complete — expect CORR-001, CORR-002, and CORR-003.")
def main() -> None:
parser = argparse.ArgumentParser(description="SentinelIDS Safe Lab Attack Simulator")
parser.add_argument(
"scenario",
choices=(
"icmp-sweep",
"port-scan",
"brute-force",
"scanner-ua",
"plaintext-creds",
"malicious-dns",
"dos-burst",
"custom-traversal",
"honeypot-probe",
"correlation-chain",
"slow-scan",
"all-rules",
),
)
parser.add_argument("--target", default="127.0.0.1", help="Loopback or RFC1918 lab IP only")
parser.add_argument("--delay", type=float, default=6.0, help="Delay for slow-scan test")
args = parser.parse_args()
target_ip = validate_lab_target(args.target)
dispatch = {
"icmp-sweep": lambda: sim_icmp_sweep(target_ip),
"port-scan": lambda: sim_port_scan(target_ip),
"brute-force": lambda: sim_brute_force(target_ip),
"scanner-ua": lambda: sim_scanner_user_agent(target_ip),
"plaintext-creds": lambda: sim_plaintext_creds(target_ip),
"malicious-dns": lambda: sim_malicious_dns(target_ip),
"dos-burst": lambda: sim_dos_burst(target_ip),
"custom-traversal": lambda: sim_custom_traversal(target_ip),
"honeypot-probe": lambda: sim_honeypot_probe(target_ip),
"correlation-chain": lambda: sim_correlation_chain(target_ip),
"slow-scan": lambda: sim_slow_scan_gap_test(target_ip, delay_seconds=args.delay),
}
if args.scenario == "all-rules":
for name in (
"icmp-sweep",
"port-scan",
"brute-force",
"scanner-ua",
"plaintext-creds",
"malicious-dns",
"custom-traversal",
"dos-burst",
):
dispatch[name]()
time.sleep(0.5)
else:
dispatch[args.scenario]()
if __name__ == "__main__":
main()