wilma-sec 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wilma/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """
2
+ Wilma - AWS Bedrock Security Posture Assessment
3
+
4
+ An AWS Bedrock security posture assessment tool that maps automated evidence to
5
+ Bedrock Security Indicators and external security frameworks.
6
+
7
+ Copyright (C) 2024 Ethan Troy
8
+
9
+ This program is free software: you can redistribute it and/or modify
10
+ it under the terms of the GNU General Public License as published by
11
+ the Free Software Foundation, either version 3 of the License, or
12
+ (at your option) any later version.
13
+ """
14
+
15
+ __version__ = "0.2.1"
16
+ __author__ = "Ethan Troy"
17
+ __license__ = "GPL-3.0-or-later"
18
+
19
+ from wilma.api import ScanResult, WilmaScanner
20
+ from wilma.checker import BedrockSecurityChecker
21
+ from wilma.enums import RiskLevel, SecurityMode
22
+ from wilma.exceptions import WilmaCredentialsError, WilmaError
23
+
24
+ __all__ = [
25
+ "BedrockSecurityChecker",
26
+ "RiskLevel",
27
+ "ScanResult",
28
+ "SecurityMode",
29
+ "WilmaCredentialsError",
30
+ "WilmaError",
31
+ "WilmaScanner",
32
+ "__version__",
33
+ ]
wilma/__main__.py ADDED
@@ -0,0 +1,189 @@
1
+ """
2
+ CLI entry point for Wilma
3
+
4
+ Copyright (C) 2024 Ethan Troy
5
+
6
+ This program is free software: you can redistribute it and/or modify
7
+ it under the terms of the GNU General Public License as published by
8
+ the Free Software Foundation, either version 3 of the License, or
9
+ (at your option) any later version.
10
+ """
11
+
12
+ import argparse
13
+ import sys
14
+ import time
15
+ from contextlib import nullcontext, redirect_stdout
16
+
17
+ from rich.console import Console
18
+
19
+ from wilma import __version__
20
+ from wilma.assessment import risk_level_label
21
+ from wilma.checker import BedrockSecurityChecker
22
+ from wilma.config import WilmaConfig, create_example_config
23
+ from wilma.enums import RiskLevel, SecurityMode
24
+ from wilma.reports import ReportGenerator
25
+
26
+
27
+ def _scan_output_context(quiet: bool):
28
+ """Redirect noisy scan progress to stderr when stdout must be machine-readable."""
29
+ return redirect_stdout(sys.stderr) if quiet else nullcontext()
30
+
31
+
32
+ def _run_yabba_intro():
33
+ """Show a short local terminal-only animation for the fun presentation mode."""
34
+ console = Console()
35
+ console.print("[bold magenta]Yabba Dabba Doo![/bold magenta] Wilma is rolling over the Bedrock...")
36
+ with console.status("Carving the stone tablet scorecard...", spinner="dots"):
37
+ time.sleep(0.6)
38
+
39
+
40
+ def main():
41
+ """Main function to run the Bedrock posture assessment."""
42
+ parser = argparse.ArgumentParser(
43
+ description='Wilma - AWS Bedrock Security Posture Assessment',
44
+ formatter_class=argparse.RawDescriptionHelpFormatter,
45
+ epilog="""
46
+ Examples:
47
+ %(prog)s # Run posture assessment (default)
48
+ %(prog)s --explain # Explain the scoring and indicator model
49
+ %(prog)s --learn # Alias for --explain
50
+ %(prog)s --yabba-dabba-doo # Fun local terminal presentation mode
51
+ %(prog)s --output json # Output in JSON format
52
+ %(prog)s --fix logging # Get step-by-step fix for logging issues
53
+ %(prog)s --config ~/.wilma/custom.yaml # Use custom configuration
54
+ %(prog)s --checks iam,network # Run only selected automated checks
55
+ %(prog)s --min-risk HIGH # Show only HIGH and CRITICAL findings
56
+ %(prog)s --create-config # Create example config file
57
+ """
58
+ )
59
+
60
+ parser.add_argument('--profile', help='AWS profile name to use', default=None)
61
+ parser.add_argument('--region', help='AWS region to check', default=None)
62
+ parser.add_argument('--explain', action='store_true', help='Explain Wilma scoring, indicators, and framework mappings')
63
+ parser.add_argument('--learn', action='store_true', help='Alias for --explain')
64
+ parser.add_argument('--yabba-dabba-doo', action='store_true',
65
+ help='Fun local terminal presentation mode; scan logic and JSON stay unchanged')
66
+ parser.add_argument('--fix', help='Get detailed remediation steps for a specific issue type')
67
+ parser.add_argument('--output', choices=['json', 'text'], default='text', help='Output format')
68
+ parser.add_argument('--output-file', help='Save report to file', default=None)
69
+ parser.add_argument('--config', help='Path to custom configuration file', default=None)
70
+ parser.add_argument('--checks', help='Comma-separated list of checks to run (e.g., iam,network,genai)', default=None)
71
+ parser.add_argument('--min-risk', choices=['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'],
72
+ help='Minimum risk level to include in report', default=None)
73
+ parser.add_argument('--create-config', help='Create an example configuration file at specified path',
74
+ metavar='PATH', default=None)
75
+ parser.add_argument('--show-config', action='store_true', help='Display current configuration and exit')
76
+ parser.add_argument('--version', action='version', version=f'wilma-sec {__version__}')
77
+
78
+ args = parser.parse_args()
79
+ presentation_mode = "yabba_dabba_doo" if args.yabba_dabba_doo else "standard"
80
+
81
+ # Handle --create-config flag
82
+ if args.create_config:
83
+ output_path = args.create_config
84
+ create_example_config(output_path)
85
+ print(f"\n[SUCCESS] Example configuration created at: {output_path}")
86
+ print("Edit this file to customize Wilma's behavior, then use --config to load it.")
87
+ return
88
+
89
+ # Explain mode should not require AWS credentials.
90
+ if args.explain or args.learn:
91
+ report_generator = ReportGenerator(
92
+ checker=None,
93
+ presentation_mode=presentation_mode,
94
+ emit=not args.output_file,
95
+ )
96
+ report = report_generator.generate_report(output_format='text', explain=True)
97
+ if args.output_file:
98
+ with open(args.output_file, 'w') as f:
99
+ f.write(report)
100
+ print(f"\n[SUCCESS] Explain report saved to: {args.output_file}")
101
+ return
102
+
103
+ quiet_scan_output = args.output == 'json'
104
+ with _scan_output_context(quiet_scan_output):
105
+ # Load configuration
106
+ config = WilmaConfig(config_path=args.config)
107
+
108
+ # Override config with CLI arguments if provided
109
+ if args.checks:
110
+ check_list = [c.strip() for c in args.checks.split(',')]
111
+ config.config['checks']['enabled'] = check_list
112
+ config._validate_config()
113
+ print(f"[INFO] Running selective checks: {', '.join(config.enabled_checks)}")
114
+
115
+ if args.min_risk:
116
+ config.config['output']['min_risk_level'] = args.min_risk
117
+ config._validate_config()
118
+ print(f"[INFO] Filtering findings: minimum risk level = {args.min_risk}")
119
+
120
+ # Handle --show-config flag
121
+ if args.show_config:
122
+ config.print_config()
123
+ return
124
+
125
+ mode = SecurityMode.STANDARD
126
+
127
+ # Handle fix mode
128
+ if args.fix:
129
+ print(f"\n[FIX] Remediation Guide for: {args.fix}")
130
+ print("This feature is coming soon!")
131
+ print("For now, run the posture assessment to see fix commands for each issue.")
132
+ return
133
+
134
+ try:
135
+ if args.yabba_dabba_doo and args.output == 'text' and not args.output_file:
136
+ _run_yabba_intro()
137
+
138
+ # Initialize and run the checker
139
+ with _scan_output_context(quiet_scan_output):
140
+ checker = BedrockSecurityChecker(
141
+ profile_name=args.profile,
142
+ region=args.region,
143
+ mode=mode,
144
+ config=config,
145
+ presentation_mode=presentation_mode,
146
+ )
147
+
148
+ # Run all checks
149
+ checker.run_all_checks()
150
+
151
+ # Generate report
152
+ report_generator = ReportGenerator(
153
+ checker,
154
+ presentation_mode=presentation_mode,
155
+ emit=not args.output_file,
156
+ )
157
+ report = report_generator.generate_report(output_format=args.output)
158
+
159
+ # Output report
160
+ if args.output_file:
161
+ with open(args.output_file, 'w') as f:
162
+ f.write(report)
163
+ print(f"\n[SUCCESS] There! Report saved to: {args.output_file}")
164
+ elif args.output == 'json':
165
+ print(report)
166
+
167
+ # Exit with appropriate code
168
+ reported_findings = checker.filtered_findings()
169
+ if any(risk_level_label(f.get('risk_level')) == RiskLevel.CRITICAL.label for f in reported_findings):
170
+ sys.exit(2)
171
+ elif any(risk_level_label(f.get('risk_level')) == RiskLevel.HIGH.label for f in reported_findings):
172
+ sys.exit(1)
173
+ else:
174
+ sys.exit(0)
175
+
176
+ except KeyboardInterrupt:
177
+ print("\n\n[WARN] Check interrupted by user")
178
+ sys.exit(3)
179
+ except Exception as e:
180
+ print(f"\n[ERROR] Oh Fred... Error running posture assessment: {str(e)}")
181
+ print("\n[TIPS] Let me help you troubleshoot:")
182
+ print(" 1. Check your AWS credentials: aws configure list")
183
+ print(" 2. Ensure you have the necessary IAM permissions")
184
+ print(" 3. Try specifying a region: --region us-east-1")
185
+ sys.exit(3)
186
+
187
+
188
+ if __name__ == '__main__':
189
+ main()
wilma/api.py ADDED
@@ -0,0 +1,51 @@
1
+ """Embeddable library API for Wilma scans."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Optional
5
+
6
+ from wilma.assessment import AssessmentBuilder
7
+ from wilma.checker import BedrockSecurityChecker
8
+ from wilma.config import WilmaConfig
9
+ from wilma.enums import SecurityMode
10
+
11
+
12
+ @dataclass
13
+ class ScanResult:
14
+ """Structured result returned by the library scanner."""
15
+
16
+ assessment: dict
17
+ findings: list[dict]
18
+ checker: BedrockSecurityChecker
19
+
20
+
21
+ class WilmaScanner:
22
+ """Programmatic scanner for security tools that embed Wilma."""
23
+
24
+ def __init__(
25
+ self,
26
+ profile: Optional[str] = None,
27
+ region: Optional[str] = None,
28
+ config: Optional[WilmaConfig] = None,
29
+ mode: SecurityMode = SecurityMode.STANDARD,
30
+ ):
31
+ self.profile = profile
32
+ self.region = region
33
+ self.config = config
34
+ self.mode = mode
35
+
36
+ def scan(self) -> ScanResult:
37
+ """Run a Bedrock posture assessment and return the structured assessment."""
38
+ checker = BedrockSecurityChecker(
39
+ profile_name=self.profile,
40
+ region=self.region,
41
+ mode=self.mode,
42
+ config=self.config,
43
+ exit_on_error=False,
44
+ )
45
+ checker.run_all_checks()
46
+ assessment = AssessmentBuilder(checker).build()
47
+ return ScanResult(
48
+ assessment=assessment,
49
+ findings=assessment["findings"],
50
+ checker=checker,
51
+ )