diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d685b5c --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +__pycache__ +logs +creds.json/* +logs.zip +temp/ +temp.txt +env/ +actionPolicies/ +actionsUsers/ +crudActions/ +finalUserPolicies/ +userPolicies*/ +presentPolicies*/ +logs*/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d0e77ad --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM python:3.9-alpine + +RUN apk add --no-cache python3-dev gcc musl-dev libffi-dev libpq-dev openssl-dev make && \ + apk add --no-cache redis + +WORKDIR /app +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt +COPY . . +EXPOSE 8000 +CMD ["sh", "-c", "redis-server & uvicorn app:app --reload --host 0.0.0.0"] + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..5d5a4df --- /dev/null +++ b/README.md @@ -0,0 +1,78 @@ +![CloudDefence](assets/banner.png) + +## AWS Zero Trust policy by CloudDefenseAI + +The AWS Policy Generator API is a FastAPI application that helps you generate AWS IAM policies based on AWS CloudTrail logs. The API accepts a JSON payload containing the required AWS credentials, regions, and other relevant information, and then runs the policy generation process. Upon successful completion, it returns the time taken to generate the policies. + +![data flow](assets/Data_Flow.jpg) + +## Prerequisites + +Before you begin, make sure you have the following prerequisites in place: + +To run the AWS Policy Generator API, you need: + +1. Python 3.6 or higher +2. FastAPI and Uvicorn packages installed +3. redis server + +## Installation + +To install and use the extended rule set for Falco runtime security, follow these steps: + +1. Clone the Repository: Start by cloning this GitHub repository to your local system: + +``` +git clone https://github.com/CloudDefenseAI/AWSZeroTrustPolicy +``` + +2. Navigate to the Repository: Change to the repository directory: + +``` +cd AWSZeroTrustPolicy +``` + +3. install python libraries + +``` +pip install -r requirements.txt +``` + +## Usage + +1. Run Redis server + `redis-server` + +2. Run the uvicorn application + `uvicorn app:app --reload --host 0.0.0.0 --log-level debug` + +3. Send the following curl request to generate the zerotrust policy + +``` +curl -X POST -H "Content-Type: application/json" -d '{ + "accountType": "Credential", + "accessKey": "accessKey", + "secretKey": "secretKey", + "externalId": "externalId", + "roleArn": "roleArn", + "accountId": "accountId", + "days": 30, + "bucketData": { + "us-east-1": "aws-cloudtrail-logs-407638845061-1f72c339" + } +}' http://localhost:8000/run +``` + +## Contributing + +If you want to help and wish to contribute, please review our contribution guidelines. Code contributions are always encouraged and welcome! + +## License + +This extended rule set for Falco runtime security is released under the [Apache-2.0 License](url). + +## Disclaimer: + +The content and code available in this GitHub repository are currently a work in progress. Please note that the rules, guidelines, or any other materials provided here are subject to change without prior notice. +While we aim to ensure the accuracy and completeness of the information presented, there may be errors or omissions. We kindly request users to exercise caution and critical judgment when utilizing or relying on any content found in this repository. +We appreciate your understanding and patience as we continue to develop and refine the content within this repository. Contributions, feedback, and suggestions are welcome and greatly valued, as they contribute to the ongoing improvement of this project. diff --git a/app.py b/app.py new file mode 100644 index 0000000..36f7c70 --- /dev/null +++ b/app.py @@ -0,0 +1,23 @@ +import json +from fastapi import FastAPI, HTTPException, Depends, Request +from fastapi.middleware.cors import CORSMiddleware +from schemas import Script +from runner import runner +from datetime import datetime + +app = FastAPI() + +@app.post("/run") +def run_script(script: Script): + print(f"Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") + print("Payload:") + print(json.dumps(script.dict(), indent=4)) + + try: + resp = runner(script.accountType, script.accessKey, script.secretKey, script.accountId, script.days + , script.bucketData, script.roleArn, script.externalId) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + return {"accountId": resp['accountId'], "generatedPolicies": resp['generatedPolicies'], "consolidatedPolicies": resp['consolidatedPolicies'], "excessivePolicies": resp['excessivePolicies']} + diff --git a/assets/Data_Flow.jpg b/assets/Data_Flow.jpg new file mode 100644 index 0000000..9f4454c Binary files /dev/null and b/assets/Data_Flow.jpg differ diff --git a/assets/banner.png b/assets/banner.png new file mode 100644 index 0000000..41f130b Binary files /dev/null and b/assets/banner.png differ diff --git a/aws/awsOps.py b/aws/awsOps.py new file mode 100644 index 0000000..2bdee9a --- /dev/null +++ b/aws/awsOps.py @@ -0,0 +1,103 @@ +import json +import boto3 +from botocore.credentials import Credentials +from botocore.exceptions import ClientError, NoCredentialsError, BotoCoreError +from fastapi import HTTPException + +class AWSOperations: + def connect_to_iam_with_assumed_role(self, aws_credentials): + # Create a new session with the temporary credentials + session = boto3.Session( + aws_access_key_id=aws_credentials.access_key, + aws_secret_access_key=aws_credentials.secret_key, + aws_session_token=aws_credentials.token + ) + # Use the new session to connect to IAM + iam_client = session.client('iam') + return iam_client + + def get_iam_connection(self): + try: + with open("config.json", "r") as f: + data = json.loads(f.read()) + if data['accountType'] == "CloudFormation": + aws_credentials = self.get_assume_role_credentials(data) + iam_client = self.connect_to_iam_with_assumed_role(aws_credentials) + elif data['accountType'] == "Credential": + iam_client = self.connect("iam", data['aws_access_key_id'], data['aws_secret_access_key']) + return iam_client + except (FileNotFoundError, json.JSONDecodeError) as e: + raise HTTPException(status_code=500, detail=f"Error reading or parsing config.json: {e}") + + except (ClientError, NoCredentialsError, BotoCoreError) as e: + raise HTTPException(status_code=500, detail=f"Error connecting to IAM: {e}") + + + def connect(self,serviceName,aws_access_key_id,aws_secret_access_key): + s3Client = boto3.client(serviceName,aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key) + return s3Client + + def connect_to_s3_with_assumed_role(self,aws_credentials): + # Create a new session with the temporary credentials + session = boto3.Session( + aws_access_key_id=aws_credentials.access_key, + aws_secret_access_key=aws_credentials.secret_key, + aws_session_token=aws_credentials.token + ) + # Use the new session to connect to S3 + s3_client = session.client('s3') + return s3_client + + def getConnection(self): + try: + with open("config.json", "r") as f: + data = json.loads(f.read()) + if data['accountType'] == "CloudFormation": + aws_credentials = self.get_assume_role_credentials(data) + s3_client = self.connect_to_s3_with_assumed_role(aws_credentials) + elif data['accountType'] == "Credential": + s3_client = self.connect("s3", data['aws_access_key_id'], data['aws_secret_access_key']) + return s3_client + except (FileNotFoundError, json.JSONDecodeError) as e: + raise HTTPException(status_code=500, detail=f"Error reading or parsing config.json: {e}") + except (ClientError, NoCredentialsError, BotoCoreError) as e: + raise HTTPException(status_code=500, detail=f"Error connecting to S3: {e}") + + def get_assume_role_credentials(self, account): + try: + # Create an STS client with the IAM user's access and secret keys + sts_client = boto3.client( + 'sts', + aws_access_key_id=account['aws_access_key_id'], + aws_secret_access_key=account['aws_secret_access_key'] + ) + + # Assume the IAM role + response = sts_client.assume_role( + RoleArn=account['role_arn'], + RoleSessionName='Assume_Role_Session', + DurationSeconds=43200, + ExternalId=account['externalid'] + ) + + # Extract the temporary credentials + creds = response['Credentials'] + session_credentials = boto3.Session( + aws_access_key_id=creds['AccessKeyId'], + aws_secret_access_key=creds['SecretAccessKey'], + aws_session_token=creds['SessionToken'] + ).get_credentials() + + # Create an AwsCredentials object with the temporary credentials + aws_credentials = Credentials( + access_key=session_credentials.access_key, + secret_key=session_credentials.secret_key, + token=session_credentials.token + ) + + return aws_credentials + + except (ClientError, NoCredentialsError, BotoCoreError) as e: + raise HTTPException(status_code=500, detail=f"Error assuming role: {e}") + + diff --git a/aws/comparePolicies.py b/aws/comparePolicies.py new file mode 100644 index 0000000..99d96e2 --- /dev/null +++ b/aws/comparePolicies.py @@ -0,0 +1,177 @@ +import json +import os +from policy_sentry.querying.actions import get_actions_for_service +from redisops.redisOps import RedisOperations +import re +from concurrent.futures import ThreadPoolExecutor +from collections import defaultdict + +crudConnection = RedisOperations() +crudConnection.connect("localhost", 6379, 0) + +services = defaultdict(set) + +# hdServices = ['a4b','account','amplify','apprunner','appsync','aps','billing','codebuild','codecommit','connect','databrew','eks','emrcontainers','forecast','frauddetector','fsx','gamelift','greengrassv2','health','iot','iotanalytics','iotevents','iotfleethub','iotthingsgraph','kafka','kendra','kinesisvideo','lakeformation','licensemanager','lookoutvision','macie','managedblockchain','marketplacecatalog','mediaconnect','mediaconvert','medialive','mediapackage','mediapackage-vod','mediastore','mediastore-data','mediatailor','meteringmarketplace','migrationhub-config','mobile','mq','neptune','networkmanager','outposts','personalize','pinpoint','pinpoint-email','pinpoint-sms-voice','polly','pricing','qldb','quicksight','ram','rds-data','robomaker','route53resolver','sagemaker','sagemaker-a2i-runtime','sagemaker-edge','sagemaker-featurestore-runtime','sagemaker-runtime','savingsplans','schemas','secretsmanager','securityhub','serverlessrepo','servicecatalog','servicecatalog-appregistry','servicequotas','sesv2','shield','signer','sms','snowball','snowball-edge','sso','sso-oidc','ssm','stepfunctions','storagegateway','synthetics','textract','transcribe','transfer','translate','waf-regional','wafv2','worklink','workmail','workmailmessageflow','workspaces','xray','autoscaling','iam','ec2','s3','rds','elasticache','elasticbeanstalk','elasticloadbalancing','elasticmapreduce','cloudfront','cloudtrail','cloudwatch','cloudwatchevents','cloudwatchlogs','config','datapipeline','directconnect','dynamodb','ecr','ecs','elasticfilesystem','elastictranscoder','glacier','kinesis','kms','lambda','opsworks','redshift','route53','route53domains','sdb','ses','sns','sqs','storagegateway','sts','support','swf','waf','workspaces','xray'] +# hdServices.extend(['acm','acm-pca','alexaforbusiness','amplifybackend','appconfig','appflow','appintegrations','appmesh','appstream','appsync','athena','auditmanager','autoscaling-plans','backup','batch','braket','budgets','ce','chime','cloud9','clouddirectory','cloudformation','cloudhsm','cloudhsmv2','cloudsearch','cloudsearchdomain','cloudtrail','cloudwatch','cloudwatchevents','cloudwatchlogs','codeartifact','codebuild','codecommit','codedeploy','codeguru-reviewer','codeguru-reviewer-runtime','codeguru-profiler','codeguru-profiler-runtime','codepipeline','codestar','codestar-connections','codestar-notifications','cognito-identity','cognito-idp','cognito-sync','comprehend','comprehendmedical','compute-optimizer','connect','connect-contact-lens','connectparticipant','cur','customer-profiles','dataexchange','datapipeline','datasync','dax','detective','devicefarm','devops-guru','directconnect','discovery','dlm','dms','docdb','ds','dynamodb','dynamodbstreams','ec2','ec2-instance-connect','ecr','ecr-public','ecs','eks','elastic-inference','elasticache','elasticbeanstalk','elasticfilesystem','elasticloadbalancing','elasticloadbalancingv2','elasticmapreduce','elastictranscoder','email','es','events','firehose','fms','forecast','forecastquery','frauddetector','fsx','gamelift','glacier','globalaccelerator','glue','greengrass','greengrassv2','groundstation','guardduty','health','healthlake','honeycode','iam','identitystore','imagebuilder','importexport','inspector','iot','iot-data','iot-jobs-data','iot1click-devices','iot1click-projects','iotanalytics','iotdeviceadvisor','iotevents','iotevents-data','iotfleethub','iotsecuretunneling','iotthingsgraph','iotwireless','ivs','kafka','kendra','kinesis','kinesis-video-archived-media','kinesis-video-media','kinesis-video-signaling','kinesisvideo','kinesisanalytics','kinesisanalyticsv2','kinesisvideoarchivedmedia','kinesis']) + +def create_services_list(actions_data): + for action in actions_data: + action_data = json.loads(action) + event_source = action_data["eventSource"] + service = event_source.split(".")[0] + services[service].add(service) + +def create_service_actions_cache(services): + service_actions_cache = {} + + for service in services: + actions = get_actions_for_service(service) + service_actions_cache[service] = actions + + # for service in hdServices: + # if service in service_actions_cache: + # continue + # else: + # actions = get_actions_for_service(service) + # service_actions_cache[service] = actions + + return service_actions_cache + +def write_service_actions_cache_to_file(service_actions_cache, file_path): + with open(file_path, 'w') as f: + json.dump(service_actions_cache, f, indent=2) + +def load_policy(filepath): + with open(filepath, "r") as f: + policy = json.load(f) + return policy + +def is_valid_action(action): + return re.match(r'^[a-zA-Z0-9_]+:(\*|[a-zA-Z0-9_\*]+)$', action) + +def compare_policy_worker(present_policy_filepath, user_policy_filepath, output_filepath): + print(f"Started thread for {user_policy_filepath}") + + current_policy = load_policy(present_policy_filepath) + generated_policy = load_policy(user_policy_filepath) + + excessive_permissions = compare_policy(current_policy, generated_policy) + + with open(output_filepath, "w") as f_write: + f_write.write(json.dumps(excessive_permissions, indent=2)) + print(f"Generated excessive policy for {os.path.basename(user_policy_filepath)}") + +# def expand_wildcard_actions(actions_list, service_actions_cache=None): +# if service_actions_cache is None: +# with open("service_actions_cache.json", "r") as f: +# service_actions_cache = json.load(f) + +# expanded_actions = [] + +# for action in actions_list: +# if re.match(r'^[a-zA-Z0-9_]+:[a-zA-Z0-9_]+$', action): +# service, action_name = action.split(":") +# if service in service_actions_cache: +# if "*" in action_name: +# expanded_actions.extend([f"{a}" for a in service_actions_cache[service] if action_name.replace("*", "") in a]) +# else: +# expanded_actions.append(action) +# else: +# print(f"Warning: Service '{service}' not found in the service_actions_cache. for this the action was {action}") +# elif action == '*': +# for service in service_actions_cache: +# expanded_actions.extend([f"{a}" for a in service_actions_cache[service]]) + +# return expanded_actions + +def expand_wildcard_actions(actions_list, service_actions_cache=None): + if service_actions_cache is None: + with open("service_actions_cache.json", "r") as f: + service_actions_cache = json.load(f) + + expanded_actions = [] + + if isinstance(actions_list, str): + actions_list = [actions_list] + + for action in actions_list: + if is_valid_action(action): + service, action_name = action.split(":") + if "*" in action_name: + expanded_actions.extend([f"{a}" for a in service_actions_cache.get(service, []) if action_name.replace("*", "") in a]) + else: + expanded_actions.append(action) + + elif action == '*': + for service in service_actions_cache: + expanded_actions.extend([f"{a}" for a in service_actions_cache[service]]) + + return expanded_actions + +def compare_policy(current_policy, generated_policy): + excessive_permissions = { + "Version": "2012-10-17", + "Statement": [] + } + + for current_statement in current_policy["Statement"]: + excessive_statement = { + "Effect": current_statement["Effect"], + "Action": [], + "Resource": current_statement["Resource"] + } + + current_actions_expanded = expand_wildcard_actions(current_statement["Action"]) + + for action in current_actions_expanded: + action_in_generated = False + for generated_statement in generated_policy["Statement"]: + generated_actions_expanded = expand_wildcard_actions(generated_statement["Action"]) + + # Check if the action and resource match in both policies + if action in generated_actions_expanded: + for current_resource in current_statement["Resource"]: + if current_resource in generated_statement["Resource"]: + action_in_generated = True + break + if action_in_generated: + break + + if not action_in_generated: + excessive_statement["Action"].append(action) + + if excessive_statement["Action"]: + excessive_permissions["Statement"].append(excessive_statement) + + return excessive_permissions + +def compare_policies(): + crudKeys = crudConnection.get_all_keys() + for user_arn in crudKeys: + actions_data = crudConnection.get_list_items(user_arn) + create_services_list(actions_data) + + service_actions_cache = create_service_actions_cache(services) + write_service_actions_cache_to_file(service_actions_cache, 'service_actions_cache.json') + print("Service actions cache created successfully.") + + # present_policies_dir = "presentPolicies" + # user_policies_dir = "userPolicies" + # output_dir = "excessivePolicies" + + # if not os.path.exists(output_dir): + # os.makedirs(output_dir) + + # with ThreadPoolExecutor() as executor: + # futures = [] + # for user_policy_filename in os.listdir(user_policies_dir): + # present_policy_filepath = os.path.join(present_policies_dir, user_policy_filename) + # user_policy_filepath = os.path.join(user_policies_dir, user_policy_filename) + # output_filepath = os.path.join(output_dir, user_policy_filename) + + # if os.path.exists(present_policy_filepath): + # future = executor.submit(compare_policy_worker, present_policy_filepath, user_policy_filepath, output_filepath) + # futures.append(future) + + # for future in futures: + # future.result() diff --git a/aws/createServiceMap.py b/aws/createServiceMap.py new file mode 100644 index 0000000..9f49371 --- /dev/null +++ b/aws/createServiceMap.py @@ -0,0 +1,44 @@ +import json +import os +from policy_sentry.querying.actions import get_actions_for_service +import re +from collections import defaultdict + +services = defaultdict(set) + +def create_services_list(actions_data): + for action in actions_data: + action_data = json.loads(action) + event_source = action_data["eventSource"] + service = event_source.split(".")[0] + services[service].add(service) + +def create_service_actions_cache(services): + service_actions_cache = {} + + for service in services: + actions = get_actions_for_service(service) + service_actions_cache[service] = actions + return service_actions_cache + +def write_service_actions_cache_to_file(service_actions_cache, file_path): + with open(file_path, 'w') as f: + json.dump(service_actions_cache, f, indent=2) + +def load_policy(filepath): + with open(filepath, "r") as f: + policy = json.load(f) + return policy + +def is_valid_action(action): + return re.match(r'^[a-zA-Z0-9_]+:(\*|[a-zA-Z0-9_\*]+)$', action) + +def create_service_map(mergedData): + print("Creating service map") + for username, actions in mergedData.items(): + actions_list = [action for action in actions] + create_services_list(actions_list) + + service_actions_cache = create_service_actions_cache(services) + write_service_actions_cache_to_file(service_actions_cache, 'service_actions_cache.json') + print("Service actions cache created successfully.") diff --git a/aws/dataCleanup.py b/aws/dataCleanup.py new file mode 100644 index 0000000..1a96e6a --- /dev/null +++ b/aws/dataCleanup.py @@ -0,0 +1,26 @@ +import pendulum + +class DataCleanup: + def __init__(self, redis_connection): + self.redis_connection = redis_connection + + def cleanup(self): + now = pendulum.now() + keys_to_delete = [] + + for key in self.redis_connection.r.scan_iter("*"): + date_str = key.decode("utf-8").split("_")[2] + try: + date = pendulum.from_format(date_str, "YYYY/MM/DD") + except ValueError: + continue + + days_diff = (now - date).days + if days_diff > 90: + keys_to_delete.append(key) + + print(f"Found {len(keys_to_delete)} keys to delete.") + + for key in keys_to_delete: + self.redis_connection.r.delete(key) + print(f"Deleted key: {key.decode('utf-8')}") diff --git a/aws/getPreviousPolicies.py b/aws/getPreviousPolicies.py new file mode 100644 index 0000000..ca4b8fd --- /dev/null +++ b/aws/getPreviousPolicies.py @@ -0,0 +1,76 @@ +import os +import json +from botocore.exceptions import ClientError +from aws.awsOps import AWSOperations +from utils.colors import colors +import concurrent.futures +import re +from redisops.redisOps import RedisOperations + +arnStore = RedisOperations() +arnStore.connect("localhost",6379,2) + +def is_valid_arn(arn): + return re.match(r'^arn:aws:iam::\d{12}:user/[\w+=,.@-]+$', arn.decode()) is not None + +def get_policies_for_users(path, merged_data): + ops = AWSOperations() + iam_client = ops.get_iam_connection() + + valid_user_list = [user.encode() for user in merged_data.keys() if is_valid_arn(user.encode())] + + with concurrent.futures.ThreadPoolExecutor() as executor: + futures = [executor.submit(get_previous_policies, iam_client, path, user.decode()) for user in valid_user_list] + + for future in concurrent.futures.as_completed(futures): + try: + future.result() + except Exception as e: + print(f"Error occurred during parallel processing: {e}") + +def get_previous_policies(iam_client,path, current_user): + user_arn = current_user + current_user = current_user.split("/")[-1] + arnStore.insertKeyVal(current_user, user_arn) + + print(f"Started Thread for Fetching policies for {current_user}") + try: + if isinstance(current_user, bytes): + current_user = current_user.decode() + + policy_dict = {'Version': '2012-10-17', 'Statement': []} + + if user_exists(iam_client, current_user): + policies = iam_client.list_attached_user_policies(UserName=current_user)['AttachedPolicies'] + inline_policies = iam_client.list_user_policies(UserName=current_user)['PolicyNames'] + + # Fetch managed policies + for policy in policies: + policy_arn = policy['PolicyArn'] + policy_version = iam_client.get_policy(PolicyArn=policy_arn)['Policy']['DefaultVersionId'] + policy_doc = iam_client.get_policy_version(PolicyArn=policy_arn, VersionId=policy_version)['PolicyVersion']['Document'] + policy_dict['Statement'].extend(policy_doc['Statement']) + + # Fetch inline policies + for policy_name in inline_policies: + policy_doc = iam_client.get_user_policy(UserName=current_user, PolicyName=policy_name)['PolicyDocument'] + policy_dict['Statement'].extend(policy_doc['Statement']) + else: + print(f"User {current_user} does not exist. Creating an empty policy.") + + outfileName = f'policy_{current_user}.json' + outfileName = outfileName.replace(":","-").replace("/","_").replace("\\","__") + with open(os.path.join(path, outfileName), 'w') as f: + json.dump(policy_dict, f, indent=2) + + print( + f"Fetched Present Policies for {current_user}") + except ClientError as e: + print(f"Error occurred: {e}") + +def user_exists(iam_client, user_name): + try: + iam_client.get_user(UserName=user_name) + return True + except iam_client.exceptions.NoSuchEntityException: + return False \ No newline at end of file diff --git a/aws/policygenOps.py b/aws/policygenOps.py new file mode 100644 index 0000000..995463d --- /dev/null +++ b/aws/policygenOps.py @@ -0,0 +1,135 @@ +import ijson +import gzip +import re +import os +from tqdm import tqdm +from utils.colors import colors +from redisops.redisOps import RedisOperations +import json +# from policy_sentry.writing.template import get_crud_template_dict +# from policy_sentry.command.write_policy import write_policy_with_template +from collections import defaultdict + +crudConnection = RedisOperations() +crudConnection.connect("localhost",6379,0) +arnStore = RedisOperations() +arnStore.connect("localhost",6379,2) + +def get_event_type(event_name): + read_events = ["^Get", "^Describe", "^Head"] + write_events = ["^Create", "^Put", "^Post", "^Copy", + "^Complete", "^Delete", "^Update", "^Modify"] + tagging_events = ["^Tag", "^Untag"] + list_events = ["^List"] + for pattern in read_events: + if re.search(pattern, event_name): + return "read" + + for pattern in write_events: + if re.search(pattern, event_name): + return "write" + + for pattern in tagging_events: + if re.search(pattern, event_name): + return "tagging" + for pattern in list_events: + if re.search(pattern,event_name): + return "list" + return None + +def load_service_actions_cache(file_path): + with open(file_path, 'r') as f: + return json.load(f) + +def load_service_replace_map(file_path): + with open(file_path, 'r') as f: + return json.load(f) + +def generate_least_privilege_policy(user_arn, actions_data, service_actions_cache, service_replace_map): + policy = { + "Version": "2012-10-17", + "Statement": [] + } + resource_actions = defaultdict(lambda: defaultdict(set)) + + for action_data in actions_data: + if action_data["username"] != user_arn: + continue + + service = action_data['eventSource'].split('.')[0] + action = f"{service}:{action_data['eventName']}" + + if action in service_replace_map: + action = service_replace_map[action] + + if action not in service_actions_cache.get(service, []): + continue + + resource = action_data['arn'] + resource_prefix = resource.split(':')[5].split('/')[0] + resource_actions[resource_prefix][resource].add(action) + + for resource_prefix, resources in resource_actions.items(): + statement = { + "Effect": "Allow", + "Action": [], + "Resource": [] + } + + for resource, actions in resources.items(): + statement["Action"].extend(actions) + statement["Resource"].append(resource) + + statement["Action"] = list(set(statement["Action"])) + policy["Statement"].append(statement) + + policy_json = json.dumps(policy) + + if len(policy_json) > 6144: + print(f"Generated policy exceeds the 6144 character limit for {user_arn}") + + return policy + +def generateLeastprivPolicies(user_arn, policy_output_dir, actions_list): + service_actions_cache = load_service_actions_cache("service_actions_cache.json") + service_replace_map = load_service_replace_map("service_replace_map.json") + policy = generate_least_privilege_policy(user_arn, actions_list, service_actions_cache, service_replace_map) + username = user_arn.split("/")[-1] + filename = f'policy_{username}.json' + filename = filename.replace(":", "-").replace("/", "_").replace("\\", "__") + + with open(os.path.join(policy_output_dir, filename), "w") as f_write: + f_write.write(json.dumps(policy, indent=2)) + print(f"Generated policy for {username}") + + +def runPolicyGeneratorCRUD(filePath,date,region,bucketName, accountID): + with gzip.open(f"{filePath}", 'rt') as f: + parser = ijson.parse(f) + startKey = "Records.item.eventVersion" + startLoop = False + currentBlock = {} + + for prefix, event, value in parser: + if prefix == startKey: + if startLoop == False: + startLoop = True + else: + startLoop = False + if currentBlock.get("username") is not None and currentBlock.get("arn") is not None: + userNameCB = currentBlock.get("username") + outerKey = f"{accountID}_{bucketName}_{date}_{region}" + crudConnection.push_back_nested_json(outerKey, userNameCB, currentBlock) + currentBlock = {} + if startLoop: + if prefix == "Records.item.resources.item.ARN": + currentBlock["arn"] = value + if prefix == "Records.item.userIdentity.type": + currentBlock["userIdentityType"] = value + if prefix == "Records.item.userIdentity.arn" and currentBlock.get("userIdentityType") == "IAMUser": + currentBlock["username"] = value + if prefix == "Records.item.eventSource": + currentBlock["eventSource"] = value + if prefix == "Records.item.eventName": + currentBlock["eventName"] = value + diff --git a/aws/s3Ops.py b/aws/s3Ops.py new file mode 100644 index 0000000..f7bb4a6 --- /dev/null +++ b/aws/s3Ops.py @@ -0,0 +1,221 @@ +from aws.awsOps import AWSOperations +import json +from utils import helpers +from utils.colors import colors +# from constants import default_regions +from tqdm import tqdm +import os +import time +# from datetime import datetime +import threading +from aws.policygenOps import runPolicyGeneratorCRUD , generateLeastprivPolicies +from redisops.redisOps import RedisOperations +from aws.getPreviousPolicies import get_policies_for_users +from aws.comparePolicies import compare_policies +from aws.createServiceMap import create_service_map +from contextlib import contextmanager +import pendulum +from pendulum import timezone +from concurrent.futures import ThreadPoolExecutor +import itertools +from aws.dataCleanup import DataCleanup + +completedBucketsLock = threading.Lock() + +utc_timezone = timezone("UTC") +pendulum.set_local_timezone(utc_timezone) + +@contextmanager +def measure_time_block(message: str = "Execution time"): + start = time.time() + yield + end = time.time() + duration = end - start + + if duration >= 3600: + hours = int(duration // 3600) + duration %= 3600 + print(f"{message} completed in {hours} hour(s) {int(duration // 60)} minute(s) {duration % 60:.2f} second(s)") + elif duration >= 60: + minutes = int(duration // 60) + print(f"{message} completed in {minutes} minute(s) {duration % 60:.2f} second(s)") + else: + print(f"{message} completed in {duration:.2f} second(s)") + + +class s3Operations(AWSOperations): + def __init__(self): + super().__init__() + self.crudConnection = RedisOperations() + self.crudConnection.connect("localhost", 6379, 0) + self.data_cleanup = DataCleanup(self.crudConnection) + + def getConfig(self): + with open("config.json", "r") as f: + data = json.loads(f.read()) + return data + + def mergeData(self, accountId, num_days, bucketData): + print(f"Merging data for {num_days}") + now = pendulum.now() + previousData = [(now - pendulum.duration(days=i)).strftime("%Y/%m/%d") for i in range(num_days)] + merged_data = {} + + for bucketName, regions in bucketData.items(): + for region, date in itertools.product(regions, previousData): + day_data_str = self.crudConnection.read_json(f"{bucketName}_{accountId}_{date}_{region}") + if day_data_str: + for username, actions in day_data_str.items(): + if username not in merged_data: + merged_data[username] = set(actions) + else: + merged_data[username].update(actions) + + # Convert sets back to lists + for username in merged_data: + merged_data[username] = list(merged_data[username]) + return merged_data + + def is_request_processed(self, account_id, bucket_name, date, region): + outer_key = f"{bucket_name}_{account_id}_{date}_{region}" + return self.crudConnection.exists(outer_key) + + def getObjects(self, completedBuckets, bucketData, num_days,unique_id): + self.data_cleanup.cleanup() + try: + config = self.getConfig() + accountId = config['accountId'] + today = pendulum.now() + endDay = today.date() + startDay = today.subtract(days=num_days).date() + + day_diff = (endDay - startDay).days + 1 + + for bucketName, regions in bucketData.items(): + + thread = threading.Thread(target=bucketThreadFn, args=(completedBuckets, bucketName, regions, startDay, endDay, accountId, day_diff,unique_id)) + thread.start() + + except KeyError as err: + print(helpers.colors.FAIL + "Invalid key " + str(err)) + + except Exception as exp: + helpers.logException(exp) + + def getPolicies(self, account_id, num_days, bucketData,unique_id): + user_policies_dir = f"userPolicies_{account_id}_{unique_id}" + present_policies_dir = f"presentPolicies_{account_id}_{unique_id}" + + mergedData = self.mergeData(account_id,num_days, bucketData) + create_service_map(mergedData) + + with measure_time_block("Generating Policies"): + print("Generating Policies") + for username, actions in mergedData.items(): + actions_list = [json.loads(action) for action in actions] + generateLeastprivPolicies(username, user_policies_dir, actions_list) + + with measure_time_block("Getting Present Policies"): + print("Getting Present Policies") + get_policies_for_users(present_policies_dir, mergedData) + + # with measure_time_block("Comparing the policies"): + # print("Comparing the policies to get excessive policies") + # compare_policies() + +def bucketThreadFn(completedBuckets, bucketName, regions, startDay, endDay, accountId, day_diff,unique_id): + print("Started thread for Bucket : " + bucketName) + + s3Ops = s3Operations() + s3Client = s3Ops.getConnection() + + completedRegions = [] + region_events = [threading.Event() for _ in regions] + + with ThreadPoolExecutor(max_workers=5) as executor: + for idx, region in enumerate(regions): + executor.submit(regionThreadFn, startDay, endDay, accountId, region, s3Client, bucketName, completedRegions, region_events[idx],unique_id) + + for event in region_events: + event.wait() + + with completedBucketsLock: + completedBuckets.append(bucketName) + print(f"Completed thread for Bucket : {bucketName}") + + +def regionThreadFn(startDay, endDay, accountId, region, s3Client, bucketName ,completedRegions,region_event,unique_id): + + print(f"Starting thread for {region}") + completedDays = [] + day_threads = [] + + day = startDay + while day <= endDay: + thread = threading.Thread(target=dayThreadFn, args=(day, accountId, region, s3Client, bucketName,completedDays,unique_id)) + day_threads.append(thread) + thread.start() + day = day.add(days=1) + + for thread in day_threads: + thread.join() + + print(f"Completed thread for {region}") + completedRegions.append(region) + region_event.set() + + +def dayThreadFn(day, accountId, region, s3Client, bucketName, completedDays,unique_id): + + date_str = day.strftime("%Y/%m/%d") + s3obj = s3Operations() + + if s3obj.is_request_processed(accountId, bucketName, date_str, region): + print(f"Skipping {region} : {date_str} as it has already been processed") + completedDays.append(day) + return + + try: + print(f"Starting thread for {region} : {day.format('YYYY/MM/DD')}") + prefix = f"AWSLogs/{accountId}/CloudTrail/{region}/{day.format('YYYY/MM/DD')}" + response = s3Client.list_objects(Bucket=bucketName, Prefix=prefix) + contents = response.get('Contents', []) + + total_items = len(contents) + processed_items = 0 + + for item in contents: + key = str(item['Key']) + filePath = key.split('/')[-1] + with open(os.path.join(f"logs_{accountId}_{unique_id}", filePath), "wb") as data: + s3Client.download_fileobj(bucketName, key, data) + downloaded = False + retry_count = 0 + max_retries = 3 + + while not downloaded and retry_count < max_retries: + try: + runPolicyGeneratorCRUD(f"logs_{accountId}_{unique_id}/{filePath}", f"{day.format('YYYY/MM/DD')}", region, accountId, bucketName) + os.remove(f"logs_{accountId}_{unique_id}/{filePath}") + downloaded = True + except OSError as e: + if e.errno == 32: + time.sleep(0.1) + else: + retry_count += 1 + time.sleep(1) + except Exception as e: + print(f"Error in runPolicyGeneratorCRUD for {region} : {day.format('YYYY/MM/DD')}: {str(e)}") + retry_count += 1 + time.sleep(1) + + processed_items += 1 + print(f"Processed {processed_items}/{total_items} items for {region} : {day.format('YYYY/MM/DD')}") + + print(f"Completed thread for {region} : {day.format('YYYY/MM/DD')}") + completedDays.append(day) + + except Exception as e: + print(f"Error in dayThreadFn for {region} : {day.format('YYYY/MM/DD')}: {str(e)}") + + diff --git a/aws/todo.md b/aws/todo.md new file mode 100644 index 0000000..fa790cb --- /dev/null +++ b/aws/todo.md @@ -0,0 +1,3 @@ +1. Fix the timing window +2. Integrate the timing window through out the application +3. test the code in and out. diff --git a/constants.py b/constants.py new file mode 100644 index 0000000..24bf5a5 --- /dev/null +++ b/constants.py @@ -0,0 +1,7 @@ +aws_regions_testing = ["us-east-1"] + +aws_regions = ["us-east-2", "us-east-1", "us-west-1", "us-west-2", "ap-south-1", "ap-northeast-3", "ap-northeast-2", "ap-southeast-1", + "ap-southeast-2", "ap-northeast-1", "ca-central-1", "eu-central-1", "eu-west-1", "eu-west-2", "eu-west-3", "eu-north-1", "sa-east-1"] + +default_regions = aws_regions +# default_regions = aws_regions_testing diff --git a/redisTest.py b/redisTest.py new file mode 100644 index 0000000..db74b4d --- /dev/null +++ b/redisTest.py @@ -0,0 +1,10 @@ +import json +from redisops.redisOps import RedisOperations + +redis_ops = RedisOperations() +redis_ops.connect("localhost", 6379, 0) +redis_dump = redis_ops.get_redis_dump() + +# Print the JSON dump in a pretty format + +print(json.dumps(redis_dump, indent=2)) diff --git a/redisops/redisOps.py b/redisops/redisOps.py new file mode 100644 index 0000000..6e83c5f --- /dev/null +++ b/redisops/redisOps.py @@ -0,0 +1,93 @@ +import redis +import json + +class RedisOperations: + def connect(self,host,port,dbNum): + self.r = redis.Redis(host=host,port=port,db=dbNum) + + def insertKeyVal(self,key,value): + self.r.set(key,value) + + def createList(self,key,value_list): + for item in value_list: + self.r.rpush(key,item) + + # insert a value at the end of a list + def push_back(self,key,value): + self.r.rpush(key,value) + + # insert a value at the front of a list + def push_front(self,key,value): + self.r.lpush(key,value) + + def push_back_json(self, key, jsonObj): + jsonStr = json.dumps(jsonObj) + pos = self.r.lpos(key, jsonStr) + if pos == None: + self.r.rpush(key, jsonStr) + + def pop_back(self,key): + self.r.rpop(key) + + def pop_front(self,key): + self.r.lpop(key) + + def insert_json(self,key,json_object): + self.r.set(key,json.dumps(json_object)) + + def read_json(self, key): + val = self.r.get(key) + if val is not None: + return json.loads(val.decode()) + return None + + def insert_jsonobj_list(self,key,listOfJsonObjects): + for jsonObject in listOfJsonObjects: + self.push_back(key,json.dumps(jsonObject)) + + def get_list_items(self,key): + items = self.r.lrange(key,0,-1) + return items + + def get_all_keys(self): + return self.r.scan_iter() + + # flush all keys from current DB + def flushdb(self): + self.r.flushdb() + + def push_back_nested_json(self, outer_key, inner_key, jsonObj): + jsonStr = json.dumps(jsonObj) + current_data_str = self.r.get(outer_key) + if current_data_str: + current_data = json.loads(current_data_str) + else: + current_data = {} + + if inner_key not in current_data: + current_data[inner_key] = [] + + if jsonStr not in current_data[inner_key]: + current_data[inner_key].append(jsonStr) + + self.r.set(outer_key, json.dumps(current_data)) + + def get_redis_dump(self): + all_keys = self.r.keys() + redis_dump = {} + for key in all_keys: + key_str = key.decode() + value = self.r.get(key) + if value: + try: + value_json = json.loads(value) + except json.JSONDecodeError: + value_json = value.decode() + redis_dump[key_str] = value_json + else: + list_items = self.r.lrange(key, 0, -1) + redis_dump[key_str] = [json.loads(item) for item in list_items] + return redis_dump + + def exists(self, key): + return self.r.exists(key) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..ab76e7b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +boto3==1.26.87 +botocore==1.29.87 +fastapi==0.95.0 +httpx==0.23.3 +ijson==3.2.0.post0 +pendulum==2.1.2 +policy_sentry==0.12.6 +pydantic==1.10.6 +PyYAML==6.0 +redis==4.5.4 +tqdm==4.64.1 +uvicorn==0.21.1 +mangum==0.17.0 diff --git a/runner.py b/runner.py new file mode 100644 index 0000000..37d33a7 --- /dev/null +++ b/runner.py @@ -0,0 +1,156 @@ +from aws.s3Ops import s3Operations +import os +import shutil +import time +import json +import glob +from redisops.redisOps import RedisOperations +from contextlib import contextmanager +import uuid + +arnStore = RedisOperations() +arnStore.connect("localhost", 6379, 2) + +unique_id = uuid.uuid4().hex[:6] + +@contextmanager +def measure_time_block(message: str = "Execution time"): + start = time.time() + yield + end = time.time() + duration = end - start + + if duration >= 3600: + hours = int(duration // 3600) + duration %= 3600 + print(f"{message} completed in {hours} hour(s) {int(duration // 60)} minute(s) {duration % 60:.2f} second(s)") + elif duration >= 60: + minutes = int(duration // 60) + print(f"{message} completed in {minutes} minute(s) {duration % 60:.2f} second(s)") + else: + print(f"{message} completed in {duration:.2f} second(s)") + +def create_dirs(account_id): + base_dir = os.path.dirname(os.path.abspath(__file__)) + directories = [ + os.path.join(base_dir, f"logs_{account_id}_{unique_id}"), + os.path.join(base_dir, f"userPolicies_{account_id}_{unique_id}"), + os.path.join(base_dir, f"presentPolicies_{account_id}_{unique_id}"), + # os.path.join(base_dir, f"excessivePolicies_{account_id}"), + ] + for directory in directories: + if not os.path.exists(directory): + os.makedirs(directory) + + empty_directory(f"logs_{account_id}_{unique_id}") + empty_directory(f"userPolicies_{account_id}_{unique_id}") + empty_directory(f"presentPolicies_{account_id}_{unique_id}") + # empty_directory(f"excessivePolicies_{account_id}") + +def empty_directory(directory_name): + base_dir = os.path.dirname(os.path.abspath(__file__)) + directory_path = os.path.join(base_dir, directory_name) + + if not os.path.exists(directory_path): + print(f"Path '{directory_path}' does not exist.") + return + + for file in os.listdir(directory_path): + file_path = os.path.join(directory_path, file) + try: + if os.path.isfile(file_path) or os.path.islink(file_path): + os.unlink(file_path) + elif os.path.isdir(file_path): + shutil.rmtree(file_path) + except Exception as e: + print(f"Failed to delete {file_path}. Reason: {e}") + + print(f"Emptied directory: {directory_path}") + + +def get_policy_from_file(folder, username): + filename = f"{username}.json" + filepath = os.path.join(folder, filename) + with open(filepath, 'r') as f: + return json.load(f) + + +def get_user_arn(username): + user_arn = arnStore.r.get(username) + if user_arn is None: + return None + return user_arn.decode() + + +def load_policies_from_directory(directory_name: str): + base_dir = os.path.dirname(os.path.abspath(__file__)) + policies_path = os.path.join(base_dir, directory_name) + policies_files = glob.glob(os.path.join(policies_path, "policy_*.json")) + + policies = {} + + for file_path in policies_files: + with open(file_path, 'r') as policy_file: + policy = json.load(policy_file) + + username = os.path.basename(file_path).replace('policy_', '').replace('.json', '') + user_arn = get_user_arn(username) + policies[user_arn] = policy + + return policies + + +def reformat_bucket_data(bucket_data): + reformatted_data = {} + for region, bucket_name in bucket_data.items(): + if bucket_name in reformatted_data: + reformatted_data[bucket_name].append(region) + else: + reformatted_data[bucket_name] = [region] + return reformatted_data + +def runner(accountType,aws_access_key_id,aws_secret_access_key,accountId,num_days,bucketData,role_arn,externalid): + print(f"Running for {num_days} days") + with measure_time_block("Data Population"): + create_dirs(accountId) + s3Ops = s3Operations() + + print("Starting to generate Heap") + + bucketData = reformat_bucket_data(bucketData) + + config_data = { + "accountType": accountType, + "bucketData": bucketData, + "aws_access_key_id": aws_access_key_id, + "aws_secret_access_key": aws_secret_access_key, + "externalid": externalid, + "role_arn": role_arn, + "accountId": accountId + } + + with open('config.json', 'w') as config_file: + json.dump(config_data, config_file) + + completedBuckets = [] + + s3Ops.getObjects(completedBuckets,bucketData,num_days,unique_id) + + while len(completedBuckets) < len(bucketData): + time.sleep(10) + + print("Generating Policies") + s3Ops.getPolicies(accountId, num_days, bucketData,unique_id) + + generated_policies = load_policies_from_directory(f"userPolicies_{accountId}_{unique_id}") + consolidated_policies = load_policies_from_directory(f"presentPolicies_{accountId}_{unique_id}") + excessive_policies = load_policies_from_directory(f"excessivePolicies_{accountId}_{unique_id}") + + response = { + "accountId": accountId, + "generatedPolicies": generated_policies, + "consolidatedPolicies": consolidated_policies, + "excessivePolicies": excessive_policies, + } + + return response diff --git a/schemas.py b/schemas.py new file mode 100644 index 0000000..9cb7684 --- /dev/null +++ b/schemas.py @@ -0,0 +1,12 @@ +from pydantic import BaseModel +from typing import Dict + +class Script(BaseModel): + accountType: str + accessKey: str + secretKey: str + externalId: str + roleArn: str + accountId: str + days: int + bucketData: Dict[str, str] diff --git a/service_actions_cache.json b/service_actions_cache.json new file mode 100644 index 0000000..9faffcb --- /dev/null +++ b/service_actions_cache.json @@ -0,0 +1,292 @@ +{ + "sts": [ + "sts:AssumeRole", + "sts:AssumeRoleWithSAML", + "sts:AssumeRoleWithWebIdentity", + "sts:DecodeAuthorizationMessage", + "sts:GetAccessKeyInfo", + "sts:GetCallerIdentity", + "sts:GetFederationToken", + "sts:GetServiceBearerToken", + "sts:GetSessionToken", + "sts:SetSourceIdentity", + "sts:TagSession" + ], + "s3": [ + "s3:AbortMultipartUpload", + "s3:BypassGovernanceRetention", + "s3:CreateAccessPoint", + "s3:CreateAccessPointForObjectLambda", + "s3:CreateBucket", + "s3:CreateJob", + "s3:CreateMultiRegionAccessPoint", + "s3:DeleteAccessPoint", + "s3:DeleteAccessPointForObjectLambda", + "s3:DeleteAccessPointPolicy", + "s3:DeleteAccessPointPolicyForObjectLambda", + "s3:DeleteBucket", + "s3:DeleteBucketPolicy", + "s3:DeleteBucketWebsite", + "s3:DeleteJobTagging", + "s3:DeleteMultiRegionAccessPoint", + "s3:DeleteObject", + "s3:DeleteObjectTagging", + "s3:DeleteObjectVersion", + "s3:DeleteObjectVersionTagging", + "s3:DeleteStorageLensConfiguration", + "s3:DeleteStorageLensConfigurationTagging", + "s3:DescribeJob", + "s3:DescribeMultiRegionAccessPointOperation", + "s3:GetAccelerateConfiguration", + "s3:GetAccessPoint", + "s3:GetAccessPointConfigurationForObjectLambda", + "s3:GetAccessPointForObjectLambda", + "s3:GetAccessPointPolicy", + "s3:GetAccessPointPolicyForObjectLambda", + "s3:GetAccessPointPolicyStatus", + "s3:GetAccessPointPolicyStatusForObjectLambda", + "s3:GetAccountPublicAccessBlock", + "s3:GetAnalyticsConfiguration", + "s3:GetBucketAcl", + "s3:GetBucketCORS", + "s3:GetBucketLocation", + "s3:GetBucketLogging", + "s3:GetBucketNotification", + "s3:GetBucketObjectLockConfiguration", + "s3:GetBucketOwnershipControls", + "s3:GetBucketPolicy", + "s3:GetBucketPolicyStatus", + "s3:GetBucketPublicAccessBlock", + "s3:GetBucketRequestPayment", + "s3:GetBucketTagging", + "s3:GetBucketVersioning", + "s3:GetBucketWebsite", + "s3:GetEncryptionConfiguration", + "s3:GetIntelligentTieringConfiguration", + "s3:GetInventoryConfiguration", + "s3:GetJobTagging", + "s3:GetLifecycleConfiguration", + "s3:GetMetricsConfiguration", + "s3:GetMultiRegionAccessPoint", + "s3:GetMultiRegionAccessPointPolicy", + "s3:GetMultiRegionAccessPointPolicyStatus", + "s3:GetObject", + "s3:GetObjectAcl", + "s3:GetObjectAttributes", + "s3:GetObjectLegalHold", + "s3:GetObjectRetention", + "s3:GetObjectTagging", + "s3:GetObjectTorrent", + "s3:GetObjectVersion", + "s3:GetObjectVersionAcl", + "s3:GetObjectVersionAttributes", + "s3:GetObjectVersionForReplication", + "s3:GetObjectVersionTagging", + "s3:GetObjectVersionTorrent", + "s3:GetReplicationConfiguration", + "s3:GetStorageLensConfiguration", + "s3:GetStorageLensConfigurationTagging", + "s3:GetStorageLensDashboard", + "s3:InitiateReplication", + "s3:ListAccessPoints", + "s3:ListAccessPointsForObjectLambda", + "s3:ListAllMyBuckets", + "s3:ListBucket", + "s3:ListBucketMultipartUploads", + "s3:ListBucketVersions", + "s3:ListJobs", + "s3:ListMultiRegionAccessPoints", + "s3:ListMultipartUploadParts", + "s3:ListStorageLensConfigurations", + "s3:ObjectOwnerOverrideToBucketOwner", + "s3:PutAccelerateConfiguration", + "s3:PutAccessPointConfigurationForObjectLambda", + "s3:PutAccessPointPolicy", + "s3:PutAccessPointPolicyForObjectLambda", + "s3:PutAccessPointPublicAccessBlock", + "s3:PutAccountPublicAccessBlock", + "s3:PutAnalyticsConfiguration", + "s3:PutBucketAcl", + "s3:PutBucketCORS", + "s3:PutBucketLogging", + "s3:PutBucketNotification", + "s3:PutBucketObjectLockConfiguration", + "s3:PutBucketOwnershipControls", + "s3:PutBucketPolicy", + "s3:PutBucketPublicAccessBlock", + "s3:PutBucketRequestPayment", + "s3:PutBucketTagging", + "s3:PutBucketVersioning", + "s3:PutBucketWebsite", + "s3:PutEncryptionConfiguration", + "s3:PutIntelligentTieringConfiguration", + "s3:PutInventoryConfiguration", + "s3:PutJobTagging", + "s3:PutLifecycleConfiguration", + "s3:PutMetricsConfiguration", + "s3:PutMultiRegionAccessPointPolicy", + "s3:PutObject", + "s3:PutObjectAcl", + "s3:PutObjectLegalHold", + "s3:PutObjectRetention", + "s3:PutObjectTagging", + "s3:PutObjectVersionAcl", + "s3:PutObjectVersionTagging", + "s3:PutReplicationConfiguration", + "s3:PutStorageLensConfiguration", + "s3:PutStorageLensConfigurationTagging", + "s3:ReplicateDelete", + "s3:ReplicateObject", + "s3:ReplicateTags", + "s3:RestoreObject", + "s3:UpdateJobPriority", + "s3:UpdateJobStatus" + ], + "ssm": [ + "ssm:AddTagsToResource", + "ssm:AssociateOpsItemRelatedItem", + "ssm:CancelCommand", + "ssm:CancelMaintenanceWindowExecution", + "ssm:CreateActivation", + "ssm:CreateAssociation", + "ssm:CreateAssociationBatch", + "ssm:CreateDocument", + "ssm:CreateMaintenanceWindow", + "ssm:CreateOpsItem", + "ssm:CreateOpsMetadata", + "ssm:CreatePatchBaseline", + "ssm:CreateResourceDataSync", + "ssm:DeleteActivation", + "ssm:DeleteAssociation", + "ssm:DeleteDocument", + "ssm:DeleteInventory", + "ssm:DeleteMaintenanceWindow", + "ssm:DeleteOpsMetadata", + "ssm:DeleteParameter", + "ssm:DeleteParameters", + "ssm:DeletePatchBaseline", + "ssm:DeleteResourceDataSync", + "ssm:DeregisterManagedInstance", + "ssm:DeregisterPatchBaselineForPatchGroup", + "ssm:DeregisterTargetFromMaintenanceWindow", + "ssm:DeregisterTaskFromMaintenanceWindow", + "ssm:DescribeActivations", + "ssm:DescribeAssociation", + "ssm:DescribeAssociationExecutionTargets", + "ssm:DescribeAssociationExecutions", + "ssm:DescribeAutomationExecutions", + "ssm:DescribeAutomationStepExecutions", + "ssm:DescribeAvailablePatches", + "ssm:DescribeDocument", + "ssm:DescribeDocumentParameters", + "ssm:DescribeDocumentPermission", + "ssm:DescribeEffectiveInstanceAssociations", + "ssm:DescribeEffectivePatchesForPatchBaseline", + "ssm:DescribeInstanceAssociationsStatus", + "ssm:DescribeInstanceInformation", + "ssm:DescribeInstancePatchStates", + "ssm:DescribeInstancePatchStatesForPatchGroup", + "ssm:DescribeInstancePatches", + "ssm:DescribeInstanceProperties", + "ssm:DescribeInventoryDeletions", + "ssm:DescribeMaintenanceWindowExecutionTaskInvocations", + "ssm:DescribeMaintenanceWindowExecutionTasks", + "ssm:DescribeMaintenanceWindowExecutions", + "ssm:DescribeMaintenanceWindowSchedule", + "ssm:DescribeMaintenanceWindowTargets", + "ssm:DescribeMaintenanceWindowTasks", + "ssm:DescribeMaintenanceWindows", + "ssm:DescribeMaintenanceWindowsForTarget", + "ssm:DescribeOpsItems", + "ssm:DescribeParameters", + "ssm:DescribePatchBaselines", + "ssm:DescribePatchGroupState", + "ssm:DescribePatchGroups", + "ssm:DescribePatchProperties", + "ssm:DescribeSessions", + "ssm:DisassociateOpsItemRelatedItem", + "ssm:GetAutomationExecution", + "ssm:GetCalendar", + "ssm:GetCalendarState", + "ssm:GetCommandInvocation", + "ssm:GetConnectionStatus", + "ssm:GetDefaultPatchBaseline", + "ssm:GetDeployablePatchSnapshotForInstance", + "ssm:GetDocument", + "ssm:GetInventory", + "ssm:GetInventorySchema", + "ssm:GetMaintenanceWindow", + "ssm:GetMaintenanceWindowExecution", + "ssm:GetMaintenanceWindowExecutionTask", + "ssm:GetMaintenanceWindowExecutionTaskInvocation", + "ssm:GetMaintenanceWindowTask", + "ssm:GetManifest", + "ssm:GetOpsItem", + "ssm:GetOpsMetadata", + "ssm:GetOpsSummary", + "ssm:GetParameter", + "ssm:GetParameterHistory", + "ssm:GetParameters", + "ssm:GetParametersByPath", + "ssm:GetPatchBaseline", + "ssm:GetPatchBaselineForPatchGroup", + "ssm:GetServiceSetting", + "ssm:LabelParameterVersion", + "ssm:ListAssociationVersions", + "ssm:ListAssociations", + "ssm:ListCommandInvocations", + "ssm:ListCommands", + "ssm:ListComplianceItems", + "ssm:ListComplianceSummaries", + "ssm:ListDocumentMetadataHistory", + "ssm:ListDocumentVersions", + "ssm:ListDocuments", + "ssm:ListInstanceAssociations", + "ssm:ListInventoryEntries", + "ssm:ListOpsItemEvents", + "ssm:ListOpsItemRelatedItems", + "ssm:ListOpsMetadata", + "ssm:ListResourceComplianceSummaries", + "ssm:ListResourceDataSync", + "ssm:ListTagsForResource", + "ssm:ModifyDocumentPermission", + "ssm:PutCalendar", + "ssm:PutComplianceItems", + "ssm:PutConfigurePackageResult", + "ssm:PutInventory", + "ssm:PutParameter", + "ssm:RegisterDefaultPatchBaseline", + "ssm:RegisterManagedInstance", + "ssm:RegisterPatchBaselineForPatchGroup", + "ssm:RegisterTargetWithMaintenanceWindow", + "ssm:RegisterTaskWithMaintenanceWindow", + "ssm:RemoveTagsFromResource", + "ssm:ResetServiceSetting", + "ssm:ResumeSession", + "ssm:SendAutomationSignal", + "ssm:SendCommand", + "ssm:StartAssociationsOnce", + "ssm:StartAutomationExecution", + "ssm:StartChangeRequestExecution", + "ssm:StartSession", + "ssm:StopAutomationExecution", + "ssm:TerminateSession", + "ssm:UnlabelParameterVersion", + "ssm:UpdateAssociation", + "ssm:UpdateAssociationStatus", + "ssm:UpdateDocument", + "ssm:UpdateDocumentDefaultVersion", + "ssm:UpdateDocumentMetadata", + "ssm:UpdateInstanceAssociationStatus", + "ssm:UpdateInstanceInformation", + "ssm:UpdateMaintenanceWindow", + "ssm:UpdateMaintenanceWindowTarget", + "ssm:UpdateMaintenanceWindowTask", + "ssm:UpdateManagedInstanceRole", + "ssm:UpdateOpsItem", + "ssm:UpdateOpsMetadata", + "ssm:UpdatePatchBaseline", + "ssm:UpdateResourceDataSync", + "ssm:UpdateServiceSetting" + ] +} \ No newline at end of file diff --git a/service_replace_map.json b/service_replace_map.json new file mode 100644 index 0000000..5aee592 --- /dev/null +++ b/service_replace_map.json @@ -0,0 +1,6 @@ +{ + "s3:HeadObject": "s3:GetObject", + "s3:HeadBucket": "s3:ListBucket", + "s3:ListObjects": "s3:ListBucket", + "s3:GetBucketReplication": "s3:GetReplicationConfiguration" +} diff --git a/utils/colors.py b/utils/colors.py new file mode 100644 index 0000000..8e3ea9f --- /dev/null +++ b/utils/colors.py @@ -0,0 +1,13 @@ +class colors: + HEADER = '\033[95m' + OKBLUE = '\033[94m' + OKCYAN = '\033[96m' + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + +def yellowPrint(message): + print( message) \ No newline at end of file diff --git a/utils/helpers.py b/utils/helpers.py new file mode 100644 index 0000000..aac2444 --- /dev/null +++ b/utils/helpers.py @@ -0,0 +1,75 @@ +from utils.colors import colors +import os +import datetime +import calendar + +def fatal(message): + assert type(message) == str + print(colors.FAIL + message) + exit(0) + +def logException(exp): + print(exp) + exit(0) + +def getTimings(num_days): + today = datetime.datetime.now() + end_day = today - datetime.timedelta(days=1) + start_day = end_day - datetime.timedelta(days=num_days - 1) + start_month = start_day.strftime("%m") + start_year = start_day.strftime("%Y") + end_year = end_day.strftime("%Y") + end_month = end_day.strftime("%m") + days_in_current_month = calendar.monthrange(int(end_year), int(end_month))[1] + days_left_in_current_month = days_in_current_month - end_day.day + + if num_days <= days_in_current_month - days_left_in_current_month: + today = datetime.datetime.now() + endDay = today - datetime.timedelta(days=1) + startDay = endDay - datetime.timedelta(days=num_days-1) + startMonth = startDay.strftime("%m") + startYear = startDay.strftime("%Y") + diff = (endDay.day - startDay.day) + 1 + return { + "sw1": { + "start_day": startDay.day, + "target_month": startMonth, + "end_day": endDay.day, + "year": startYear, + "day_diff": diff + } + } + else: + today = datetime.datetime.now() + current_date = today - datetime.timedelta(days=1) + current_month = current_date.strftime("%m") + previous_date = current_date - datetime.timedelta(days=num_days-1) + previous_month = previous_date.strftime("%m") + previous_year = previous_date.strftime("%Y") + current_year = current_date.strftime("%Y") + prev_total_days = calendar.monthrange(int(current_year), int(previous_month))[1] + prev_start_day = previous_date.day + prev_end_day = prev_total_days + current_start_day = current_date.day - current_date.day + 1 + current_end_day = current_date.day + prev_day_diff = prev_end_day - prev_start_day + 1 + current_day_diff = current_end_day - current_start_day + 1 + return { + "sw1": { + "start_day": prev_start_day, + "target_month": previous_month, + "end_day": prev_end_day, + "year": previous_year, + "day_diff": prev_day_diff + }, + "sw2": { + "start_day": current_start_day, + "target_month": current_month, + "end_day": current_end_day, + "year": current_year, + "day_diff": current_day_diff + } + } + + +