├── .gitignore ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── Training and Promotional Materials └── Understanding Current Access and Usage.mp4 ├── app.py ├── assets ├── Data_Flow.jpg └── banner.png ├── aws ├── awsOps.py ├── comparePolicies.py ├── createServiceMap.py ├── dataCleanup.py ├── getPreviousPolicies.py ├── policygenOps.py ├── s3Ops.py └── todo.md ├── constants.py ├── redisTest.py ├── redisops └── redisOps.py ├── requirements.txt ├── runner.py ├── schemas.py ├── service_actions_cache.json ├── service_replace_map.json └── utils ├── colors.py └── helpers.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | logs 3 | creds.json/* 4 | logs.zip 5 | temp/ 6 | temp.txt 7 | env/ 8 | actionPolicies/ 9 | actionsUsers/ 10 | crudActions/ 11 | finalUserPolicies/ 12 | userPolicies*/ 13 | presentPolicies*/ 14 | logs*/ 15 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to AWSZeroTrustPolicy 2 | 3 | We love your input! We want to make contributing to this project as easy and transparent as possible, whether it's: 4 | 5 | - Reporting a bug 6 | - Discussing the current state of the code 7 | - Submitting a fix 8 | - Proposing new features 9 | - Becoming a maintainer 10 | 11 | ## We Develop with Github 12 | 13 | We use github to host code, to track issues and feature requests, as well as accept pull requests. 14 | 15 | ## We Use [Github Flow](https://docs.github.com/en/get-started/quickstart/github-flow), So All Code Changes Happen Through Pull Requests 16 | 17 | Pull requests are the best way to propose changes to the codebase (we use [Github Flow](https://docs.github.com/en/get-started/quickstart/github-flow)). We actively welcome your pull requests: 18 | 19 | 1. Fork the repo and create your branch from `master`. 20 | 2. If you've added code that should be tested, add tests. 21 | 3. If you've changed APIs, update the documentation. 22 | 4. Ensure the test suite passes. 23 | 5. Make sure your code lints. 24 | 6. Issue that pull request! 25 | 26 | ## Any contributions you make will be under the MIT Software License 27 | 28 | In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern. 29 | 30 | ## Report bugs using Github's [issues](https://github.com/CloudDefenseAI/AWSZeroTrustPolicy/issues) 31 | 32 | We use GitHub issues to track public bugs. Report a bug by [opening a new issue](https://github.com/CloudDefenseAI/AWSZeroTrustPolicy/issues/new); it's that easy! 33 | 34 | ## Write bug reports with detail, background, and sample code 35 | 36 | **Great Bug Reports** tend to have: 37 | 38 | - A quick summary and/or background 39 | - Steps to reproduce 40 | - Be specific! 41 | - Give sample code if you can. 42 | - What you expected would happen 43 | - What actually happens 44 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) 45 | 46 | People _love_ thorough bug reports. I'm not even kidding. 47 | 48 | - 2 spaces for indentation rather than tabs 49 | - You can try running `npm run lint` for style unification 50 | 51 | ## License 52 | 53 | By contributing, you agree that your contributions will be licensed under its MIT License. 54 | 55 | ## References 56 | 57 | This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/a9316a723f9e918afde44dea68b5f9f39b7d9b00/CONTRIBUTING.md) 58 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.9-alpine 2 | 3 | RUN apk add --no-cache python3-dev gcc musl-dev libffi-dev libpq-dev openssl-dev make && \ 4 | apk add --no-cache redis 5 | 6 | WORKDIR /app 7 | COPY requirements.txt ./ 8 | RUN pip install --no-cache-dir -r requirements.txt 9 | 10 | COPY . . 11 | EXPOSE 8000 12 | CMD ["sh", "-c", "redis-server & uvicorn app:app --reload --host 0.0.0.0"] 13 | 14 | 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2023] [CloudDefenseAI] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![CloudDefence](assets/banner.png) 2 | 3 | ## AWS Zero Trust policy by CloudDefenseAI 4 | 5 | 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. 6 | 7 | ![data flow](assets/Data_Flow.jpg) 8 | 9 | ## Prerequisites 10 | 11 | Before you begin, make sure you have the following prerequisites in place: 12 | 13 | To run the AWS Policy Generator API, you need: 14 | 15 | 1. Python 3.6 or higher 16 | 2. FastAPI and Uvicorn packages installed 17 | 3. redis server 18 | 19 | ## Installation 20 | 21 | To install and use the extended rule set for Falco runtime security, follow these steps: 22 | 23 | 1. Clone the Repository: Start by cloning this GitHub repository to your local system: 24 | 25 | ``` 26 | git clone https://github.com/CloudDefenseAI/AWSZeroTrustPolicy 27 | ``` 28 | 29 | 2. Navigate to the Repository: Change to the repository directory: 30 | 31 | ``` 32 | cd AWSZeroTrustPolicy 33 | ``` 34 | 35 | 3. install python libraries 36 | 37 | ``` 38 | pip install -r requirements.txt 39 | ``` 40 | 41 | ## Usage 42 | 43 | 1. Run Redis server 44 | `redis-server` 45 | 46 | 2. Run the uvicorn application 47 | `uvicorn app:app --reload --host 0.0.0.0 --log-level debug` 48 | 49 | 3. Send the following curl request to generate the zerotrust policy 50 | 51 | ``` 52 | curl -X POST -H "Content-Type: application/json" -d '{ 53 | "accountType": "Credential", 54 | "accessKey": "accessKey", 55 | "secretKey": "secretKey", 56 | "externalId": "externalId", 57 | "roleArn": "roleArn", 58 | "accountId": "accountId", 59 | "days": 30, 60 | "bucketData": { 61 | "us-east-1": "aws-cloudtrail-logs-bucketid" 62 | } 63 | }' http://localhost:8000/run 64 | ``` 65 | 66 | ## Contributing 67 | 68 | If you want to help and wish to contribute, please review our contribution guidelines. Code contributions are always encouraged and welcome! 69 | 70 | ## License 71 | 72 | This project is released under the [Apache-2.0 License](<[url](https://github.com/CloudDefenseAI/AWSZeroTrustPolicy/blob/master/LICENSE)>). 73 | 74 | ## Disclaimer: 75 | 76 | 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. 77 | 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. 78 | 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. 79 | -------------------------------------------------------------------------------- /Training and Promotional Materials/Understanding Current Access and Usage.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CloudDefenseAI/AWSZeroTrustPolicy/2d000adb61df5e9090382f12fbe0ab590b804cd4/Training and Promotional Materials/Understanding Current Access and Usage.mp4 -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import json 2 | from fastapi import FastAPI, HTTPException, Depends, Request 3 | from fastapi.middleware.cors import CORSMiddleware 4 | from schemas import Script 5 | from runner import runner 6 | from datetime import datetime 7 | 8 | app = FastAPI() 9 | 10 | 11 | @app.post("/run") 12 | def run_script(script: Script): 13 | print(f"Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") 14 | print("Payload:") 15 | print(json.dumps(script.dict(), indent=4)) 16 | 17 | try: 18 | resp = runner( 19 | script.accountType, 20 | script.accessKey, 21 | script.secretKey, 22 | script.accountId, 23 | script.days, 24 | script.bucketData, 25 | script.roleArn, 26 | script.externalId, 27 | ) 28 | except Exception as e: 29 | raise HTTPException(status_code=500, detail=str(e)) 30 | 31 | return { 32 | "accountId": resp["accountId"], 33 | "generatedPolicies": resp["generatedPolicies"], 34 | "consolidatedPolicies": resp["consolidatedPolicies"], 35 | "excessivePolicies": resp["excessivePolicies"], 36 | } 37 | -------------------------------------------------------------------------------- /assets/Data_Flow.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CloudDefenseAI/AWSZeroTrustPolicy/2d000adb61df5e9090382f12fbe0ab590b804cd4/assets/Data_Flow.jpg -------------------------------------------------------------------------------- /assets/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CloudDefenseAI/AWSZeroTrustPolicy/2d000adb61df5e9090382f12fbe0ab590b804cd4/assets/banner.png -------------------------------------------------------------------------------- /aws/awsOps.py: -------------------------------------------------------------------------------- 1 | import json 2 | import boto3 3 | from botocore.credentials import Credentials 4 | from botocore.exceptions import ClientError, NoCredentialsError, BotoCoreError 5 | from fastapi import HTTPException 6 | 7 | 8 | class AWSOperations: 9 | def connect_to_iam_with_assumed_role(self, aws_credentials): 10 | # Create a new session with the temporary credentials 11 | session = boto3.Session( 12 | aws_access_key_id=aws_credentials.access_key, 13 | aws_secret_access_key=aws_credentials.secret_key, 14 | aws_session_token=aws_credentials.token, 15 | ) 16 | # Use the new session to connect to IAM 17 | iam_client = session.client("iam") 18 | return iam_client 19 | 20 | def get_iam_connection(self): 21 | try: 22 | with open("config.json", "r") as f: 23 | data = json.loads(f.read()) 24 | if data["accountType"] == "CloudFormation": 25 | aws_credentials = self.get_assume_role_credentials(data) 26 | iam_client = self.connect_to_iam_with_assumed_role(aws_credentials) 27 | elif data["accountType"] == "Credential": 28 | iam_client = self.connect( 29 | "iam", data["aws_access_key_id"], data["aws_secret_access_key"] 30 | ) 31 | return iam_client 32 | except (FileNotFoundError, json.JSONDecodeError) as e: 33 | raise HTTPException( 34 | status_code=500, detail=f"Error reading or parsing config.json: {e}" 35 | ) 36 | 37 | except (ClientError, NoCredentialsError, BotoCoreError) as e: 38 | raise HTTPException(status_code=500, detail=f"Error connecting to IAM: {e}") 39 | 40 | def connect(self, serviceName, aws_access_key_id, aws_secret_access_key): 41 | s3Client = boto3.client( 42 | serviceName, 43 | aws_access_key_id=aws_access_key_id, 44 | aws_secret_access_key=aws_secret_access_key, 45 | ) 46 | return s3Client 47 | 48 | def connect_to_s3_with_assumed_role(self, aws_credentials): 49 | # Create a new session with the temporary credentials 50 | session = boto3.Session( 51 | aws_access_key_id=aws_credentials.access_key, 52 | aws_secret_access_key=aws_credentials.secret_key, 53 | aws_session_token=aws_credentials.token, 54 | ) 55 | # Use the new session to connect to S3 56 | s3_client = session.client("s3") 57 | return s3_client 58 | 59 | def getConnection(self): 60 | try: 61 | with open("config.json", "r") as f: 62 | data = json.loads(f.read()) 63 | if data["accountType"] == "CloudFormation": 64 | aws_credentials = self.get_assume_role_credentials(data) 65 | s3_client = self.connect_to_s3_with_assumed_role(aws_credentials) 66 | elif data["accountType"] == "Credential": 67 | s3_client = self.connect( 68 | "s3", data["aws_access_key_id"], data["aws_secret_access_key"] 69 | ) 70 | return s3_client 71 | except (FileNotFoundError, json.JSONDecodeError) as e: 72 | raise HTTPException( 73 | status_code=500, detail=f"Error reading or parsing config.json: {e}" 74 | ) 75 | except (ClientError, NoCredentialsError, BotoCoreError) as e: 76 | raise HTTPException(status_code=500, detail=f"Error connecting to S3: {e}") 77 | 78 | def get_assume_role_credentials(self, account): 79 | try: 80 | # Create an STS client with the IAM user's access and secret keys 81 | sts_client = boto3.client( 82 | "sts", 83 | aws_access_key_id=account["aws_access_key_id"], 84 | aws_secret_access_key=account["aws_secret_access_key"], 85 | ) 86 | 87 | # Assume the IAM role 88 | response = sts_client.assume_role( 89 | RoleArn=account["role_arn"], 90 | RoleSessionName="Assume_Role_Session", 91 | DurationSeconds=43200, 92 | ExternalId=account["externalid"], 93 | ) 94 | 95 | # Extract the temporary credentials 96 | creds = response["Credentials"] 97 | session_credentials = boto3.Session( 98 | aws_access_key_id=creds["AccessKeyId"], 99 | aws_secret_access_key=creds["SecretAccessKey"], 100 | aws_session_token=creds["SessionToken"], 101 | ).get_credentials() 102 | 103 | # Create an AwsCredentials object with the temporary credentials 104 | aws_credentials = Credentials( 105 | access_key=session_credentials.access_key, 106 | secret_key=session_credentials.secret_key, 107 | token=session_credentials.token, 108 | ) 109 | 110 | return aws_credentials 111 | 112 | except (ClientError, NoCredentialsError, BotoCoreError) as e: 113 | raise HTTPException(status_code=500, detail=f"Error assuming role: {e}") 114 | -------------------------------------------------------------------------------- /aws/comparePolicies.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | from policy_sentry.querying.actions import get_actions_for_service 4 | from redisops.redisOps import RedisOperations 5 | import re 6 | from concurrent.futures import ThreadPoolExecutor 7 | from collections import defaultdict 8 | 9 | crudConnection = RedisOperations() 10 | crudConnection.connect("localhost", 6379, 0) 11 | 12 | services = defaultdict(set) 13 | 14 | # 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'] 15 | # 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']) 16 | 17 | 18 | def create_services_list(actions_data): 19 | for action in actions_data: 20 | action_data = json.loads(action) 21 | event_source = action_data["eventSource"] 22 | service = event_source.split(".")[0] 23 | services[service].add(service) 24 | 25 | 26 | def create_service_actions_cache(services): 27 | service_actions_cache = {} 28 | 29 | for service in services: 30 | actions = get_actions_for_service(service) 31 | service_actions_cache[service] = actions 32 | 33 | # for service in hdServices: 34 | # if service in service_actions_cache: 35 | # continue 36 | # else: 37 | # actions = get_actions_for_service(service) 38 | # service_actions_cache[service] = actions 39 | 40 | return service_actions_cache 41 | 42 | 43 | def write_service_actions_cache_to_file(service_actions_cache, file_path): 44 | with open(file_path, "w") as f: 45 | json.dump(service_actions_cache, f, indent=2) 46 | 47 | 48 | def load_policy(filepath): 49 | with open(filepath, "r") as f: 50 | policy = json.load(f) 51 | return policy 52 | 53 | 54 | def is_valid_action(action): 55 | return re.match(r"^[a-zA-Z0-9_]+:(\*|[a-zA-Z0-9_\*]+)$", action) 56 | 57 | 58 | def compare_policy_worker( 59 | present_policy_filepath, user_policy_filepath, output_filepath 60 | ): 61 | print(f"Started thread for {user_policy_filepath}") 62 | 63 | current_policy = load_policy(present_policy_filepath) 64 | generated_policy = load_policy(user_policy_filepath) 65 | 66 | excessive_permissions = compare_policy(current_policy, generated_policy) 67 | 68 | with open(output_filepath, "w") as f_write: 69 | f_write.write(json.dumps(excessive_permissions, indent=2)) 70 | print( 71 | f"Generated excessive policy for {os.path.basename(user_policy_filepath)}" 72 | ) 73 | 74 | 75 | # def expand_wildcard_actions(actions_list, service_actions_cache=None): 76 | # if service_actions_cache is None: 77 | # with open("service_actions_cache.json", "r") as f: 78 | # service_actions_cache = json.load(f) 79 | 80 | # expanded_actions = [] 81 | 82 | # for action in actions_list: 83 | # if re.match(r'^[a-zA-Z0-9_]+:[a-zA-Z0-9_]+$', action): 84 | # service, action_name = action.split(":") 85 | # if service in service_actions_cache: 86 | # if "*" in action_name: 87 | # expanded_actions.extend([f"{a}" for a in service_actions_cache[service] if action_name.replace("*", "") in a]) 88 | # else: 89 | # expanded_actions.append(action) 90 | # else: 91 | # print(f"Warning: Service '{service}' not found in the service_actions_cache. for this the action was {action}") 92 | # elif action == '*': 93 | # for service in service_actions_cache: 94 | # expanded_actions.extend([f"{a}" for a in service_actions_cache[service]]) 95 | 96 | # return expanded_actions 97 | 98 | 99 | def expand_wildcard_actions(actions_list, service_actions_cache=None): 100 | if service_actions_cache is None: 101 | with open("service_actions_cache.json", "r") as f: 102 | service_actions_cache = json.load(f) 103 | 104 | expanded_actions = [] 105 | 106 | if isinstance(actions_list, str): 107 | actions_list = [actions_list] 108 | 109 | for action in actions_list: 110 | if is_valid_action(action): 111 | service, action_name = action.split(":") 112 | if "*" in action_name: 113 | expanded_actions.extend( 114 | [ 115 | f"{a}" 116 | for a in service_actions_cache.get(service, []) 117 | if action_name.replace("*", "") in a 118 | ] 119 | ) 120 | else: 121 | expanded_actions.append(action) 122 | 123 | elif action == "*": 124 | for service in service_actions_cache: 125 | expanded_actions.extend( 126 | [f"{a}" for a in service_actions_cache[service]] 127 | ) 128 | 129 | return expanded_actions 130 | 131 | 132 | def compare_policy(current_policy, generated_policy): 133 | excessive_permissions = {"Version": "2012-10-17", "Statement": []} 134 | 135 | for current_statement in current_policy["Statement"]: 136 | excessive_statement = { 137 | "Effect": current_statement["Effect"], 138 | "Action": [], 139 | "Resource": current_statement["Resource"], 140 | } 141 | 142 | current_actions_expanded = expand_wildcard_actions(current_statement["Action"]) 143 | 144 | for action in current_actions_expanded: 145 | action_in_generated = False 146 | for generated_statement in generated_policy["Statement"]: 147 | generated_actions_expanded = expand_wildcard_actions( 148 | generated_statement["Action"] 149 | ) 150 | 151 | # Check if the action and resource match in both policies 152 | if action in generated_actions_expanded: 153 | for current_resource in current_statement["Resource"]: 154 | if current_resource in generated_statement["Resource"]: 155 | action_in_generated = True 156 | break 157 | if action_in_generated: 158 | break 159 | 160 | if not action_in_generated: 161 | excessive_statement["Action"].append(action) 162 | 163 | if excessive_statement["Action"]: 164 | excessive_permissions["Statement"].append(excessive_statement) 165 | 166 | return excessive_permissions 167 | 168 | 169 | def compare_policies(): 170 | crudKeys = crudConnection.get_all_keys() 171 | for user_arn in crudKeys: 172 | actions_data = crudConnection.get_list_items(user_arn) 173 | create_services_list(actions_data) 174 | 175 | service_actions_cache = create_service_actions_cache(services) 176 | write_service_actions_cache_to_file( 177 | service_actions_cache, "service_actions_cache.json" 178 | ) 179 | print("Service actions cache created successfully.") 180 | 181 | # present_policies_dir = "presentPolicies" 182 | # user_policies_dir = "userPolicies" 183 | # output_dir = "excessivePolicies" 184 | 185 | # if not os.path.exists(output_dir): 186 | # os.makedirs(output_dir) 187 | 188 | # with ThreadPoolExecutor() as executor: 189 | # futures = [] 190 | # for user_policy_filename in os.listdir(user_policies_dir): 191 | # present_policy_filepath = os.path.join(present_policies_dir, user_policy_filename) 192 | # user_policy_filepath = os.path.join(user_policies_dir, user_policy_filename) 193 | # output_filepath = os.path.join(output_dir, user_policy_filename) 194 | 195 | # if os.path.exists(present_policy_filepath): 196 | # future = executor.submit(compare_policy_worker, present_policy_filepath, user_policy_filepath, output_filepath) 197 | # futures.append(future) 198 | 199 | # for future in futures: 200 | # future.result() 201 | -------------------------------------------------------------------------------- /aws/createServiceMap.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | from policy_sentry.querying.actions import get_actions_for_service 4 | import re 5 | from collections import defaultdict 6 | 7 | services = defaultdict(set) 8 | 9 | 10 | def create_services_list(actions_data): 11 | for action in actions_data: 12 | action_data = json.loads(action) 13 | event_source = action_data["eventSource"] 14 | service = event_source.split(".")[0] 15 | services[service].add(service) 16 | 17 | 18 | def create_service_actions_cache(services): 19 | service_actions_cache = {} 20 | 21 | for service in services: 22 | actions = get_actions_for_service(service) 23 | service_actions_cache[service] = actions 24 | return service_actions_cache 25 | 26 | 27 | def write_service_actions_cache_to_file(service_actions_cache, file_path): 28 | with open(file_path, "w") as f: 29 | json.dump(service_actions_cache, f, indent=2) 30 | 31 | 32 | def load_policy(filepath): 33 | with open(filepath, "r") as f: 34 | policy = json.load(f) 35 | return policy 36 | 37 | 38 | def is_valid_action(action): 39 | return re.match(r"^[a-zA-Z0-9_]+:(\*|[a-zA-Z0-9_\*]+)$", action) 40 | 41 | 42 | def create_service_map(mergedData): 43 | print("Creating service map") 44 | for username, actions in mergedData.items(): 45 | actions_list = [action for action in actions] 46 | create_services_list(actions_list) 47 | 48 | service_actions_cache = create_service_actions_cache(services) 49 | write_service_actions_cache_to_file( 50 | service_actions_cache, "service_actions_cache.json" 51 | ) 52 | print("Service actions cache created successfully.") 53 | -------------------------------------------------------------------------------- /aws/dataCleanup.py: -------------------------------------------------------------------------------- 1 | import pendulum 2 | 3 | 4 | class DataCleanup: 5 | def __init__(self, redis_connection): 6 | self.redis_connection = redis_connection 7 | 8 | def cleanup(self): 9 | now = pendulum.now() 10 | keys_to_delete = [] 11 | 12 | for key in self.redis_connection.r.scan_iter("*"): 13 | date_str = key.decode("utf-8").split("_")[2] 14 | try: 15 | date = pendulum.from_format(date_str, "YYYY/MM/DD") 16 | except ValueError: 17 | continue 18 | 19 | days_diff = (now - date).days 20 | if days_diff > 90: 21 | keys_to_delete.append(key) 22 | 23 | print(f"Found {len(keys_to_delete)} keys to delete.") 24 | 25 | for key in keys_to_delete: 26 | self.redis_connection.r.delete(key) 27 | print(f"Deleted key: {key.decode('utf-8')}") 28 | -------------------------------------------------------------------------------- /aws/getPreviousPolicies.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | from botocore.exceptions import ClientError 4 | from aws.awsOps import AWSOperations 5 | from utils.colors import colors 6 | import concurrent.futures 7 | import re 8 | from redisops.redisOps import RedisOperations 9 | 10 | arnStore = RedisOperations() 11 | arnStore.connect("localhost", 6379, 2) 12 | 13 | 14 | def is_valid_arn(arn): 15 | return re.match(r"^arn:aws:iam::\d{12}:user/[\w+=,.@-]+$", arn.decode()) is not None 16 | 17 | 18 | def get_policies_for_users(path, merged_data): 19 | ops = AWSOperations() 20 | iam_client = ops.get_iam_connection() 21 | 22 | valid_user_list = [ 23 | user.encode() for user in merged_data.keys() if is_valid_arn(user.encode()) 24 | ] 25 | 26 | with concurrent.futures.ThreadPoolExecutor() as executor: 27 | futures = [ 28 | executor.submit(get_previous_policies, iam_client, path, user.decode()) 29 | for user in valid_user_list 30 | ] 31 | 32 | for future in concurrent.futures.as_completed(futures): 33 | try: 34 | future.result() 35 | except Exception as e: 36 | print(f"Error occurred during parallel processing: {e}") 37 | 38 | 39 | def get_previous_policies(iam_client, path, current_user): 40 | user_arn = current_user 41 | current_user = current_user.split("/")[-1] 42 | arnStore.insertKeyVal(current_user, user_arn) 43 | 44 | print(f"Started Thread for Fetching policies for {current_user}") 45 | try: 46 | if isinstance(current_user, bytes): 47 | current_user = current_user.decode() 48 | 49 | policy_dict = {"Version": "2012-10-17", "Statement": []} 50 | 51 | if user_exists(iam_client, current_user): 52 | policies = iam_client.list_attached_user_policies(UserName=current_user)[ 53 | "AttachedPolicies" 54 | ] 55 | inline_policies = iam_client.list_user_policies(UserName=current_user)[ 56 | "PolicyNames" 57 | ] 58 | 59 | # Fetch managed policies 60 | for policy in policies: 61 | policy_arn = policy["PolicyArn"] 62 | policy_version = iam_client.get_policy(PolicyArn=policy_arn)["Policy"][ 63 | "DefaultVersionId" 64 | ] 65 | policy_doc = iam_client.get_policy_version( 66 | PolicyArn=policy_arn, VersionId=policy_version 67 | )["PolicyVersion"]["Document"] 68 | policy_dict["Statement"].extend(policy_doc["Statement"]) 69 | 70 | # Fetch inline policies 71 | for policy_name in inline_policies: 72 | policy_doc = iam_client.get_user_policy( 73 | UserName=current_user, PolicyName=policy_name 74 | )["PolicyDocument"] 75 | policy_dict["Statement"].extend(policy_doc["Statement"]) 76 | else: 77 | print(f"User {current_user} does not exist. Creating an empty policy.") 78 | 79 | outfileName = f"policy_{current_user}.json" 80 | outfileName = ( 81 | outfileName.replace(":", "-").replace("/", "_").replace("\\", "__") 82 | ) 83 | with open(os.path.join(path, outfileName), "w") as f: 84 | json.dump(policy_dict, f, indent=2) 85 | 86 | print(f"Fetched Present Policies for {current_user}") 87 | except ClientError as e: 88 | print(f"Error occurred: {e}") 89 | 90 | 91 | def user_exists(iam_client, user_name): 92 | try: 93 | iam_client.get_user(UserName=user_name) 94 | return True 95 | except iam_client.exceptions.NoSuchEntityException: 96 | return False 97 | -------------------------------------------------------------------------------- /aws/policygenOps.py: -------------------------------------------------------------------------------- 1 | import ijson 2 | import gzip 3 | import re 4 | import os 5 | from tqdm import tqdm 6 | from utils.colors import colors 7 | from redisops.redisOps import RedisOperations 8 | import json 9 | 10 | # from policy_sentry.writing.template import get_crud_template_dict 11 | # from policy_sentry.command.write_policy import write_policy_with_template 12 | from collections import defaultdict 13 | 14 | crudConnection = RedisOperations() 15 | crudConnection.connect("localhost", 6379, 0) 16 | arnStore = RedisOperations() 17 | arnStore.connect("localhost", 6379, 2) 18 | 19 | 20 | def get_event_type(event_name): 21 | read_events = ["^Get", "^Describe", "^Head"] 22 | write_events = [ 23 | "^Create", 24 | "^Put", 25 | "^Post", 26 | "^Copy", 27 | "^Complete", 28 | "^Delete", 29 | "^Update", 30 | "^Modify", 31 | ] 32 | tagging_events = ["^Tag", "^Untag"] 33 | list_events = ["^List"] 34 | for pattern in read_events: 35 | if re.search(pattern, event_name): 36 | return "read" 37 | 38 | for pattern in write_events: 39 | if re.search(pattern, event_name): 40 | return "write" 41 | 42 | for pattern in tagging_events: 43 | if re.search(pattern, event_name): 44 | return "tagging" 45 | for pattern in list_events: 46 | if re.search(pattern, event_name): 47 | return "list" 48 | return None 49 | 50 | 51 | def load_service_actions_cache(file_path): 52 | with open(file_path, "r") as f: 53 | return json.load(f) 54 | 55 | 56 | def load_service_replace_map(file_path): 57 | with open(file_path, "r") as f: 58 | return json.load(f) 59 | 60 | 61 | def generate_least_privilege_policy( 62 | user_arn, actions_data, service_actions_cache, service_replace_map 63 | ): 64 | policy = {"Version": "2012-10-17", "Statement": []} 65 | resource_actions = defaultdict(lambda: defaultdict(set)) 66 | 67 | for action_data in actions_data: 68 | if action_data["username"] != user_arn: 69 | continue 70 | 71 | service = action_data["eventSource"].split(".")[0] 72 | action = f"{service}:{action_data['eventName']}" 73 | 74 | if action in service_replace_map: 75 | action = service_replace_map[action] 76 | 77 | if action not in service_actions_cache.get(service, []): 78 | continue 79 | 80 | resource = action_data["arn"] 81 | resource_prefix = resource.split(":")[5].split("/")[0] 82 | resource_actions[resource_prefix][resource].add(action) 83 | 84 | for resource_prefix, resources in resource_actions.items(): 85 | statement = {"Effect": "Allow", "Action": [], "Resource": []} 86 | 87 | for resource, actions in resources.items(): 88 | statement["Action"].extend(actions) 89 | statement["Resource"].append(resource) 90 | 91 | statement["Action"] = list(set(statement["Action"])) 92 | policy["Statement"].append(statement) 93 | 94 | policy_json = json.dumps(policy) 95 | 96 | if len(policy_json) > 6144: 97 | print(f"Generated policy exceeds the 6144 character limit for {user_arn}") 98 | 99 | return policy 100 | 101 | 102 | def generateLeastprivPolicies(user_arn, policy_output_dir, actions_list): 103 | service_actions_cache = load_service_actions_cache("service_actions_cache.json") 104 | service_replace_map = load_service_replace_map("service_replace_map.json") 105 | policy = generate_least_privilege_policy( 106 | user_arn, actions_list, service_actions_cache, service_replace_map 107 | ) 108 | username = user_arn.split("/")[-1] 109 | filename = f"policy_{username}.json" 110 | filename = filename.replace(":", "-").replace("/", "_").replace("\\", "__") 111 | 112 | with open(os.path.join(policy_output_dir, filename), "w") as f_write: 113 | f_write.write(json.dumps(policy, indent=2)) 114 | print(f"Generated policy for {username}") 115 | 116 | 117 | def runPolicyGeneratorCRUD(filePath, date, region, bucketName, accountID): 118 | with gzip.open(f"{filePath}", "rt") as f: 119 | parser = ijson.parse(f) 120 | startKey = "Records.item.eventVersion" 121 | startLoop = False 122 | currentBlock = {} 123 | 124 | for prefix, event, value in parser: 125 | if prefix == startKey: 126 | if startLoop == False: 127 | startLoop = True 128 | else: 129 | startLoop = False 130 | if ( 131 | currentBlock.get("username") is not None 132 | and currentBlock.get("arn") is not None 133 | ): 134 | userNameCB = currentBlock.get("username") 135 | outerKey = f"{accountID}_{bucketName}_{date}_{region}" 136 | crudConnection.push_back_nested_json( 137 | outerKey, userNameCB, currentBlock 138 | ) 139 | currentBlock = {} 140 | if startLoop: 141 | if prefix == "Records.item.resources.item.ARN": 142 | currentBlock["arn"] = value 143 | if prefix == "Records.item.userIdentity.type": 144 | currentBlock["userIdentityType"] = value 145 | if ( 146 | prefix == "Records.item.userIdentity.arn" 147 | and currentBlock.get("userIdentityType") == "IAMUser" 148 | ): 149 | currentBlock["username"] = value 150 | if prefix == "Records.item.eventSource": 151 | currentBlock["eventSource"] = value 152 | if prefix == "Records.item.eventName": 153 | currentBlock["eventName"] = value 154 | -------------------------------------------------------------------------------- /aws/s3Ops.py: -------------------------------------------------------------------------------- 1 | from aws.awsOps import AWSOperations 2 | import json 3 | from utils import helpers 4 | from utils.colors import colors 5 | 6 | # from constants import default_regions 7 | from tqdm import tqdm 8 | import os 9 | import time 10 | 11 | # from datetime import datetime 12 | import threading 13 | from aws.policygenOps import runPolicyGeneratorCRUD, generateLeastprivPolicies 14 | from redisops.redisOps import RedisOperations 15 | from aws.getPreviousPolicies import get_policies_for_users 16 | from aws.comparePolicies import compare_policies 17 | from aws.createServiceMap import create_service_map 18 | from contextlib import contextmanager 19 | import pendulum 20 | from pendulum import timezone 21 | from concurrent.futures import ThreadPoolExecutor 22 | import itertools 23 | from aws.dataCleanup import DataCleanup 24 | 25 | completedBucketsLock = threading.Lock() 26 | 27 | utc_timezone = timezone("UTC") 28 | pendulum.set_local_timezone(utc_timezone) 29 | 30 | 31 | @contextmanager 32 | def measure_time_block(message: str = "Execution time"): 33 | start = time.time() 34 | yield 35 | end = time.time() 36 | duration = end - start 37 | 38 | if duration >= 3600: 39 | hours = int(duration // 3600) 40 | duration %= 3600 41 | print( 42 | f"{message} completed in {hours} hour(s) {int(duration // 60)} minute(s) {duration % 60:.2f} second(s)" 43 | ) 44 | elif duration >= 60: 45 | minutes = int(duration // 60) 46 | print( 47 | f"{message} completed in {minutes} minute(s) {duration % 60:.2f} second(s)" 48 | ) 49 | else: 50 | print(f"{message} completed in {duration:.2f} second(s)") 51 | 52 | 53 | class s3Operations(AWSOperations): 54 | def __init__(self): 55 | super().__init__() 56 | self.crudConnection = RedisOperations() 57 | self.crudConnection.connect("localhost", 6379, 0) 58 | self.data_cleanup = DataCleanup(self.crudConnection) 59 | 60 | def getConfig(self): 61 | with open("config.json", "r") as f: 62 | data = json.loads(f.read()) 63 | return data 64 | 65 | def mergeData(self, accountId, num_days, bucketData): 66 | print(f"Merging data for {num_days}") 67 | now = pendulum.now() 68 | previousData = [ 69 | (now - pendulum.duration(days=i)).strftime("%Y/%m/%d") 70 | for i in range(num_days) 71 | ] 72 | merged_data = {} 73 | 74 | for bucketName, regions in bucketData.items(): 75 | for region, date in itertools.product(regions, previousData): 76 | day_data_str = self.crudConnection.read_json( 77 | f"{bucketName}_{accountId}_{date}_{region}" 78 | ) 79 | if day_data_str: 80 | for username, actions in day_data_str.items(): 81 | if username not in merged_data: 82 | merged_data[username] = set(actions) 83 | else: 84 | merged_data[username].update(actions) 85 | 86 | # Convert sets back to lists 87 | for username in merged_data: 88 | merged_data[username] = list(merged_data[username]) 89 | return merged_data 90 | 91 | def is_request_processed(self, account_id, bucket_name, date, region): 92 | outer_key = f"{bucket_name}_{account_id}_{date}_{region}" 93 | return self.crudConnection.exists(outer_key) 94 | 95 | def getObjects(self, completedBuckets, bucketData, num_days, unique_id): 96 | self.data_cleanup.cleanup() 97 | try: 98 | config = self.getConfig() 99 | accountId = config["accountId"] 100 | today = pendulum.now() 101 | endDay = today.date() 102 | startDay = today.subtract(days=num_days).date() 103 | 104 | day_diff = (endDay - startDay).days + 1 105 | 106 | for bucketName, regions in bucketData.items(): 107 | 108 | thread = threading.Thread( 109 | target=bucketThreadFn, 110 | args=( 111 | completedBuckets, 112 | bucketName, 113 | regions, 114 | startDay, 115 | endDay, 116 | accountId, 117 | day_diff, 118 | unique_id, 119 | ), 120 | ) 121 | thread.start() 122 | 123 | except KeyError as err: 124 | print(helpers.colors.FAIL + "Invalid key " + str(err)) 125 | 126 | except Exception as exp: 127 | helpers.logException(exp) 128 | 129 | def getPolicies(self, account_id, num_days, bucketData, unique_id): 130 | user_policies_dir = f"userPolicies_{account_id}_{unique_id}" 131 | present_policies_dir = f"presentPolicies_{account_id}_{unique_id}" 132 | 133 | mergedData = self.mergeData(account_id, num_days, bucketData) 134 | create_service_map(mergedData) 135 | 136 | with measure_time_block("Generating Policies"): 137 | print("Generating Policies") 138 | for username, actions in mergedData.items(): 139 | actions_list = [json.loads(action) for action in actions] 140 | generateLeastprivPolicies(username, user_policies_dir, actions_list) 141 | 142 | with measure_time_block("Getting Present Policies"): 143 | print("Getting Present Policies") 144 | get_policies_for_users(present_policies_dir, mergedData) 145 | 146 | # with measure_time_block("Comparing the policies"): 147 | # print("Comparing the policies to get excessive policies") 148 | # compare_policies() 149 | 150 | 151 | def bucketThreadFn( 152 | completedBuckets, 153 | bucketName, 154 | regions, 155 | startDay, 156 | endDay, 157 | accountId, 158 | day_diff, 159 | unique_id, 160 | ): 161 | print("Started thread for Bucket : " + bucketName) 162 | 163 | s3Ops = s3Operations() 164 | s3Client = s3Ops.getConnection() 165 | 166 | completedRegions = [] 167 | region_events = [threading.Event() for _ in regions] 168 | 169 | with ThreadPoolExecutor(max_workers=5) as executor: 170 | for idx, region in enumerate(regions): 171 | executor.submit( 172 | regionThreadFn, 173 | startDay, 174 | endDay, 175 | accountId, 176 | region, 177 | s3Client, 178 | bucketName, 179 | completedRegions, 180 | region_events[idx], 181 | unique_id, 182 | ) 183 | 184 | for event in region_events: 185 | event.wait() 186 | 187 | with completedBucketsLock: 188 | completedBuckets.append(bucketName) 189 | print(f"Completed thread for Bucket : {bucketName}") 190 | 191 | 192 | def regionThreadFn( 193 | startDay, 194 | endDay, 195 | accountId, 196 | region, 197 | s3Client, 198 | bucketName, 199 | completedRegions, 200 | region_event, 201 | unique_id, 202 | ): 203 | 204 | print(f"Starting thread for {region}") 205 | completedDays = [] 206 | day_threads = [] 207 | 208 | day = startDay 209 | while day <= endDay: 210 | thread = threading.Thread( 211 | target=dayThreadFn, 212 | args=( 213 | day, 214 | accountId, 215 | region, 216 | s3Client, 217 | bucketName, 218 | completedDays, 219 | unique_id, 220 | ), 221 | ) 222 | day_threads.append(thread) 223 | thread.start() 224 | day = day.add(days=1) 225 | 226 | for thread in day_threads: 227 | thread.join() 228 | 229 | print(f"Completed thread for {region}") 230 | completedRegions.append(region) 231 | region_event.set() 232 | 233 | 234 | def dayThreadFn(day, accountId, region, s3Client, bucketName, completedDays, unique_id): 235 | 236 | date_str = day.strftime("%Y/%m/%d") 237 | s3obj = s3Operations() 238 | 239 | if s3obj.is_request_processed(accountId, bucketName, date_str, region): 240 | print(f"Skipping {region} : {date_str} as it has already been processed") 241 | completedDays.append(day) 242 | return 243 | 244 | try: 245 | print(f"Starting thread for {region} : {day.format('YYYY/MM/DD')}") 246 | prefix = f"AWSLogs/{accountId}/CloudTrail/{region}/{day.format('YYYY/MM/DD')}" 247 | response = s3Client.list_objects(Bucket=bucketName, Prefix=prefix) 248 | contents = response.get("Contents", []) 249 | 250 | total_items = len(contents) 251 | processed_items = 0 252 | 253 | for item in contents: 254 | key = str(item["Key"]) 255 | filePath = key.split("/")[-1] 256 | with open( 257 | os.path.join(f"logs_{accountId}_{unique_id}", filePath), "wb" 258 | ) as data: 259 | s3Client.download_fileobj(bucketName, key, data) 260 | downloaded = False 261 | retry_count = 0 262 | max_retries = 3 263 | 264 | while not downloaded and retry_count < max_retries: 265 | try: 266 | runPolicyGeneratorCRUD( 267 | f"logs_{accountId}_{unique_id}/{filePath}", 268 | f"{day.format('YYYY/MM/DD')}", 269 | region, 270 | accountId, 271 | bucketName, 272 | ) 273 | os.remove(f"logs_{accountId}_{unique_id}/{filePath}") 274 | downloaded = True 275 | except OSError as e: 276 | if e.errno == 32: 277 | time.sleep(0.1) 278 | else: 279 | retry_count += 1 280 | time.sleep(1) 281 | except Exception as e: 282 | print( 283 | f"Error in runPolicyGeneratorCRUD for {region} : {day.format('YYYY/MM/DD')}: {str(e)}" 284 | ) 285 | retry_count += 1 286 | time.sleep(1) 287 | 288 | processed_items += 1 289 | print( 290 | f"Processed {processed_items}/{total_items} items for {region} : {day.format('YYYY/MM/DD')}" 291 | ) 292 | 293 | print(f"Completed thread for {region} : {day.format('YYYY/MM/DD')}") 294 | completedDays.append(day) 295 | 296 | except Exception as e: 297 | print( 298 | f"Error in dayThreadFn for {region} : {day.format('YYYY/MM/DD')}: {str(e)}" 299 | ) 300 | -------------------------------------------------------------------------------- /aws/todo.md: -------------------------------------------------------------------------------- 1 | 1. Fix the timing window 2 | 2. Integrate the timing window through out the application 3 | 3. test the code in and out. 4 | -------------------------------------------------------------------------------- /constants.py: -------------------------------------------------------------------------------- 1 | aws_regions_testing = ["us-east-1"] 2 | 3 | aws_regions = [ 4 | "us-east-2", 5 | "us-east-1", 6 | "us-west-1", 7 | "us-west-2", 8 | "ap-south-1", 9 | "ap-northeast-3", 10 | "ap-northeast-2", 11 | "ap-southeast-1", 12 | "ap-southeast-2", 13 | "ap-northeast-1", 14 | "ca-central-1", 15 | "eu-central-1", 16 | "eu-west-1", 17 | "eu-west-2", 18 | "eu-west-3", 19 | "eu-north-1", 20 | "sa-east-1", 21 | ] 22 | 23 | default_regions = aws_regions 24 | # default_regions = aws_regions_testing 25 | -------------------------------------------------------------------------------- /redisTest.py: -------------------------------------------------------------------------------- 1 | import json 2 | from redisops.redisOps import RedisOperations 3 | 4 | redis_ops = RedisOperations() 5 | redis_ops.connect("localhost", 6379, 0) 6 | redis_dump = redis_ops.get_redis_dump() 7 | 8 | 9 | print(json.dumps(redis_dump, indent=2)) 10 | -------------------------------------------------------------------------------- /redisops/redisOps.py: -------------------------------------------------------------------------------- 1 | import redis 2 | import json 3 | 4 | 5 | class RedisOperations: 6 | def connect(self, host, port, dbNum): 7 | self.r = redis.Redis(host=host, port=port, db=dbNum) 8 | 9 | def insertKeyVal(self, key, value): 10 | self.r.set(key, value) 11 | 12 | def createList(self, key, value_list): 13 | for item in value_list: 14 | self.r.rpush(key, item) 15 | 16 | # insert a value at the end of a list 17 | def push_back(self, key, value): 18 | self.r.rpush(key, value) 19 | 20 | # insert a value at the front of a list 21 | def push_front(self, key, value): 22 | self.r.lpush(key, value) 23 | 24 | def push_back_json(self, key, jsonObj): 25 | jsonStr = json.dumps(jsonObj) 26 | pos = self.r.lpos(key, jsonStr) 27 | if pos == None: 28 | self.r.rpush(key, jsonStr) 29 | 30 | def pop_back(self, key): 31 | self.r.rpop(key) 32 | 33 | def pop_front(self, key): 34 | self.r.lpop(key) 35 | 36 | def insert_json(self, key, json_object): 37 | self.r.set(key, json.dumps(json_object)) 38 | 39 | def read_json(self, key): 40 | val = self.r.get(key) 41 | if val is not None: 42 | return json.loads(val.decode()) 43 | return None 44 | 45 | def insert_jsonobj_list(self, key, listOfJsonObjects): 46 | for jsonObject in listOfJsonObjects: 47 | self.push_back(key, json.dumps(jsonObject)) 48 | 49 | def get_list_items(self, key): 50 | items = self.r.lrange(key, 0, -1) 51 | return items 52 | 53 | def get_all_keys(self): 54 | return self.r.scan_iter() 55 | 56 | # flush all keys from current DB 57 | def flushdb(self): 58 | self.r.flushdb() 59 | 60 | def push_back_nested_json(self, outer_key, inner_key, jsonObj): 61 | jsonStr = json.dumps(jsonObj) 62 | current_data_str = self.r.get(outer_key) 63 | if current_data_str: 64 | current_data = json.loads(current_data_str) 65 | else: 66 | current_data = {} 67 | 68 | if inner_key not in current_data: 69 | current_data[inner_key] = [] 70 | 71 | if jsonStr not in current_data[inner_key]: 72 | current_data[inner_key].append(jsonStr) 73 | 74 | self.r.set(outer_key, json.dumps(current_data)) 75 | 76 | def get_redis_dump(self): 77 | all_keys = self.r.keys() 78 | redis_dump = {} 79 | for key in all_keys: 80 | key_str = key.decode() 81 | value = self.r.get(key) 82 | if value: 83 | try: 84 | value_json = json.loads(value) 85 | except json.JSONDecodeError: 86 | value_json = value.decode() 87 | redis_dump[key_str] = value_json 88 | else: 89 | list_items = self.r.lrange(key, 0, -1) 90 | redis_dump[key_str] = [json.loads(item) for item in list_items] 91 | return redis_dump 92 | 93 | def exists(self, key): 94 | return self.r.exists(key) 95 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.26.87 2 | botocore==1.29.87 3 | fastapi==0.95.0 4 | httpx==0.23.3 5 | ijson==3.2.0.post0 6 | pendulum==2.1.2 7 | policy_sentry==0.12.6 8 | pydantic==1.10.6 9 | redis==4.5.4 10 | tqdm==4.64.1 11 | uvicorn==0.21.1 12 | mangum==0.17.0 13 | 14 | -------------------------------------------------------------------------------- /runner.py: -------------------------------------------------------------------------------- 1 | from aws.s3Ops import s3Operations 2 | import os 3 | import shutil 4 | import time 5 | import json 6 | import glob 7 | from redisops.redisOps import RedisOperations 8 | from contextlib import contextmanager 9 | import uuid 10 | 11 | arnStore = RedisOperations() 12 | arnStore.connect("localhost", 6379, 2) 13 | 14 | unique_id = uuid.uuid4().hex[:6] 15 | 16 | 17 | @contextmanager 18 | def measure_time_block(message: str = "Execution time"): 19 | start = time.time() 20 | yield 21 | end = time.time() 22 | duration = end - start 23 | 24 | if duration >= 3600: 25 | hours = int(duration // 3600) 26 | duration %= 3600 27 | print( 28 | f"{message} completed in {hours} hour(s) {int(duration // 60)} minute(s) {duration % 60:.2f} second(s)" 29 | ) 30 | elif duration >= 60: 31 | minutes = int(duration // 60) 32 | print( 33 | f"{message} completed in {minutes} minute(s) {duration % 60:.2f} second(s)" 34 | ) 35 | else: 36 | print(f"{message} completed in {duration:.2f} second(s)") 37 | 38 | 39 | def create_dirs(account_id): 40 | base_dir = os.path.dirname(os.path.abspath(__file__)) 41 | directories = [ 42 | os.path.join(base_dir, f"logs_{account_id}_{unique_id}"), 43 | os.path.join(base_dir, f"userPolicies_{account_id}_{unique_id}"), 44 | os.path.join(base_dir, f"presentPolicies_{account_id}_{unique_id}"), 45 | # os.path.join(base_dir, f"excessivePolicies_{account_id}"), 46 | ] 47 | for directory in directories: 48 | if not os.path.exists(directory): 49 | os.makedirs(directory) 50 | 51 | empty_directory(f"logs_{account_id}_{unique_id}") 52 | empty_directory(f"userPolicies_{account_id}_{unique_id}") 53 | empty_directory(f"presentPolicies_{account_id}_{unique_id}") 54 | # empty_directory(f"excessivePolicies_{account_id}") 55 | 56 | 57 | def empty_directory(directory_name): 58 | base_dir = os.path.dirname(os.path.abspath(__file__)) 59 | directory_path = os.path.join(base_dir, directory_name) 60 | 61 | if not os.path.exists(directory_path): 62 | print(f"Path '{directory_path}' does not exist.") 63 | return 64 | 65 | for file in os.listdir(directory_path): 66 | file_path = os.path.join(directory_path, file) 67 | try: 68 | if os.path.isfile(file_path) or os.path.islink(file_path): 69 | os.unlink(file_path) 70 | elif os.path.isdir(file_path): 71 | shutil.rmtree(file_path) 72 | except Exception as e: 73 | print(f"Failed to delete {file_path}. Reason: {e}") 74 | 75 | print(f"Emptied directory: {directory_path}") 76 | 77 | 78 | def get_policy_from_file(folder, username): 79 | filename = f"{username}.json" 80 | filepath = os.path.join(folder, filename) 81 | with open(filepath, "r") as f: 82 | return json.load(f) 83 | 84 | 85 | def get_user_arn(username): 86 | user_arn = arnStore.r.get(username) 87 | if user_arn is None: 88 | return None 89 | return user_arn.decode() 90 | 91 | 92 | def load_policies_from_directory(directory_name: str): 93 | base_dir = os.path.dirname(os.path.abspath(__file__)) 94 | policies_path = os.path.join(base_dir, directory_name) 95 | policies_files = glob.glob(os.path.join(policies_path, "policy_*.json")) 96 | 97 | policies = {} 98 | 99 | for file_path in policies_files: 100 | with open(file_path, "r") as policy_file: 101 | policy = json.load(policy_file) 102 | 103 | username = ( 104 | os.path.basename(file_path).replace("policy_", "").replace(".json", "") 105 | ) 106 | user_arn = get_user_arn(username) 107 | policies[user_arn] = policy 108 | 109 | return policies 110 | 111 | 112 | def reformat_bucket_data(bucket_data): 113 | reformatted_data = {} 114 | for region, bucket_name in bucket_data.items(): 115 | if bucket_name in reformatted_data: 116 | reformatted_data[bucket_name].append(region) 117 | else: 118 | reformatted_data[bucket_name] = [region] 119 | return reformatted_data 120 | 121 | 122 | def runner( 123 | accountType, 124 | aws_access_key_id, 125 | aws_secret_access_key, 126 | accountId, 127 | num_days, 128 | bucketData, 129 | role_arn, 130 | externalid, 131 | ): 132 | print(f"Running for {num_days} days") 133 | with measure_time_block("Data Population"): 134 | create_dirs(accountId) 135 | s3Ops = s3Operations() 136 | 137 | print("Starting to generate Heap") 138 | 139 | bucketData = reformat_bucket_data(bucketData) 140 | 141 | config_data = { 142 | "accountType": accountType, 143 | "bucketData": bucketData, 144 | "aws_access_key_id": aws_access_key_id, 145 | "aws_secret_access_key": aws_secret_access_key, 146 | "externalid": externalid, 147 | "role_arn": role_arn, 148 | "accountId": accountId, 149 | } 150 | 151 | with open("config.json", "w") as config_file: 152 | json.dump(config_data, config_file) 153 | 154 | completedBuckets = [] 155 | 156 | s3Ops.getObjects(completedBuckets, bucketData, num_days, unique_id) 157 | 158 | while len(completedBuckets) < len(bucketData): 159 | time.sleep(10) 160 | 161 | print("Generating Policies") 162 | s3Ops.getPolicies(accountId, num_days, bucketData, unique_id) 163 | 164 | generated_policies = load_policies_from_directory( 165 | f"userPolicies_{accountId}_{unique_id}" 166 | ) 167 | consolidated_policies = load_policies_from_directory( 168 | f"presentPolicies_{accountId}_{unique_id}" 169 | ) 170 | excessive_policies = load_policies_from_directory( 171 | f"excessivePolicies_{accountId}_{unique_id}" 172 | ) 173 | 174 | response = { 175 | "accountId": accountId, 176 | "generatedPolicies": generated_policies, 177 | "consolidatedPolicies": consolidated_policies, 178 | "excessivePolicies": excessive_policies, 179 | } 180 | 181 | return response 182 | -------------------------------------------------------------------------------- /schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import Dict 3 | 4 | 5 | class Script(BaseModel): 6 | accountType: str 7 | accessKey: str 8 | secretKey: str 9 | externalId: str 10 | roleArn: str 11 | accountId: str 12 | days: int 13 | bucketData: Dict[str, str] 14 | -------------------------------------------------------------------------------- /service_actions_cache.json: -------------------------------------------------------------------------------- 1 | { 2 | "sts": [ 3 | "sts:AssumeRole", 4 | "sts:AssumeRoleWithSAML", 5 | "sts:AssumeRoleWithWebIdentity", 6 | "sts:DecodeAuthorizationMessage", 7 | "sts:GetAccessKeyInfo", 8 | "sts:GetCallerIdentity", 9 | "sts:GetFederationToken", 10 | "sts:GetServiceBearerToken", 11 | "sts:GetSessionToken", 12 | "sts:SetSourceIdentity", 13 | "sts:TagSession" 14 | ], 15 | "s3": [ 16 | "s3:AbortMultipartUpload", 17 | "s3:BypassGovernanceRetention", 18 | "s3:CreateAccessPoint", 19 | "s3:CreateAccessPointForObjectLambda", 20 | "s3:CreateBucket", 21 | "s3:CreateJob", 22 | "s3:CreateMultiRegionAccessPoint", 23 | "s3:DeleteAccessPoint", 24 | "s3:DeleteAccessPointForObjectLambda", 25 | "s3:DeleteAccessPointPolicy", 26 | "s3:DeleteAccessPointPolicyForObjectLambda", 27 | "s3:DeleteBucket", 28 | "s3:DeleteBucketPolicy", 29 | "s3:DeleteBucketWebsite", 30 | "s3:DeleteJobTagging", 31 | "s3:DeleteMultiRegionAccessPoint", 32 | "s3:DeleteObject", 33 | "s3:DeleteObjectTagging", 34 | "s3:DeleteObjectVersion", 35 | "s3:DeleteObjectVersionTagging", 36 | "s3:DeleteStorageLensConfiguration", 37 | "s3:DeleteStorageLensConfigurationTagging", 38 | "s3:DescribeJob", 39 | "s3:DescribeMultiRegionAccessPointOperation", 40 | "s3:GetAccelerateConfiguration", 41 | "s3:GetAccessPoint", 42 | "s3:GetAccessPointConfigurationForObjectLambda", 43 | "s3:GetAccessPointForObjectLambda", 44 | "s3:GetAccessPointPolicy", 45 | "s3:GetAccessPointPolicyForObjectLambda", 46 | "s3:GetAccessPointPolicyStatus", 47 | "s3:GetAccessPointPolicyStatusForObjectLambda", 48 | "s3:GetAccountPublicAccessBlock", 49 | "s3:GetAnalyticsConfiguration", 50 | "s3:GetBucketAcl", 51 | "s3:GetBucketCORS", 52 | "s3:GetBucketLocation", 53 | "s3:GetBucketLogging", 54 | "s3:GetBucketNotification", 55 | "s3:GetBucketObjectLockConfiguration", 56 | "s3:GetBucketOwnershipControls", 57 | "s3:GetBucketPolicy", 58 | "s3:GetBucketPolicyStatus", 59 | "s3:GetBucketPublicAccessBlock", 60 | "s3:GetBucketRequestPayment", 61 | "s3:GetBucketTagging", 62 | "s3:GetBucketVersioning", 63 | "s3:GetBucketWebsite", 64 | "s3:GetEncryptionConfiguration", 65 | "s3:GetIntelligentTieringConfiguration", 66 | "s3:GetInventoryConfiguration", 67 | "s3:GetJobTagging", 68 | "s3:GetLifecycleConfiguration", 69 | "s3:GetMetricsConfiguration", 70 | "s3:GetMultiRegionAccessPoint", 71 | "s3:GetMultiRegionAccessPointPolicy", 72 | "s3:GetMultiRegionAccessPointPolicyStatus", 73 | "s3:GetObject", 74 | "s3:GetObjectAcl", 75 | "s3:GetObjectAttributes", 76 | "s3:GetObjectLegalHold", 77 | "s3:GetObjectRetention", 78 | "s3:GetObjectTagging", 79 | "s3:GetObjectTorrent", 80 | "s3:GetObjectVersion", 81 | "s3:GetObjectVersionAcl", 82 | "s3:GetObjectVersionAttributes", 83 | "s3:GetObjectVersionForReplication", 84 | "s3:GetObjectVersionTagging", 85 | "s3:GetObjectVersionTorrent", 86 | "s3:GetReplicationConfiguration", 87 | "s3:GetStorageLensConfiguration", 88 | "s3:GetStorageLensConfigurationTagging", 89 | "s3:GetStorageLensDashboard", 90 | "s3:InitiateReplication", 91 | "s3:ListAccessPoints", 92 | "s3:ListAccessPointsForObjectLambda", 93 | "s3:ListAllMyBuckets", 94 | "s3:ListBucket", 95 | "s3:ListBucketMultipartUploads", 96 | "s3:ListBucketVersions", 97 | "s3:ListJobs", 98 | "s3:ListMultiRegionAccessPoints", 99 | "s3:ListMultipartUploadParts", 100 | "s3:ListStorageLensConfigurations", 101 | "s3:ObjectOwnerOverrideToBucketOwner", 102 | "s3:PutAccelerateConfiguration", 103 | "s3:PutAccessPointConfigurationForObjectLambda", 104 | "s3:PutAccessPointPolicy", 105 | "s3:PutAccessPointPolicyForObjectLambda", 106 | "s3:PutAccessPointPublicAccessBlock", 107 | "s3:PutAccountPublicAccessBlock", 108 | "s3:PutAnalyticsConfiguration", 109 | "s3:PutBucketAcl", 110 | "s3:PutBucketCORS", 111 | "s3:PutBucketLogging", 112 | "s3:PutBucketNotification", 113 | "s3:PutBucketObjectLockConfiguration", 114 | "s3:PutBucketOwnershipControls", 115 | "s3:PutBucketPolicy", 116 | "s3:PutBucketPublicAccessBlock", 117 | "s3:PutBucketRequestPayment", 118 | "s3:PutBucketTagging", 119 | "s3:PutBucketVersioning", 120 | "s3:PutBucketWebsite", 121 | "s3:PutEncryptionConfiguration", 122 | "s3:PutIntelligentTieringConfiguration", 123 | "s3:PutInventoryConfiguration", 124 | "s3:PutJobTagging", 125 | "s3:PutLifecycleConfiguration", 126 | "s3:PutMetricsConfiguration", 127 | "s3:PutMultiRegionAccessPointPolicy", 128 | "s3:PutObject", 129 | "s3:PutObjectAcl", 130 | "s3:PutObjectLegalHold", 131 | "s3:PutObjectRetention", 132 | "s3:PutObjectTagging", 133 | "s3:PutObjectVersionAcl", 134 | "s3:PutObjectVersionTagging", 135 | "s3:PutReplicationConfiguration", 136 | "s3:PutStorageLensConfiguration", 137 | "s3:PutStorageLensConfigurationTagging", 138 | "s3:ReplicateDelete", 139 | "s3:ReplicateObject", 140 | "s3:ReplicateTags", 141 | "s3:RestoreObject", 142 | "s3:UpdateJobPriority", 143 | "s3:UpdateJobStatus" 144 | ], 145 | "ssm": [ 146 | "ssm:AddTagsToResource", 147 | "ssm:AssociateOpsItemRelatedItem", 148 | "ssm:CancelCommand", 149 | "ssm:CancelMaintenanceWindowExecution", 150 | "ssm:CreateActivation", 151 | "ssm:CreateAssociation", 152 | "ssm:CreateAssociationBatch", 153 | "ssm:CreateDocument", 154 | "ssm:CreateMaintenanceWindow", 155 | "ssm:CreateOpsItem", 156 | "ssm:CreateOpsMetadata", 157 | "ssm:CreatePatchBaseline", 158 | "ssm:CreateResourceDataSync", 159 | "ssm:DeleteActivation", 160 | "ssm:DeleteAssociation", 161 | "ssm:DeleteDocument", 162 | "ssm:DeleteInventory", 163 | "ssm:DeleteMaintenanceWindow", 164 | "ssm:DeleteOpsMetadata", 165 | "ssm:DeleteParameter", 166 | "ssm:DeleteParameters", 167 | "ssm:DeletePatchBaseline", 168 | "ssm:DeleteResourceDataSync", 169 | "ssm:DeregisterManagedInstance", 170 | "ssm:DeregisterPatchBaselineForPatchGroup", 171 | "ssm:DeregisterTargetFromMaintenanceWindow", 172 | "ssm:DeregisterTaskFromMaintenanceWindow", 173 | "ssm:DescribeActivations", 174 | "ssm:DescribeAssociation", 175 | "ssm:DescribeAssociationExecutionTargets", 176 | "ssm:DescribeAssociationExecutions", 177 | "ssm:DescribeAutomationExecutions", 178 | "ssm:DescribeAutomationStepExecutions", 179 | "ssm:DescribeAvailablePatches", 180 | "ssm:DescribeDocument", 181 | "ssm:DescribeDocumentParameters", 182 | "ssm:DescribeDocumentPermission", 183 | "ssm:DescribeEffectiveInstanceAssociations", 184 | "ssm:DescribeEffectivePatchesForPatchBaseline", 185 | "ssm:DescribeInstanceAssociationsStatus", 186 | "ssm:DescribeInstanceInformation", 187 | "ssm:DescribeInstancePatchStates", 188 | "ssm:DescribeInstancePatchStatesForPatchGroup", 189 | "ssm:DescribeInstancePatches", 190 | "ssm:DescribeInstanceProperties", 191 | "ssm:DescribeInventoryDeletions", 192 | "ssm:DescribeMaintenanceWindowExecutionTaskInvocations", 193 | "ssm:DescribeMaintenanceWindowExecutionTasks", 194 | "ssm:DescribeMaintenanceWindowExecutions", 195 | "ssm:DescribeMaintenanceWindowSchedule", 196 | "ssm:DescribeMaintenanceWindowTargets", 197 | "ssm:DescribeMaintenanceWindowTasks", 198 | "ssm:DescribeMaintenanceWindows", 199 | "ssm:DescribeMaintenanceWindowsForTarget", 200 | "ssm:DescribeOpsItems", 201 | "ssm:DescribeParameters", 202 | "ssm:DescribePatchBaselines", 203 | "ssm:DescribePatchGroupState", 204 | "ssm:DescribePatchGroups", 205 | "ssm:DescribePatchProperties", 206 | "ssm:DescribeSessions", 207 | "ssm:DisassociateOpsItemRelatedItem", 208 | "ssm:GetAutomationExecution", 209 | "ssm:GetCalendar", 210 | "ssm:GetCalendarState", 211 | "ssm:GetCommandInvocation", 212 | "ssm:GetConnectionStatus", 213 | "ssm:GetDefaultPatchBaseline", 214 | "ssm:GetDeployablePatchSnapshotForInstance", 215 | "ssm:GetDocument", 216 | "ssm:GetInventory", 217 | "ssm:GetInventorySchema", 218 | "ssm:GetMaintenanceWindow", 219 | "ssm:GetMaintenanceWindowExecution", 220 | "ssm:GetMaintenanceWindowExecutionTask", 221 | "ssm:GetMaintenanceWindowExecutionTaskInvocation", 222 | "ssm:GetMaintenanceWindowTask", 223 | "ssm:GetManifest", 224 | "ssm:GetOpsItem", 225 | "ssm:GetOpsMetadata", 226 | "ssm:GetOpsSummary", 227 | "ssm:GetParameter", 228 | "ssm:GetParameterHistory", 229 | "ssm:GetParameters", 230 | "ssm:GetParametersByPath", 231 | "ssm:GetPatchBaseline", 232 | "ssm:GetPatchBaselineForPatchGroup", 233 | "ssm:GetServiceSetting", 234 | "ssm:LabelParameterVersion", 235 | "ssm:ListAssociationVersions", 236 | "ssm:ListAssociations", 237 | "ssm:ListCommandInvocations", 238 | "ssm:ListCommands", 239 | "ssm:ListComplianceItems", 240 | "ssm:ListComplianceSummaries", 241 | "ssm:ListDocumentMetadataHistory", 242 | "ssm:ListDocumentVersions", 243 | "ssm:ListDocuments", 244 | "ssm:ListInstanceAssociations", 245 | "ssm:ListInventoryEntries", 246 | "ssm:ListOpsItemEvents", 247 | "ssm:ListOpsItemRelatedItems", 248 | "ssm:ListOpsMetadata", 249 | "ssm:ListResourceComplianceSummaries", 250 | "ssm:ListResourceDataSync", 251 | "ssm:ListTagsForResource", 252 | "ssm:ModifyDocumentPermission", 253 | "ssm:PutCalendar", 254 | "ssm:PutComplianceItems", 255 | "ssm:PutConfigurePackageResult", 256 | "ssm:PutInventory", 257 | "ssm:PutParameter", 258 | "ssm:RegisterDefaultPatchBaseline", 259 | "ssm:RegisterManagedInstance", 260 | "ssm:RegisterPatchBaselineForPatchGroup", 261 | "ssm:RegisterTargetWithMaintenanceWindow", 262 | "ssm:RegisterTaskWithMaintenanceWindow", 263 | "ssm:RemoveTagsFromResource", 264 | "ssm:ResetServiceSetting", 265 | "ssm:ResumeSession", 266 | "ssm:SendAutomationSignal", 267 | "ssm:SendCommand", 268 | "ssm:StartAssociationsOnce", 269 | "ssm:StartAutomationExecution", 270 | "ssm:StartChangeRequestExecution", 271 | "ssm:StartSession", 272 | "ssm:StopAutomationExecution", 273 | "ssm:TerminateSession", 274 | "ssm:UnlabelParameterVersion", 275 | "ssm:UpdateAssociation", 276 | "ssm:UpdateAssociationStatus", 277 | "ssm:UpdateDocument", 278 | "ssm:UpdateDocumentDefaultVersion", 279 | "ssm:UpdateDocumentMetadata", 280 | "ssm:UpdateInstanceAssociationStatus", 281 | "ssm:UpdateInstanceInformation", 282 | "ssm:UpdateMaintenanceWindow", 283 | "ssm:UpdateMaintenanceWindowTarget", 284 | "ssm:UpdateMaintenanceWindowTask", 285 | "ssm:UpdateManagedInstanceRole", 286 | "ssm:UpdateOpsItem", 287 | "ssm:UpdateOpsMetadata", 288 | "ssm:UpdatePatchBaseline", 289 | "ssm:UpdateResourceDataSync", 290 | "ssm:UpdateServiceSetting" 291 | ] 292 | } 293 | -------------------------------------------------------------------------------- /service_replace_map.json: -------------------------------------------------------------------------------- 1 | { 2 | "s3:HeadObject": "s3:GetObject", 3 | "s3:HeadBucket": "s3:ListBucket", 4 | "s3:ListObjects": "s3:ListBucket", 5 | "s3:GetBucketReplication": "s3:GetReplicationConfiguration" 6 | } 7 | -------------------------------------------------------------------------------- /utils/colors.py: -------------------------------------------------------------------------------- 1 | class colors: 2 | HEADER = "\033[95m" 3 | OKBLUE = "\033[94m" 4 | OKCYAN = "\033[96m" 5 | OKGREEN = "\033[92m" 6 | WARNING = "\033[93m" 7 | FAIL = "\033[91m" 8 | ENDC = "\033[0m" 9 | BOLD = "\033[1m" 10 | UNDERLINE = "\033[4m" 11 | -------------------------------------------------------------------------------- /utils/helpers.py: -------------------------------------------------------------------------------- 1 | from utils.colors import colors 2 | import datetime 3 | import calendar 4 | 5 | 6 | def fatal(message): 7 | assert type(message) == str 8 | print(colors.FAIL + message) 9 | exit(0) 10 | 11 | 12 | def logException(exp): 13 | print(exp) 14 | exit(0) 15 | 16 | 17 | def getTimings(num_days): 18 | today = datetime.datetime.now() 19 | end_day = today - datetime.timedelta(days=1) 20 | start_day = end_day - datetime.timedelta(days=num_days - 1) 21 | start_month = start_day.strftime("%m") 22 | start_year = start_day.strftime("%Y") 23 | end_year = end_day.strftime("%Y") 24 | end_month = end_day.strftime("%m") 25 | days_in_current_month = calendar.monthrange(int(end_year), int(end_month))[1] 26 | days_left_in_current_month = days_in_current_month - end_day.day 27 | 28 | if num_days <= days_in_current_month - days_left_in_current_month: 29 | today = datetime.datetime.now() 30 | endDay = today - datetime.timedelta(days=1) 31 | startDay = endDay - datetime.timedelta(days=num_days - 1) 32 | startMonth = startDay.strftime("%m") 33 | startYear = startDay.strftime("%Y") 34 | diff = (endDay.day - startDay.day) + 1 35 | return { 36 | "sw1": { 37 | "start_day": startDay.day, 38 | "end_day": endDay.day, 39 | "day_diff": diff, 40 | "target_month": startMonth, 41 | "year": startYear, 42 | } 43 | } 44 | else: 45 | today = datetime.datetime.now() 46 | current_date = today - datetime.timedelta(days=1) 47 | current_month = current_date.strftime("%m") 48 | previous_date = current_date - datetime.timedelta(days=num_days - 1) 49 | previous_month = previous_date.strftime("%m") 50 | previous_year = previous_date.strftime("%Y") 51 | current_year = current_date.strftime("%Y") 52 | prev_total_days = calendar.monthrange(int(current_year), int(previous_month))[1] 53 | prev_start_day = previous_date.day 54 | prev_end_day = prev_total_days 55 | current_start_day = current_date.day - current_date.day + 1 56 | current_end_day = current_date.day 57 | prev_day_diff = prev_end_day - prev_start_day + 1 58 | current_day_diff = current_end_day - current_start_day + 1 59 | return { 60 | "sw1": { 61 | "start_day": prev_start_day, 62 | "end_day": prev_end_day, 63 | "day_diff": prev_day_diff, 64 | "target_month": previous_month, 65 | "year": previous_year, 66 | }, 67 | "sw2": { 68 | "start_day": current_start_day, 69 | "end_day": current_end_day, 70 | "day_diff": current_day_diff, 71 | "target_month": current_month, 72 | "year": current_year, 73 | }, 74 | } 75 | --------------------------------------------------------------------------------