runbooks 0.1.7__py3-none-any.whl → 0.1.8__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 (55) hide show
  1. runbooks/__init__.py +1 -1
  2. runbooks/aws/__init__.py +58 -0
  3. runbooks/aws/dynamodb_operations.py +231 -0
  4. runbooks/aws/ec2_copy_image_cross-region.py +195 -0
  5. runbooks/aws/ec2_describe_instances.py +202 -0
  6. runbooks/aws/ec2_ebs_snapshots_delete.py +186 -0
  7. runbooks/aws/ec2_run_instances.py +207 -0
  8. runbooks/aws/ec2_start_stop_instances.py +199 -0
  9. runbooks/aws/ec2_terminate_instances.py +143 -0
  10. runbooks/aws/ec2_unused_eips.py +196 -0
  11. runbooks/aws/ec2_unused_volumes.py +184 -0
  12. runbooks/aws/s3_create_bucket.py +140 -0
  13. runbooks/aws/s3_list_buckets.py +152 -0
  14. runbooks/aws/s3_list_objects.py +151 -0
  15. runbooks/aws/s3_object_operations.py +183 -0
  16. runbooks/aws/tagging_lambda_handler.py +172 -0
  17. runbooks/python101/calculator.py +34 -0
  18. runbooks/python101/config.py +1 -0
  19. runbooks/python101/exceptions.py +16 -0
  20. runbooks/python101/file_manager.py +218 -0
  21. runbooks/python101/toolkit.py +153 -0
  22. runbooks/security_baseline/__init__.py +0 -0
  23. runbooks/security_baseline/checklist/__init__.py +17 -0
  24. runbooks/security_baseline/checklist/account_level_bucket_public_access.py +86 -0
  25. runbooks/security_baseline/checklist/alternate_contacts.py +65 -0
  26. runbooks/security_baseline/checklist/bucket_public_access.py +82 -0
  27. runbooks/security_baseline/checklist/cloudwatch_alarm_configuration.py +66 -0
  28. runbooks/security_baseline/checklist/direct_attached_policy.py +69 -0
  29. runbooks/security_baseline/checklist/guardduty_enabled.py +71 -0
  30. runbooks/security_baseline/checklist/iam_password_policy.py +43 -0
  31. runbooks/security_baseline/checklist/iam_user_mfa.py +39 -0
  32. runbooks/security_baseline/checklist/multi_region_instance_usage.py +55 -0
  33. runbooks/security_baseline/checklist/multi_region_trail.py +64 -0
  34. runbooks/security_baseline/checklist/root_access_key.py +72 -0
  35. runbooks/security_baseline/checklist/root_mfa.py +39 -0
  36. runbooks/security_baseline/checklist/root_usage.py +128 -0
  37. runbooks/security_baseline/checklist/trail_enabled.py +68 -0
  38. runbooks/security_baseline/checklist/trusted_advisor.py +24 -0
  39. runbooks/security_baseline/report_generator.py +149 -0
  40. runbooks/security_baseline/run_script.py +76 -0
  41. runbooks/security_baseline/security_baseline_tester.py +179 -0
  42. runbooks/security_baseline/utils/__init__.py +1 -0
  43. runbooks/security_baseline/utils/common.py +109 -0
  44. runbooks/security_baseline/utils/enums.py +44 -0
  45. runbooks/security_baseline/utils/language.py +762 -0
  46. runbooks/security_baseline/utils/level_const.py +5 -0
  47. runbooks/security_baseline/utils/permission_list.py +26 -0
  48. runbooks/utils/__init__.py +0 -0
  49. runbooks/utils/logger.py +36 -0
  50. {runbooks-0.1.7.dist-info → runbooks-0.1.8.dist-info}/METADATA +2 -2
  51. runbooks-0.1.8.dist-info/RECORD +54 -0
  52. runbooks-0.1.7.dist-info/RECORD +0 -6
  53. {runbooks-0.1.7.dist-info → runbooks-0.1.8.dist-info}/WHEEL +0 -0
  54. {runbooks-0.1.7.dist-info → runbooks-0.1.8.dist-info}/entry_points.txt +0 -0
  55. {runbooks-0.1.7.dist-info → runbooks-0.1.8.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,16 @@
1
+ class CalculatorError(Exception):
2
+ """Custom exception for errors in the Calculator."""
3
+
4
+ pass
5
+
6
+
7
+ class InvalidOperationError(CalculatorError):
8
+ """Raised when an invalid operation is attempted."""
9
+
10
+ pass
11
+
12
+
13
+ class InputValidationError(CalculatorError):
14
+ """Raised when input validation fails."""
15
+
16
+ pass
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ Utilities to create a specified folder and an empty file inside it with safe error handling.
5
+
6
+ Author: Python Developer
7
+ Date: 2025-01-05
8
+ Version: 1.0.0
9
+
10
+ Usage:
11
+ file_manager.py <folder_name> <file_name>
12
+ """
13
+
14
+ import os
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Union
18
+
19
+
20
+ ## ==============================
21
+ ## VALIDATION UTILITIES
22
+ ## ==============================
23
+ def validate_input(value: Union[str, float, int]) -> float:
24
+ """
25
+ Validates and converts input into a float.
26
+
27
+ Args:
28
+ value (Union[str, float, int]): The input value to validate and convert.
29
+
30
+ Returns:
31
+ float: The validated and converted float value.
32
+
33
+ Raises:
34
+ TypeError: If input type is unsupported.
35
+ ValueError: If input cannot be converted to float, or fails constraints.
36
+ """
37
+
38
+ ## ✅ Step 1.1: Input Type Validation
39
+ if not isinstance(value, (str, int, float)):
40
+ raise TypeError(f"Invalid type '{type(value).__name__}'. Expected str, int, or float.")
41
+
42
+ ## ✅ Step 1.2: Handle Empty String
43
+ if isinstance(value, str) and not value.strip():
44
+ raise ValueError(f"Invalid input '{value}'. Input cannot be empty or whitespace-only.")
45
+
46
+ ## ✅ Step 2: Convert Input to Float
47
+ try:
48
+ result = float(value) ## Attempt numeric conversion
49
+ except ValueError as e:
50
+ raise ValueError(f"Invalid input '{value}'. Must be a valid number.") from e
51
+
52
+ ## ✅ Step 3: Return Validated Float
53
+ return result
54
+
55
+
56
+ def validate_folder_name(folder_name: str) -> None:
57
+ """
58
+ Validates folder name for OS-specific constraints.
59
+
60
+ Args:
61
+ folder_name (str): The folder name to validate.
62
+
63
+ Raises:
64
+ ValueError: If the folder name violates naming constraints.
65
+ """
66
+ if not folder_name:
67
+ raise ValueError("Folder name cannot be empty.")
68
+
69
+ if len(folder_name) > 255: # Max length in most file systems
70
+ raise ValueError("Folder name exceeds maximum length (255 characters).")
71
+
72
+ invalid_chars = '<>:"/\\|?*' # Reserved characters in Windows
73
+ if any(char in invalid_chars for char in folder_name):
74
+ raise ValueError(f"Folder name '{folder_name}' contains invalid characters.")
75
+
76
+ if folder_name in {"CON", "PRN", "AUX", "NUL"}: # Reserved Windows names
77
+ raise ValueError(f"Folder name '{folder_name}' is a reserved keyword.")
78
+
79
+ if folder_name.startswith(" ") or folder_name.endswith(" "):
80
+ raise ValueError("Folder name cannot start or end with spaces.")
81
+
82
+
83
+ def validate_file_name(file_name: str) -> None:
84
+ """
85
+ Validates file name for OS-specific constraints.
86
+
87
+ Args:
88
+ file_name (str): The file name to validate.
89
+
90
+ Raises:
91
+ ValueError: If the file name violates naming constraints.
92
+ """
93
+ if not file_name:
94
+ raise ValueError("File name cannot be empty.")
95
+
96
+ if len(file_name) > 255:
97
+ raise ValueError("File name exceeds maximum length (255 characters).")
98
+
99
+ invalid_chars = '<>:"/\\|?*'
100
+ if any(char in invalid_chars for char in file_name):
101
+ raise ValueError(f"File name '{file_name}' contains invalid characters.")
102
+
103
+ if file_name.startswith(" ") or file_name.endswith(" "):
104
+ raise ValueError("File name cannot start or end with spaces.")
105
+
106
+ if len(Path(file_name).suffix) == 0: # Ensure file has an extension
107
+ raise ValueError("File name must include a valid extension (e.g., '.txt').")
108
+
109
+
110
+ ## ==============================
111
+ ## FILE SYSTEM UTILITIES
112
+ ## ==============================
113
+ def create_folder_and_file(folder_name: str, file_name: str) -> None:
114
+ """
115
+ Create a folder and an empty file safely with robust error handling.
116
+
117
+ Args:
118
+ folder_name (str): Name of the folder to be created.
119
+ file_name (str): Name of the file to be created inside the folder.
120
+
121
+ Raises:
122
+ FileExistsError: If the folder already exists.
123
+ FileNotFoundError: If the folder path is invalid.
124
+ PermissionError: If there are insufficient permissions.
125
+ ValueError: If inputs are invalid.
126
+ """
127
+ ## ✅ Input Validation
128
+ validate_folder_name(folder_name)
129
+ validate_file_name(file_name)
130
+
131
+ ## ✅ Create Path Object
132
+ folder_path = Path(folder_name)
133
+ file_path = folder_path / file_name
134
+
135
+ try:
136
+ ## ✅ Create folder if it doesn't exist; same behavior as the POSIX `mkdir -p` command
137
+ folder_path.mkdir(parents=True, exist_ok=True) ## Safe parent directory creation
138
+ print(f"✅ Folder '{folder_name}' created successfully.")
139
+
140
+ ## ✅ Create an empty file inside the folder
141
+ # os.chdir(folder_name) ## May Raise FileNotFoundError
142
+ # with open(file_name, 'a'):
143
+ # pass
144
+ if file_path.exists():
145
+ raise FileExistsError(f"File '{file_name}' already exists in '{folder_name}'.")
146
+
147
+ file_path.touch(exist_ok=False) ## Create an empty file; Fails safely if file exists
148
+ print(f"✅ File '{file_name}' created successfully inside '{folder_name}'.")
149
+
150
+ except FileExistsError as e:
151
+ raise FileExistsError(str(e)) # Re-raise exception without exiting
152
+
153
+ except PermissionError:
154
+ print("❌ Permission denied. Check your user permissions.")
155
+ sys.exit(1)
156
+
157
+ except Exception as e:
158
+ print(f"❌ Unexpected error: {e}")
159
+ sys.exit(1)
160
+
161
+
162
+ ## ✅ Handle Arguments Dynamically for Terminal and Debugger Compatibility
163
+ def parse_arguments() -> tuple[str, str]:
164
+ """
165
+ Parses and validates command-line arguments for both terminal and VSCode debugger compatibility.
166
+
167
+ Returns:
168
+ tuple[str, str]: A tuple containing folder_name and file_name.
169
+
170
+ Raises:
171
+ ValueError: If arguments are invalid or insufficient.
172
+ """
173
+ import shlex # Safely split arguments with quotes (if present)
174
+
175
+ ## ✅ Check Arguments Length
176
+ if len(sys.argv) < 2:
177
+ raise ValueError("Provide exactly 2 arguments: <folder_name> <file_name>")
178
+
179
+ ## ✅ Handle Debugger Inputs (Single Combined Argument)
180
+ if len(sys.argv) == 2:
181
+ args = shlex.split(sys.argv[1]) # Split safely with quote handling
182
+ else:
183
+ args = sys.argv[1:] # Use normal command-line arguments
184
+
185
+ ## ✅ Validate Number of Arguments
186
+ if len(args) != 2:
187
+ raise ValueError("❌ Invalid arguments. Provide exactly 2 arguments: <folder_name> <file_name>")
188
+
189
+ ## ✅ Extract Folder and File Names
190
+ folder_name, file_name = args[0], args[1]
191
+ return folder_name, file_name
192
+
193
+
194
+ ## ==============================
195
+ ## MAIN FUNCTION
196
+ ## ==============================
197
+ def main() -> None:
198
+ """
199
+ Main entry point for the script.
200
+ """
201
+ try:
202
+ ## ✅ Handle Debugger Arguments (Optional for Debugging Tools)
203
+ folder_name, file_name = parse_arguments()
204
+
205
+ ## ✅ Execute Function for Folder and File Creation
206
+ print(f"✅ Usage: file_manager.py '{folder_name}' '{file_name}'")
207
+ create_folder_and_file(folder_name, file_name)
208
+ except ValueError as e:
209
+ print(f"❌ Error: {e}")
210
+ sys.exit(1)
211
+
212
+ except Exception as e:
213
+ print(f"❌ Unexpected Error: {e}")
214
+ sys.exit(1)
215
+
216
+
217
+ if __name__ == "__main__":
218
+ main()
@@ -0,0 +1,153 @@
1
+ """
2
+ Toolkit Module: Implements basic arithmetic operations.
3
+
4
+ This module provides functions to perform addition, subtraction,
5
+ multiplication, and division with detailed input validation.
6
+
7
+ Features:
8
+ - Handles edge cases like NaN, Infinity, and division by zero.
9
+ - Supports logging for better traceability.
10
+ - Enforces type checks for input safety.
11
+
12
+ Author: Python Developer
13
+ """
14
+
15
+ from typing import Union
16
+
17
+ from loguru import logger
18
+
19
+ # Define a type alias for supported numeric types
20
+ Number = Union[int, float]
21
+
22
+ # Configure loguru logger to simplify logs for testing
23
+ logger.remove()
24
+ logger.add(lambda msg: print(msg, end=""), format="{message}", level="DEBUG")
25
+
26
+
27
+ def _validate_inputs(a: Number, b: Number, allow_zero: bool = True) -> None:
28
+ """
29
+ Validates numeric inputs and checks edge cases.
30
+
31
+ Args:
32
+ a (Number): The first input value.
33
+ b (Number): The second input value.
34
+ allow_zero (bool): Whether zero is allowed as a value for `b`. Default is True.
35
+
36
+ Raises:
37
+ TypeError: If inputs are not integers or floats.
38
+ ValueError: If inputs are NaN or Infinity.
39
+ ZeroDivisionError: If `b` is zero and `allow_zero` is False.
40
+ """
41
+ # Type check
42
+ if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
43
+ raise TypeError(f"Inputs must be numbers. Received: {type(a)} and {type(b)}")
44
+
45
+ # Edge cases: NaN or Infinity
46
+ for value in [a, b]:
47
+ if value != value or value in [float("inf"), float("-inf")]:
48
+ raise ValueError(f"Invalid input {value}. Must be a finite number.")
49
+
50
+ # Zero Division Check
51
+ if not allow_zero and b == 0:
52
+ raise ZeroDivisionError("division by zero")
53
+
54
+
55
+ def add(a: Number, b: Number) -> float:
56
+ """
57
+ Adds two numbers and returns the result.
58
+
59
+ Examples:
60
+ >>> add(4.0, 2.0)
61
+ 6.0
62
+ >>> add(4, 2)
63
+ 6.0
64
+
65
+ Args:
66
+ a (Number): The first number.
67
+ b (Number): The second number.
68
+
69
+ Returns:
70
+ float: The sum of `a` and `b`.
71
+
72
+ Raises:
73
+ TypeError: If inputs are not numbers.
74
+ """
75
+ _validate_inputs(a, b)
76
+ logger.debug(f"Adding {a} + {b}")
77
+ return float(a + b)
78
+
79
+
80
+ def subtract(a: Number, b: Number) -> float:
81
+ """
82
+ Subtracts the second number from the first.
83
+
84
+ Examples:
85
+ >>> subtract(4.0, 2.0)
86
+ 2.0
87
+ >>> subtract(4, 2)
88
+ 2.0
89
+
90
+ Args:
91
+ a (Number): The first number.
92
+ b (Number): The second number.
93
+
94
+ Returns:
95
+ float: The result of `a - b`.
96
+
97
+ Raises:
98
+ TypeError: If inputs are not numbers.
99
+ """
100
+ _validate_inputs(a, b)
101
+ logger.debug(f"Subtracting {a} - {b}")
102
+ return float(a - b)
103
+
104
+
105
+ def multiply(a: Number, b: Number) -> float:
106
+ """
107
+ Multiplies two numbers and returns the result.
108
+
109
+ Examples:
110
+ >>> multiply(4.0, 2.0)
111
+ 8.0
112
+ >>> multiply(4, 2)
113
+ 8.0
114
+
115
+ Args:
116
+ a (Number): The first number.
117
+ b (Number): The second number.
118
+
119
+ Returns:
120
+ float: The result of `a * b`.
121
+
122
+ Raises:
123
+ TypeError: If inputs are not numbers.
124
+ """
125
+ _validate_inputs(a, b)
126
+ logger.debug(f"Multiplying {a} * {b}")
127
+ return float(a * b)
128
+
129
+
130
+ def divide(a: Number, b: Number) -> float:
131
+ """
132
+ Divides the first number by the second.
133
+
134
+ Examples:
135
+ >>> divide(4.0, 2.0)
136
+ 2.0
137
+ >>> divide(4, 2)
138
+ 2.0
139
+
140
+ Args:
141
+ a (Number): The numerator.
142
+ b (Number): The denominator.
143
+
144
+ Returns:
145
+ float: The result of `a / b`.
146
+
147
+ Raises:
148
+ TypeError: If inputs are not numbers.
149
+ ZeroDivisionError: If `b` is zero.
150
+ """
151
+ _validate_inputs(a, b, allow_zero=False)
152
+ logger.debug(f"Dividing {a} / {b}")
153
+ return float(a / b)
File without changes
@@ -0,0 +1,17 @@
1
+ __all__ = [
2
+ "root_mfa",
3
+ "root_usage",
4
+ "root_access_key",
5
+ "iam_user_mfa",
6
+ "iam_password_policy",
7
+ "direct_attached_policy",
8
+ "alternate_contacts",
9
+ "trail_enabled",
10
+ "multi_region_trail",
11
+ "account_level_bucket_public_access",
12
+ "bucket_public_access",
13
+ "cloudwatch_alarm_configuration",
14
+ "multi_region_instance_usage",
15
+ "guardduty_enabled",
16
+ "trusted_advisor",
17
+ ]
@@ -0,0 +1,86 @@
1
+ import logging
2
+
3
+ import botocore.exceptions
4
+ from utils import common
5
+ from utils import level_const as level
6
+
7
+
8
+ def check_account_level_bucket_public_access(session, translator) -> common.CheckResult:
9
+ logging.info(translator.translate("checking"))
10
+
11
+ ret = common.CheckResult()
12
+ ret.title = translator.translate("title")
13
+ ret.result_cols = ["Policy Name", "Public Access Setting"]
14
+
15
+ sts_client = session.client("sts")
16
+ s3control_client = session.client("s3control")
17
+
18
+ try:
19
+ account_id = sts_client.get_caller_identity()["Account"]
20
+ except botocore.exceptions.ClientError as e:
21
+ logging.error(f"Failed to get caller identity: {str(e)}", exc_info=True)
22
+ ret.level = level.error
23
+ ret.msg = translator.translate("failed_get_identity")
24
+ ret.result_rows.append(["ERR", "ERR"])
25
+ ret.error_message = str(e)
26
+ return ret
27
+
28
+ try:
29
+ account_policy = s3control_client.get_public_access_block(AccountId=account_id)[
30
+ "PublicAccessBlockConfiguration"
31
+ ]
32
+ except s3control_client.exceptions.NoSuchPublicAccessBlockConfiguration:
33
+ ret.level = level.danger
34
+ ret.msg = translator.translate("no_such_public_access_block_config")
35
+ ret.result_rows.append(["ALL", "Not Exist"])
36
+ return ret
37
+ except botocore.exceptions.ClientError as e:
38
+ error_code = e.response["Error"]["Code"]
39
+ error_message = e.response["Error"]["Message"]
40
+ logging.error(f"AWS API error: {error_code} - {error_message}", exc_info=True)
41
+ ret.level = level.error
42
+ ret.msg = translator.translate("aws_api_error")
43
+ ret.result_rows.append(["ERR", "ERR"])
44
+ ret.error_message = f"{error_code}: {error_message}"
45
+ return ret
46
+ except botocore.exceptions.BotoCoreError as e:
47
+ logging.error(f"Boto3 error occurred: {str(e)}", exc_info=True)
48
+ ret.level = level.error
49
+ ret.msg = translator.translate("boto3_error")
50
+ ret.result_rows.append(["ERR", "ERR"])
51
+ ret.error_message = str(e)
52
+ return ret
53
+ except Exception as e:
54
+ logging.error(f"Unexpected error occurred: {str(e)}", exc_info=True)
55
+ ret.level = level.error
56
+ ret.msg = translator.translate("unexpected_error")
57
+ ret.result_rows.append(["ERR", "ERR"])
58
+ ret.error_message = str(e)
59
+ return ret
60
+
61
+ public_allow_policy_counter = 0
62
+ for policy_name, setting in account_policy.items():
63
+ # if setting == False: ## E712 lint error
64
+ if not setting:
65
+ public_allow_policy_counter += 1
66
+ ret.result_rows.append([policy_name, "Allow"])
67
+ else:
68
+ ret.result_rows.append([policy_name, "Block"])
69
+
70
+ nums_of_public_block_access_policies = len(account_policy.items())
71
+
72
+ if public_allow_policy_counter == 0:
73
+ ret.level = level.success
74
+ ret.msg = translator.translate("success")
75
+ elif 0 < public_allow_policy_counter < nums_of_public_block_access_policies:
76
+ ret.level = level.warning
77
+ ret.msg = translator.translate("warning")
78
+ elif public_allow_policy_counter == nums_of_public_block_access_policies:
79
+ ret.level = level.danger
80
+ ret.msg = translator.translate("danger")
81
+ else:
82
+ ret.level = level.error
83
+ ret.msg = translator.translate("unexpected_error")
84
+ ret.result_rows = ["ERR", "ERR"]
85
+
86
+ return ret
@@ -0,0 +1,65 @@
1
+ import logging
2
+
3
+ import botocore.exceptions
4
+ from utils import common
5
+ from utils import level_const as level
6
+
7
+
8
+ def check_alternate_contact_filling(session, translator) -> common.CheckResult:
9
+ logging.info(translator.translate("checking"))
10
+
11
+ ret = common.CheckResult()
12
+ ret.title = translator.translate("title")
13
+ ret.result_cols = ["Contact Type", "Name", "E-Mail", "Contacts"]
14
+
15
+ contact_type_list = ["BILLING", "SECURITY", "OPERATIONS"]
16
+ client = session.client("account")
17
+ ret.level = level.success
18
+
19
+ for contact_type in contact_type_list:
20
+ try:
21
+ contact = client.get_alternate_contact(AlternateContactType=contact_type)["AlternateContact"]
22
+ except client.exceptions.ResourceNotFoundException:
23
+ ret.level = level.warning
24
+ contact = {"Name": "-", "EmailAddress": "-", "PhoneNumber": "-"}
25
+ except client.exceptions.ValidationException as e:
26
+ ret.level = level.error
27
+ contact = {"Name": "ERR", "EmailAddress": "ERR", "PhoneNumber": "ERR"}
28
+ ret.error_message = f"Validation Exception: {str(e)}"
29
+ logging.error(ret.error_message, exc_info=True)
30
+ except client.exceptions.AccessDeniedException as e:
31
+ ret.level = level.error
32
+ contact = {"Name": "ERR", "EmailAddress": "ERR", "PhoneNumber": "ERR"}
33
+ ret.error_message = f"Access Denied: {str(e)}"
34
+ logging.error(ret.error_message, exc_info=True)
35
+ except client.exceptions.TooManyRequestsException:
36
+ ret.level = level.error
37
+ contact = {"Name": "ERR", "EmailAddress": "ERR", "PhoneNumber": "ERR"}
38
+ ret.error_message = "Too Many Request Exception. Please Try Again Later."
39
+ logging.error(ret.error_message, exc_info=True)
40
+ except client.exceptions.InternalServerException:
41
+ ret.level = level.error
42
+ contact = {"Name": "ERR", "EmailAddress": "ERR", "PhoneNumber": "ERR"}
43
+ ret.error_message = "Internal Server Exception"
44
+ logging.error(ret.error_message, exc_info=True)
45
+ except botocore.exceptions.ClientError as e:
46
+ ret.level = level.error
47
+ contact = {"Name": "ERR", "EmailAddress": "ERR", "PhoneNumber": "ERR"}
48
+ ret.error_message = f"Unexpected ClientError: {str(e)}"
49
+ logging.error(ret.error_message, exc_info=True)
50
+ except Exception as e:
51
+ ret.level = level.error
52
+ contact = {"Name": "ERR", "EmailAddress": "ERR", "PhoneNumber": "ERR"}
53
+ ret.error_message = f"Unexpected Exception: {str(e)}"
54
+ logging.error(ret.error_message, exc_info=True)
55
+ finally:
56
+ ret.result_rows.append([contact_type, contact["Name"], contact["EmailAddress"], contact["PhoneNumber"]])
57
+
58
+ if ret.level == level.success:
59
+ ret.msg = translator.translate("success")
60
+ elif ret.level == level.warning:
61
+ ret.msg = translator.translate("warning")
62
+ else:
63
+ ret.msg = translator.translate("error")
64
+
65
+ return ret
@@ -0,0 +1,82 @@
1
+ import logging
2
+ from concurrent.futures import ThreadPoolExecutor, as_completed
3
+
4
+ import botocore.exceptions
5
+ from utils import common
6
+ from utils import level_const as level
7
+
8
+ MAXIMUM_NUMBER_OF_BUCKET_LIMIT = 1000
9
+
10
+
11
+ def get_bucket_info(client, bucket_name) -> tuple:
12
+ try:
13
+ bucket_info = client.get_public_access_block(Bucket=bucket_name)
14
+ except botocore.exceptions.ClientError as e:
15
+ if e.response["Error"]["Code"] == "NoSuchPublicAccessBlockConfiguration":
16
+ return level.danger, [bucket_name, "All Allowed"]
17
+ else:
18
+ logging.error(f"Error getting public access block for bucket {bucket_name}: {str(e)}", exc_info=True)
19
+ return level.error, [bucket_name, "ERR"]
20
+
21
+ public_access_block_policy_counter = sum(
22
+ 1 for policy_status in bucket_info["PublicAccessBlockConfiguration"].values() if policy_status
23
+ )
24
+ nums_of_public_access_block_policies = len(bucket_info["PublicAccessBlockConfiguration"])
25
+
26
+ if public_access_block_policy_counter == 0:
27
+ return level.danger, [bucket_name, "All Allowed"]
28
+ elif 0 < public_access_block_policy_counter < nums_of_public_access_block_policies:
29
+ return level.warning, [bucket_name, "Partially Allowed"]
30
+ elif public_access_block_policy_counter == nums_of_public_access_block_policies:
31
+ return level.success, [bucket_name, "All Blocked"]
32
+ else:
33
+ return level.error, [bucket_name, "Unexpected Exception"]
34
+
35
+
36
+ def check_bucket_public_access(session, translator) -> common.CheckResult:
37
+ logging.info(translator.translate("checking"))
38
+
39
+ ret = common.CheckResult()
40
+ ret.title = translator.translate("title")
41
+ ret.result_cols = ["Bucket Name", "Public Access Setting"]
42
+
43
+ s3_client = session.client("s3")
44
+
45
+ try:
46
+ bucket_list = s3_client.list_buckets()["Buckets"]
47
+ except botocore.exceptions.ClientError as e:
48
+ logging.error(f"Error listing buckets: {str(e)}", exc_info=True)
49
+ ret.level = level.error
50
+ ret.msg = translator.translate("unexpected_error")
51
+ ret.result_rows.append(["ERR", "ERR"])
52
+ ret.error_message = str(e)
53
+ return ret
54
+
55
+ with ThreadPoolExecutor() as thread_executor:
56
+ futures = []
57
+ if len(bucket_list) > MAXIMUM_NUMBER_OF_BUCKET_LIMIT:
58
+ ret.level = level.error
59
+ ret.msg = translator.translate("bucket_limit_warning").format(MAXIMUM_NUMBER_OF_BUCKET_LIMIT)
60
+ bucket_list = bucket_list[:MAXIMUM_NUMBER_OF_BUCKET_LIMIT]
61
+
62
+ for bucket in bucket_list:
63
+ futures.append(thread_executor.submit(get_bucket_info, s3_client, bucket["Name"]))
64
+
65
+ level_flag = level.success
66
+ for future in as_completed(futures):
67
+ result_level, result = future.result()
68
+ if result_level > level_flag:
69
+ level_flag = result_level
70
+ ret.result_rows.append(result)
71
+
72
+ if level_flag == level.success:
73
+ ret.msg = translator.translate("success")
74
+ elif level_flag == level.warning:
75
+ ret.msg = translator.translate("warning")
76
+ elif level_flag == level.danger:
77
+ ret.msg = translator.translate("danger")
78
+ elif ret.level != level.error: # Don't overwrite bucket limit warning
79
+ ret.msg = translator.translate("error")
80
+
81
+ ret.level = level_flag
82
+ return ret