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.
Files changed (221) hide show
  1. conftest.py +26 -0
  2. jupyter-agent/.env.template +2 -0
  3. jupyter-agent/.gitattributes +35 -0
  4. jupyter-agent/README.md +16 -0
  5. jupyter-agent/app.py +256 -0
  6. jupyter-agent/cloudops-agent.png +0 -0
  7. jupyter-agent/ds-system-prompt.txt +154 -0
  8. jupyter-agent/jupyter-agent.png +0 -0
  9. jupyter-agent/llama3_template.jinja +123 -0
  10. jupyter-agent/requirements.txt +9 -0
  11. jupyter-agent/utils.py +409 -0
  12. runbooks/__init__.py +71 -3
  13. runbooks/__main__.py +13 -0
  14. runbooks/aws/ec2_describe_instances.py +1 -1
  15. runbooks/aws/ec2_run_instances.py +8 -2
  16. runbooks/aws/ec2_start_stop_instances.py +17 -4
  17. runbooks/aws/ec2_unused_volumes.py +5 -1
  18. runbooks/aws/s3_create_bucket.py +4 -2
  19. runbooks/aws/s3_list_objects.py +6 -1
  20. runbooks/aws/tagging_lambda_handler.py +13 -2
  21. runbooks/aws/tags.json +12 -0
  22. runbooks/base.py +353 -0
  23. runbooks/cfat/README.md +49 -0
  24. runbooks/cfat/__init__.py +74 -0
  25. runbooks/cfat/app.ts +644 -0
  26. runbooks/cfat/assessment/__init__.py +40 -0
  27. runbooks/cfat/assessment/asana-import.csv +39 -0
  28. runbooks/cfat/assessment/cfat-checks.csv +31 -0
  29. runbooks/cfat/assessment/cfat.txt +520 -0
  30. runbooks/cfat/assessment/collectors.py +200 -0
  31. runbooks/cfat/assessment/jira-import.csv +39 -0
  32. runbooks/cfat/assessment/runner.py +387 -0
  33. runbooks/cfat/assessment/validators.py +290 -0
  34. runbooks/cfat/cli.py +103 -0
  35. runbooks/cfat/docs/asana-import.csv +24 -0
  36. runbooks/cfat/docs/cfat-checks.csv +31 -0
  37. runbooks/cfat/docs/cfat.txt +335 -0
  38. runbooks/cfat/docs/checks-output.png +0 -0
  39. runbooks/cfat/docs/cloudshell-console-run.png +0 -0
  40. runbooks/cfat/docs/cloudshell-download.png +0 -0
  41. runbooks/cfat/docs/cloudshell-output.png +0 -0
  42. runbooks/cfat/docs/downloadfile.png +0 -0
  43. runbooks/cfat/docs/jira-import.csv +24 -0
  44. runbooks/cfat/docs/open-cloudshell.png +0 -0
  45. runbooks/cfat/docs/report-header.png +0 -0
  46. runbooks/cfat/models.py +1026 -0
  47. runbooks/cfat/package-lock.json +5116 -0
  48. runbooks/cfat/package.json +38 -0
  49. runbooks/cfat/report.py +496 -0
  50. runbooks/cfat/reporting/__init__.py +46 -0
  51. runbooks/cfat/reporting/exporters.py +337 -0
  52. runbooks/cfat/reporting/formatters.py +496 -0
  53. runbooks/cfat/reporting/templates.py +135 -0
  54. runbooks/cfat/run-assessment.sh +23 -0
  55. runbooks/cfat/runner.py +69 -0
  56. runbooks/cfat/src/actions/check-cloudtrail-existence.ts +43 -0
  57. runbooks/cfat/src/actions/check-config-existence.ts +37 -0
  58. runbooks/cfat/src/actions/check-control-tower.ts +37 -0
  59. runbooks/cfat/src/actions/check-ec2-existence.ts +46 -0
  60. runbooks/cfat/src/actions/check-iam-users.ts +50 -0
  61. runbooks/cfat/src/actions/check-legacy-cur.ts +30 -0
  62. runbooks/cfat/src/actions/check-org-cloudformation.ts +30 -0
  63. runbooks/cfat/src/actions/check-vpc-existence.ts +43 -0
  64. runbooks/cfat/src/actions/create-asanaimport.ts +14 -0
  65. runbooks/cfat/src/actions/create-backlog.ts +372 -0
  66. runbooks/cfat/src/actions/create-jiraimport.ts +15 -0
  67. runbooks/cfat/src/actions/create-report.ts +616 -0
  68. runbooks/cfat/src/actions/define-account-type.ts +51 -0
  69. runbooks/cfat/src/actions/get-enabled-org-policy-types.ts +40 -0
  70. runbooks/cfat/src/actions/get-enabled-org-services.ts +26 -0
  71. runbooks/cfat/src/actions/get-idc-info.ts +34 -0
  72. runbooks/cfat/src/actions/get-org-da-accounts.ts +34 -0
  73. runbooks/cfat/src/actions/get-org-details.ts +35 -0
  74. runbooks/cfat/src/actions/get-org-member-accounts.ts +44 -0
  75. runbooks/cfat/src/actions/get-org-ous.ts +35 -0
  76. runbooks/cfat/src/actions/get-regions.ts +22 -0
  77. runbooks/cfat/src/actions/zip-assessment.ts +27 -0
  78. runbooks/cfat/src/types/index.d.ts +147 -0
  79. runbooks/cfat/tests/__init__.py +141 -0
  80. runbooks/cfat/tests/test_cli.py +340 -0
  81. runbooks/cfat/tests/test_integration.py +290 -0
  82. runbooks/cfat/tests/test_models.py +505 -0
  83. runbooks/cfat/tests/test_reporting.py +354 -0
  84. runbooks/cfat/tsconfig.json +16 -0
  85. runbooks/cfat/webpack.config.cjs +27 -0
  86. runbooks/config.py +260 -0
  87. runbooks/finops/__init__.py +88 -0
  88. runbooks/finops/aws_client.py +245 -0
  89. runbooks/finops/cli.py +151 -0
  90. runbooks/finops/cost_processor.py +410 -0
  91. runbooks/finops/dashboard_runner.py +448 -0
  92. runbooks/finops/helpers.py +355 -0
  93. runbooks/finops/main.py +14 -0
  94. runbooks/finops/profile_processor.py +174 -0
  95. runbooks/finops/types.py +66 -0
  96. runbooks/finops/visualisations.py +80 -0
  97. runbooks/inventory/.gitignore +354 -0
  98. runbooks/inventory/ArgumentsClass.py +261 -0
  99. runbooks/inventory/Inventory_Modules.py +6130 -0
  100. runbooks/inventory/LandingZone/delete_lz.py +1075 -0
  101. runbooks/inventory/README.md +1320 -0
  102. runbooks/inventory/__init__.py +62 -0
  103. runbooks/inventory/account_class.py +532 -0
  104. runbooks/inventory/all_my_instances_wrapper.py +123 -0
  105. runbooks/inventory/aws_decorators.py +201 -0
  106. runbooks/inventory/cfn_move_stack_instances.py +1526 -0
  107. runbooks/inventory/check_cloudtrail_compliance.py +614 -0
  108. runbooks/inventory/check_controltower_readiness.py +1107 -0
  109. runbooks/inventory/check_landingzone_readiness.py +711 -0
  110. runbooks/inventory/cloudtrail.md +727 -0
  111. runbooks/inventory/collectors/__init__.py +20 -0
  112. runbooks/inventory/collectors/aws_compute.py +518 -0
  113. runbooks/inventory/collectors/aws_networking.py +275 -0
  114. runbooks/inventory/collectors/base.py +222 -0
  115. runbooks/inventory/core/__init__.py +19 -0
  116. runbooks/inventory/core/collector.py +303 -0
  117. runbooks/inventory/core/formatter.py +296 -0
  118. runbooks/inventory/delete_s3_buckets_objects.py +169 -0
  119. runbooks/inventory/discovery.md +81 -0
  120. runbooks/inventory/draw_org_structure.py +748 -0
  121. runbooks/inventory/ec2_vpc_utils.py +341 -0
  122. runbooks/inventory/find_cfn_drift_detection.py +272 -0
  123. runbooks/inventory/find_cfn_orphaned_stacks.py +719 -0
  124. runbooks/inventory/find_cfn_stackset_drift.py +733 -0
  125. runbooks/inventory/find_ec2_security_groups.py +669 -0
  126. runbooks/inventory/find_landingzone_versions.py +201 -0
  127. runbooks/inventory/find_vpc_flow_logs.py +1221 -0
  128. runbooks/inventory/inventory.sh +659 -0
  129. runbooks/inventory/list_cfn_stacks.py +558 -0
  130. runbooks/inventory/list_cfn_stackset_operation_results.py +252 -0
  131. runbooks/inventory/list_cfn_stackset_operations.py +734 -0
  132. runbooks/inventory/list_cfn_stacksets.py +453 -0
  133. runbooks/inventory/list_config_recorders_delivery_channels.py +681 -0
  134. runbooks/inventory/list_ds_directories.py +354 -0
  135. runbooks/inventory/list_ec2_availability_zones.py +286 -0
  136. runbooks/inventory/list_ec2_ebs_volumes.py +244 -0
  137. runbooks/inventory/list_ec2_instances.py +425 -0
  138. runbooks/inventory/list_ecs_clusters_and_tasks.py +562 -0
  139. runbooks/inventory/list_elbs_load_balancers.py +411 -0
  140. runbooks/inventory/list_enis_network_interfaces.py +526 -0
  141. runbooks/inventory/list_guardduty_detectors.py +568 -0
  142. runbooks/inventory/list_iam_policies.py +404 -0
  143. runbooks/inventory/list_iam_roles.py +518 -0
  144. runbooks/inventory/list_iam_saml_providers.py +359 -0
  145. runbooks/inventory/list_lambda_functions.py +882 -0
  146. runbooks/inventory/list_org_accounts.py +446 -0
  147. runbooks/inventory/list_org_accounts_users.py +354 -0
  148. runbooks/inventory/list_rds_db_instances.py +406 -0
  149. runbooks/inventory/list_route53_hosted_zones.py +318 -0
  150. runbooks/inventory/list_servicecatalog_provisioned_products.py +575 -0
  151. runbooks/inventory/list_sns_topics.py +360 -0
  152. runbooks/inventory/list_ssm_parameters.py +402 -0
  153. runbooks/inventory/list_vpc_subnets.py +433 -0
  154. runbooks/inventory/list_vpcs.py +422 -0
  155. runbooks/inventory/lockdown_cfn_stackset_role.py +224 -0
  156. runbooks/inventory/models/__init__.py +24 -0
  157. runbooks/inventory/models/account.py +192 -0
  158. runbooks/inventory/models/inventory.py +309 -0
  159. runbooks/inventory/models/resource.py +247 -0
  160. runbooks/inventory/recover_cfn_stack_ids.py +205 -0
  161. runbooks/inventory/requirements.txt +12 -0
  162. runbooks/inventory/run_on_multi_accounts.py +211 -0
  163. runbooks/inventory/tests/common_test_data.py +3661 -0
  164. runbooks/inventory/tests/common_test_functions.py +204 -0
  165. runbooks/inventory/tests/script_test_data.py +0 -0
  166. runbooks/inventory/tests/setup.py +24 -0
  167. runbooks/inventory/tests/src.py +18 -0
  168. runbooks/inventory/tests/test_cfn_describe_stacks.py +208 -0
  169. runbooks/inventory/tests/test_ec2_describe_instances.py +162 -0
  170. runbooks/inventory/tests/test_inventory_modules.py +55 -0
  171. runbooks/inventory/tests/test_lambda_list_functions.py +86 -0
  172. runbooks/inventory/tests/test_moto_integration_example.py +273 -0
  173. runbooks/inventory/tests/test_org_list_accounts.py +49 -0
  174. runbooks/inventory/update_aws_actions.py +173 -0
  175. runbooks/inventory/update_cfn_stacksets.py +1215 -0
  176. runbooks/inventory/update_cloudwatch_logs_retention_policy.py +294 -0
  177. runbooks/inventory/update_iam_roles_cross_accounts.py +478 -0
  178. runbooks/inventory/update_s3_public_access_block.py +539 -0
  179. runbooks/inventory/utils/__init__.py +23 -0
  180. runbooks/inventory/utils/aws_helpers.py +510 -0
  181. runbooks/inventory/utils/threading_utils.py +493 -0
  182. runbooks/inventory/utils/validation.py +682 -0
  183. runbooks/inventory/verify_ec2_security_groups.py +1430 -0
  184. runbooks/main.py +785 -0
  185. runbooks/organizations/__init__.py +12 -0
  186. runbooks/organizations/manager.py +374 -0
  187. runbooks/security_baseline/README.md +324 -0
  188. runbooks/security_baseline/checklist/alternate_contacts.py +8 -1
  189. runbooks/security_baseline/checklist/bucket_public_access.py +4 -1
  190. runbooks/security_baseline/checklist/cloudwatch_alarm_configuration.py +9 -2
  191. runbooks/security_baseline/checklist/guardduty_enabled.py +9 -2
  192. runbooks/security_baseline/checklist/multi_region_instance_usage.py +5 -1
  193. runbooks/security_baseline/checklist/root_access_key.py +6 -1
  194. runbooks/security_baseline/config-origin.json +1 -1
  195. runbooks/security_baseline/config.json +1 -1
  196. runbooks/security_baseline/permission.json +1 -1
  197. runbooks/security_baseline/report_generator.py +10 -2
  198. runbooks/security_baseline/report_template_en.html +8 -8
  199. runbooks/security_baseline/report_template_jp.html +8 -8
  200. runbooks/security_baseline/report_template_kr.html +13 -13
  201. runbooks/security_baseline/report_template_vn.html +8 -8
  202. runbooks/security_baseline/requirements.txt +7 -0
  203. runbooks/security_baseline/run_script.py +8 -2
  204. runbooks/security_baseline/security_baseline_tester.py +10 -2
  205. runbooks/security_baseline/utils/common.py +5 -1
  206. runbooks/utils/__init__.py +204 -0
  207. runbooks-0.6.1.dist-info/METADATA +373 -0
  208. runbooks-0.6.1.dist-info/RECORD +237 -0
  209. {runbooks-0.2.3.dist-info → runbooks-0.6.1.dist-info}/WHEEL +1 -1
  210. runbooks-0.6.1.dist-info/entry_points.txt +7 -0
  211. runbooks-0.6.1.dist-info/licenses/LICENSE +201 -0
  212. runbooks-0.6.1.dist-info/top_level.txt +3 -0
  213. runbooks/python101/calculator.py +0 -34
  214. runbooks/python101/config.py +0 -1
  215. runbooks/python101/exceptions.py +0 -16
  216. runbooks/python101/file_manager.py +0 -218
  217. runbooks/python101/toolkit.py +0 -153
  218. runbooks-0.2.3.dist-info/METADATA +0 -435
  219. runbooks-0.2.3.dist-info/RECORD +0 -61
  220. runbooks-0.2.3.dist-info/entry_points.txt +0 -3
  221. runbooks-0.2.3.dist-info/top_level.txt +0 -1
@@ -0,0 +1,359 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ AWS IAM SAML Identity Providers Discovery and Management Script
5
+
6
+ This script provides comprehensive discovery, analysis, and optional deletion capabilities for
7
+ AWS Identity and Access Management (IAM) SAML identity providers across multi-account
8
+ environments. It's designed for enterprise identity and access management teams who need
9
+ visibility into SAML federation configuration, identity provider governance, and automated
10
+ cleanup capabilities across large-scale AWS deployments.
11
+
12
+ Key Features:
13
+ - Multi-account SAML identity provider discovery using assume role capabilities
14
+ - Comprehensive identity provider enumeration with metadata extraction
15
+ - Optional automated deletion capabilities with safety controls
16
+ - Enterprise reporting with CSV export and structured output
17
+ - Profile-based authentication with support for federated access
18
+ - Identity provider governance for organizational security standardization
19
+
20
+ Enterprise Use Cases:
21
+ - Identity provider audit and compliance reporting across organizations
22
+ - SAML federation governance and standardization across organizational boundaries
23
+ - Identity provider lifecycle management and automated cleanup
24
+ - Security incident response with identity provider configuration analysis
25
+ - Compliance reporting for identity federation and access control standards
26
+ - Multi-account identity governance and provider consolidation
27
+ - Identity provider drift detection and configuration standardization
28
+
29
+ SAML Identity Provider Features:
30
+ - Comprehensive identity provider enumeration with ARN extraction
31
+ - Provider metadata extraction for governance and compliance analysis
32
+ - Cross-account identity provider visibility for organizational oversight
33
+ - Provider configuration analysis for security and compliance assessment
34
+ - Identity provider lifecycle tracking for governance management
35
+
36
+ Security Considerations:
37
+ - Uses IAM assume role capabilities for cross-account identity provider access
38
+ - Implements proper error handling for authorization failures
39
+ - Supports optional deletion operations with explicit safety controls
40
+ - Respects IAM service permissions and regional access constraints
41
+ - Provides comprehensive audit trail through detailed logging
42
+ - Sensitive identity configuration handling with appropriate access controls
43
+
44
+ Identity Governance Features:
45
+ - Cross-account identity provider discovery for organizational oversight
46
+ - Provider configuration standardization across organizational boundaries
47
+ - Identity provider lifecycle management with automated cleanup capabilities
48
+ - Provider governance for compliance and security standardization
49
+ - Identity federation visibility for security and compliance management
50
+
51
+ Performance Considerations:
52
+ - Sequential processing for reliable identity provider discovery operations
53
+ - Progress tracking for operational visibility during large-scale operations
54
+ - Efficient credential management for cross-account identity provider access
55
+ - Memory-optimized data structures for large identity provider inventories
56
+ - Graceful error handling for authorization and throttling scenarios
57
+
58
+ Deletion Safety Features:
59
+ - Explicit deletion flags (+delete +forreal) for safety controls
60
+ - No confirmation prompts - requires explicit command-line flags
61
+ - Comprehensive logging of deletion operations for audit trails
62
+ - Error handling for deletion failures and authorization issues
63
+ - Deletion operation tracking for compliance and governance
64
+
65
+ Threading Architecture:
66
+ - Currently uses sequential processing for reliable operations
67
+ - TODO: Multi-threading enhancement planned for improved performance
68
+ - Thread-safe error handling and progress tracking architecture
69
+ - Graceful degradation for account access failures
70
+
71
+ Dependencies:
72
+ - boto3/botocore for AWS IAM API interactions
73
+ - account_class for AWS account access management
74
+ - ArgumentsClass for standardized CLI argument parsing
75
+ - Inventory_Modules for common utility functions and credential management
76
+ - colorama for enhanced output formatting
77
+
78
+ Compliance and Audit Features:
79
+ - Comprehensive identity provider discovery for security auditing
80
+ - Provider configuration analysis for compliance validation
81
+ - Cross-account identity governance for organizational security
82
+ - Provider lifecycle tracking for organizational oversight
83
+ - Identity federation visibility for compliance assessment
84
+
85
+ Future Enhancements:
86
+ - Multi-threading for improved performance across large organizations
87
+ - Identity provider configuration analysis and drift detection
88
+ - Integration with AWS Config for provider configuration monitoring
89
+ - Provider optimization recommendations for security and compliance
90
+
91
+ Author: AWS CloudOps Team
92
+ Version: 2024.03.27
93
+ """
94
+
95
+ import logging
96
+ import sys
97
+ from os.path import split
98
+ from time import time
99
+
100
+ import boto3
101
+ from account_class import aws_acct_access
102
+ from ArgumentsClass import CommonArguments
103
+ from botocore.exceptions import ClientError
104
+ from colorama import Fore, init
105
+ from Inventory_Modules import display_results, find_saml_components_in_acct2, get_child_access3
106
+
107
+ init()
108
+ __version__ = "2024.03.27"
109
+
110
+ begin_time = time()
111
+ ERASE_LINE = "\x1b[2K"
112
+
113
+
114
+ ##################
115
+
116
+
117
+ def parse_args(args):
118
+ """
119
+ Parse command line arguments for AWS IAM SAML identity provider discovery and management operations.
120
+
121
+ Configures comprehensive argument parsing for single-profile, single-region IAM SAML identity
122
+ provider operations. Supports enterprise identity and access management with profile configuration,
123
+ region targeting, role-based access, and optional deletion capabilities with explicit safety controls.
124
+
125
+ Args:
126
+ args (list): Command line arguments from sys.argv[1:]
127
+
128
+ Returns:
129
+ argparse.Namespace: Parsed arguments containing:
130
+ - Profile: AWS profile for authentication
131
+ - Region: Target region for SAML identity provider discovery
132
+ - AccessRole: IAM role for cross-account access
133
+ - Filename: Output file for CSV export
134
+ - Time: Enable performance timing metrics
135
+ - loglevel: Logging verbosity configuration
136
+ - DeletionRun: Enable identity provider deletion operations
137
+
138
+ Configuration Options:
139
+ - Single profile support for focused identity provider management
140
+ - Single region targeting for specific regional identity provider analysis
141
+ - Role-based access for cross-account identity provider operations
142
+ - File output for integration with identity management tools
143
+ - Timing metrics for performance optimization and monitoring
144
+ - Verbose logging for debugging and identity governance audit
145
+
146
+ Safety and Deletion Features:
147
+ - Explicit deletion flags (+delete +forreal) for identity provider cleanup
148
+ - No confirmation prompts - requires explicit command-line safety flags
149
+ - Deletion operation logging for compliance and governance audit
150
+ - Safety controls to prevent accidental identity provider deletion
151
+
152
+ Enterprise Identity Management:
153
+ - Single profile focus for targeted identity provider operations
154
+ - Region-specific identity provider discovery and management
155
+ - Role-based access for enterprise identity governance
156
+ - Identity provider lifecycle management with safety controls
157
+ """
158
+ script_path, script_name = split(sys.argv[0])
159
+ parser = CommonArguments()
160
+ parser.singleprofile()
161
+ parser.singleregion()
162
+ parser.roletouse()
163
+ parser.verbosity()
164
+ parser.save_to_file()
165
+ parser.timing()
166
+ parser.version(__version__)
167
+ local = parser.my_parser.add_argument_group(script_name, "Parameters specific to this script")
168
+ local.add_argument(
169
+ "+delete",
170
+ "+forreal",
171
+ dest="DeletionRun",
172
+ const=True,
173
+ default=False,
174
+ action="store_const",
175
+ help="Enable identity provider deletion - requires both flags for safety. Deletes without confirmation prompts. Use with extreme caution!",
176
+ )
177
+ return parser.my_parser.parse_args(args)
178
+
179
+
180
+ def all_my_saml_providers(faws_acct: aws_acct_access, fChildAccounts: list, f_access_role=None) -> list:
181
+ """
182
+ Discover and enumerate all SAML identity providers across multiple AWS child accounts.
183
+
184
+ Performs comprehensive SAML identity provider discovery using sequential processing
185
+ to efficiently inventory identity providers across enterprise AWS environments.
186
+ Supports organization-wide identity governance with role-based access and provider
187
+ metadata extraction for compliance and security management.
188
+
189
+ Args:
190
+ faws_acct (aws_acct_access): AWS account access object for credential management
191
+ fChildAccounts (list): List of child account dictionaries containing:
192
+ - AccountId: AWS account number
193
+ - AccountStatus: Account status (ACTIVE, SUSPENDED, CLOSED)
194
+ f_access_role (str, optional): IAM role name for cross-account access
195
+
196
+ Returns:
197
+ list: Comprehensive list of SAML identity provider dictionaries containing:
198
+ - MgmtAccount: Management account identifier for organizational hierarchy
199
+ - AccountNumber: AWS account containing the identity provider
200
+ - Region: AWS region where identity provider is configured
201
+ - IdpName: SAML identity provider name extracted from ARN
202
+ - Arn: Complete identity provider Amazon Resource Name
203
+
204
+ Enterprise Identity Features:
205
+ - Cross-account SAML provider discovery with assume role capabilities
206
+ - Provider metadata extraction for governance and compliance analysis
207
+ - Account status filtering to skip suspended or closed accounts
208
+ - Comprehensive error handling for authorization and access failures
209
+
210
+ Performance Considerations:
211
+ - Sequential processing for reliable identity provider discovery
212
+ - Progress tracking for operational visibility during discovery
213
+ - Efficient credential management for cross-account provider access
214
+ - Memory-optimized data structures for large identity provider inventories
215
+
216
+ Error Handling:
217
+ - Authorization failure detection with appropriate logging
218
+ - AWS API error management with graceful degradation
219
+ - Account status validation to skip inactive accounts
220
+ - Comprehensive error reporting for troubleshooting
221
+
222
+ Security Considerations:
223
+ - Role-based access for enterprise identity governance
224
+ - Proper credential management for cross-account operations
225
+ - Authorization failure handling with detailed logging
226
+ - Account access validation before identity provider enumeration
227
+
228
+ TODO: Enhance with multi-threading for improved performance across large organizations
229
+ """
230
+ IdpsFound = []
231
+
232
+ # Sequential processing of child accounts for SAML identity provider discovery
233
+ for account in fChildAccounts:
234
+ try:
235
+ # Only process active accounts, skip suspended or closed accounts
236
+ if account["AccountStatus"] == "ACTIVE":
237
+ print(f"{ERASE_LINE}Getting credentials for account {account['AccountId']}", end="\r")
238
+ try:
239
+ # Obtain cross-account credentials using the specified access role
240
+ account_credentials = get_child_access3(faws_acct, account["AccountId"], pRegion, f_access_role)
241
+ except ClientError as my_Error:
242
+ # Handle different types of credential and authorization failures
243
+ if "AuthFailure" in str(my_Error):
244
+ print(f"{pProfile}: Authorization Failure for account {account['AccountId']}")
245
+ else:
246
+ print(f"{pProfile}: Other kind of failure for account {account['AccountId']}")
247
+ print(my_Error)
248
+ continue
249
+
250
+ idpNum = 0
251
+ try:
252
+ # Discover SAML identity providers in the current account using inventory module
253
+ Idps = find_saml_components_in_acct2(account_credentials)
254
+ idpNum = len(Idps)
255
+ logging.info(f"Account: {account['AccountId']} | Region: {pRegion} | Found {idpNum} Idps")
256
+ logging.info(
257
+ f"{ERASE_LINE}{Fore.RED}Account: {account['AccountId']} pRegion: {pRegion} Found {idpNum} Idps.{Fore.RESET}"
258
+ )
259
+
260
+ # Process discovered identity providers and extract metadata
261
+ if idpNum > 0:
262
+ for idp in Idps:
263
+ logging.info(f"Arn: {idp['Arn']}")
264
+
265
+ # Extract identity provider name from ARN (everything after the last slash)
266
+ NameStart = idp["Arn"].find("/") + 1
267
+ logging.debug(f"Name starts at character: {NameStart}")
268
+ IdpName = idp["Arn"][NameStart:]
269
+
270
+ # Aggregate identity provider information for enterprise governance
271
+ IdpsFound.append(
272
+ {
273
+ "MgmtAccount": account_credentials["MgmtAccount"],
274
+ "AccountNumber": account_credentials["AccountId"],
275
+ "Region": account_credentials["Region"],
276
+ "IdpName": IdpName,
277
+ "Arn": idp["Arn"],
278
+ }
279
+ )
280
+ except ClientError as my_Error:
281
+ # Handle IAM API authorization failures for identity provider discovery
282
+ if "AuthFailure" in str(my_Error):
283
+ print(f"{account['AccountId']}: Authorization Failure")
284
+ else:
285
+ # Skip processing for inactive accounts
286
+ print(ERASE_LINE, f"Skipping account {account['AccountId']} since it's SUSPENDED or CLOSED", end="\r")
287
+ except KeyError as my_Error:
288
+ # Handle cases where expected account keys are missing
289
+ logging.error(f"Key Error: {my_Error}")
290
+ continue
291
+ return IdpsFound
292
+
293
+
294
+ def delete_idps(faws_acct: aws_acct_access, idps_found: list):
295
+ for idp in idps_found:
296
+ account_credentials = get_child_access3(faws_acct, idp["AccountNumber"])
297
+ session_aws = boto3.Session(
298
+ region_name=idp["pRegion"],
299
+ aws_access_key_id=account_credentials["AccessKeyId"],
300
+ aws_secret_access_key=account_credentials["SecretAccessKey"],
301
+ aws_session_token=account_credentials["SessionToken"],
302
+ )
303
+ iam_client = session_aws.client("iam")
304
+ print(f"Deleting Idp {idp['IdpName']} from account {idp['AccountId']} in pRegion {idp['pRegion']}")
305
+ response = iam_client.delete_saml_provider(SAMLProviderArn=idp["Arn"])
306
+
307
+
308
+ ##################
309
+
310
+ if __name__ == "__main__":
311
+ args = parse_args(sys.argv[1:])
312
+ pProfile = args.Profile
313
+ pRegion = args.Region
314
+ verbose = args.loglevel
315
+ pTiming = args.Time
316
+ pAccessRole = args.AccessRole
317
+ pFilename = args.Filename
318
+ DeletionRun = args.DeletionRun
319
+
320
+ logging.basicConfig(level=verbose, format="[%(filename)s:%(lineno)s - %(funcName)30s() ] %(message)s")
321
+
322
+ print()
323
+
324
+ # Get credentials
325
+ aws_acct = aws_acct_access(pProfile)
326
+ ChildAccounts = aws_acct.ChildAccounts
327
+
328
+ # Find the SAML providers
329
+ IdpsFound = all_my_saml_providers(aws_acct, ChildAccounts, pAccessRole)
330
+ print(f"{ERASE_LINE}")
331
+ # Display results
332
+ display_dict = {
333
+ "MgmtAccount": {"DisplayOrder": 1, "Heading": "Mgmt Acct"},
334
+ "AccountNumber": {"DisplayOrder": 2, "Heading": "Acct Number"},
335
+ "Region": {"DisplayOrder": 3, "Heading": "Region"},
336
+ "IdpName": {"DisplayOrder": 4, "Heading": "IdP Name"},
337
+ "Arn": {"DisplayOrder": 5, "Heading": "Arn"},
338
+ }
339
+ sorted_results = sorted(IdpsFound, key=lambda x: (x["AccountNumber"], x["Region"], x["IdpName"]))
340
+ display_results(sorted_results, display_dict, None, pFilename)
341
+ AccountsFound = list(set([x["AccountNumber"] for x in IdpsFound]))
342
+ RegionsFound = list(set([x["Region"] for x in IdpsFound]))
343
+ print()
344
+ print(
345
+ f"{Fore.RED}Found {len(IdpsFound)} Idps across {len(AccountsFound)} accounts in {len(RegionsFound)} regions{Fore.RESET}"
346
+ )
347
+ print()
348
+
349
+ # Delete saml providers if requested
350
+ if DeletionRun:
351
+ logging.warning(f"Deleting {len(IdpsFound)} Idps")
352
+ delete_idps(aws_acct, IdpsFound)
353
+
354
+ print()
355
+ if pTiming:
356
+ print(f"{Fore.GREEN}This script took {time() - begin_time:.2f} seconds{Fore.RESET}")
357
+ print()
358
+ print("Thanks for using this script...")
359
+ print()