iam-policy-validator 1.3.1__py3-none-any.whl → 1.5.0__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.
Files changed (41) hide show
  1. {iam_policy_validator-1.3.1.dist-info → iam_policy_validator-1.5.0.dist-info}/METADATA +164 -19
  2. iam_policy_validator-1.5.0.dist-info/RECORD +67 -0
  3. iam_validator/__version__.py +1 -1
  4. iam_validator/checks/__init__.py +15 -3
  5. iam_validator/checks/action_condition_enforcement.py +1 -6
  6. iam_validator/checks/condition_key_validation.py +21 -1
  7. iam_validator/checks/full_wildcard.py +67 -0
  8. iam_validator/checks/policy_size.py +1 -0
  9. iam_validator/checks/policy_type_validation.py +299 -0
  10. iam_validator/checks/principal_validation.py +776 -0
  11. iam_validator/checks/sensitive_action.py +178 -0
  12. iam_validator/checks/service_wildcard.py +105 -0
  13. iam_validator/checks/sid_uniqueness.py +45 -7
  14. iam_validator/checks/utils/sensitive_action_matcher.py +39 -31
  15. iam_validator/checks/wildcard_action.py +62 -0
  16. iam_validator/checks/wildcard_resource.py +131 -0
  17. iam_validator/commands/download_services.py +3 -8
  18. iam_validator/commands/post_to_pr.py +7 -0
  19. iam_validator/commands/validate.py +204 -16
  20. iam_validator/core/aws_fetcher.py +25 -12
  21. iam_validator/core/check_registry.py +25 -21
  22. iam_validator/core/config/__init__.py +83 -0
  23. iam_validator/core/config/aws_api.py +35 -0
  24. iam_validator/core/config/condition_requirements.py +535 -0
  25. iam_validator/core/config/defaults.py +390 -0
  26. iam_validator/core/config/principal_requirements.py +421 -0
  27. iam_validator/core/config/sensitive_actions.py +133 -0
  28. iam_validator/core/config/service_principals.py +95 -0
  29. iam_validator/core/config/wildcards.py +124 -0
  30. iam_validator/core/config_loader.py +29 -9
  31. iam_validator/core/formatters/enhanced.py +11 -5
  32. iam_validator/core/formatters/sarif.py +78 -14
  33. iam_validator/core/models.py +13 -3
  34. iam_validator/core/policy_checks.py +39 -6
  35. iam_validator/core/pr_commenter.py +30 -9
  36. iam_policy_validator-1.3.1.dist-info/RECORD +0 -54
  37. iam_validator/checks/security_best_practices.py +0 -535
  38. iam_validator/core/defaults.py +0 -366
  39. {iam_policy_validator-1.3.1.dist-info → iam_policy_validator-1.5.0.dist-info}/WHEEL +0 -0
  40. {iam_policy_validator-1.3.1.dist-info → iam_policy_validator-1.5.0.dist-info}/entry_points.txt +0 -0
  41. {iam_policy_validator-1.3.1.dist-info → iam_policy_validator-1.5.0.dist-info}/licenses/LICENSE +0 -0
@@ -1,535 +0,0 @@
1
- """Security best practices check - validates security anti-patterns."""
2
-
3
- from typing import TYPE_CHECKING
4
-
5
- from iam_validator.checks.utils.policy_level_checks import check_policy_level_actions
6
- from iam_validator.checks.utils.sensitive_action_matcher import (
7
- DEFAULT_SENSITIVE_ACTIONS,
8
- check_sensitive_actions,
9
- )
10
- from iam_validator.checks.utils.wildcard_expansion import expand_wildcard_actions
11
- from iam_validator.core.aws_fetcher import AWSServiceFetcher
12
- from iam_validator.core.check_registry import CheckConfig, PolicyCheck
13
- from iam_validator.core.models import Statement, ValidationIssue
14
-
15
- if TYPE_CHECKING:
16
- from iam_validator.core.models import IAMPolicy
17
-
18
-
19
- class SecurityBestPracticesCheck(PolicyCheck):
20
- """Checks for common security anti-patterns and best practices violations."""
21
-
22
- @property
23
- def check_id(self) -> str:
24
- return "security_best_practices"
25
-
26
- @property
27
- def description(self) -> str:
28
- return "Checks for common security anti-patterns"
29
-
30
- @property
31
- def default_severity(self) -> str:
32
- return "warning"
33
-
34
- async def execute(
35
- self,
36
- statement: Statement,
37
- statement_idx: int,
38
- fetcher: AWSServiceFetcher,
39
- config: CheckConfig,
40
- ) -> list[ValidationIssue]:
41
- """Execute security best practices checks on a statement."""
42
- issues = []
43
-
44
- # Only check Allow statements
45
- if statement.effect != "Allow":
46
- return issues
47
-
48
- statement_sid = statement.sid
49
- line_number = statement.line_number
50
- actions = statement.get_actions()
51
- resources = statement.get_resources()
52
-
53
- # Check 1: Wildcard action check
54
- if self._is_sub_check_enabled(config, "wildcard_action_check"):
55
- if "*" in actions:
56
- severity = self._get_sub_check_severity(config, "wildcard_action_check", "warning")
57
- sub_check_config = config.config.get("wildcard_action_check", {})
58
-
59
- message = sub_check_config.get("message", "Statement allows all actions (*)")
60
- suggestion_text = sub_check_config.get(
61
- "suggestion", "Consider limiting to specific actions needed"
62
- )
63
- example = sub_check_config.get("example", "")
64
-
65
- # Combine suggestion + example like action_condition_enforcement does
66
- suggestion = (
67
- f"{suggestion_text}\nExample:\n{example}" if example else suggestion_text
68
- )
69
-
70
- issues.append(
71
- ValidationIssue(
72
- severity=severity,
73
- statement_sid=statement_sid,
74
- statement_index=statement_idx,
75
- issue_type="overly_permissive",
76
- message=message,
77
- suggestion=suggestion,
78
- line_number=line_number,
79
- )
80
- )
81
-
82
- # Check 2: Wildcard resource check
83
- if self._is_sub_check_enabled(config, "wildcard_resource_check"):
84
- if "*" in resources:
85
- # Check if all actions are in the allowed_wildcards list
86
- # allowed_wildcards works by expanding wildcard patterns (like "ec2:Describe*")
87
- # to all matching AWS actions using the AWS API, then checking if the policy's
88
- # actions are in that expanded list. This ensures only validated AWS actions
89
- # are allowed with Resource: "*".
90
- allowed_wildcards_expanded = await self._get_expanded_allowed_wildcards(
91
- config, fetcher
92
- )
93
-
94
- # Check if ALL actions (excluding full wildcard "*") are in the expanded list
95
- non_wildcard_actions = [a for a in actions if a != "*"]
96
-
97
- if allowed_wildcards_expanded and non_wildcard_actions:
98
- # Check if all actions are in the expanded allowed list (exact match)
99
- all_actions_allowed = all(
100
- action in allowed_wildcards_expanded for action in non_wildcard_actions
101
- )
102
-
103
- # If all actions are in the expanded list, skip the wildcard resource warning
104
- if all_actions_allowed:
105
- # All actions are safe, Resource: "*" is acceptable
106
- pass
107
- else:
108
- # Some actions are not in allowed list, flag the issue
109
- self._add_wildcard_resource_issue(
110
- issues,
111
- config,
112
- statement_sid,
113
- statement_idx,
114
- line_number,
115
- )
116
- else:
117
- # No allowed_wildcards configured OR only has "*" action
118
- # Always flag wildcard resources in these cases
119
- self._add_wildcard_resource_issue(
120
- issues, config, statement_sid, statement_idx, line_number
121
- )
122
-
123
- # Check 3: Critical - both wildcards together
124
- if self._is_sub_check_enabled(config, "full_wildcard_check"):
125
- if "*" in actions and "*" in resources:
126
- severity = self._get_sub_check_severity(config, "full_wildcard_check", "error")
127
- sub_check_config = config.config.get("full_wildcard_check", {})
128
-
129
- message = sub_check_config.get(
130
- "message",
131
- "Statement allows all actions on all resources - CRITICAL SECURITY RISK",
132
- )
133
- suggestion_text = sub_check_config.get(
134
- "suggestion",
135
- "This grants full administrative access. Restrict to specific actions and resources.",
136
- )
137
- example = sub_check_config.get("example", "")
138
-
139
- # Combine suggestion + example
140
- suggestion = (
141
- f"{suggestion_text}\nExample:\n{example}" if example else suggestion_text
142
- )
143
-
144
- issues.append(
145
- ValidationIssue(
146
- severity=severity,
147
- statement_sid=statement_sid,
148
- statement_index=statement_idx,
149
- issue_type="security_risk",
150
- message=message,
151
- suggestion=suggestion,
152
- line_number=line_number,
153
- )
154
- )
155
-
156
- # Check 4: Service-level wildcards (e.g., "iam:*", "s3:*")
157
- if self._is_sub_check_enabled(config, "service_wildcard_check"):
158
- allowed_services = self._get_allowed_service_wildcards(config)
159
-
160
- for action in actions:
161
- # Skip full wildcard (covered by wildcard_action_check)
162
- if action == "*":
163
- continue
164
-
165
- # Check if it's a service-level wildcard (e.g., "iam:*", "s3:*")
166
- if ":" in action and action.endswith(":*"):
167
- service = action.split(":")[0]
168
-
169
- # Check if this service is in the allowed list
170
- if service not in allowed_services:
171
- severity = self._get_sub_check_severity(
172
- config, "service_wildcard_check", "warning"
173
- )
174
- sub_check_config = config.config.get("service_wildcard_check", {})
175
-
176
- # Get message template and replace placeholders
177
- message_template = sub_check_config.get(
178
- "message",
179
- "Service-level wildcard '{action}' grants all permissions for {service} service",
180
- )
181
- suggestion_template = sub_check_config.get(
182
- "suggestion",
183
- "Consider specifying explicit actions instead of '{action}'. If you need multiple actions, list them individually or use more specific wildcards like '{service}:Get*' or '{service}:List*'.",
184
- )
185
- example_template = sub_check_config.get("example", "")
186
-
187
- message = message_template.format(action=action, service=service)
188
- suggestion_text = suggestion_template.format(action=action, service=service)
189
- example = (
190
- example_template.format(action=action, service=service)
191
- if example_template
192
- else ""
193
- )
194
-
195
- # Combine suggestion + example
196
- suggestion = (
197
- f"{suggestion_text}\nExample:\n{example}"
198
- if example
199
- else suggestion_text
200
- )
201
-
202
- issues.append(
203
- ValidationIssue(
204
- severity=severity,
205
- statement_sid=statement_sid,
206
- statement_index=statement_idx,
207
- issue_type="overly_permissive",
208
- message=message,
209
- action=action,
210
- suggestion=suggestion,
211
- line_number=line_number,
212
- )
213
- )
214
-
215
- # Check 5: Sensitive actions without conditions
216
- if self._is_sub_check_enabled(config, "sensitive_action_check"):
217
- has_conditions = statement.condition is not None and len(statement.condition) > 0
218
-
219
- # Expand wildcards to actual actions using AWS API
220
- expanded_actions = await expand_wildcard_actions(actions, fetcher)
221
-
222
- # Check if sensitive actions match using any_of/all_of logic
223
- is_sensitive, matched_actions = check_sensitive_actions(
224
- expanded_actions, config, DEFAULT_SENSITIVE_ACTIONS
225
- )
226
-
227
- if is_sensitive and not has_conditions:
228
- severity = self._get_sub_check_severity(config, "sensitive_action_check", "warning")
229
- sub_check_config = config.config.get("sensitive_action_check", {})
230
-
231
- # Create appropriate message based on matched actions using configurable templates
232
- if len(matched_actions) == 1:
233
- message_template = sub_check_config.get(
234
- "message_single",
235
- "Sensitive action '{action}' should have conditions to limit when it can be used",
236
- )
237
- message = message_template.format(action=matched_actions[0])
238
- else:
239
- action_list = "', '".join(matched_actions)
240
- message_template = sub_check_config.get(
241
- "message_multiple",
242
- "Sensitive actions '{actions}' should have conditions to limit when they can be used",
243
- )
244
- message = message_template.format(actions=action_list)
245
-
246
- suggestion_text = sub_check_config.get(
247
- "suggestion",
248
- "Add conditions like 'aws:Resource/owner must match aws:Principal/owner', IP restrictions, MFA requirements, or time-based restrictions",
249
- )
250
- example = sub_check_config.get("example", "")
251
-
252
- # Combine suggestion + example
253
- suggestion = (
254
- f"{suggestion_text}\nExample:\n{example}" if example else suggestion_text
255
- )
256
-
257
- issues.append(
258
- ValidationIssue(
259
- severity=severity,
260
- statement_sid=statement_sid,
261
- statement_index=statement_idx,
262
- issue_type="missing_condition",
263
- message=message,
264
- action=(matched_actions[0] if len(matched_actions) == 1 else None),
265
- suggestion=suggestion,
266
- line_number=line_number,
267
- )
268
- )
269
-
270
- return issues
271
-
272
- async def execute_policy(
273
- self,
274
- policy: "IAMPolicy",
275
- policy_file: str,
276
- fetcher: AWSServiceFetcher,
277
- config: CheckConfig,
278
- ) -> list[ValidationIssue]:
279
- """
280
- Execute policy-level security checks.
281
-
282
- This method examines the entire policy to detect privilege escalation patterns
283
- and other security issues that span multiple statements.
284
-
285
- Args:
286
- policy: The complete IAM policy to check
287
- policy_file: Path to the policy file (for context/reporting)
288
- fetcher: AWS service fetcher for validation against AWS APIs
289
- config: Configuration for this check instance
290
-
291
- Returns:
292
- List of ValidationIssue objects found by this check
293
- """
294
- del policy_file, fetcher # Not used in current implementation
295
- issues = []
296
-
297
- # Only check if sensitive_action_check is enabled
298
- if not self._is_sub_check_enabled(config, "sensitive_action_check"):
299
- return issues
300
-
301
- # Collect all actions from all Allow statements across the entire policy
302
- all_actions: set[str] = set()
303
- statement_map: dict[
304
- str, list[tuple[int, str | None]]
305
- ] = {} # action -> [(stmt_idx, sid), ...]
306
-
307
- for idx, statement in enumerate(policy.statement):
308
- if statement.effect == "Allow":
309
- actions = statement.get_actions()
310
- # Filter out wildcards for privilege escalation detection
311
- filtered_actions = [a for a in actions if a != "*"]
312
-
313
- for action in filtered_actions:
314
- all_actions.add(action)
315
- if action not in statement_map:
316
- statement_map[action] = []
317
- statement_map[action].append((idx, statement.sid))
318
-
319
- # Get configuration for sensitive actions
320
- sub_check_config = config.config.get("sensitive_action_check", {})
321
- if not isinstance(sub_check_config, dict):
322
- return issues
323
-
324
- sensitive_actions_config = sub_check_config.get("sensitive_actions")
325
- sensitive_patterns_config = sub_check_config.get("sensitive_action_patterns")
326
-
327
- # Check for privilege escalation patterns using all_of logic
328
- # We need to check both exact actions and patterns
329
- policy_issues = []
330
-
331
- # Check sensitive_actions configuration
332
- if sensitive_actions_config:
333
- policy_issues.extend(
334
- check_policy_level_actions(
335
- list(all_actions),
336
- statement_map,
337
- sensitive_actions_config,
338
- config,
339
- "actions",
340
- self._get_sub_check_severity,
341
- )
342
- )
343
-
344
- # Check sensitive_action_patterns configuration
345
- if sensitive_patterns_config:
346
- policy_issues.extend(
347
- check_policy_level_actions(
348
- list(all_actions),
349
- statement_map,
350
- sensitive_patterns_config,
351
- config,
352
- "patterns",
353
- self._get_sub_check_severity,
354
- )
355
- )
356
-
357
- issues.extend(policy_issues)
358
- return issues
359
-
360
- def _is_sub_check_enabled(self, config: CheckConfig, sub_check_name: str) -> bool:
361
- """Check if a sub-check is enabled in the configuration."""
362
- if sub_check_name not in config.config:
363
- return True # Enabled by default
364
-
365
- sub_check_config = config.config.get(sub_check_name, {})
366
- if isinstance(sub_check_config, dict):
367
- return sub_check_config.get("enabled", True)
368
- return True
369
-
370
- def _get_sub_check_severity(
371
- self, config: CheckConfig, sub_check_name: str, default: str
372
- ) -> str:
373
- """Get severity for a sub-check."""
374
- if sub_check_name not in config.config:
375
- return default
376
-
377
- sub_check_config = config.config.get(sub_check_name, {})
378
- if isinstance(sub_check_config, dict):
379
- return sub_check_config.get("severity", default)
380
- return default
381
-
382
- def _add_wildcard_resource_issue(
383
- self,
384
- issues: list[ValidationIssue],
385
- config: CheckConfig,
386
- statement_sid: str | None,
387
- statement_idx: int,
388
- line_number: int | None,
389
- ) -> None:
390
- """Add a wildcard resource issue to the issues list.
391
-
392
- This is a helper method to avoid code duplication when adding
393
- wildcard resource warnings.
394
-
395
- Args:
396
- issues: List to append the issue to
397
- config: Check configuration
398
- statement_sid: Statement ID
399
- statement_idx: Statement index
400
- line_number: Line number in the policy file
401
- """
402
- severity = self._get_sub_check_severity(config, "wildcard_resource_check", "warning")
403
- sub_check_config = config.config.get("wildcard_resource_check", {})
404
-
405
- message = sub_check_config.get("message", "Statement applies to all resources (*)")
406
- suggestion_text = sub_check_config.get(
407
- "suggestion", "Consider limiting to specific resources"
408
- )
409
- example = sub_check_config.get("example", "")
410
-
411
- # Combine suggestion + example
412
- suggestion = f"{suggestion_text}\nExample:\n{example}" if example else suggestion_text
413
-
414
- issues.append(
415
- ValidationIssue(
416
- severity=severity,
417
- statement_sid=statement_sid,
418
- statement_index=statement_idx,
419
- issue_type="overly_permissive",
420
- message=message,
421
- suggestion=suggestion,
422
- line_number=line_number,
423
- )
424
- )
425
-
426
- def _get_allowed_service_wildcards(self, config: CheckConfig) -> set[str]:
427
- """
428
- Get list of services that are allowed to use service-level wildcards.
429
-
430
- This allows configuration like:
431
- service_wildcard_check:
432
- allowed_services:
433
- - "logs" # Allow "logs:*"
434
- - "cloudwatch" # Allow "cloudwatch:*"
435
-
436
- Returns empty set if no exceptions are configured.
437
- """
438
- sub_check_config = config.config.get("service_wildcard_check", {})
439
-
440
- if isinstance(sub_check_config, dict):
441
- allowed = sub_check_config.get("allowed_services", [])
442
- if allowed and isinstance(allowed, list):
443
- return set(allowed)
444
-
445
- return set()
446
-
447
- def _get_allowed_wildcards_for_resources(self, config: CheckConfig) -> frozenset[str]:
448
- """Get allowed_wildcards for resource check configuration.
449
-
450
- This checks for explicit allowed_wildcards configuration in wildcard_resource_check.
451
- If not configured, it falls back to the parent security_best_practices_check's allowed_wildcards.
452
-
453
- Args:
454
- config: The check configuration
455
-
456
- Returns:
457
- A frozenset of allowed wildcard patterns
458
- """
459
- sub_check_config = config.config.get("wildcard_resource_check", {})
460
- if isinstance(sub_check_config, dict) and "allowed_wildcards" in sub_check_config:
461
- # Explicitly configured in wildcard_resource_check (override)
462
- allowed_wildcards = sub_check_config.get("allowed_wildcards", [])
463
- if isinstance(allowed_wildcards, list):
464
- return frozenset(allowed_wildcards)
465
- elif isinstance(allowed_wildcards, set | frozenset):
466
- return frozenset(allowed_wildcards)
467
- return frozenset()
468
-
469
- # Fall back to parent security_best_practices_check's allowed_wildcards
470
- parent_allowed_wildcards = config.config.get("allowed_wildcards", [])
471
- if isinstance(parent_allowed_wildcards, list):
472
- return frozenset(parent_allowed_wildcards)
473
- elif isinstance(parent_allowed_wildcards, set | frozenset):
474
- return frozenset(parent_allowed_wildcards)
475
-
476
- # No configuration found, return empty set (flag all Resource: "*")
477
- return frozenset()
478
-
479
- async def _get_expanded_allowed_wildcards(
480
- self, config: CheckConfig, fetcher: AWSServiceFetcher
481
- ) -> frozenset[str]:
482
- """Get and expand allowed_wildcards configuration.
483
-
484
- This method retrieves wildcard patterns from the allowed_wildcards config
485
- and expands them using the AWS API to get all matching actual AWS actions.
486
-
487
- How it works:
488
- 1. Retrieves patterns from config (e.g., ["ec2:Describe*", "s3:List*"])
489
- 2. Expands each pattern using AWS API:
490
- - "ec2:Describe*" → ["ec2:DescribeInstances", "ec2:DescribeImages", ...]
491
- - "s3:List*" → ["s3:ListBucket", "s3:ListObjects", ...]
492
- 3. Returns a set of all expanded actions
493
-
494
- This allows you to:
495
- - Specify patterns like "ec2:Describe*" in config
496
- - Have the validator allow specific actions like "ec2:DescribeInstances" with Resource: "*"
497
- - Ensure only real AWS actions (validated via API) are allowed
498
-
499
- Example:
500
- Config: allowed_wildcards: ["ec2:Describe*"]
501
- Expands to: ["ec2:DescribeInstances", "ec2:DescribeImages", ...]
502
- Policy: "Action": ["ec2:DescribeInstances"], "Resource": "*"
503
- Result: ✅ Allowed (ec2:DescribeInstances is in expanded list)
504
-
505
- Args:
506
- config: The check configuration
507
- fetcher: AWS service fetcher for expanding wildcards via AWS API
508
-
509
- Returns:
510
- A frozenset of all expanded action names from the configured patterns
511
- """
512
- # Check wildcard_resource_check first for override
513
- sub_check_config = config.config.get("wildcard_resource_check", {})
514
- patterns_to_expand: list[str] = []
515
-
516
- if isinstance(sub_check_config, dict) and "allowed_wildcards" in sub_check_config:
517
- # Explicitly configured in wildcard_resource_check (override)
518
- patterns = sub_check_config.get("allowed_wildcards", [])
519
- if isinstance(patterns, list):
520
- patterns_to_expand = patterns
521
- else:
522
- # Fall back to parent security_best_practices_check's allowed_wildcards
523
- parent_patterns = config.config.get("allowed_wildcards", [])
524
- if isinstance(parent_patterns, list):
525
- patterns_to_expand = parent_patterns
526
-
527
- # If no patterns configured, return empty set
528
- if not patterns_to_expand:
529
- return frozenset()
530
-
531
- # Expand the wildcard patterns using the AWS API
532
- # This converts patterns like "ec2:Describe*" to actual AWS actions
533
- expanded_actions = await expand_wildcard_actions(patterns_to_expand, fetcher)
534
-
535
- return frozenset(expanded_actions)