Repository navigation
Expand file tree
/
Copy pathsecurity_tools.py
More file actions
860 lines (740 loc) · 31.1 KB
/
Copy pathsecurity_tools.py
File metadata and controls
860 lines (740 loc) · 31.1 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
"""
Ethical Hacking Python - Security Tools Module
Developed by issu321
https://github.com/issu321/Ethical-Hacking-Python
Core security utilities: scanning, password analysis, hashing, file analysis,
vulnerability simulation, and packet analytics. All tools are SAFE, EDUCATIONAL,
and DEFENSIVE-only.
"""
import os
import re
import math
import socket
import hashlib
import struct
import random
import string
import time
import json
import csv
import io
from datetime import datetime
from typing import Dict, List, Any, Optional, Tuple, Union
from concurrent.futures import ThreadPoolExecutor, as_completed
from utils import (
validate_ip, validate_domain, format_bytes, log_event,
get_common_passwords, get_dangerous_extensions, calculate_entropy,
generate_ai_insight
)
# Optional imports
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
PSUTIL_AVAILABLE = False
try:
import scapy.all as scapy
SCAPY_AVAILABLE = True
except ImportError:
SCAPY_AVAILABLE = False
# ═══════════════════════════════════════════════════════════
# NETWORK SCANNER (SAFE EDUCATIONAL)
# ═══════════════════════════════════════════════════════════
COMMON_PORTS = {
21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS",
80: "HTTP", 110: "POP3", 143: "IMAP", 443: "HTTPS", 445: "SMB",
3306: "MySQL", 3389: "RDP", 5432: "PostgreSQL", 5900: "VNC",
8080: "HTTP-Proxy", 8443: "HTTPS-Alt", 27017: "MongoDB",
6379: "Redis", 9200: "Elasticsearch", 11211: "Memcached"
}
PORT_SEVERITY = {
21: "medium", 22: "low", 23: "critical", 25: "medium", 53: "low",
80: "low", 110: "medium", 143: "medium", 443: "low", 445: "high",
3306: "medium", 3389: "high", 5432: "medium", 5900: "high",
8080: "medium", 8443: "low", 27017: "medium", 6379: "medium",
9200: "medium", 11211: "high"
}
def scan_port(ip: str, port: int, timeout: float = 1.0) -> Dict[str, Any]:
"""Scan a single port using TCP connect. Safe and educational."""
result = {
"ip": ip,
"port": port,
"state": "closed",
"service": COMMON_PORTS.get(port, "Unknown"),
"severity": PORT_SEVERITY.get(port, "info"),
"latency_ms": None,
"banner": None
}
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
start = time.time()
try:
code = sock.connect_ex((ip, port))
latency = (time.time() - start) * 1000
result["latency_ms"] = round(latency, 2)
if code == 0:
result["state"] = "open"
# Safe banner grab (just peek, no full exchange)
try:
sock.settimeout(1.0)
banner = sock.recv(1024).decode("utf-8", errors="ignore").strip()
if banner:
result["banner"] = banner[:200]
except Exception:
pass
else:
result["state"] = "closed"
except socket.timeout:
result["state"] = "filtered"
except Exception as e:
result["state"] = "error"
result["error"] = str(e)
finally:
sock.close()
return result
def scan_ports(ip: str, ports: List[int] = None, max_workers: int = 50, timeout: float = 1.0) -> Dict[str, Any]:
"""Scan multiple ports with threading. Safe educational scanner."""
if not validate_ip(ip):
return {"error": "Invalid IP address", "ip": ip}
if ports is None:
ports = list(COMMON_PORTS.keys())
result = {
"ip": ip,
"timestamp": datetime.now().isoformat(),
"ports_scanned": len(ports),
"open_ports": [],
"closed_ports": [],
"filtered_ports": [],
"all_results": [],
"risk_score": 0,
"scan_duration_ms": 0
}
start = time.time()
open_count = 0
high_risk_ports = []
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_port = {executor.submit(scan_port, ip, port, timeout): port for port in ports}
for future in as_completed(future_to_port):
port_result = future.result()
result["all_results"].append(port_result)
if port_result["state"] == "open":
result["open_ports"].append(port_result)
open_count += 1
if port_result["severity"] in ["high", "critical"]:
high_risk_ports.append(port_result)
elif port_result["state"] == "closed":
result["closed_ports"].append(port_result)
else:
result["filtered_ports"].append(port_result)
result["scan_duration_ms"] = round((time.time() - start) * 1000, 2)
# Risk score calculation (educational)
risk = min(100, open_count * 8 + len(high_risk_ports) * 15)
result["risk_score"] = risk
result["high_risk_ports"] = high_risk_ports
log_event("SCAN", f"Scanned {ip}: {open_count} open ports, risk={risk}", "info")
return result
def discover_hosts(network: str, timeout: float = 0.5) -> Dict[str, Any]:
"""Discover active hosts in a network range. Educational simulation."""
result = {
"network": network,
"timestamp": datetime.now().isoformat(),
"active_hosts": [],
"total_scanned": 0
}
try:
import ipaddress
net = ipaddress.ip_network(network, strict=False)
hosts = list(net.hosts())[:254] # Limit for safety/education
result["total_scanned"] = len(hosts)
for host in hosts:
ip = str(host)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
code = sock.connect_ex((ip, 80))
sock.close()
if code == 0 or code == 111: # Open or actively refused = host up
result["active_hosts"].append({
"ip": ip,
"status": "active",
"method": "TCP-80"
})
except Exception:
pass
except Exception as e:
result["error"] = str(e)
return result
# ═══════════════════════════════════════════════════════════
# PASSWORD STRENGTH ANALYZER
# ═══════════════════════════════════════════════════════════
def analyze_password(password: str) -> Dict[str, Any]:
"""Analyze password strength with entropy and pattern detection."""
result = {
"password_length": len(password),
"entropy": 0.0,
"entropy_bits": 0.0,
"score": 0, # 0-100
"strength_label": "",
"complexity": {
"has_lower": False,
"has_upper": False,
"has_digit": False,
"has_special": False,
"has_space": False,
},
"patterns_found": [],
"recommendations": [],
"common_password_match": False,
"character_distribution": {}
}
if not password:
result["strength_label"] = "Empty"
result["recommendations"].append("Password cannot be empty.")
return result
# Character analysis
has_lower = bool(re.search(r"[a-z]", password))
has_upper = bool(re.search(r"[A-Z]", password))
has_digit = bool(re.search(r"[0-9]", password))
has_special = bool(re.search(r"""[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>/?`~]""", password))
has_space = " " in password
result["complexity"]["has_lower"] = has_lower
result["complexity"]["has_upper"] = has_upper
result["complexity"]["has_digit"] = has_digit
result["complexity"]["has_special"] = has_special
result["complexity"]["has_space"] = has_space
# Pool size calculation
pool = 0
if has_lower: pool += 26
if has_upper: pool += 26
if has_digit: pool += 10
if has_special: pool += 33
if has_space: pool += 1
if pool == 0: pool = 1
# Entropy
length = len(password)
result["entropy_bits"] = round(length * math.log2(pool), 2)
result["entropy"] = result["entropy_bits"]
# Score calculation
score = 0
score += min(30, length * 2) # Length up to 30
score += 10 if has_lower else 0
score += 10 if has_upper else 0
score += 10 if has_digit else 0
score += 15 if has_special else 0
score += min(25, int(result["entropy_bits"] / 4)) # Entropy bonus
# Pattern penalties
patterns = []
# Common password check
common = get_common_passwords()
if password.lower() in common:
patterns.append("Common password dictionary match")
score -= 40
result["common_password_match"] = True
# Sequential characters
if re.search(r"(abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz)", password.lower()):
patterns.append("Sequential letters detected")
score -= 10
if re.search(r"(012|123|234|345|456|567|678|789|890)", password):
patterns.append("Sequential numbers detected")
score -= 10
# Repeated characters
if re.search(r"(.)\1{2,}", password):
patterns.append("Repeated characters detected")
score -= 10
# Keyboard patterns
keyboard_patterns = ["qwerty", "asdfgh", "zxcvbn", "qazwsx", "!@#$%"]
for pat in keyboard_patterns:
if pat in password.lower():
patterns.append(f"Keyboard pattern: {pat}")
score -= 15
break
# Date patterns
if re.search(r"(19|20)\d{2}", password):
patterns.append("Year pattern detected")
score -= 5
# Length penalties/bonuses
if length < 8:
patterns.append("Length below 8 characters")
score -= 20
result["recommendations"].append("Increase password length to at least 12 characters.")
elif length < 12:
result["recommendations"].append("Consider increasing length to 16+ characters for optimal security.")
if not has_special:
result["recommendations"].append("Add special characters (!@#$%^&* etc.) to increase entropy.")
if not has_digit:
result["recommendations"].append("Include numeric digits to resist dictionary attacks.")
if not has_upper or not has_lower:
result["recommendations"].append("Use mixed case (upper and lower) letters.")
if not patterns:
result["recommendations"].append("Password structure appears complex. Ensure it is also memorable or stored in a password manager.")
result["patterns_found"] = patterns
result["score"] = max(0, min(100, score))
# Label
if result["score"] < 20:
result["strength_label"] = "Very Weak"
elif result["score"] < 40:
result["strength_label"] = "Weak"
elif result["score"] < 60:
result["strength_label"] = "Moderate"
elif result["score"] < 80:
result["strength_label"] = "Strong"
else:
result["strength_label"] = "Very Strong"
# Character distribution
dist = {}
for char in password:
dist[char] = dist.get(char, 0) + 1
result["character_distribution"] = dist
return result
# ═══════════════════════════════════════════════════════════
# HASHING LABORATORY
# ═══════════════════════════════════════════════════════════
HASH_ALGORITHMS = {
"md5": hashlib.md5,
"sha1": hashlib.sha1,
"sha256": hashlib.sha256,
"sha512": hashlib.sha512,
"sha3_256": hashlib.sha3_256,
"sha3_512": hashlib.sha3_512,
"blake2b": hashlib.blake2b,
"blake2s": hashlib.blake2s,
}
def hash_text(text: str, algorithm: str = "sha256") -> Dict[str, Any]:
"""Hash text with specified algorithm."""
algo = algorithm.lower().replace("-", "_")
if algo not in HASH_ALGORITHMS:
return {"error": f"Unsupported algorithm: {algorithm}", "supported": list(HASH_ALGORITHMS.keys())}
hasher = HASH_ALGORITHMS[algo]()
hasher.update(text.encode("utf-8"))
return {
"input_type": "text",
"algorithm": algorithm.upper(),
"hash": hasher.hexdigest(),
"length": hasher.digest_size * 8,
"timestamp": datetime.now().isoformat()
}
def hash_file(file_content: bytes, algorithm: str = "sha256") -> Dict[str, Any]:
"""Hash file bytes with specified algorithm."""
algo = algorithm.lower().replace("-", "_")
if algo not in HASH_ALGORITHMS:
return {"error": f"Unsupported algorithm: {algorithm}", "supported": list(HASH_ALGORITHMS.keys())}
hasher = HASH_ALGORITHMS[algo]()
hasher.update(file_content)
return {
"input_type": "file",
"algorithm": algorithm.upper(),
"hash": hasher.hexdigest(),
"size_bytes": len(file_content),
"length": hasher.digest_size * 8,
"timestamp": datetime.now().isoformat()
}
def verify_hash(data: Union[str, bytes], algorithm: str, expected_hash: str) -> Dict[str, Any]:
"""Verify data against expected hash."""
if isinstance(data, str):
result = hash_text(data, algorithm)
else:
result = hash_file(data, algorithm)
if "error" in result:
return result
actual = result["hash"]
expected = expected_hash.lower().strip()
return {
"algorithm": algorithm.upper(),
"expected_hash": expected,
"actual_hash": actual,
"match": actual == expected,
"timestamp": datetime.now().isoformat()
}
# ═══════════════════════════════════════════════════════════
# FILE SECURITY ANALYZER
# ═══════════════════════════════════════════════════════════
def analyze_file_security(file_content: bytes, filename: str) -> Dict[str, Any]:
"""Comprehensive file security analysis. Educational and defensive."""
from osint_tools import extract_file_metadata
result = extract_file_metadata(file_content, filename)
result["timestamp"] = datetime.now().isoformat()
result["suspicious"] = False
result["risk_level"] = "Low"
result["risk_score"] = 0
result["warnings"] = []
result["recommendations"] = []
ext = result.get("extension", "")
dangerous = [e.lstrip(".") for e in get_dangerous_extensions()]
# Extension analysis
if ext in dangerous:
result["suspicious"] = True
result["warnings"].append(f"Potentially dangerous extension: .{ext}")
result["risk_score"] += 30
# Entropy analysis (high entropy may indicate packed/encrypted malware)
entropy = result.get("entropy", 0)
if entropy > 7.5 and ext in dangerous:
result["warnings"].append("High entropy detected in executable file. Possible packing/encryption.")
result["risk_score"] += 25
result["suspicious"] = True
elif entropy > 7.0:
result["warnings"].append("High entropy detected. May be compressed or encrypted.")
result["risk_score"] += 10
elif entropy < 1.0 and len(file_content) > 100:
result["warnings"].append("Very low entropy. Possible plaintext credential file or configuration dump.")
result["risk_score"] += 15
# Size analysis
size = len(file_content)
if size == 0:
result["warnings"].append("File is empty.")
result["risk_score"] += 5
elif size > 100 * 1024 * 1024:
result["warnings"].append("File exceeds 100MB. Large files may contain embedded payloads.")
result["risk_score"] += 10
# MIME mismatch
mime = result.get("mime_guess")
if mime and ext:
mime_ext_map = {
"image/png": ["png"], "image/jpeg": ["jpg", "jpeg"],
"image/gif": ["gif"], "application/pdf": ["pdf"],
"application/zip": ["zip"], "application/x-elf": ["elf"],
"application/x-dosexec": ["exe", "dll", "scr"]
}
expected_exts = mime_ext_map.get(mime, [])
if expected_exts and ext not in expected_exts:
result["warnings"].append(f"Extension .{ext} does not match detected MIME type {mime}.")
result["risk_score"] += 20
result["suspicious"] = True
# Magic bytes for executables
magic = result.get("magic_bytes", "")
if magic and magic.startswith("4D5A") and ext not in ["exe", "dll", "scr", "msi"]:
result["warnings"].append("Windows executable magic bytes detected but extension is not .exe/.dll.")
result["risk_score"] += 35
result["suspicious"] = True
# Risk level
if result["risk_score"] >= 60:
result["risk_level"] = "Critical"
elif result["risk_score"] >= 40:
result["risk_level"] = "High"
elif result["risk_score"] >= 20:
result["risk_level"] = "Medium"
else:
result["risk_level"] = "Low"
if result["warnings"]:
result["recommendations"].append("Review all warnings before executing or processing this file.")
if result["suspicious"]:
result["recommendations"].append("Consider submitting to sandbox environment for dynamic analysis.")
result["recommendations"].append("Quarantine file until classification is complete.")
else:
result["recommendations"].append("File appears low-risk based on static analysis. Continue with standard procedures.")
return result
# ═══════════════════════════════════════════════════════════
# VULNERABILITY ASSESSMENT SIMULATION
# ═══════════════════════════════════════════════════════════
SIMULATED_VULNERABILITIES = [
{
"id": "SIM-001",
"name": "Exposed Telnet Service",
"description": "Telnet (port 23) is open. Telnet transmits data in plaintext including credentials.",
"severity": "critical",
"cvss_simulated": 9.8,
"port": 23,
"recommendation": "Disable Telnet and migrate to SSH with key-based authentication."
},
{
"id": "SIM-002",
"name": "Open RDP Without NLA",
"description": "Remote Desktop Protocol exposed. Brute-force and BlueKeep-style attacks possible.",
"severity": "high",
"cvss_simulated": 8.5,
"port": 3389,
"recommendation": "Enable Network Level Authentication. Restrict access via VPN or firewall rules."
},
{
"id": "SIM-003",
"name": "SMBv1 Exposure",
"description": "SMB service detected. Legacy SMBv1 is vulnerable to EternalBlue and similar exploits.",
"severity": "high",
"cvss_simulated": 8.1,
"port": 445,
"recommendation": "Disable SMBv1. Ensure SMB signing is enabled. Apply latest security patches."
},
{
"id": "SIM-004",
"name": "Unsecured VNC Access",
"description": "VNC service without authentication allows remote desktop control.",
"severity": "critical",
"cvss_simulated": 9.5,
"port": 5900,
"recommendation": "Enable VNC authentication with strong password. Tunnel through SSH or VPN."
},
{
"id": "SIM-005",
"name": "Memcached Without Authentication",
"description": "Memcached exposed. Can be abused for amplification DDoS attacks.",
"severity": "high",
"cvss_simulated": 7.5,
"port": 11211,
"recommendation": "Bind Memcached to localhost or enable SASL authentication. Firewall egress."
},
{
"id": "SIM-006",
"name": "Default/FTP Anonymous Access",
"description": "FTP service may allow anonymous login. Data exfiltration risk.",
"severity": "medium",
"cvss_simulated": 6.5,
"port": 21,
"recommendation": "Disable anonymous FTP. Use SFTP or FTPS with strong authentication."
},
{
"id": "SIM-007",
"name": "Outdated SSH Version",
"description": "SSH service detected. Older versions may be vulnerable to Terrapin or similar.",
"severity": "medium",
"cvss_simulated": 5.9,
"port": 22,
"recommendation": "Update OpenSSH to latest stable. Disable weak ciphers and algorithms."
},
{
"id": "SIM-008",
"name": "HTTP Without HTTPS Redirect",
"description": "Plain HTTP service active. Data transmitted without encryption.",
"severity": "medium",
"cvss_simulated": 5.3,
"port": 80,
"recommendation": "Implement HTTPS with HSTS. Redirect all HTTP traffic to HTTPS."
},
{
"id": "SIM-009",
"name": "Elasticsearch Exposure",
"description": "Elasticsearch API exposed without authentication. Data leakage risk.",
"severity": "high",
"cvss_simulated": 7.8,
"port": 9200,
"recommendation": "Enable X-Pack security. Bind to localhost or internal network only."
},
{
"id": "SIM-010",
"name": "Redis Without Authentication",
"description": "Redis instance exposed. Can lead to remote code execution via module loading.",
"severity": "critical",
"cvss_simulated": 9.1,
"port": 6379,
"recommendation": "Enable requirepass and protected-mode. Bind to localhost or use Unix socket."
},
]
def simulate_vulnerability_assessment(scan_results: Dict[str, Any]) -> Dict[str, Any]:
"""Simulate vulnerability assessment based on port scan results. Educational only."""
result = {
"timestamp": datetime.now().isoformat(),
"target": scan_results.get("ip", "unknown"),
"vulnerabilities": [],
"summary": {
"critical": 0,
"high": 0,
"medium": 0,
"low": 0,
"info": 0,
"total": 0
},
"overall_cvss": 0.0,
"risk_level": "Low",
"recommendations": []
}
open_ports = {p["port"]: p for p in scan_results.get("open_ports", [])}
for vuln in SIMULATED_VULNERABILITIES:
if vuln["port"] in open_ports:
finding = vuln.copy()
finding["detected_on"] = open_ports[vuln["port"]]
result["vulnerabilities"].append(finding)
result["summary"][vuln["severity"]] += 1
result["summary"]["total"] += 1
# Calculate overall simulated CVSS
if result["vulnerabilities"]:
total_cvss = sum(v["cvss_simulated"] for v in result["vulnerabilities"])
result["overall_cvss"] = round(total_cvss / len(result["vulnerabilities"]), 1)
# Risk level
if result["summary"]["critical"] > 0:
result["risk_level"] = "Critical"
elif result["summary"]["high"] > 0:
result["risk_level"] = "High"
elif result["summary"]["medium"] > 0:
result["risk_level"] = "Medium"
elif result["summary"]["low"] > 0:
result["risk_level"] = "Low"
else:
result["risk_level"] = "Info"
# Aggregate recommendations
all_recs = list(set(v["recommendation"] for v in result["vulnerabilities"]))
result["recommendations"] = all_recs
if not result["vulnerabilities"]:
result["recommendations"].append("No simulated vulnerabilities detected. Maintain regular scanning cadence.")
return result
# ═══════════════════════════════════════════════════════════
# PACKET ANALYTICS (SAFE EDUCATIONAL)
# ═══════════════════════════════════════════════════════════
def get_packet_analytics() -> Dict[str, Any]:
"""Generate safe packet/network analytics using psutil. Educational only."""
result = {
"timestamp": datetime.now().isoformat(),
"interfaces": [],
"connections": [],
"protocol_distribution": {},
"traffic_stats": {},
"packet_simulation": {}
}
if not PSUTIL_AVAILABLE:
result["error"] = "psutil not installed. Run: pip install psutil"
# Generate simulated data for visualization
result["packet_simulation"] = generate_simulated_packet_data()
return result
try:
# Network IO counters
io_stats = psutil.net_io_counters(pernic=True)
for iface, stats in io_stats.items():
result["interfaces"].append({
"name": iface,
"bytes_sent": stats.bytes_sent,
"bytes_recv": stats.bytes_recv,
"packets_sent": stats.packets_sent,
"packets_recv": stats.packets_recv,
"err_in": stats.errin,
"err_out": stats.errout,
"drop_in": stats.dropin,
"drop_out": stats.dropout
})
# Connections
try:
conns = psutil.net_connections(kind="inet")
for conn in conns[:50]: # Limit for performance
result["connections"].append({
"fd": conn.fd,
"family": str(conn.family),
"type": str(conn.type),
"local_addr": f"{conn.laddr.ip}:{conn.laddr.port}" if conn.laddr else None,
"remote_addr": f"{conn.raddr.ip}:{conn.raddr.port}" if conn.raddr else None,
"status": conn.status,
"pid": conn.pid
})
except (psutil.AccessDenied, PermissionError):
result["connections_error"] = "Permission denied. Run with elevated privileges to view connections."
# Protocol distribution simulation based on ports
proto_dist = {"TCP": 0, "UDP": 0, "ICMP": 0, "Other": 0}
for conn in result["connections"]:
if conn["type"] == "SocketKind.SOCK_STREAM":
proto_dist["TCP"] += 1
elif conn["type"] == "SocketKind.SOCK_DGRAM":
proto_dist["UDP"] += 1
else:
proto_dist["Other"] += 1
if sum(proto_dist.values()) == 0:
proto_dist = {"TCP": 65, "UDP": 25, "ICMP": 8, "Other": 2}
result["protocol_distribution"] = proto_dist
# Traffic stats summary
total_sent = sum(i["bytes_sent"] for i in result["interfaces"])
total_recv = sum(i["bytes_recv"] for i in result["interfaces"])
result["traffic_stats"] = {
"total_bytes_sent": total_sent,
"total_bytes_recv": total_recv,
"total_packets_sent": sum(i["packets_sent"] for i in result["interfaces"]),
"total_packets_recv": sum(i["packets_recv"] for i in result["interfaces"]),
}
except Exception as e:
result["error"] = str(e)
result["packet_simulation"] = generate_simulated_packet_data()
return result
def generate_simulated_packet_data() -> Dict[str, Any]:
"""Generate simulated packet data for educational visualization when psutil is unavailable."""
random.seed(int(time.time() // 60))
return {
"note": "Simulated data for educational visualization.",
"protocol_distribution": {
"TCP": random.randint(50, 80),
"UDP": random.randint(15, 35),
"ICMP": random.randint(2, 10),
"ARP": random.randint(1, 5),
"Other": random.randint(1, 5)
},
"packet_sizes": {
"64-127": random.randint(100, 500),
"128-255": random.randint(200, 800),
"256-511": random.randint(150, 600),
"512-1023": random.randint(100, 400),
"1024-1518": random.randint(50, 300)
},
"top_ports": [
{"port": 443, "count": random.randint(1000, 5000), "service": "HTTPS"},
{"port": 80, "count": random.randint(500, 2000), "service": "HTTP"},
{"port": 53, "count": random.randint(300, 1500), "service": "DNS"},
{"port": 22, "count": random.randint(50, 300), "service": "SSH"},
{"port": 123, "count": random.randint(20, 100), "service": "NTP"},
],
"bandwidth_mbps": round(random.uniform(10, 500), 2)
}
# ═══════════════════════════════════════════════════════════
# SYSTEM MONITOR
# ═══════════════════════════════════════════════════════════
def get_system_monitor_data() -> Dict[str, Any]:
"""Gather system resource usage."""
result = {
"timestamp": datetime.now().isoformat(),
"cpu": {},
"memory": {},
"disk": {},
"network": {},
"processes": [],
"boot_time": None,
"users": []
}
if not PSUTIL_AVAILABLE:
result["error"] = "psutil not installed. Run: pip install psutil"
return result
try:
# CPU
result["cpu"]["percent"] = psutil.cpu_percent(interval=0.5)
result["cpu"]["count_physical"] = psutil.cpu_count(logical=False)
result["cpu"]["count_logical"] = psutil.cpu_count(logical=True)
result["cpu"]["freq"] = psutil.cpu_freq()._asdict() if psutil.cpu_freq() else {}
result["cpu"]["per_cpu"] = psutil.cpu_percent(percpu=True, interval=0.5)
# Memory
mem = psutil.virtual_memory()
result["memory"] = {
"total": mem.total,
"available": mem.available,
"percent": mem.percent,
"used": mem.used,
"free": mem.free,
"buffers": getattr(mem, "buffers", 0),
"cached": getattr(mem, "cached", 0)
}
# Disk
disk = psutil.disk_usage("/")
result["disk"] = {
"total": disk.total,
"used": disk.used,
"free": disk.free,
"percent": disk.percent
}
# Network
net_io = psutil.net_io_counters()
result["network"] = {
"bytes_sent": net_io.bytes_sent,
"bytes_recv": net_io.bytes_recv,
"packets_sent": net_io.packets_sent,
"packets_recv": net_io.packets_recv,
"errin": net_io.errin,
"errout": net_io.errout
}
# Processes (top 10 by CPU)
procs = []
for p in psutil.process_iter(["pid", "name", "cpu_percent", "memory_percent", "status", "username"]):
try:
procs.append(p.info)
except Exception:
pass
procs.sort(key=lambda x: x.get("cpu_percent", 0) or 0, reverse=True)
result["processes"] = procs[:15]
# Boot time
result["boot_time"] = datetime.fromtimestamp(psutil.boot_time()).isoformat()
# Users
try:
result["users"] = [u._asdict() for u in psutil.users()]
except Exception:
pass
except Exception as e:
result["error"] = str(e)
return result