-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlinux_security_audit.py
More file actions
3491 lines (3140 loc) · 150 KB
/
linux_security_audit.py
File metadata and controls
3491 lines (3140 loc) · 150 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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
linux_security_audit.py
Comprehensive Linux Security Audit Script
Version: 2.2
GitHub: https://github.com/Sandler73/Linux-Security-Audit-Project.git
SYNOPSIS:
Comprehensive module-based Linux security audit script supporting multiple compliance frameworks.
DESCRIPTION:
This script audits Linux systems against multiple security frameworks including:
- Core Security (baseline checks)
- CIS Benchmarks
- CISA Best Practices
- DISA STIGs
- ENISA Cybersecurity Guidelines
- ISO/IEC 27001 Information Security Management
- NIST Cybersecurity Framework
- NSA Cybersecurity Guidance
Features:
- Multi-format output (HTML, CSV, JSON, XML, Console)
- Interactive HTML reports with filtering, sorting, and export
- Automated and interactive remediation
- Selective issue remediation from exported JSON
- Dark/Light theme support in HTML reports
- Comprehensive logging and statistics
- SharedDataCache for performance (reads configs/commands once, shares across modules)
- Parallel module execution for faster audits
- Structured logging with file and console output
- Severity levels and cross-framework control mapping
PARAMETERS:
--modules, -m : Comma-separated list of modules (Core,CIS,NIST,STIG,NSA,CISA,All)
--output-format, -f : Output format (HTML,CSV,JSON,XML,Console)
--output-path, -o : Path for output file
--remediate : Interactively remediate failed checks
--remediate-fail : Remediate only FAIL status issues
--remediate-warning : Remediate only WARNING status issues
--remediate-info : Remediate only INFO status issues
--auto-remediate : Automatically remediate without prompting
--remediation-file : JSON file with specific issues to remediate
--parallel : Execute modules in parallel for faster completion
--workers N : Number of parallel workers (default: 4, max: 16)
--no-cache : Disable shared data caching (for debugging)
--profile : Show detailed timing/performance breakdown
--log-level LEVEL : Logging verbosity (DEBUG, INFO, WARNING, ERROR)
--log-file PATH : Write detailed log to file
--json-log : Use JSON format for log file (for SIEM)
-v, --verbose : Enable verbose output (log level DEBUG)
-q, --quiet : Suppress informational output (log level WARNING)
EXAMPLES:
python3 linux_security_audit.py
Run all modules with default HTML output
python3 linux_security_audit.py -m Core,NIST,CISA -f CSV
Run specific modules and output to CSV
python3 linux_security_audit.py --parallel --workers 8
Run all modules in parallel with 8 workers
python3 linux_security_audit.py --profile -v
Run with verbose output and performance profiling
python3 linux_security_audit.py -f XML
Generate XML report suitable for SIEM ingestion
python3 linux_security_audit.py --remediate-fail --auto-remediate
Automatically remediate all FAIL status issues with safety confirmations
python3 linux_security_audit.py --auto-remediate --remediation-file selected-issues.json
Automatically remediate only specific issues from exported JSON file
python3 linux_security_audit.py --log-file audit.log --json-log
Run with JSON-structured log file for SIEM ingestion
NOTES:
Requires: Linux (Ubuntu/Debian/RHEL/CentOS/Fedora), Python 3.6+
Run with sudo/root for complete results and remediation capabilities
PERFORMANCE:
When audit_common.py is present, the SharedDataCache pre-reads common
configuration files and commands once, then shares them across all modules.
This typically reduces execution time by 50-70%.
REMEDIATION WORKFLOW:
1. Run audit: python3 linux_security_audit.py
2. Review HTML report and select specific issues to fix
3. Export selected issues to JSON using "Export Selected" button
4. Run auto-remediation: python3 linux_security_audit.py --auto-remediate --remediation-file Selected-Report.json
"""
import os
import sys
import re
import json
import csv
import argparse
import subprocess
import platform
import socket
import datetime
import time
import html
import logging
import concurrent.futures
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass, asdict, field
# ============================================================================
# Shared Library Integration
# ============================================================================
# Import the consolidated shared library for caching, OS detection, and logging.
# Tries shared_components/ package first, then flat-file layout, then falls back.
try:
sys.path.insert(0, str(Path(__file__).parent.absolute()))
from shared_components.audit_common import (
SharedDataCache, OSInfo, detect_os as common_detect_os,
configure_logging as common_configure_logging,
get_module_logger, get_cache_statistics,
clear_command_cache, COMMON_LIB_VERSION,
AuditResult as CommonAuditResult,
)
HAS_COMMON_LIB = True
except ImportError:
try:
from audit_common import (
SharedDataCache, OSInfo, detect_os as common_detect_os,
configure_logging as common_configure_logging,
get_module_logger, get_cache_statistics,
clear_command_cache, COMMON_LIB_VERSION,
AuditResult as CommonAuditResult,
)
HAS_COMMON_LIB = True
except ImportError:
HAS_COMMON_LIB = False
# ============================================================================
# Configuration
# ============================================================================
SCRIPT_VERSION = "2.2"
SCRIPT_PATH = Path(__file__).parent.absolute()
LOG_DIR = SCRIPT_PATH / "logs"
REPORT_DIR = SCRIPT_PATH / "reports"
VALID_STATUS_VALUES = ["Pass", "Fail", "Warning", "Info", "Error"]
# Performance defaults
DEFAULT_PARALLEL_WORKERS = 4
MAX_PARALLEL_WORKERS = 16
def get_safe_hostname() -> str:
"""
Get the system hostname sanitized for safe use in filenames.
Strips any characters that are not alphanumeric, hyphens, underscores,
or dots to prevent filesystem issues. Falls back to 'unknown-host' if
hostname cannot be determined or results in an empty string.
Returns:
Sanitized hostname string safe for use in file paths
"""
try:
raw = socket.gethostname()
# Strip anything that is not filename-safe
safe = re.sub(r'[^\w.\-]', '', raw)
return safe if safe else 'unknown-host'
except Exception:
return 'unknown-host'
def get_system_ip_addresses() -> List[str]:
"""
Retrieve non-loopback IP addresses for the local system.
Enumerates network interfaces and collects their IPv4 and IPv6
addresses, excluding loopback (127.x.x.x, ::1) and link-local
(169.254.x.x, fe80::) addresses. Uses socket-based methods with
subprocess fallback for maximum compatibility across distributions.
Provides paired identification (hostname + OS + IPs)
for accurate attribution in SIEMs and multi-host environments.
Returns:
Sorted list of unique IP address strings. Returns ['N/A'] if
no usable addresses can be determined.
"""
addresses = set()
# --- Method 1: Parse /proc/net/if_inet6 for IPv6 addresses ---
try:
import ipaddress as _ipaddress
with open('/proc/net/if_inet6', 'r') as f:
for line in f:
parts = line.strip().split()
if len(parts) >= 4:
hex_addr = parts[0]
groups = [hex_addr[i:i+4] for i in range(0, 32, 4)]
ipv6_str = ':'.join(groups)
try:
addr = _ipaddress.ip_address(ipv6_str)
if not addr.is_loopback and not addr.is_link_local:
addresses.add(str(addr))
except ValueError:
pass
except (FileNotFoundError, PermissionError, OSError, ImportError):
pass
# --- Method 2: socket.getaddrinfo for hostname resolution ---
try:
hostname = socket.gethostname()
for info in socket.getaddrinfo(hostname, None):
addr = info[4][0]
if addr and not addr.startswith('127.') and addr != '::1' \
and not addr.startswith('169.254.') and not addr.startswith('fe80:'):
addresses.add(addr)
except (socket.gaierror, socket.herror, OSError):
pass
# --- Method 3: Subprocess fallback (hostname -I) ---
if not addresses:
try:
result = subprocess.run(
['hostname', '-I'], capture_output=True, text=True, timeout=5
)
if result.returncode == 0 and result.stdout.strip():
for addr in result.stdout.strip().split():
addr = addr.strip()
if addr and not addr.startswith('127.') and addr != '::1' \
and not addr.startswith('169.254.') and not addr.startswith('fe80:'):
addresses.add(addr)
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
pass
# --- Method 4: ip addr show fallback ---
if not addresses:
try:
result = subprocess.run(
['ip', '-o', 'addr', 'show'], capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
for line in result.stdout.strip().splitlines():
parts = line.split()
for i, p in enumerate(parts):
if p in ('inet', 'inet6') and i + 1 < len(parts):
addr = parts[i + 1].split('/')[0]
if addr and not addr.startswith('127.') and addr != '::1' \
and not addr.startswith('169.254.') and not addr.startswith('fe80:'):
addresses.add(addr)
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
pass
return sorted(addresses) if addresses else ['N/A']
# ============================================================================
# Data Classes
# ============================================================================
@dataclass
class AuditResult:
"""Represents a single audit check result"""
module: str
category: str
status: str
message: str
details: str = ""
remediation: str = ""
severity: str = "Medium"
cross_references: Dict[str, str] = field(default_factory=dict)
timestamp: str = field(default_factory=lambda: datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary"""
return asdict(self)
def validate(self) -> Tuple[bool, List[str]]:
"""Validate the result object"""
issues = []
if not self.module:
issues.append("Missing: module")
if not self.category:
issues.append("Missing: category")
if not self.message:
issues.append("Missing: message")
if not self.status:
issues.append("Missing: status")
elif self.status not in VALID_STATUS_VALUES:
issues.append(f"Invalid Status: '{self.status}'")
return len(issues) == 0, issues
@dataclass
class ExecutionInfo:
"""
Information about the audit execution.
Stores host identification (hostname, OS, IPs), timing, module list,
result counts, and compliance scores for reporting and export.
"""
hostname: str
os_version: str
ip_addresses: List[str]
scan_date: str
duration: str
modules_run: List[str]
total_checks: int
pass_count: int
fail_count: int
warning_count: int
info_count: int
error_count: int
compliance_scores: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary"""
return asdict(self)
@dataclass
class ComplianceScore:
"""
Compliance scoring for a module or overall audit.
Scoring methods:
- simple_pct: Pass / Applicable * 100
- weighted_pct: (Pass*1.0 + Warn*0.5) / Applicable * 100
- (overall instance) Aggregated across all modules
- severity_weighted_pct: Adjusted by severity impact factors
- threshold_result: PASS/FAIL against configurable threshold
Severity impact factors: Critical=5.0, High=3.0, Medium=1.5, Low=0.5
Info checks excluded from applicable count (informational-only).
"""
module_name: str
total_checks: int
passed: int
failed: int
warnings: int
info: int
errors: int
simple_pct: float = 0.0
weighted_pct: float = 0.0
severity_weighted_pct: float = 0.0
threshold: float = 70.0
threshold_result: str = "N/A"
def compute(self, severity_distribution: Dict[str, int] = None):
"""
Compute all compliance scores.
Args:
severity_distribution: Dict of {severity_name: count} for
severity-weighted scoring.
"""
# Simple pass percentage (exclude Info)
applicable = self.total_checks - self.info
if applicable > 0:
self.simple_pct = round(self.passed / applicable * 100, 2)
else:
self.simple_pct = 100.0
# Weighted scoring (Pass=1.0, Warn=0.5, Fail=0, Error=0)
if applicable > 0:
weighted_sum = (self.passed * 1.0) + (self.warnings * 0.5)
self.weighted_pct = round(weighted_sum / applicable * 100, 2)
else:
self.weighted_pct = 100.0
# Severity-weighted compliance score
if severity_distribution and applicable > 0:
severity_weights = {
'Critical': 5.0, 'High': 3.0, 'Medium': 1.5,
'Low': 0.5, 'Informational': 0.0,
}
total_weight = sum(
severity_weights.get(sev, 1.0) * count
for sev, count in severity_distribution.items()
if sev != 'Informational'
)
if total_weight > 0:
fail_rate = (self.failed + self.errors) / applicable
crit_high_weight = (
severity_weights['Critical'] * severity_distribution.get('Critical', 0) +
severity_weights['High'] * severity_distribution.get('High', 0)
)
severity_factor = 1.0 + (crit_high_weight / total_weight)
adjusted_fail_rate = min(1.0, fail_rate * severity_factor)
self.severity_weighted_pct = round((1.0 - adjusted_fail_rate) * 100, 2)
self.severity_weighted_pct = max(0.0, min(100.0, self.severity_weighted_pct))
else:
self.severity_weighted_pct = self.simple_pct
else:
self.severity_weighted_pct = self.weighted_pct
# Threshold determination
self.threshold_result = "PASS" if self.weighted_pct >= self.threshold else "FAIL"
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for export"""
return asdict(self)
@dataclass
class ModuleStatistics:
"""Statistics for a single module"""
total: int
passed: int
failed: int
warnings: int
info: int
errors: int
class Statistics:
"""Global statistics tracker"""
def __init__(self):
self.validation_issues: List[Dict[str, Any]] = []
self.normalized_results: int = 0
self.module_stats: Dict[str, ModuleStatistics] = {}
def add_validation_issue(self, module: str, issues: List[str]):
"""Add validation issues"""
self.validation_issues.append({
"module": module,
"issues": "; ".join(issues),
"timestamp": datetime.datetime.now().isoformat()
})
def increment_normalized(self):
"""Increment normalized results counter"""
self.normalized_results += 1
# Global statistics instance
statistics = Statistics()
# ============================================================================
# Color Output Functions
# ============================================================================
class Colors:
"""ANSI color codes for terminal output"""
CYAN = '\033[96m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
MAGENTA = '\033[95m'
GRAY = '\033[90m'
WHITE = '\033[97m'
RESET = '\033[0m'
BOLD = '\033[1m'
# Module-level logger for structured logging alongside colored console output
logger = logging.getLogger('audit')
# Map ANSI color codes to logging levels for hybrid output
_COLOR_LOG_LEVEL = {
Colors.RED: logging.ERROR,
Colors.YELLOW: logging.WARNING,
Colors.GREEN: logging.INFO,
Colors.CYAN: logging.INFO,
Colors.WHITE: logging.INFO,
Colors.MAGENTA: logging.INFO,
Colors.GRAY: logging.DEBUG,
}
def print_colored(text: str, color: str = Colors.WHITE, bold: bool = False):
"""Print colored text to console"""
style = Colors.BOLD if bold else ""
print(f"{style}{color}{text}{Colors.RESET}")
def log_and_print(text: str, color: str = Colors.WHITE, bold: bool = False,
level: int = None):
"""
Hybrid output: print colored to console AND log to structured log file.
Maintains the full console UX with ANSI colors while simultaneously
writing a clean (color-stripped) message to the log file at the
appropriate severity level. Use for operational events that should be
captured in both places (module start/stop, errors, remediation, exports).
Args:
text: Message text (may contain ANSI codes or brackets like [+] [!])
color: ANSI color code for console output
bold: Whether to bold the console output
level: Explicit logging level; auto-detected from color if None
"""
# Print to console with colors
style = Colors.BOLD if bold else ""
print(f"{style}{color}{text}{Colors.RESET}")
# Log to file without ANSI codes
clean_text = text.strip()
if not clean_text:
return
log_level = level if level is not None else _COLOR_LOG_LEVEL.get(color, logging.INFO)
logger.log(log_level, clean_text)
def print_banner():
"""Display the script banner"""
print()
print_colored("=" * 100, Colors.CYAN)
print_colored(f" Linux Security Audit Script v{SCRIPT_VERSION}", Colors.CYAN)
print_colored(" Comprehensive Multi-Framework Security Assessment", Colors.CYAN)
print_colored("=" * 100, Colors.CYAN)
print_colored("\nSupported Frameworks:", Colors.WHITE, bold=True)
print_colored(" - Core Security Baseline", Colors.GRAY)
print_colored(" - CIS Benchmarks", Colors.GRAY)
print_colored(" - CISA Best Practices", Colors.GRAY)
print_colored(" - DISA STIGs", Colors.GRAY)
print_colored(" - ENISA Cybersecurity Guidelines", Colors.GRAY)
print_colored(" - ISO/IEC 27001 Information Security Management", Colors.GRAY)
print_colored(" - NIST Cybersecurity Framework", Colors.GRAY)
print_colored(" - NSA Cybersecurity Guidance", Colors.GRAY)
if HAS_COMMON_LIB:
print_colored(f"\n Shared Library: v{COMMON_LIB_VERSION} (caching, parallel execution enabled)", Colors.GREEN)
print_colored("\n" + "=" * 100 + "\n", Colors.CYAN)
# ============================================================================
# Prerequisites Check
# ============================================================================
def check_prerequisites(require_root: bool = False) -> Tuple[bool, bool]:
"""
Check system prerequisites
Args:
require_root: If True, return False when not running as root
Returns:
Tuple of (prerequisites_met: bool, is_root: bool)
"""
print_colored("[*] Checking prerequisites...", Colors.YELLOW)
# Check Python version
py_version = sys.version_info
if py_version.major < 3 or (py_version.major == 3 and py_version.minor < 6):
log_and_print(f"[!] Python 3.6+ required. Current: {py_version.major}.{py_version.minor}", Colors.RED)
return False, False
log_and_print(f"[+] Python version: {py_version.major}.{py_version.minor}.{py_version.micro}", Colors.GREEN)
# Check if running as root
is_root = os.geteuid() == 0
if not is_root:
log_and_print("[!] INFO: Not running as root/sudo", Colors.CYAN)
print_colored(" Some checks may be limited or unavailable", Colors.CYAN)
print_colored(" Remediation features will be disabled", Colors.CYAN)
if require_root:
print_colored("[!] ERROR: Remediation requires root privileges", Colors.RED)
print_colored(" Run with: sudo python3 linux_security_audit.py --remediate", Colors.YELLOW)
return False, False
else:
log_and_print("[+] Running with root privileges", Colors.GREEN)
print_colored(" All checks and remediation available", Colors.GREEN)
# Check OS
os_info = f"{platform.system()} {platform.release()}"
log_and_print(f"[+] Operating System: {os_info}", Colors.GREEN)
# Check for required commands
required_commands = ['grep', 'awk'] # Basic commands
recommended_commands = ['systemctl'] # Useful but not critical
missing_required = []
missing_recommended = []
for cmd in required_commands:
if not which(cmd):
missing_required.append(cmd)
for cmd in recommended_commands:
if not which(cmd):
missing_recommended.append(cmd)
# Check for network tools (ss OR netstat - at least one should be available)
has_ss = which('ss') is not None
has_netstat = which('netstat') is not None
if not has_ss and not has_netstat:
missing_recommended.append('ss or netstat')
if missing_required:
log_and_print(f"[!] ERROR: Missing required commands: {', '.join(missing_required)}", Colors.RED)
return False, is_root
if missing_recommended:
log_and_print(f"[!] INFO: Missing recommended commands: {', '.join(missing_recommended)}", Colors.CYAN)
print_colored(" Some checks may be skipped", Colors.CYAN)
return True, is_root
def which(command: str) -> Optional[str]:
"""Check if command exists (uses shutil.which for performance)"""
import shutil
return shutil.which(command)
# ============================================================================
# Result Validation and Normalization
# ============================================================================
def validate_result(result: AuditResult, module_name: str) -> bool:
"""Validate a result object"""
is_valid, issues = result.validate()
if not is_valid:
statistics.add_validation_issue(module_name, issues)
return is_valid
def normalize_result(result: AuditResult, module_name: str) -> AuditResult:
"""Normalize and repair a result object"""
normalized = False
# Ensure module exists
if not result.module:
result.module = module_name
normalized = True
# Ensure category exists
if not result.category:
result.category = "Uncategorized"
normalized = True
# Ensure message exists
if not result.message:
result.message = "No message"
normalized = True
# Normalize status value (case-insensitive matching)
if result.status:
matched_status = None
for valid_status in VALID_STATUS_VALUES:
if result.status.lower() == valid_status.lower():
matched_status = valid_status
break
if matched_status and result.status != matched_status:
result.status = matched_status
normalized = True
elif not matched_status:
result.status = "Error"
normalized = True
else:
result.status = "Error"
normalized = True
if normalized:
statistics.increment_normalized()
return result
def get_validated_results(results: List[AuditResult], module_name: str) -> List[AuditResult]:
"""Validate and normalize a list of results"""
if not results:
log_and_print(f"[!] Module {module_name} returned no results", Colors.YELLOW)
return []
validated_results = []
for result in results:
if validate_result(result, module_name):
validated_results.append(result)
else:
repaired_result = normalize_result(result, module_name)
if validate_result(repaired_result, module_name):
validated_results.append(repaired_result)
return validated_results
# ============================================================================
# Module Statistics
# ============================================================================
def calculate_module_statistics(results: List[AuditResult]) -> ModuleStatistics:
"""Calculate statistics for a module's results"""
return ModuleStatistics(
total=len(results),
passed=sum(1 for r in results if r.status == "Pass"),
failed=sum(1 for r in results if r.status == "Fail"),
warnings=sum(1 for r in results if r.status == "Warning"),
info=sum(1 for r in results if r.status == "Info"),
errors=sum(1 for r in results if r.status == "Error")
)
# ============================================================================
# Module Management
# ============================================================================
def get_available_modules() -> Dict[str, Path]:
"""
Dynamically discover and return available modules from the modules directory
Scans the modules/ directory for Python files that follow the module pattern:
- Filename: module_*.py
- Contains: run_checks() function
- Contains: MODULE_NAME variable
Returns:
Dictionary mapping module names to their file paths
"""
modules_dir = SCRIPT_PATH / "modules"
available_modules = {}
if not modules_dir.exists():
print_colored(f"[!] WARNING: Modules directory not found: {modules_dir}", Colors.YELLOW)
return available_modules
# Scan for module files
module_files = sorted(modules_dir.glob("module_*.py"))
for module_file in module_files:
# Extract module name from filename (e.g., module_core.py -> Core)
module_name_raw = module_file.stem.replace("module_", "")
module_name = module_name_raw.title() # Capitalize first letter
# Special case for acronyms/uppercase module names
if module_name_raw.upper() in ['CIS', 'NIST', 'STIG', 'NSA', 'CISA', 'ENISA']:
module_name = module_name_raw.upper()
elif module_name_raw.lower() == 'iso27001':
module_name = 'ISO27001'
# Validate module has required structure
try:
# Quick validation: check if file contains required elements
with open(module_file, 'r', encoding='utf-8') as f:
content = f.read()
if 'def run_checks(' in content:
available_modules[module_name] = module_file
else:
print_colored(f"[!] WARNING: Skipping {module_file.name} - missing run_checks() function", Colors.YELLOW)
except Exception as e:
print_colored(f"[!] WARNING: Could not validate module {module_file.name}: {e}", Colors.YELLOW)
return available_modules
def list_available_modules():
"""List all available modules to the console"""
modules = get_available_modules()
if not modules:
print_colored("[!] No modules found in modules/ directory", Colors.YELLOW)
return
print_colored("\n[*] Available Modules:", Colors.CYAN, bold=True)
for module_name, module_path in sorted(modules.items()):
# Try to read module docstring for description
try:
with open(module_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
description = "No description available"
# Look for SYNOPSIS in docstring
in_docstring = False
for line in lines[:50]: # Check first 50 lines
if '"""' in line or "'''" in line:
in_docstring = not in_docstring
elif in_docstring and 'SYNOPSIS' in line.upper():
# Get next non-empty line
idx = lines.index(line)
for next_line in lines[idx+1:idx+5]:
desc = next_line.strip()
if desc and not desc.startswith('"""') and not desc.startswith("'''"):
description = desc
break
break
print_colored(f" - {module_name.ljust(12)} - {description}", Colors.WHITE)
except:
print_colored(f" - {module_name}", Colors.WHITE)
print_colored(f"\nTotal modules found: {len(modules)}\n", Colors.CYAN)
def check_module_exists(module_name: str) -> bool:
"""Check if a module file exists"""
available_modules = get_available_modules()
if module_name not in available_modules:
return False
module_path = available_modules[module_name]
return module_path.exists()
def execute_security_module(module_name: str, shared_data: Dict[str, Any]) -> List[AuditResult]:
"""Execute a security audit module"""
available_modules = get_available_modules()
module_path = available_modules.get(module_name)
if not module_path or not module_path.exists():
log_and_print(f"[!] Module not found: {module_name}", Colors.RED)
return []
try:
log_and_print(f"\n[*] Executing module: {module_name}", Colors.CYAN)
module_start = time.time()
# Import and execute the module
import importlib.util
load_start = time.time()
spec = importlib.util.spec_from_file_location(f"module_{module_name.lower()}", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
load_elapsed = time.time() - load_start
logger.info(f"Module {module_name} loaded in {load_elapsed:.3f}s from {module_path}")
# Call the module's main function
if hasattr(module, 'run_checks'):
check_start = time.time()
results = module.run_checks(shared_data)
check_elapsed = time.time() - check_start
logger.info(f"Module {module_name} run_checks() executed in {check_elapsed:.3f}s")
else:
log_and_print(f"[!] Module {module_name} missing run_checks function", Colors.RED)
return []
# Validate and normalize results
validated_results = get_validated_results(results, module_name)
# Calculate and display module statistics
stats = calculate_module_statistics(validated_results)
statistics.module_stats[module_name] = stats
module_elapsed = time.time() - module_start
log_and_print(f"[+] Module {module_name} completed: {stats.total} checks in {module_elapsed:.1f}s", Colors.GREEN)
print_colored(f" Pass: {stats.passed} | Fail: {stats.failed} | Warning: {stats.warnings} | Info: {stats.info} | Error: {stats.errors}", Colors.GRAY)
return validated_results
except Exception as e:
log_and_print(f"[!] Error executing module {module_name}: {e}", Colors.RED)
logger.error(f"Module {module_name} exception details", exc_info=True)
import traceback
traceback.print_exc()
return []
# ============================================================================
# Remediation Functions
# ============================================================================
def invoke_remediation(results: List[AuditResult], args: argparse.Namespace):
"""Handle remediation of issues"""
auto_mode = args.auto_remediate
remediate_all = args.remediate
remediate_fail = args.remediate_fail
remediate_warning = args.remediate_warning
remediate_info = args.remediate_info
remediation_file = args.remediation_file
print_colored("\n" + "=" * 100, Colors.YELLOW)
print_colored(" REMEDIATION MODE", Colors.YELLOW, bold=True)
print_colored("=" * 100, Colors.YELLOW)
remediable_results = []
# Check if using remediation file
if remediation_file:
if not os.path.exists(remediation_file):
log_and_print(f"[!] ERROR: Remediation file not found: {remediation_file}", Colors.RED)
print_colored("=" * 100 + "\n", Colors.YELLOW)
return
try:
with open(remediation_file, 'r') as f:
remediation_data = json.load(f)
if 'modules' not in remediation_data:
log_and_print("[!] ERROR: Invalid remediation file format. Expected 'modules' array.", Colors.RED)
print_colored("=" * 100 + "\n", Colors.YELLOW)
return
# Match results from remediation file
targeted_checks = []
for module_data in remediation_data['modules']:
module_name = module_data['moduleName']
for result_data in module_data['results']:
for result in results:
if (result.module == module_name and
result.category == result_data.get('Category') and
result.message == result_data.get('Finding') and
result.remediation):
targeted_checks.append(result)
break
if not targeted_checks:
log_and_print("[!] No matching remediable issues found in remediation file.", Colors.YELLOW)
print_colored("=" * 100 + "\n", Colors.YELLOW)
return
print_colored(f"[*] Found {len(targeted_checks)} targeted issue(s) to remediate", Colors.CYAN)
remediable_results = targeted_checks
except Exception as e:
log_and_print(f"[!] ERROR: Failed to parse remediation file: {e}", Colors.RED)
print_colored("=" * 100 + "\n", Colors.YELLOW)
return
else:
# Standard mode - filter by status
statuses_to_remediate = []
if remediate_all:
statuses_to_remediate = ["Fail", "Warning", "Info"]
print_colored("[*] Mode: Remediate ALL issues (Fail, Warning, Info)", Colors.CYAN)
else:
if remediate_fail:
statuses_to_remediate.append("Fail")
if remediate_warning:
statuses_to_remediate.append("Warning")
if remediate_info:
statuses_to_remediate.append("Info")
print_colored(f"[*] Mode: Remediate {', '.join(statuses_to_remediate)} issues only", Colors.CYAN)
remediable_results = [r for r in results if r.status in statuses_to_remediate and r.remediation]
if not remediable_results:
print_colored("\n[*] No remediable issues found for selected status types.", Colors.CYAN)
print_colored("=" * 100 + "\n", Colors.YELLOW)
return
print_colored(f"[*] Found {len(remediable_results)} issue(s) with remediation available", Colors.YELLOW)
# Auto-remediation safety confirmation
if auto_mode:
print_colored("\n+" + "-" * 98 + "+", Colors.RED)
print_colored("|" + " " * 34 + "WARNING - AUTO-REMEDIATION" + " " * 37 + "|", Colors.RED)
print_colored("+" + "-" * 98 + "+", Colors.RED)
print_colored("|" + " " * 98 + "|", Colors.RED)
print_colored(f"| This will automatically apply {str(len(remediable_results)).ljust(3)} remediation(s) WITHOUT prompting for each one." + " " * (98 - 76 - len(str(len(remediable_results)))) + "|", Colors.RED)
print_colored("|" + " " * 98 + "|", Colors.RED)
print_colored("| RISKS:" + " " * 91 + "|", Colors.RED)
print_colored("| - System configuration will be modified automatically" + " " * 44 + "|", Colors.RED)
print_colored("| - Changes may affect system functionality or applications" + " " * 39 + "|", Colors.RED)
print_colored("| - Some changes may require system restart" + " " * 56 + "|", Colors.RED)
print_colored("| - Automated remediation may have unintended consequences" + " " * 41 + "|", Colors.RED)
print_colored("|" + " " * 98 + "|", Colors.RED)
print_colored("| RECOMMENDATION: Review each remediation in interactive mode first" + " " * 31 + "|", Colors.RED)
print_colored("|" + " " * 98 + "|", Colors.RED)
print_colored("+" + "-" * 98 + "+", Colors.RED)
print()
print_colored("Issues to be remediated:", Colors.YELLOW)
for result in remediable_results:
print_colored(f" - [{result.status}] {result.module} - {result.message}", Colors.GRAY)
print()
# First confirmation
first_confirm = input(print_colored("Do you want to proceed with AUTO-REMEDIATION? Type 'YES' to continue: ", Colors.YELLOW, bold=True) or "")
if first_confirm != 'YES':
print_colored("\n[*] Auto-remediation cancelled by user.", Colors.YELLOW)
print_colored("=" * 100 + "\n", Colors.YELLOW)
return
# Second confirmation with countdown
print_colored("\nFinal confirmation required. Type 'CONFIRM' within 10 seconds to proceed: ", Colors.RED, bold=True, end='')
import select
timeout = 10
start_time = time.time()
second_confirm = None
# Platform-specific input with timeout
if sys.platform != 'win32':
i, o, e = select.select([sys.stdin], [], [], timeout)
if i:
second_confirm = sys.stdin.readline().strip()
else:
# Windows fallback (no timeout)
second_confirm = input()
if second_confirm != 'CONFIRM':
print_colored("\n[*] Auto-remediation cancelled (timeout or incorrect confirmation).", Colors.YELLOW)
print_colored("=" * 100 + "\n", Colors.YELLOW)
return
print_colored("\n[*] AUTO-REMEDIATION CONFIRMED - Beginning automated remediation...", Colors.GREEN)
time.sleep(2)
else:
print_colored("[*] Interactive mode (will prompt for each remediation)", Colors.CYAN)
print()
remediated_count = 0
skipped_count = 0
failed_remediation_count = 0
remediation_log = []
for result in remediable_results:
print_colored(f"[*] Issue: {result.message}", Colors.CYAN)
print_colored(f" Module: {result.module} | Status: {result.status} | Category: {result.category}", Colors.GRAY)
print_colored(f" Remediation: {result.remediation}", Colors.GRAY)
should_remediate = False
if auto_mode:
should_remediate = True
log_and_print(" [AUTO] Applying remediation...", Colors.YELLOW)
else:
response = input(" Apply remediation? (Y/N/S=Skip remaining): ")
if response.upper() == 'S':
print_colored(" [*] Skipping all remaining remediations", Colors.YELLOW)
skipped_count += (len(remediable_results) - remediated_count - failed_remediation_count - skipped_count)
break
should_remediate = response.upper() == 'Y'
if should_remediate:
try:
# Execute remediation command
result_code = subprocess.run(result.remediation, shell=True, capture_output=True, text=True)
if result_code.returncode == 0:
log_and_print(" [+] Remediation applied successfully", Colors.GREEN)