runbooks 0.2.3__py3-none-any.whl → 0.6.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.
- conftest.py +26 -0
- jupyter-agent/.env.template +2 -0
- jupyter-agent/.gitattributes +35 -0
- jupyter-agent/README.md +16 -0
- jupyter-agent/app.py +256 -0
- jupyter-agent/cloudops-agent.png +0 -0
- jupyter-agent/ds-system-prompt.txt +154 -0
- jupyter-agent/jupyter-agent.png +0 -0
- jupyter-agent/llama3_template.jinja +123 -0
- jupyter-agent/requirements.txt +9 -0
- jupyter-agent/utils.py +409 -0
- runbooks/__init__.py +71 -3
- runbooks/__main__.py +13 -0
- runbooks/aws/ec2_describe_instances.py +1 -1
- runbooks/aws/ec2_run_instances.py +8 -2
- runbooks/aws/ec2_start_stop_instances.py +17 -4
- runbooks/aws/ec2_unused_volumes.py +5 -1
- runbooks/aws/s3_create_bucket.py +4 -2
- runbooks/aws/s3_list_objects.py +6 -1
- runbooks/aws/tagging_lambda_handler.py +13 -2
- runbooks/aws/tags.json +12 -0
- runbooks/base.py +353 -0
- runbooks/cfat/README.md +49 -0
- runbooks/cfat/__init__.py +74 -0
- runbooks/cfat/app.ts +644 -0
- runbooks/cfat/assessment/__init__.py +40 -0
- runbooks/cfat/assessment/asana-import.csv +39 -0
- runbooks/cfat/assessment/cfat-checks.csv +31 -0
- runbooks/cfat/assessment/cfat.txt +520 -0
- runbooks/cfat/assessment/collectors.py +200 -0
- runbooks/cfat/assessment/jira-import.csv +39 -0
- runbooks/cfat/assessment/runner.py +387 -0
- runbooks/cfat/assessment/validators.py +290 -0
- runbooks/cfat/cli.py +103 -0
- runbooks/cfat/docs/asana-import.csv +24 -0
- runbooks/cfat/docs/cfat-checks.csv +31 -0
- runbooks/cfat/docs/cfat.txt +335 -0
- runbooks/cfat/docs/checks-output.png +0 -0
- runbooks/cfat/docs/cloudshell-console-run.png +0 -0
- runbooks/cfat/docs/cloudshell-download.png +0 -0
- runbooks/cfat/docs/cloudshell-output.png +0 -0
- runbooks/cfat/docs/downloadfile.png +0 -0
- runbooks/cfat/docs/jira-import.csv +24 -0
- runbooks/cfat/docs/open-cloudshell.png +0 -0
- runbooks/cfat/docs/report-header.png +0 -0
- runbooks/cfat/models.py +1026 -0
- runbooks/cfat/package-lock.json +5116 -0
- runbooks/cfat/package.json +38 -0
- runbooks/cfat/report.py +496 -0
- runbooks/cfat/reporting/__init__.py +46 -0
- runbooks/cfat/reporting/exporters.py +337 -0
- runbooks/cfat/reporting/formatters.py +496 -0
- runbooks/cfat/reporting/templates.py +135 -0
- runbooks/cfat/run-assessment.sh +23 -0
- runbooks/cfat/runner.py +69 -0
- runbooks/cfat/src/actions/check-cloudtrail-existence.ts +43 -0
- runbooks/cfat/src/actions/check-config-existence.ts +37 -0
- runbooks/cfat/src/actions/check-control-tower.ts +37 -0
- runbooks/cfat/src/actions/check-ec2-existence.ts +46 -0
- runbooks/cfat/src/actions/check-iam-users.ts +50 -0
- runbooks/cfat/src/actions/check-legacy-cur.ts +30 -0
- runbooks/cfat/src/actions/check-org-cloudformation.ts +30 -0
- runbooks/cfat/src/actions/check-vpc-existence.ts +43 -0
- runbooks/cfat/src/actions/create-asanaimport.ts +14 -0
- runbooks/cfat/src/actions/create-backlog.ts +372 -0
- runbooks/cfat/src/actions/create-jiraimport.ts +15 -0
- runbooks/cfat/src/actions/create-report.ts +616 -0
- runbooks/cfat/src/actions/define-account-type.ts +51 -0
- runbooks/cfat/src/actions/get-enabled-org-policy-types.ts +40 -0
- runbooks/cfat/src/actions/get-enabled-org-services.ts +26 -0
- runbooks/cfat/src/actions/get-idc-info.ts +34 -0
- runbooks/cfat/src/actions/get-org-da-accounts.ts +34 -0
- runbooks/cfat/src/actions/get-org-details.ts +35 -0
- runbooks/cfat/src/actions/get-org-member-accounts.ts +44 -0
- runbooks/cfat/src/actions/get-org-ous.ts +35 -0
- runbooks/cfat/src/actions/get-regions.ts +22 -0
- runbooks/cfat/src/actions/zip-assessment.ts +27 -0
- runbooks/cfat/src/types/index.d.ts +147 -0
- runbooks/cfat/tests/__init__.py +141 -0
- runbooks/cfat/tests/test_cli.py +340 -0
- runbooks/cfat/tests/test_integration.py +290 -0
- runbooks/cfat/tests/test_models.py +505 -0
- runbooks/cfat/tests/test_reporting.py +354 -0
- runbooks/cfat/tsconfig.json +16 -0
- runbooks/cfat/webpack.config.cjs +27 -0
- runbooks/config.py +260 -0
- runbooks/finops/__init__.py +88 -0
- runbooks/finops/aws_client.py +245 -0
- runbooks/finops/cli.py +151 -0
- runbooks/finops/cost_processor.py +410 -0
- runbooks/finops/dashboard_runner.py +448 -0
- runbooks/finops/helpers.py +355 -0
- runbooks/finops/main.py +14 -0
- runbooks/finops/profile_processor.py +174 -0
- runbooks/finops/types.py +66 -0
- runbooks/finops/visualisations.py +80 -0
- runbooks/inventory/.gitignore +354 -0
- runbooks/inventory/ArgumentsClass.py +261 -0
- runbooks/inventory/Inventory_Modules.py +6130 -0
- runbooks/inventory/LandingZone/delete_lz.py +1075 -0
- runbooks/inventory/README.md +1320 -0
- runbooks/inventory/__init__.py +62 -0
- runbooks/inventory/account_class.py +532 -0
- runbooks/inventory/all_my_instances_wrapper.py +123 -0
- runbooks/inventory/aws_decorators.py +201 -0
- runbooks/inventory/cfn_move_stack_instances.py +1526 -0
- runbooks/inventory/check_cloudtrail_compliance.py +614 -0
- runbooks/inventory/check_controltower_readiness.py +1107 -0
- runbooks/inventory/check_landingzone_readiness.py +711 -0
- runbooks/inventory/cloudtrail.md +727 -0
- runbooks/inventory/collectors/__init__.py +20 -0
- runbooks/inventory/collectors/aws_compute.py +518 -0
- runbooks/inventory/collectors/aws_networking.py +275 -0
- runbooks/inventory/collectors/base.py +222 -0
- runbooks/inventory/core/__init__.py +19 -0
- runbooks/inventory/core/collector.py +303 -0
- runbooks/inventory/core/formatter.py +296 -0
- runbooks/inventory/delete_s3_buckets_objects.py +169 -0
- runbooks/inventory/discovery.md +81 -0
- runbooks/inventory/draw_org_structure.py +748 -0
- runbooks/inventory/ec2_vpc_utils.py +341 -0
- runbooks/inventory/find_cfn_drift_detection.py +272 -0
- runbooks/inventory/find_cfn_orphaned_stacks.py +719 -0
- runbooks/inventory/find_cfn_stackset_drift.py +733 -0
- runbooks/inventory/find_ec2_security_groups.py +669 -0
- runbooks/inventory/find_landingzone_versions.py +201 -0
- runbooks/inventory/find_vpc_flow_logs.py +1221 -0
- runbooks/inventory/inventory.sh +659 -0
- runbooks/inventory/list_cfn_stacks.py +558 -0
- runbooks/inventory/list_cfn_stackset_operation_results.py +252 -0
- runbooks/inventory/list_cfn_stackset_operations.py +734 -0
- runbooks/inventory/list_cfn_stacksets.py +453 -0
- runbooks/inventory/list_config_recorders_delivery_channels.py +681 -0
- runbooks/inventory/list_ds_directories.py +354 -0
- runbooks/inventory/list_ec2_availability_zones.py +286 -0
- runbooks/inventory/list_ec2_ebs_volumes.py +244 -0
- runbooks/inventory/list_ec2_instances.py +425 -0
- runbooks/inventory/list_ecs_clusters_and_tasks.py +562 -0
- runbooks/inventory/list_elbs_load_balancers.py +411 -0
- runbooks/inventory/list_enis_network_interfaces.py +526 -0
- runbooks/inventory/list_guardduty_detectors.py +568 -0
- runbooks/inventory/list_iam_policies.py +404 -0
- runbooks/inventory/list_iam_roles.py +518 -0
- runbooks/inventory/list_iam_saml_providers.py +359 -0
- runbooks/inventory/list_lambda_functions.py +882 -0
- runbooks/inventory/list_org_accounts.py +446 -0
- runbooks/inventory/list_org_accounts_users.py +354 -0
- runbooks/inventory/list_rds_db_instances.py +406 -0
- runbooks/inventory/list_route53_hosted_zones.py +318 -0
- runbooks/inventory/list_servicecatalog_provisioned_products.py +575 -0
- runbooks/inventory/list_sns_topics.py +360 -0
- runbooks/inventory/list_ssm_parameters.py +402 -0
- runbooks/inventory/list_vpc_subnets.py +433 -0
- runbooks/inventory/list_vpcs.py +422 -0
- runbooks/inventory/lockdown_cfn_stackset_role.py +224 -0
- runbooks/inventory/models/__init__.py +24 -0
- runbooks/inventory/models/account.py +192 -0
- runbooks/inventory/models/inventory.py +309 -0
- runbooks/inventory/models/resource.py +247 -0
- runbooks/inventory/recover_cfn_stack_ids.py +205 -0
- runbooks/inventory/requirements.txt +12 -0
- runbooks/inventory/run_on_multi_accounts.py +211 -0
- runbooks/inventory/tests/common_test_data.py +3661 -0
- runbooks/inventory/tests/common_test_functions.py +204 -0
- runbooks/inventory/tests/script_test_data.py +0 -0
- runbooks/inventory/tests/setup.py +24 -0
- runbooks/inventory/tests/src.py +18 -0
- runbooks/inventory/tests/test_cfn_describe_stacks.py +208 -0
- runbooks/inventory/tests/test_ec2_describe_instances.py +162 -0
- runbooks/inventory/tests/test_inventory_modules.py +55 -0
- runbooks/inventory/tests/test_lambda_list_functions.py +86 -0
- runbooks/inventory/tests/test_moto_integration_example.py +273 -0
- runbooks/inventory/tests/test_org_list_accounts.py +49 -0
- runbooks/inventory/update_aws_actions.py +173 -0
- runbooks/inventory/update_cfn_stacksets.py +1215 -0
- runbooks/inventory/update_cloudwatch_logs_retention_policy.py +294 -0
- runbooks/inventory/update_iam_roles_cross_accounts.py +478 -0
- runbooks/inventory/update_s3_public_access_block.py +539 -0
- runbooks/inventory/utils/__init__.py +23 -0
- runbooks/inventory/utils/aws_helpers.py +510 -0
- runbooks/inventory/utils/threading_utils.py +493 -0
- runbooks/inventory/utils/validation.py +682 -0
- runbooks/inventory/verify_ec2_security_groups.py +1430 -0
- runbooks/main.py +785 -0
- runbooks/organizations/__init__.py +12 -0
- runbooks/organizations/manager.py +374 -0
- runbooks/security_baseline/README.md +324 -0
- runbooks/security_baseline/checklist/alternate_contacts.py +8 -1
- runbooks/security_baseline/checklist/bucket_public_access.py +4 -1
- runbooks/security_baseline/checklist/cloudwatch_alarm_configuration.py +9 -2
- runbooks/security_baseline/checklist/guardduty_enabled.py +9 -2
- runbooks/security_baseline/checklist/multi_region_instance_usage.py +5 -1
- runbooks/security_baseline/checklist/root_access_key.py +6 -1
- runbooks/security_baseline/config-origin.json +1 -1
- runbooks/security_baseline/config.json +1 -1
- runbooks/security_baseline/permission.json +1 -1
- runbooks/security_baseline/report_generator.py +10 -2
- runbooks/security_baseline/report_template_en.html +8 -8
- runbooks/security_baseline/report_template_jp.html +8 -8
- runbooks/security_baseline/report_template_kr.html +13 -13
- runbooks/security_baseline/report_template_vn.html +8 -8
- runbooks/security_baseline/requirements.txt +7 -0
- runbooks/security_baseline/run_script.py +8 -2
- runbooks/security_baseline/security_baseline_tester.py +10 -2
- runbooks/security_baseline/utils/common.py +5 -1
- runbooks/utils/__init__.py +204 -0
- runbooks-0.6.1.dist-info/METADATA +373 -0
- runbooks-0.6.1.dist-info/RECORD +237 -0
- {runbooks-0.2.3.dist-info → runbooks-0.6.1.dist-info}/WHEEL +1 -1
- runbooks-0.6.1.dist-info/entry_points.txt +7 -0
- runbooks-0.6.1.dist-info/licenses/LICENSE +201 -0
- runbooks-0.6.1.dist-info/top_level.txt +3 -0
- runbooks/python101/calculator.py +0 -34
- runbooks/python101/config.py +0 -1
- runbooks/python101/exceptions.py +0 -16
- runbooks/python101/file_manager.py +0 -218
- runbooks/python101/toolkit.py +0 -153
- runbooks-0.2.3.dist-info/METADATA +0 -435
- runbooks-0.2.3.dist-info/RECORD +0 -61
- runbooks-0.2.3.dist-info/entry_points.txt +0 -3
- runbooks-0.2.3.dist-info/top_level.txt +0 -1
@@ -0,0 +1,404 @@
|
|
1
|
+
#!/usr/bin/env python3
|
2
|
+
|
3
|
+
"""
|
4
|
+
AWS IAM Policies Discovery and Action Analysis Script
|
5
|
+
|
6
|
+
This script provides comprehensive discovery and analysis capabilities for AWS Identity
|
7
|
+
and Access Management (IAM) policies across multiple accounts and regions. It's designed
|
8
|
+
for enterprise security and compliance teams who need visibility into policy distribution,
|
9
|
+
permission analysis, and action-specific security assessment across large-scale AWS deployments.
|
10
|
+
|
11
|
+
Key Features:
|
12
|
+
- Multi-account IAM policy discovery using assume role capabilities
|
13
|
+
- Policy action analysis for permission tracking and security assessment
|
14
|
+
- Customer-managed policy filtering for organizational policy governance
|
15
|
+
- Fragment-based search for targeted policy discovery and analysis
|
16
|
+
- Enterprise reporting with CSV export and structured output
|
17
|
+
- Profile-based authentication with support for federated access
|
18
|
+
|
19
|
+
Enterprise Use Cases:
|
20
|
+
- Security policy audit and compliance reporting across organizations
|
21
|
+
- Permission analysis for least privilege access implementation
|
22
|
+
- Policy governance and standardization across organizational boundaries
|
23
|
+
- Security incident response with policy and permission analysis
|
24
|
+
- Compliance reporting for access control and authorization standards
|
25
|
+
- Multi-account IAM governance and policy lifecycle management
|
26
|
+
- Risk assessment through policy action enumeration and analysis
|
27
|
+
|
28
|
+
IAM Policy Analysis Features:
|
29
|
+
- Comprehensive policy enumeration with metadata extraction
|
30
|
+
- Policy action discovery for permission tracking and analysis
|
31
|
+
- Customer-managed policy identification for organizational governance
|
32
|
+
- Cross-account policy consistency analysis and standardization
|
33
|
+
- Policy fragment search for targeted security assessment
|
34
|
+
- Permission correlation across organizational boundaries
|
35
|
+
|
36
|
+
Security Considerations:
|
37
|
+
- Uses IAM assume role capabilities for cross-account policy access
|
38
|
+
- Implements proper error handling for authorization failures
|
39
|
+
- Supports read-only operations with no policy modification capabilities
|
40
|
+
- Respects IAM service permissions and regional access constraints
|
41
|
+
- Provides comprehensive audit trail through detailed logging
|
42
|
+
- Sensitive permission information handling with appropriate access controls
|
43
|
+
|
44
|
+
Policy Governance Features:
|
45
|
+
- Customer-managed policy filtering for organizational policy oversight
|
46
|
+
- Policy action enumeration for security and compliance analysis
|
47
|
+
- Cross-account policy visibility for governance and standardization
|
48
|
+
- Fragment-based search for targeted policy discovery and assessment
|
49
|
+
- Policy lifecycle tracking for governance and compliance management
|
50
|
+
|
51
|
+
Performance Considerations:
|
52
|
+
- Multi-threaded processing for concurrent IAM API operations
|
53
|
+
- Progress tracking for operational visibility during large-scale operations
|
54
|
+
- Efficient credential management for cross-account policy access
|
55
|
+
- Memory-optimized data structures for large policy inventories
|
56
|
+
- Queue-based worker architecture for scalable policy discovery
|
57
|
+
|
58
|
+
Threading Architecture:
|
59
|
+
- Worker thread pool with configurable concurrency for policy action analysis
|
60
|
+
- Queue-based task distribution for efficient policy processing
|
61
|
+
- Thread-safe error handling and progress tracking
|
62
|
+
- Graceful degradation for account access failures
|
63
|
+
|
64
|
+
Dependencies:
|
65
|
+
- boto3/botocore for AWS IAM API interactions
|
66
|
+
- Inventory_Modules for common utility functions and credential management
|
67
|
+
- ArgumentsClass for standardized CLI argument parsing
|
68
|
+
- threading and queue for concurrent processing architecture
|
69
|
+
- colorama for enhanced output formatting
|
70
|
+
|
71
|
+
Compliance and Audit Features:
|
72
|
+
- Comprehensive policy discovery for security auditing
|
73
|
+
- Action-specific permission analysis for compliance validation
|
74
|
+
- Cross-account policy governance for organizational security
|
75
|
+
- Customer-managed policy tracking for organizational oversight
|
76
|
+
- Fragment-based search for targeted compliance assessment
|
77
|
+
|
78
|
+
Future Enhancements:
|
79
|
+
- Policy risk assessment with privilege escalation detection
|
80
|
+
- Automated policy compliance checking against security standards
|
81
|
+
- Integration with AWS Config for policy configuration drift detection
|
82
|
+
- Policy optimization recommendations for least privilege implementation
|
83
|
+
|
84
|
+
Author: AWS CloudOps Team
|
85
|
+
Version: 2023.12.12
|
86
|
+
"""
|
87
|
+
|
88
|
+
# import boto3
|
89
|
+
import logging
|
90
|
+
import sys
|
91
|
+
from queue import Queue
|
92
|
+
from threading import Thread
|
93
|
+
from time import time
|
94
|
+
|
95
|
+
from ArgumentsClass import CommonArguments
|
96
|
+
from botocore.exceptions import ClientError
|
97
|
+
from colorama import Fore, init
|
98
|
+
from Inventory_Modules import display_results, find_account_policies2, find_policy_action2, get_all_credentials
|
99
|
+
|
100
|
+
init()
|
101
|
+
__version__ = "2023.12.12"
|
102
|
+
ERASE_LINE = "\x1b[2K"
|
103
|
+
begin_time = time()
|
104
|
+
|
105
|
+
|
106
|
+
##################
|
107
|
+
def parse_args(args):
|
108
|
+
"""
|
109
|
+
Parse command line arguments for AWS IAM policy discovery and action analysis operations.
|
110
|
+
|
111
|
+
Configures comprehensive argument parsing for multi-account, multi-region IAM policy
|
112
|
+
inventory operations. Supports enterprise security and compliance management with profile
|
113
|
+
management, region targeting, organizational access controls, fragment-based search,
|
114
|
+
and policy action analysis for permission tracking and security assessment.
|
115
|
+
|
116
|
+
Args:
|
117
|
+
args (list): Command line arguments from sys.argv[1:]
|
118
|
+
|
119
|
+
Returns:
|
120
|
+
argparse.Namespace: Parsed arguments containing:
|
121
|
+
- Profiles: List of AWS profiles to process
|
122
|
+
- Regions: Target regions for IAM policy discovery
|
123
|
+
- SkipProfiles/SkipAccounts: Exclusion filters
|
124
|
+
- RootOnly: Limit to organization root accounts
|
125
|
+
- Fragments: Policy name fragments for targeted search
|
126
|
+
- Filename: Output file for CSV export
|
127
|
+
- Time: Enable performance timing metrics
|
128
|
+
- loglevel: Logging verbosity configuration
|
129
|
+
- paction: Specific policy actions to analyze
|
130
|
+
- pcmp: Filter for customer-managed policies only
|
131
|
+
- Exact: Enable exact fragment matching
|
132
|
+
|
133
|
+
Configuration Options:
|
134
|
+
- Multi-region scanning with region filters for targeted policy analysis
|
135
|
+
- Multi-profile support for federated access across security infrastructure
|
136
|
+
- Extended arguments for advanced filtering and account selection
|
137
|
+
- Root-only mode for organization-level policy inventory
|
138
|
+
- Fragment search for finding specific policies by name patterns
|
139
|
+
- File output for integration with security management tools
|
140
|
+
- Timing metrics for performance optimization and monitoring
|
141
|
+
- Verbose logging for debugging and security audit
|
142
|
+
|
143
|
+
IAM-Specific Features:
|
144
|
+
- Policy action analysis for permission tracking and security assessment
|
145
|
+
- Customer-managed policy filtering for organizational governance
|
146
|
+
- Fragment-based search for targeted security policy discovery
|
147
|
+
- Support for compliance analysis and policy governance workflows
|
148
|
+
|
149
|
+
Security Analysis Options:
|
150
|
+
- Specific action enumeration for permission analysis
|
151
|
+
- Customer-managed policy focus for organizational security oversight
|
152
|
+
- Cross-account policy visibility for governance and standardization
|
153
|
+
- Exact matching for precise policy identification and analysis
|
154
|
+
"""
|
155
|
+
parser = CommonArguments()
|
156
|
+
parser.my_parser.description = "Discover and analyze AWS IAM policies and actions across multiple accounts and regions for enterprise security governance and compliance management."
|
157
|
+
parser.multiprofile()
|
158
|
+
parser.multiregion()
|
159
|
+
parser.extendedargs()
|
160
|
+
parser.rootOnly()
|
161
|
+
parser.fragment()
|
162
|
+
parser.timing()
|
163
|
+
parser.save_to_file()
|
164
|
+
parser.verbosity()
|
165
|
+
parser.version(__version__)
|
166
|
+
parser.my_parser.add_argument(
|
167
|
+
"--action",
|
168
|
+
dest="paction",
|
169
|
+
nargs="*",
|
170
|
+
metavar="AWS Action",
|
171
|
+
default=None,
|
172
|
+
help="Specific AWS actions to search for within policy documents - supports multiple actions for comprehensive permission analysis",
|
173
|
+
)
|
174
|
+
parser.my_parser.add_argument(
|
175
|
+
"--cmp",
|
176
|
+
"--customer_managed_policies",
|
177
|
+
dest="pcmp",
|
178
|
+
action="store_true",
|
179
|
+
help="Filter results to show only customer-managed policies for organizational governance and policy oversight",
|
180
|
+
)
|
181
|
+
return parser.my_parser.parse_args(args)
|
182
|
+
|
183
|
+
|
184
|
+
def check_accounts_for_policies(CredentialList, fRegionList=None, fActions=None, fFragments=None):
|
185
|
+
"""
|
186
|
+
Discover and analyze AWS IAM policies across multiple accounts with optional action analysis.
|
187
|
+
|
188
|
+
Performs comprehensive IAM policy discovery using multi-threaded processing to efficiently
|
189
|
+
inventory policies across enterprise AWS environments. Supports fragment-based filtering
|
190
|
+
for targeted discovery and action analysis for permission tracking and security assessment.
|
191
|
+
|
192
|
+
Args:
|
193
|
+
CredentialList (list): List of credential dictionaries for cross-account access containing:
|
194
|
+
- AccountId: AWS account number
|
195
|
+
- Region: Target AWS region
|
196
|
+
- Success: Boolean indicating credential validity
|
197
|
+
- MgmtAccount: Management account identifier
|
198
|
+
- ParentProfile: Source AWS profile
|
199
|
+
fRegionList (list, optional): Target regions for policy discovery (defaults to us-east-1)
|
200
|
+
fActions (list, optional): Specific AWS actions to search for within policy documents
|
201
|
+
fFragments (list, optional): Policy name fragments for targeted search and filtering
|
202
|
+
|
203
|
+
Returns:
|
204
|
+
list: Comprehensive list of policy dictionaries containing:
|
205
|
+
- MgmtAccount: Management account identifier for organizational hierarchy
|
206
|
+
- AccountNumber: AWS account containing the policy
|
207
|
+
- Region: AWS region where policy is managed
|
208
|
+
- PolicyName: IAM policy name identifier
|
209
|
+
- PolicyArn: Unique policy Amazon Resource Name
|
210
|
+
- Action: Specific actions found (if action analysis enabled)
|
211
|
+
- Document: Policy document content for analysis
|
212
|
+
|
213
|
+
Threading Architecture:
|
214
|
+
- Worker thread pool with configurable concurrency for policy action analysis
|
215
|
+
- Queue-based task distribution for efficient policy processing
|
216
|
+
- Thread-safe error handling and progress tracking
|
217
|
+
- Graceful degradation for account access failures and authorization issues
|
218
|
+
|
219
|
+
Enterprise Features:
|
220
|
+
- Cross-account policy discovery with assume role capabilities
|
221
|
+
- Fragment-based search for targeted policy identification
|
222
|
+
- Action analysis for permission tracking and security assessment
|
223
|
+
- Comprehensive error handling for authorization and throttling scenarios
|
224
|
+
|
225
|
+
Security Analysis:
|
226
|
+
- Policy action enumeration for permission analysis
|
227
|
+
- Customer-managed policy filtering for organizational governance
|
228
|
+
- Cross-account policy visibility for security governance
|
229
|
+
- Fragment-based search for targeted compliance assessment
|
230
|
+
|
231
|
+
Error Handling:
|
232
|
+
- Authorization failure detection with appropriate logging
|
233
|
+
- AWS API throttling management with graceful degradation
|
234
|
+
- Thread-safe error reporting and progress updates
|
235
|
+
- Graceful handling of missing policies and empty responses
|
236
|
+
|
237
|
+
Performance Considerations:
|
238
|
+
- Dynamic thread pool sizing based on policy count and credential set
|
239
|
+
- Efficient memory management for large policy inventories
|
240
|
+
- Progress tracking for operational visibility during discovery
|
241
|
+
- Policy metadata extraction for enterprise security management
|
242
|
+
"""
|
243
|
+
|
244
|
+
# Worker thread class for concurrent policy action analysis
|
245
|
+
class FindActions(Thread):
|
246
|
+
def __init__(self, queue):
|
247
|
+
Thread.__init__(self)
|
248
|
+
self.queue = queue
|
249
|
+
|
250
|
+
def run(self):
|
251
|
+
while True:
|
252
|
+
# Get the work from the queue and expand the tuple
|
253
|
+
c_account_credentials, c_policy, c_action, c_PlacesToLook, c_PlaceCount = self.queue.get()
|
254
|
+
logging.info(f"De-queued info for account {c_account_credentials['AccountId']}")
|
255
|
+
try:
|
256
|
+
logging.info(f"Attempting to connect to {c_account_credentials['AccountId']}")
|
257
|
+
|
258
|
+
# Analyze specific policy for the requested action using inventory module
|
259
|
+
policy_actions = find_policy_action2(c_account_credentials, c_policy, c_action)
|
260
|
+
logging.info(
|
261
|
+
f"Successfully connected to account {c_account_credentials['AccountId']} for policy {c_policy['PolicyName']}"
|
262
|
+
)
|
263
|
+
|
264
|
+
# Aggregate discovered policy actions for enterprise security analysis
|
265
|
+
if len(policy_actions) > 0:
|
266
|
+
AllPolicies.extend(policy_actions)
|
267
|
+
|
268
|
+
except KeyError as my_Error:
|
269
|
+
# Handle cases where expected keys are missing from IAM API responses
|
270
|
+
logging.error(f"Account Access failed - trying to access {c_account_credentials['AccountId']}")
|
271
|
+
logging.info(f"Actual Error: {my_Error}")
|
272
|
+
pass
|
273
|
+
except AttributeError as my_Error:
|
274
|
+
# Handle cases where profile configuration is incorrect
|
275
|
+
logging.error(f"Error: Likely that one of the supplied profiles {pProfiles} was wrong")
|
276
|
+
logging.warning(my_Error)
|
277
|
+
continue
|
278
|
+
finally:
|
279
|
+
# Provide progress tracking for operational visibility and ensure queue management
|
280
|
+
print(
|
281
|
+
f"{ERASE_LINE}Finished finding policy actions in account {c_account_credentials['AccountId']} - {c_PlaceCount} / {c_PlacesToLook}",
|
282
|
+
end="\r",
|
283
|
+
)
|
284
|
+
self.queue.task_done()
|
285
|
+
|
286
|
+
if fRegionList is None:
|
287
|
+
fRegionList = ["us-east-1"]
|
288
|
+
if fFragments is None:
|
289
|
+
fFragments = []
|
290
|
+
checkqueue = Queue()
|
291
|
+
|
292
|
+
AllPolicies = []
|
293
|
+
AccountCount = 0
|
294
|
+
Policies = []
|
295
|
+
PolicyCount = 0
|
296
|
+
|
297
|
+
print()
|
298
|
+
for credential in CredentialList:
|
299
|
+
try:
|
300
|
+
logging.info(f"Connecting to account {credential['AccountId']}")
|
301
|
+
Policies = find_account_policies2(credential, fRegionList[0], fFragments, pExact, pCMP)
|
302
|
+
AccountCount += 1
|
303
|
+
if fActions is None:
|
304
|
+
PlacesToLook = len(Policies)
|
305
|
+
else:
|
306
|
+
PlacesToLook = len(Policies) * len(fActions)
|
307
|
+
print(
|
308
|
+
f"{ERASE_LINE}Found {PlacesToLook} matching policies in account {credential['AccountId']} ({AccountCount}/{len(CredentialList)})",
|
309
|
+
end="\r",
|
310
|
+
)
|
311
|
+
# print(f"{ERASE_LINE}Queuing account {credential['AccountId']} in region {region}", end='\r')
|
312
|
+
if fActions is None:
|
313
|
+
AllPolicies.extend(Policies)
|
314
|
+
else:
|
315
|
+
for policy in Policies:
|
316
|
+
PolicyCount += 1
|
317
|
+
for action in fActions:
|
318
|
+
checkqueue.put((credential, policy, action, PlacesToLook, PolicyCount))
|
319
|
+
except ClientError as my_Error:
|
320
|
+
if "AuthFailure" in str(my_Error):
|
321
|
+
logging.error(f"Authorization Failure accessing account {credential['AccountId']}")
|
322
|
+
pass
|
323
|
+
|
324
|
+
# WorkerThreads = min(len(Policies) * len(fAction), 250)
|
325
|
+
WorkerThreads = min(round(len(AllPolicies) / len(CredentialList)), 200)
|
326
|
+
|
327
|
+
for x in range(WorkerThreads):
|
328
|
+
worker = FindActions(checkqueue)
|
329
|
+
# Setting daemon to True will let the main thread exit even though the workers are blocking
|
330
|
+
worker.daemon = True
|
331
|
+
worker.start()
|
332
|
+
|
333
|
+
checkqueue.join()
|
334
|
+
return AllPolicies
|
335
|
+
|
336
|
+
|
337
|
+
##################
|
338
|
+
|
339
|
+
if __name__ == "__main__":
|
340
|
+
args = parse_args(sys.argv[1:])
|
341
|
+
|
342
|
+
pProfiles = args.Profiles
|
343
|
+
pSkipAccounts = args.SkipAccounts
|
344
|
+
pSkipProfiles = args.SkipProfiles
|
345
|
+
pAccounts = args.Accounts
|
346
|
+
pFragments = args.Fragments
|
347
|
+
pRootOnly = args.RootOnly
|
348
|
+
pActions = args.paction
|
349
|
+
pCMP = args.pcmp
|
350
|
+
pExact = args.Exact
|
351
|
+
pTiming = args.Time
|
352
|
+
pFilename = args.Filename
|
353
|
+
verbose = args.loglevel
|
354
|
+
# Setup logging levels
|
355
|
+
logging.basicConfig(level=verbose, format="[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
|
356
|
+
logging.getLogger("boto3").setLevel(logging.CRITICAL)
|
357
|
+
logging.getLogger("botocore").setLevel(logging.CRITICAL)
|
358
|
+
logging.getLogger("s3transfer").setLevel(logging.CRITICAL)
|
359
|
+
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
|
360
|
+
|
361
|
+
logging.info(f"Profiles: {pProfiles}")
|
362
|
+
|
363
|
+
print()
|
364
|
+
print(f"Checking for matching Policies... ")
|
365
|
+
print()
|
366
|
+
|
367
|
+
PoliciesFound = []
|
368
|
+
AllChildAccounts = []
|
369
|
+
# TODO: Will have to be changed to support single region-only accounts, but that's a ways off yet.
|
370
|
+
pRegionList = RegionList = ["us-east-1"]
|
371
|
+
|
372
|
+
# Get credentials for all Child Accounts
|
373
|
+
AllCredentials = get_all_credentials(
|
374
|
+
pProfiles, pTiming, pSkipProfiles, pSkipAccounts, pRootOnly, pAccounts, pRegionList
|
375
|
+
)
|
376
|
+
# Find all the policies
|
377
|
+
PoliciesFound.extend(check_accounts_for_policies(AllCredentials, RegionList, pActions, pFragments))
|
378
|
+
# Display the information we've found this far
|
379
|
+
sorted_policies = sorted(
|
380
|
+
PoliciesFound, key=lambda x: (x["MgmtAccount"], x["AccountNumber"], x["Region"], x["PolicyName"])
|
381
|
+
)
|
382
|
+
|
383
|
+
display_dict = {
|
384
|
+
"MgmtAccount": {"DisplayOrder": 1, "Heading": "Mgmt Acct"},
|
385
|
+
"AccountNumber": {"DisplayOrder": 2, "Heading": "Acct Number"},
|
386
|
+
"Region": {"DisplayOrder": 3, "Heading": "Region"},
|
387
|
+
"PolicyName": {"DisplayOrder": 4, "Heading": "Policy Name"},
|
388
|
+
"Action": {"DisplayOrder": 5, "Heading": "Action"},
|
389
|
+
}
|
390
|
+
|
391
|
+
display_results(sorted_policies, display_dict, pActions, pFilename)
|
392
|
+
|
393
|
+
if pTiming:
|
394
|
+
print(ERASE_LINE)
|
395
|
+
print(f"{Fore.GREEN}This script took {time() - begin_time:.2f} seconds{Fore.RESET}")
|
396
|
+
print(f"These accounts were skipped - as requested: {pSkipAccounts}") if pSkipAccounts is not None else print()
|
397
|
+
print()
|
398
|
+
print(
|
399
|
+
f"Found {len(PoliciesFound)} policies across {len(AllCredentials)} accounts across {len(RegionList)} regions\n"
|
400
|
+
f" that matched the fragment{'s' if len(pFragments) > 1 else ''} that you specified: {pFragments}"
|
401
|
+
)
|
402
|
+
print()
|
403
|
+
print("Thank you for using this script")
|
404
|
+
print()
|