├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── requirements.txt ├── setup.py └── src └── cloudshovel ├── __init__.py ├── main.py └── utils ├── __init__.py ├── bash_scripts ├── install_ntfs_3g.sh └── mount_and_dig.sh └── digger.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .huskyrc.json 3 | out 4 | log.log 5 | **/node_modules 6 | *.pyc 7 | *.vsix 8 | envVars.txt 9 | **/.vscode/.ropeproject/** 10 | **/testFiles/**/.cache/** 11 | *.noseids 12 | .nyc_output 13 | .vscode-test 14 | __pycache__ 15 | npm-debug.log 16 | **/.mypy_cache/** 17 | !yarn.lock 18 | coverage/ 19 | cucumber-report.json 20 | **/.vscode-test/** 21 | **/.vscode test/** 22 | **/.vscode-smoke/** 23 | **/.venv*/ 24 | port.txt 25 | precommit.hook 26 | python_files/lib/** 27 | python_files/get-pip.py 28 | debug_coverage*/** 29 | languageServer/** 30 | languageServer.*/** 31 | bin/** 32 | obj/** 33 | .pytest_cache 34 | tmp/** 35 | .python-version 36 | .vs/ 37 | test-results*.xml 38 | xunit-test-results.xml 39 | build/ci/performance/performance-results.json 40 | !build/ 41 | debug*.log 42 | debugpy*.log 43 | pydevd*.log 44 | nodeLanguageServer/** 45 | nodeLanguageServer.*/** 46 | dist/** 47 | # translation files 48 | *.xlf 49 | package.nls.*.json 50 | l10n/ 51 | python-env-tools/** 52 | # coverage files produced as test output 53 | python_files/tests/*/.data/.coverage* 54 | python_files/tests/*/.data/*/.coverage* 55 | src/testTestingRootWkspc/coverageWorkspace/.coverage 56 | .vscode/launch.json 57 | /cloudshovel.egg-info 58 | /src/cloudshovel.egg-info 59 | /build 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.md 3 | include requirements.txt 4 | recursive-include src/cloudshovel/utils/bash_scripts *.sh 5 | recursive-include src *.py 6 | global-include *.py 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Introduction 2 | 3 | CloudShovel is a tool designed to search for sensitive information within public or private Amazon Machine Images (AMIs). It automates the process of launching instances from target AMIs, mounting their volumes, and scanning for potential secrets or sensitive data. 4 | 5 | The tool is a modified version of what was used for the research [AWS CloudQuarry: Digging for Secrets in Public AMIs](https://securitycafe.ro/2024/05/08/aws-cloudquarry-digging-for-secrets-in-public-amis/) 6 | 7 | Authors: 8 | - [Eduard Agavriloae](https://www.linkedin.com/in/eduard-k-agavriloae/) - [hacktodef.com](https://hacktodef.com) 9 | - [Matei Josephs](https://www.linkedin.com/in/l31/) - [hivehack.tech](https://hivehack.tech) 10 | 11 | 12 | **Disclaimer** 13 | 14 | > This is not a tool that will fit all scenarios. There will be errors when starting an EC2 instance based on the target AMI or when trying to mount the volumes. We accept pull requests for covering more cases, but our recommendation is to manually try to handle those cases. 15 | 16 | Table of Contents: 17 | 18 | - [Introduction](#introduction) 19 | - [Prerequisites](#prerequisites) 20 | - [Installation](#installation) 21 | - [Using pip](#using-pip) 22 | - [Manually](#manually) 23 | - [Usage](#usage) 24 | - [How It Works](#how-it-works) 25 | - [Customizing scanning](#customizing-scanning) 26 | - [Resources Created](#resources-created) 27 | - [Required Permissions](#required-permissions) 28 | - [Cleaning Up](#cleaning-up) 29 | - [Troubleshooting](#troubleshooting) 30 | 31 | 32 | ## Prerequisites 33 | 34 | Before using CloudShovel, ensure you have the following: 35 | 36 | - Python 3.6 or higher 37 | - Access to your own AWS account and IAM identity 38 | - Python libraries (can be installed automatically) 39 | - Boto3 library installed (`pip install boto3`) 40 | - Colorama library installed (`pip install colorama`) 41 | 42 | ## Installation 43 | 44 | ### Using pip 45 | From terminal: 46 | 47 | ```bash 48 | python3 -m pip install cloudshovel 49 | ``` 50 | 51 | ### Manually 52 | 53 | 1. Clone the CloudShovel repository: 54 | ``` 55 | git clone https://github.com/your-repo/cloudshovel.git 56 | cd cloudshovel 57 | ``` 58 | 59 | 2. Install the required Python libraries: 60 | ``` 61 | pip install -r requirements.txt 62 | ``` 63 | 64 | ## Usage 65 | 66 | To use CloudShovel, run the `main.py` script with the following syntax: 67 | 68 | ``` 69 | cloudshovel --bucket [--profile | --access-key --secret-key (--session-token )] [--region ] 70 | ``` 71 | 72 | Arguments: 73 | - `ami_id`: The ID of the AMI you want to scan (required) 74 | - `--bucket`: The name of the S3 bucket to store results (required) 75 | - Authentication with configured AWS CLI profile 76 | - `--profile`: AWS CLI profile name (default is 'default') 77 | - Authentication with access keys 78 | - `--access-key`: AWS Access Key ID 79 | - `--secret-key`: AWS Secret Access Key 80 | - `--session-token`: AWS Session Token (optional) 81 | - `--region`: AWS region (default is 'us-east-1') 82 | 83 | If you don't specify an argument for authentication, the tool will try to automatically use the `default` profile. 84 | 85 | Example: 86 | ``` 87 | cloudshovel ami-1234567890abcdef --bucket my-cloudshovel-results --profile my-aws-profile --region us-west-2 88 | ``` 89 | 90 | ## How It Works 91 | 92 | CloudShovel operates through the following steps: 93 | 94 | 1. **Initialization**: 95 | - Parses command-line arguments and creates an AWS session. 96 | - Validates the target AMI's existence. 97 | 98 | 2. **Setup**: 99 | - Creates or verifies the existence of the specified S3 bucket. 100 | - Creates an IAM role and instance profile for the "secret searcher" EC2 instance. 101 | - Uploads necessary scripts to the S3 bucket. 102 | 103 | 3. **Secret Searcher Instance**: 104 | - Launches an EC2 instance (the "secret searcher") based on the latest Amazon Linux 202* AMI. 105 | - Installs required tools on the secret searcher instance. 106 | 107 | 4. **Target AMI Processing**: 108 | - Launches an EC2 instance from the target AMI. 109 | - Stops the instance and detaches its volumes. 110 | - Attaches these volumes to the secret searcher instance. 111 | 112 | 5. **Scanning**: 113 | - Mounts the attached volumes on the secret searcher instance. 114 | - Executes the `mount_and_dig.sh` script to search for potential secrets. 115 | - The script looks for specific file names and patterns that might indicate sensitive information. 116 | 117 | 6. **Results**: 118 | - Uploads the scanning results to the specified S3 bucket. 119 | 120 | 7. **Cleanup**: 121 | - Detaches and deletes the volumes from the target AMI. 122 | - Terminates instances and removes created IAM resources. 123 | 124 | ## Customizing scanning 125 | 126 | By default, the tool will execute the next command to search for files and folders that might be of interest: 127 | 128 | ```bash 129 | for item in $(find . \( ! -path "./Windows/*" -a ! -path "./Program Files/*" -a ! -path "./Program Files (x86)/*" \) -size -25M \ 130 | \( -name ".aws" -o -name ".ssh" -o -name "credentials.xml" \ 131 | -o -name "secrets.yml" -o -name "config.php" -o -name "_history" \ 132 | -o -name "autologin.conf" -o -name "web.config" -o -name ".env" \ 133 | -o -name ".git" \) -not -empty) 134 | do 135 | echo "[+] Found $item. Copying to output..." 136 | save_name_item=${item:1} 137 | save_name_item=${save_name_item////\\} 138 | cp -r $item /home/ec2-user/OUTPUT/$counter/${save_name_item} 139 | done 140 | ``` 141 | 142 | The full code can be found in `src\cloudshovel\utils\bash_scripts\mount_and_dig.sh`. Feel free to modify the function and search for other files or folders, increase the file size limit or exclude additional folders from the search. 143 | 144 | You can also modify the function and replace the usage of `find` with `trufflehog` or `linpeas`. The difference is that using find takes about 1 minute to execute whereas other scanning alternatives might take tens of minutes or hours depending on volume size. 145 | 146 | ## Resources Created 147 | 148 | CloudShovel creates the following AWS resources during its operation: 149 | 150 | 1. **S3 Bucket**: Stores scanning scripts and results. 151 | 2. **IAM Role and Instance Profile**: Named "minimal-ssm", used by the secret searcher instance. 152 | 3. **EC2 Instances**: 153 | - A "secret searcher" instance based on Amazon Linux 2023. 154 | - A temporary instance launched from the target AMI (terminated after volume detachment). 155 | 4. **EBS Volumes**: Temporary attachments to the secret searcher instance (deleted after scanning). 156 | 157 | ## Required Permissions 158 | 159 | To run CloudShovel, your AWS account or IAM identity needs the following permissions: 160 | 161 | - EC2: 162 | - Describe, run, stop, and terminate instances 163 | - Describe, create, attach, detach, and delete volumes 164 | - Describe and create tags 165 | - IAM: 166 | - Create, delete, and manage roles and instance profiles 167 | - Attach and detach role policies 168 | - S3: 169 | - Create buckets 170 | - Put, get, and delete objects 171 | - SSM: 172 | - Send commands to EC2 instances 173 | - Get command invocation results 174 | 175 | It's recommended to use the principle of least privilege and create a specific IAM user or role for running CloudShovel with only the necessary permissions. 176 | 177 | ## Cleaning Up 178 | 179 | CloudShovel attempts to clean up all created resources after completion or in case of errors. However, it's good practice to verify that all resources have been properly removed, especially: 180 | 181 | - Check the EC2 console for any running instances tagged with "usage: CloudQuarry" or "usage: SecretSearcher". 182 | - Verify that the IAM role and instance profile "minimal-ssm" have been deleted. 183 | - The S3 bucket **is not** automatically deleted to preserve results. Delete it manually if no longer needed. 184 | 185 | ## Troubleshooting 186 | 187 | - If the script fails to mount volumes, ensure that the necessary filesystem tools (e.g., ntfs-3g for NTFS volumes) are installed on the secret searcher instance. 188 | - For permission-related errors, verify that your AWS credentials have all the required permissions listed above. 189 | - If experiencing issues with specific AMIs, check their requirements (e.g., virtualization type, ENA support) and adjust the instance types in the script accordingly. 190 | 191 | Use this tool responsibly and ensure you have the right to scan the AMIs you're targeting. 192 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.28.45 2 | botocore==1.31.45 3 | colorama==0.4.6 4 | pyfiglet==1.0.2 5 | setuptools==65.5.0 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | with open("README.md", "r", encoding="utf-8") as fh: 4 | long_description = fh.read() 5 | 6 | setup( 7 | name="cloudshovel", 8 | version="1.0.2", 9 | author="Eduard Agavriloae", 10 | author_email="eduard.agavriloae@hacktodef.com", 11 | description="A tool for digging secrets in public AMIs", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/saw-your-packet/CloudShovel", 15 | packages=find_packages(where="src"), 16 | package_dir={"": "src"}, 17 | classifiers=[ 18 | "Development Status :: 4 - Beta", 19 | "Intended Audience :: Developers", 20 | "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", 21 | "Operating System :: OS Independent", 22 | "Topic :: Security", 23 | "Programming Language :: Python :: 3", 24 | "Programming Language :: Python :: 3.6", 25 | "Programming Language :: Python :: 3.7", 26 | "Programming Language :: Python :: 3.8", 27 | "Programming Language :: Python :: 3.9", 28 | "Programming Language :: Python :: 3.10", 29 | "Programming Language :: Python :: 3.11", 30 | ], 31 | python_requires=">=3.6", 32 | install_requires=[ 33 | "boto3", 34 | "colorama", 35 | ], 36 | entry_points={ 37 | "console_scripts": [ 38 | "cloudshovel=cloudshovel.main:main", 39 | ], 40 | }, 41 | include_package_data=True, 42 | keywords="aws ami secrets cloudshovel cloudquarry" 43 | ) -------------------------------------------------------------------------------- /src/cloudshovel/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saw-your-packet/CloudShovel/9d141f24a1822a3dc3e84e30566b302eb41fd9e7/src/cloudshovel/__init__.py -------------------------------------------------------------------------------- /src/cloudshovel/main.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import boto3 3 | import botocore 4 | from pyfiglet import figlet_format 5 | from cloudshovel.utils.digger import dig, log_error, log_warning 6 | 7 | def parse_args(): 8 | parser = argparse.ArgumentParser() 9 | 10 | print(figlet_format('CloudShovel', font='rectangles')) 11 | 12 | print("Authors:") 13 | print("\t- Eduard Agavriloae / @saw_your_packet / hacktodef.com") 14 | print("\t- Matei Josephs / hivehack.tech\n") 15 | 16 | # Positional argument for AMI ID (without a flag) 17 | parser.add_argument("ami_id", help="AWS AMI ID to launch") 18 | 19 | # Global arguments 20 | auth_group = parser.add_mutually_exclusive_group() 21 | auth_group.add_argument("--profile", help="AWS CLI profile name (Default is 'default')", default="default") 22 | auth_group.add_argument("--access-key", help="AWS Access Key ID (Default profile will be used if access keys not provided)") 23 | 24 | parser.add_argument("--secret-key", help="AWS Secret Access Key") 25 | parser.add_argument("--session-token", help="AWS Session Token (optional)") 26 | 27 | parser.add_argument("--region", help="AWS Region", default="us-east-1") 28 | 29 | parser.add_argument("--bucket", help="S3 Bucket name to upload and download auxiliary scripts (Bucket will be created if doesn't already exist in your account)", required=True) 30 | 31 | return parser.parse_args() 32 | 33 | 34 | def create_boto3_session(args): 35 | session_kwargs = {'region_name': args.region} 36 | 37 | if args.profile: 38 | session_kwargs['profile_name'] = args.profile 39 | elif args.access_key: 40 | if not args.secret_key: 41 | raise ValueError("Secret key must be provided with access key") 42 | session_kwargs['aws_access_key_id'] = args.access_key 43 | session_kwargs['aws_secret_access_key'] = args.secret_key 44 | if args.session_token: 45 | session_kwargs['aws_session_token'] = args.session_token 46 | 47 | try: 48 | session = boto3.Session(**session_kwargs) 49 | # Test the session by making a simple API call 50 | identity = session.client('sts').get_caller_identity() 51 | log_warning(f'The script will run using the identity {identity["Arn"]}') 52 | confirmation = input("Please confirm if you want to continue by typing 'yes' [yes/NO]:") 53 | 54 | if confirmation != 'yes': 55 | log_warning('The execution will end now. Exiting...') 56 | exit() 57 | 58 | return session 59 | except botocore.exceptions.ClientError as e: 60 | log_error(f"Failed to create boto3 session: {str(e)}") 61 | exit() 62 | 63 | 64 | def main(): 65 | args = parse_args() 66 | 67 | print(f"AMI ID: {args.ami_id}") 68 | print(f"Region: {args.region}") 69 | print(f"Authentication method: { args.secret_key and args.access_key or args.profile}") 70 | 71 | session = create_boto3_session(args) 72 | 73 | dig(args, session) 74 | 75 | if __name__ == '__main__': 76 | main() 77 | -------------------------------------------------------------------------------- /src/cloudshovel/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saw-your-packet/CloudShovel/9d141f24a1822a3dc3e84e30566b302eb41fd9e7/src/cloudshovel/utils/__init__.py -------------------------------------------------------------------------------- /src/cloudshovel/utils/bash_scripts/install_ntfs_3g.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if test -f /usr/local/bin/ntfs-3g.probe; then 4 | echo "[x] Library ntfs-3g already installed" 5 | exit 6 | fi 7 | 8 | cd /home/ec2-user/ 9 | wget -O ntfs.tgz https://www.tuxera.com/opensource/ntfs-3g_ntfsprogs-2017.3.23.tgz 10 | tar -xf ntfs.tgz 11 | yum groupinstall "Development Tools" -y 12 | cd ntfs-3g_ntfsprogs-2017.3.23/ && ./configure --prefix=/usr/local --disable-static 13 | make 14 | make install 15 | echo "[x] Installation done" 16 | -------------------------------------------------------------------------------- /src/cloudshovel/utils/bash_scripts/mount_and_dig.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ $# -lt 1 ]; then 4 | echo "[*] Usage: $0 " 5 | echo " Multiple devices should be separated by spaces." 6 | echo " E.g.: $0 /dev/sdf /dev/sdg" 7 | exit 8 | fi 9 | 10 | if [ "$EUID" -ne 0 ]; then 11 | echo "[*] This script must be run as root. Exiting." 12 | exit 1 13 | fi 14 | 15 | # Installing udisksctl 16 | yum install udisks2 -y 17 | 18 | check_and_fix_uuid() { 19 | local dev=$1 20 | local uuid=$(blkid -s UUID -o value $dev) 21 | local fs_type=$(blkid -s TYPE -o value $dev) 22 | 23 | if [ "$fs_type" == "xfs" ]; then 24 | # Check if this UUID is already in use 25 | if grep -q $uuid /etc/fstab || blkid | grep -v $dev | grep -q $uuid; then 26 | echo "[!] UUID collision detected for $dev" 27 | echo "[*] Generating new UUID for $dev" 28 | 29 | # Generate new UUID 30 | xfs_admin -U generate $dev 31 | 32 | # Get the new UUID 33 | new_uuid=$(blkid -s UUID -o value $dev) 34 | echo "[*] New UUID for $dev: $new_uuid" 35 | fi 36 | fi 37 | } 38 | 39 | mount_and_search(){ 40 | if [ $# -lt 1 ]; then 41 | echo " [!] Function $0 requires 1 argument. Something went wrong since no arguments were passed." 42 | return 1 43 | fi 44 | 45 | dev=$1 46 | echo "[x] Trying to mount $dev" 47 | 48 | # Check if the filesystem is NTFS 49 | fs_type=$(blkid -o value -s TYPE $dev) 50 | if [ "$fs_type" == "ntfs" ]; then 51 | echo "[x] NTFS filesystem detected. Using ntfs-3g driver." 52 | mount_point="/mnt/ntfs_$RANDOM" 53 | mkdir -p $mount_point 54 | if mount -t ntfs-3g $dev $mount_point; then 55 | echo "[x] Mount successful for $dev at $mount_point" 56 | else 57 | echo "[!] Failed to mount NTFS volume $dev" 58 | rmdir $mount_point 59 | return 1 60 | fi 61 | elif [ "$fs_type" == "xfs" ]; then 62 | echo "[x] XFS filesystem detected." 63 | # Check and fix UUID if necessary 64 | check_and_fix_uuid $dev 65 | 66 | mount_point="/mnt/xfs_$RANDOM" 67 | mkdir -p $mount_point 68 | if mount -t xfs $dev $mount_point; then 69 | echo "[x] Mount successful for $dev at $mount_point" 70 | else 71 | echo "[!] Failed to mount XFS volume $dev" 72 | rmdir $mount_point 73 | return 1 74 | fi 75 | else 76 | if udisksctl mount -b $dev ; then 77 | mount_point=$(udisksctl info -b $dev | grep MountPoints | tr -s ' ' | cut -d ' ' -f 3) 78 | echo "[x] Mount successful for $dev at $mount_point" 79 | else 80 | echo "[!] Failed to mount $dev" 81 | return 1 82 | fi 83 | fi 84 | 85 | mkdir /home/ec2-user/OUTPUT/$counter 2>/dev/null 86 | cd $mount_point 87 | 88 | find . \( ! -path "./proc/*" -a ! -path "./Windows/*" -a ! -path "./usr/*" -a ! -path "./sys/*" -a \ 89 | ! -path "./mnt/*" -a ! -path "./dev/*" -a ! -path "./tmp/*" -a ! -path "./sbin/*" -a \ 90 | ! -path "./bin/*" -a ! -path "./lib*" -a ! -path "./boot/*" -a ! -path "./Program Files/*" -a \ 91 | ! -path "./Program Files (x86)/*" \) \ 92 | -not -empty > /home/ec2-user/OUTPUT/$counter/all_files_cloud_quarry.txt 93 | 94 | for item in $(find . \( ! -path "./Windows/*" -a ! -path "./Program Files/*" -a ! -path "./Program Files (x86)/*" \) -size -25M \ 95 | \( -name ".aws" -o -name ".ssh" -o -name "credentials.xml" \ 96 | -o -name "secrets.yml" -o -name "config.php" -o -name "_history" \ 97 | -o -name "autologin.conf" -o -name "web.config" -o -name ".env" \ 98 | -o -name ".git" \) -not -empty) 99 | do 100 | echo "[+] Found $item. Copying to output..." 101 | save_name_item=${item:1} 102 | save_name_item=${save_name_item////\\} 103 | cp -r $item /home/ec2-user/OUTPUT/$counter/${save_name_item} 104 | done 105 | 106 | if [ -d "./var/www" ]; then 107 | echo "Web Server Present in /var/www" > /home/ec2-user/OUTPUT/$counter/web_server_true.txt 108 | fi 109 | if [ -d "./inetpub" ]; then 110 | echo "Web Server Present in /inetpub" > /home/ec2-user/OUTPUT/$counter/web_server_true.txt 111 | fi 112 | if [ -d "./usr/share/nginx/" ]; then 113 | echo "Web Server Present in /usr/share/nginx" > /home/ec2-user/OUTPUT/$counter/web_server_true.txt 114 | fi 115 | 116 | echo "[x] Unmounting $dev" 117 | if [ "$fs_type" == "ntfs" ] || [ "$fs_type" == "xfs" ]; then 118 | umount $mount_point 119 | rmdir $mount_point 120 | else 121 | udisksctl unmount -b $dev -f 122 | fi 123 | 124 | return 0 125 | } 126 | 127 | counter=1 128 | something_was_searched=0 129 | mkdir /home/ec2-user/OUTPUT 2>/dev/null 130 | 131 | echo "[*] Mounting $# devices ($@):" 132 | for dev in "$@"; do 133 | device_was_searched=0 134 | echo "[x] Devices: " 135 | blkid -o device -u filesystem ${dev}* 136 | for device in $(blkid -o device -u filesystem ${dev}*); do if mount_and_search $device; then ((counter++)) && something_was_searched=1 && device_was_searched=1; fi done 137 | 138 | if [ $device_was_searched -eq 0 ]; then 139 | echo " [!] Mounting and secret searching for $dev did not work" 140 | fi 141 | done 142 | 143 | if [ $something_was_searched -eq 0 ]; then 144 | echo " [!] Mounting or scanning not successful. Check output for lsblk:" 145 | lsblk --output NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,LABEL 146 | exit 3 147 | fi -------------------------------------------------------------------------------- /src/cloudshovel/utils/digger.py: -------------------------------------------------------------------------------- 1 | import json 2 | import time 3 | from pathlib import Path 4 | from datetime import datetime 5 | from botocore.exceptions import ClientError 6 | from colorama import init, Fore, Style 7 | 8 | availability_zone = 'a' 9 | secret_searcher_role_name = 'minimal-ssm' 10 | tags = [{'Key': 'usage', 'Value': 'CloudQuarry'}] 11 | devices = ['/dev/sdf', 12 | '/dev/sdg', 13 | '/dev/sdh', 14 | '/dev/sdi', 15 | '/dev/sdj', 16 | '/dev/sdk', 17 | '/dev/sdl', 18 | '/dev/sdm', 19 | '/dev/sdn', 20 | '/dev/sdo', 21 | '/dev/sdp'] 22 | 23 | # list of objects of the form {'/dev/sdf':'ami-123456'} to keep track of what device in use 24 | in_use_devices = {} 25 | s3_bucket_name = '' 26 | s3_bucket_region = '' 27 | scanning_script_name = 'mount_and_dig.sh' 28 | install_ntfs_3g_script_name = 'install_ntfs_3g.sh' 29 | boto3_session = None 30 | 31 | def get_ami(ami_id, region): 32 | try: 33 | log_success(f'Retrieving the data for AMI {ami_id} from region {region} (search is performed through deprecated AMIs as well)') 34 | ec2_client = boto3_session.client('ec2', region_name=region) 35 | 36 | response = ec2_client.describe_images( 37 | ImageIds=[ami_id], 38 | IncludeDeprecated=True # This allows searching through deprecated AMIs as well 39 | ) 40 | 41 | # Check if any images were returned 42 | if len(response['Images']) > 0: 43 | ami = response['Images'][0] 44 | log_success(f"AMI {ami_id} found in region {region}") 45 | log_success(f"AMI JSON Object: {ami}") 46 | return ami 47 | else: 48 | log_error(f"AMI {ami_id} not found in region {region}. Exiting...") 49 | cleanup(region) 50 | exit() 51 | except ClientError as e: 52 | error_code = e.response['Error']['Code'] 53 | error_message = e.response['Error']['Message'] 54 | if error_code == 'InvalidAMIID.Malformed': 55 | log_error(f"Invalid AMI ID format: {ami_id}. Exiting...") 56 | elif error_code == 'InvalidAMIID.NotFound': 57 | log_error(f"AMI {ami_id} not found in region {region}. Exiting...") 58 | else: 59 | log_error(f"Unexpected error: {error_message}. Exiting...") 60 | 61 | cleanup(region) 62 | exit() 63 | 64 | 65 | def create_s3_bucket(region): 66 | log_success(f'Checking if S3 bucket {s3_bucket_name} exists...') 67 | s3 = boto3_session.client('s3') 68 | buckets = s3.list_buckets()['Buckets'] 69 | 70 | for bucket in buckets: 71 | if bucket['Name'] == s3_bucket_name: 72 | log_success(f'Bucket {s3_bucket_name} exists in current AWS account') 73 | set_bucket_region(s3_bucket_name) 74 | return 75 | 76 | try: 77 | log_warning('Bucket not found. Creating...') 78 | response = s3.create_bucket(Bucket=s3_bucket_name, CreateBucketConfiguration={'LocationConstraint': region}) 79 | log_success(f'Bucket created: {response["Location"]}') 80 | set_bucket_region(s3_bucket_name) 81 | except ClientError as e: 82 | error_code = e.response['Error']['Code'] 83 | if error_code == 'BucketAlreadyExists': 84 | log_error(f'Bucket {s3_bucket_name} already exists and is owned by somebody else. Please modify the bucket name and run the script again.') 85 | cleanup(region) 86 | exit() 87 | else: 88 | log_error('Unknown error occurred. Execution might continue as expected...') 89 | 90 | 91 | def set_bucket_region(bucket_name): 92 | s3 = boto3_session.client('s3') 93 | 94 | try: 95 | response = s3.get_bucket_location(Bucket=bucket_name) 96 | region = response['LocationConstraint'] 97 | 98 | # AWS returns None for buckets in us-east-1 instead of 'us-east-1' 99 | global s3_bucket_region 100 | s3_bucket_region = region if region else 'us-east-1' 101 | 102 | except Exception as e: 103 | log_error(f"An error occurred: {e}") 104 | return None 105 | 106 | def upload_script_to_bucket(script_name): 107 | log_success(f'Checking if script {script_name} is already inside the bucket {s3_bucket_name}...') 108 | s3 = boto3_session.client('s3', region_name=s3_bucket_region) 109 | response = s3.list_objects_v2(Bucket=s3_bucket_name, Prefix=script_name) 110 | 111 | if 'Contents' in response: 112 | log_success(f'Script found') 113 | return 114 | 115 | log_warning(f'Script {script_name} not found in bucket {s3_bucket_name}. Uploading...') 116 | 117 | base_path = Path(__file__).parent 118 | 119 | f = open(f'{base_path}/bash_scripts/{script_name}') 120 | script = f.read() 121 | f.close() 122 | 123 | s3.put_object(Bucket=s3_bucket_name, Body=script, Key=script_name) 124 | log_success(f'Script {script_name} uploaded in bucket {s3_bucket_name}') 125 | 126 | 127 | def get_instance_profile_secret_searcher(region): 128 | iam = boto3_session.client('iam') 129 | log_success(f'Checking if role {secret_searcher_role_name} for Secret Searcher instance exists') 130 | 131 | try: 132 | response = iam.get_role(RoleName=secret_searcher_role_name) 133 | 134 | log_success(f'Role {response["Role"]["Arn"]} was found') 135 | except ClientError as e: 136 | if e.response['Error']['Code'] != 'NoSuchEntity': 137 | log_error(f'Unknown error: {e["Error"]["Code"]}. Exiting...') 138 | cleanup(region) 139 | exit() 140 | 141 | log_warning('Role doesn\'t exist. Creating...') 142 | response = iam.create_role(RoleName=secret_searcher_role_name, AssumeRolePolicyDocument= 143 | """{ 144 | "Version": "2012-10-17", 145 | "Statement": [ 146 | { 147 | "Effect": "Allow", 148 | "Principal": { 149 | "Service": "ec2.amazonaws.com" 150 | }, 151 | "Action": "sts:AssumeRole" 152 | } 153 | ] 154 | }""", Tags=tags) 155 | 156 | iam.attach_role_policy(RoleName=secret_searcher_role_name, PolicyArn='arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore') 157 | iam.attach_role_policy(RoleName=secret_searcher_role_name, PolicyArn='arn:aws:iam::aws:policy/AmazonS3FullAccess') 158 | 159 | log_success(f'Role {response["Role"]["Arn"]} created and policy configured') 160 | 161 | try: 162 | log_success(f'Checking if instance profile {secret_searcher_role_name} exists') 163 | response = iam.get_instance_profile(InstanceProfileName=secret_searcher_role_name) 164 | log_success(f'Instance profile found: {response["InstanceProfile"]["Arn"]}') 165 | 166 | return response["InstanceProfile"]["Arn"] 167 | except ClientError as e: 168 | log_warning('Instance profile not found') 169 | 170 | if e.response['Error']['Code'] != 'NoSuchEntity': 171 | log_error(f'Unknown error: {e["Error"]["Code"]}. Exiting...') 172 | cleanup(region) 173 | exit() 174 | 175 | log_warning('Creating instance profile...') 176 | response = iam.create_instance_profile(InstanceProfileName=secret_searcher_role_name, Tags=tags) 177 | iam.add_role_to_instance_profile(InstanceProfileName=secret_searcher_role_name, RoleName=secret_searcher_role_name) 178 | 179 | log_success(f'Created instance profile {response["InstanceProfile"]["Arn"]}') 180 | log_success('Waiting 1 min for the instance profile to be fully available in AWS') 181 | time.sleep(60) 182 | 183 | return response["InstanceProfile"]["Arn"] 184 | 185 | 186 | def wait_for_instance_status(instance_id, desired_status, region): 187 | log_success(f'Checking instance status every 2s until the instance has status \'{desired_status}\'') 188 | 189 | ec2 = boto3_session.client('ec2', region) 190 | status_reached = False 191 | 192 | while status_reached == False: 193 | instance = ec2.describe_instances(InstanceIds=[instance_id]) 194 | status_reached = instance['Reservations'][0]['Instances'][0]['State']['Name'] == desired_status 195 | 196 | if status_reached == False: 197 | time.sleep(2) 198 | 199 | log_success(f'Instance {instance_id} reached the status \'{desired_status}\'') 200 | 201 | 202 | def create_secret_searcher(region, instance_profile_arn): 203 | ec2 = boto3_session.client('ec2', region) 204 | 205 | log_success('Checking if a secret searcher is already running in this region...') 206 | instances = ec2.describe_instances(Filters=[{'Name':'tag-key', 'Values':['usage']}, 207 | {'Name':'tag-value','Values':['SecretSearcher']}, 208 | {'Name':'instance-state-name', 'Values':['pending','running']}]) 209 | 210 | if len(instances['Reservations']) > 0: 211 | instance_id = instances['Reservations'][0]['Instances'][0]['InstanceId'] 212 | 213 | log_success(f'Secret searcher found: {instance_id}') 214 | log_success(f"Checking and waiting the instance to be in 'running' state") 215 | 216 | wait_for_instance_status(instance_id, 'running', region) 217 | 218 | log_success(f'Secret searcher is ready and running in this region') 219 | return instance_id 220 | 221 | log_warning('No secret searcher instance found. Starting creation process...') 222 | log_success('Getting AMI for latest Amazon Linux 202* for current region...') 223 | 224 | response = ec2.describe_images(Filters=[{'Name':'name','Values':['al202*-ami-202*-x86_64']}], 225 | Owners=['amazon']) 226 | 227 | sorted_images = sorted( 228 | response['Images'], 229 | key=lambda x: datetime.strptime(x['CreationDate'], '%Y-%m-%dT%H:%M:%S.%fZ'), 230 | reverse=True 231 | ) 232 | 233 | amazon_ami_id = sorted_images[0]['ImageId'] 234 | 235 | log_success(f'Creating Secret Searcher instance based on official and most recent Amazon Image AMI {amazon_ami_id}...') 236 | secret_searcher_instance = ec2.run_instances(InstanceType='c5.large', 237 | Placement={'AvailabilityZone':f'{region}{availability_zone}'}, 238 | IamInstanceProfile ={'Arn':instance_profile_arn}, 239 | ImageId=amazon_ami_id, 240 | MinCount=1, 241 | MaxCount=1, 242 | BlockDeviceMappings=[{'DeviceName':'/dev/xvda', 'Ebs': {'VolumeSize': 50}}], 243 | TagSpecifications=[{'ResourceType': 'instance', 'Tags':[{'Key': 'usage', 'Value': 'SecretSearcher'}]}]) 244 | 245 | instance_id = secret_searcher_instance['Instances'][0]['InstanceId'] 246 | log_success(f"Secret Searcher instance {instance_id} created. Waiting for instance to be in 'running' state...") 247 | 248 | wait_for_instance_status(instance_id, 'running', region) 249 | log_success('Waiting 1 more min for the instance to start SSM Agent') 250 | time.sleep(60) 251 | 252 | return instance_id 253 | 254 | 255 | def install_searching_tools(instance_id, region, is_windows=False): 256 | log_success(f'Installing tools on Secret Searcher instance {instance_id} for searching secrets...') 257 | ssm = boto3_session.client('ssm', region) 258 | 259 | # Download the script at /home/ec2-user/ and execute it 260 | if is_windows: 261 | command = ssm.send_command(InstanceIds=[instance_id], 262 | DocumentName='AWS-RunRemoteScript', 263 | Parameters={ 264 | 'sourceType': ['S3'], 265 | 'sourceInfo': [f'{{"path":"https://{s3_bucket_name}.s3.{s3_bucket_region}.amazonaws.com/{install_ntfs_3g_script_name}"}}'], 266 | 'commandLine': [f'bash /home/ec2-user/{install_ntfs_3g_script_name}'], 267 | 'workingDirectory': ['/home/ec2-user/'] 268 | }) 269 | 270 | log_success('Installation started. Waiting for completion...') 271 | waiter = ssm.get_waiter('command_executed') 272 | waiter.wait(CommandId=command['Command']['CommandId'], InstanceId=instance_id, WaiterConfig={'Delay':15, 'MaxAttempts':60}) 273 | 274 | output = ssm.get_command_invocation(CommandId=command['Command']['CommandId'], InstanceId=instance_id) 275 | log_success(f'Command execution finished with status: {output["Status"]}') 276 | 277 | if output['Status'] != 'Success': 278 | log_error(f'Installation failed. Please check what went wrong or install it manually and disable this step. Exiting...') 279 | cleanup() 280 | exit() 281 | 282 | log_success(f'Copying {scanning_script_name} from S3 bucket {s3_bucket_name} to Secret Searcher instance {instance_id} using SSM...') 283 | bash_command = f"if test -f /home/ec2-user/{scanning_script_name}; then echo '[INFO] Script already present on disk';else aws --region {s3_bucket_region} s3 cp s3://{s3_bucket_name}/{scanning_script_name} /home/ec2-user/{scanning_script_name} && chmod +x /home/ec2-user/{scanning_script_name}; fi" 284 | command = ssm.send_command(InstanceIds=[instance_id], 285 | DocumentName='AWS-RunShellScript', 286 | Parameters={'commands':[bash_command]}) 287 | 288 | waiter = ssm.get_waiter('command_executed') 289 | waiter.wait(CommandId=command['Command']['CommandId'], InstanceId=instance_id) 290 | 291 | output = ssm.get_command_invocation(CommandId=command['Command']['CommandId'], InstanceId=instance_id) 292 | log_success(f'Command execution finished with status: {output["Status"]}') 293 | 294 | 295 | def get_targets(region, os='all'): 296 | f = open('targets.json') 297 | all_amis = json.loads(f.read()) 298 | f.close() 299 | 300 | targets = [x for x in all_amis if x['Region'] == region] 301 | 302 | if os == 'all': 303 | return targets 304 | 305 | if os == 'linux': 306 | linux_targets = [x for x in targets if 'Platform' not in x] 307 | return linux_targets 308 | 309 | if os == 'windows': 310 | windows_targets = [x for x in targets if 'Platform' in x] 311 | return windows_targets 312 | 313 | def start_instance_with_target_ami(ami_object, region, is_ena=False): 314 | ec2 = boto3_session.client('ec2', region) 315 | log_success(f"Starting EC2 instance for AMI {ami_object['ImageId']}...") 316 | 317 | try: 318 | instance_type = 'c5.large' 319 | if 'VirtualizationType' in ami_object and ami_object['VirtualizationType'] == 'paravirtual': 320 | log_warning('VirtualizationType is paravirtual. Instance type will be changed from c5.large to c3.large') 321 | instance_type = 'c3.large' 322 | elif is_ena: 323 | log_warning('ENA support is required. Instance type will be changed from c5.large to t2.medium and will have a public IP address.') 324 | instance_type = 't2.medium' 325 | 326 | instance = None 327 | if is_ena == False: 328 | instance = ec2.run_instances(InstanceType=instance_type, 329 | Placement={'AvailabilityZone':f'{region}{availability_zone}'}, 330 | NetworkInterfaces=[{'AssociatePublicIpAddress':False, 'DeviceIndex':0}], 331 | MaxCount=1, MinCount=1, 332 | ImageId=ami_object['ImageId'], 333 | TagSpecifications=[{'ResourceType': 'instance', 'Tags':tags}]) 334 | else: 335 | instance = ec2.run_instances(InstanceType=instance_type, 336 | Placement={'AvailabilityZone':f'{region}{availability_zone}'}, 337 | MaxCount=1, MinCount=1, 338 | ImageId=ami_object['ImageId'], 339 | TagSpecifications=[{'ResourceType': 'instance', 'Tags':tags}]) 340 | 341 | instance_id = instance['Instances'][0]['InstanceId'] 342 | log_success(f"Instance {instance_id} created. Waiting to be in 'running' state...") 343 | 344 | waiter = ec2.get_waiter('instance_running') 345 | waiter.wait(InstanceIds=[instance_id], WaiterConfig={'Delay': 5, 'MaxAttempts': 120}) 346 | 347 | log_success(f"Instance {instance_id} based on ami {ami_object['ImageId']} is ready") 348 | 349 | return {"instanceId": instance_id, "ami": ami_object['ImageId']} 350 | except Exception as e: 351 | error = 'failed ' 352 | if hasattr(e, 'message'): 353 | error = f'{error} {e.message}' 354 | else: 355 | error = f'{error} {e}' 356 | 357 | if '(ENA)' in error and is_ena == False: 358 | log_warning(f'AMI {ami_object["ImageId"]} requires ENA support. Attempting to start the instance again with ENA support compatibility...') 359 | return start_instance_with_target_ami(ami_object, region, is_ena=True) 360 | else: 361 | log_error(f"Something went wrong when launching instance with AMI {ami_object['ImageId']}: {str(e)}") 362 | log_error("To fix this you might need to edit the script and change the instance type to be compatible with the AMIs requirements. Check instance types here: https://aws.amazon.com/ec2/instance-types/") 363 | log_error("Script can't resume execution and will exit...") 364 | cleanup() 365 | exit() 366 | 367 | def stop_instance(instance_ids, region): 368 | try: 369 | log_success(f'Stopping EC2 instances {instance_ids}') 370 | ec2 = boto3_session.client('ec2', region) 371 | ec2.stop_instances(InstanceIds=instance_ids) 372 | 373 | waiter = ec2.get_waiter('instance_stopped') 374 | waiter.wait(InstanceIds=instance_ids, WaiterConfig={'Delay':5, 'MaxAttempts':1000}) 375 | 376 | except Exception as e: 377 | log_error(f'Error when stopping instances {instance_ids}. Error: {str(e)}') 378 | 379 | 380 | def move_volumes_and_terminate_instance(instance_id, instance_id_secret_searcher, ami, region): 381 | ec2 = boto3_session.client('ec2', region) 382 | log_success('Starting detaching volumes procedure...') 383 | 384 | volumes = ec2.describe_volumes(Filters=[{'Name':'attachment.instance-id', 'Values':[instance_id]}]) 385 | volume_ids = [x['VolumeId'] for x in volumes['Volumes']] 386 | 387 | if len(devices) < len(volume_ids): 388 | log_error('Target AMI has more EBS volumes than the number of supported EBS volumes that can be attached to an EC2 instance. This case is not covered by the script. Exiting...') 389 | exit() 390 | 391 | log_success(f'Volumes to detach: {volume_ids}') 392 | 393 | for volume_id in volume_ids: 394 | log_success(f'Detaching volume {volume_id}...') 395 | ec2.detach_volume(VolumeId=volume_id) 396 | 397 | log_success("Waiting for all detached volumes to be in 'available' state...") 398 | 399 | is_available = False 400 | while is_available == False: 401 | volumes = ec2.describe_volumes(VolumeIds=volume_ids) 402 | is_available = all([x['State'] == 'available' for x in volumes['Volumes']]) 403 | 404 | if is_available == False: 405 | time.sleep(5) 406 | 407 | log_success("All volumes are in 'available' state") 408 | 409 | log_warning(f'Terminating instance {instance_id} created for target AMI...') 410 | ec2.terminate_instances(InstanceIds=[instance_id]) 411 | log_success('Instance {instance_id} terminated') 412 | 413 | log_success('Moving volumes to secret searching instance...') 414 | 415 | for volume_id in volume_ids: 416 | device = devices[0] 417 | 418 | log_success(f'Attaching volume {volume_id} as device {device}') 419 | ec2.attach_volume(Device=device, InstanceId=instance_id_secret_searcher, VolumeId=volume_id) 420 | 421 | devices.remove(device) 422 | in_use_devices[device]=ami 423 | 424 | log_success("Waiting for volumes to be in 'in-use' state...") 425 | waiter = ec2.get_waiter('volume_in_use') 426 | waiter.wait(VolumeIds=volume_ids, WaiterConfig={'Delay':3, 'MaxAttempts':60}) 427 | log_success('Volumes are ready to be searched') 428 | 429 | return volume_ids 430 | 431 | 432 | def start_digging_for_secrets(instance_id_secret_searcher, target_ami, region): 433 | log_success('Starting digging for secrets...') 434 | ssm = boto3_session.client('ssm', region) 435 | volumes = [] 436 | 437 | for in_use_device in in_use_devices.keys(): 438 | if target_ami in in_use_devices[in_use_device]: 439 | volumes.append(in_use_device) 440 | 441 | parameter_volumes = ' '.join(volumes) 442 | 443 | command = ssm.send_command(InstanceIds=[instance_id_secret_searcher], 444 | DocumentName='AWS-RunShellScript', 445 | Parameters={'commands':[f'/home/ec2-user/{scanning_script_name} {parameter_volumes}']}) 446 | 447 | log_success(f'Secret searching in {parameter_volumes} started. Waiting for completion...') 448 | 449 | waiter = ssm.get_waiter('command_executed') 450 | waiter.wait(CommandId=command['Command']['CommandId'], 451 | InstanceId=instance_id_secret_searcher, 452 | WaiterConfig={'Delay':5, 'MaxAttempts':720}) 453 | 454 | log_success('Scanning completed') 455 | 456 | 457 | def upload_results(instance_id_secret_searcher, target_ami, region): 458 | log_success(f'Uploading results for AMI {target_ami} to S3 bucket {s3_bucket_name}...') 459 | 460 | ssm = boto3_session.client('ssm', region) 461 | command = ssm.send_command(InstanceIds=[instance_id_secret_searcher], 462 | DocumentName='AWS-RunShellScript', 463 | Parameters={'commands':[f'aws --region {s3_bucket_region} s3 sync /home/ec2-user/OUTPUT/ s3://{s3_bucket_name}/{region}/{target_ami}/', 'rm -rf /home/ec2-user/OUTPUT/']}) 464 | 465 | log_success(f'Upload started. Waiting for upload to complete (this might take a while)...') 466 | waiter = ssm.get_waiter('command_executed') 467 | waiter.wait(CommandId=command['Command']['CommandId'], InstanceId=instance_id_secret_searcher, WaiterConfig={'Delay':5, 'MaxAttempts':800}) 468 | log_success(f'Upload completed') 469 | 470 | 471 | def delete_volumes(volume_ids, region): 472 | log_success(f'Starting deleting volumes {volume_ids} procedure...') 473 | ec2 = boto3_session.client('ec2', region) 474 | 475 | log_success(f'Detaching volumes {volume_ids}...') 476 | for volume_id in volume_ids: 477 | ec2.detach_volume(VolumeId=volume_id) 478 | 479 | log_success("Waiting volumes to be in 'available' state...") 480 | 481 | waiter = ec2.get_waiter('volume_available') 482 | waiter.wait(VolumeIds=volume_ids, WaiterConfig={'Delay':3, 'MaxAttempts':80}) 483 | 484 | log_warning(f'Deleting volumes {volume_ids}') 485 | for volume_id in volume_ids: 486 | ec2.delete_volume(VolumeId=volume_id) 487 | 488 | log_warning("All volumes were set for deletion. The script doesn't wait for deletion confirmation. Please check manually if everything was deleted.") 489 | 490 | 491 | def cleanup(region): 492 | log_warning('Starting cleanup (the S3 bucket will not be deleted)...') 493 | ec2 = boto3_session.client('ec2', region) 494 | 495 | log_success('Deleting EC2 secret searcher instance...') 496 | instances = ec2.describe_instances(Filters=[{'Name':'tag-key', 'Values':['usage']}, 497 | {'Name':'tag-value','Values':['SecretSearcher']}, 498 | {'Name':'instance-state-name', 'Values':['pending','running']}]) 499 | 500 | if len(instances['Reservations']) == 0: 501 | log_warning('No secret searcher instance found. Continuing with next resource') 502 | else: 503 | # should be only one instance, but just to be sure 504 | instance_ids = [x['InstanceId'] for x in instances['Reservations'][0]['Instances']] 505 | log_success(f'Terminating instances: {instance_ids}') 506 | ec2.terminate_instances(InstanceIds=instance_ids) 507 | 508 | iam = boto3_session.client('iam') 509 | 510 | log_success('Deleting role and instance profile...') 511 | try: 512 | iam.remove_role_from_instance_profile(InstanceProfileName=secret_searcher_role_name, RoleName=secret_searcher_role_name) 513 | iam.delete_instance_profile(InstanceProfileName=secret_searcher_role_name) 514 | iam.detach_role_policy(RoleName=secret_searcher_role_name, PolicyArn='arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore') 515 | iam.detach_role_policy(RoleName=secret_searcher_role_name, PolicyArn='arn:aws:iam::aws:policy/AmazonS3FullAccess') 516 | iam.delete_role(RoleName=secret_searcher_role_name) 517 | log_success('Role and instance profile deleted') 518 | except ClientError as e: 519 | if e.response['Error']['Code'] != 'NoSuchEntity': 520 | log_error(f'Unknown error: {e["Error"]["Code"]}. Exiting...') 521 | exit() 522 | else: 523 | log_success(f'No role {secret_searcher_role_name} found.') 524 | 525 | 526 | init() # Initialize colorama 527 | 528 | def log_success(message): 529 | print(f"{Fore.GREEN}[INFO]{Style.RESET_ALL} {message}") 530 | 531 | def log_warning(message): 532 | print(f"{Fore.YELLOW}[WARN]{Style.RESET_ALL} {message}") 533 | 534 | def log_error(message): 535 | print(f"{Fore.RED}[ERROR]{Style.RESET_ALL} {message}") 536 | 537 | def dig(args, session): 538 | global boto3_session 539 | boto3_session = session 540 | global s3_bucket_name 541 | s3_bucket_name = args.bucket 542 | region = args.region 543 | searched = False 544 | start_scan_time = time.time() 545 | volume_ids = [] 546 | 547 | try: 548 | log_warning("If ran in an EC2 instance, make sure it has the required permissions to execute the tool") 549 | target_ami = get_ami(args.ami_id, region) 550 | 551 | instance_profile_arn_secret_searcher = get_instance_profile_secret_searcher(region) 552 | instance_id_secret_searcher = create_secret_searcher(region, instance_profile_arn_secret_searcher) 553 | create_s3_bucket(region) 554 | upload_script_to_bucket(scanning_script_name) 555 | 556 | is_windows = 'Platform' in target_ami and target_ami['Platform'] == 'windows' 557 | if is_windows: 558 | upload_script_to_bucket(install_ntfs_3g_script_name) 559 | 560 | install_searching_tools(instance_id_secret_searcher, region, is_windows) 561 | 562 | instance = start_instance_with_target_ami(target_ami, region) 563 | stop_instance([instance['instanceId']], region) 564 | 565 | volume_ids = move_volumes_and_terminate_instance(instance['instanceId'], instance_id_secret_searcher, instance['ami'], region) 566 | start_scan_time = time.time() 567 | start_digging_for_secrets(instance_id_secret_searcher, instance['ami'], region) 568 | 569 | searched = True 570 | delete_volumes(volume_ids, region) 571 | except Exception as e: 572 | log_error(f'Exception occurred for ami {target_ami}') 573 | 574 | log_error(f'Error: {e}') 575 | 576 | if searched == False and len(volume_ids) > 0: 577 | delete_volumes(volume_ids, region) 578 | elif len(volume_ids) > 0: 579 | log_error("An error occurred while deleting the volumes. Please check manually what happened.") 580 | else: 581 | upload_results(instance_id_secret_searcher, instance['ami'], region) 582 | log_success(f"Total duration for ami {target_ami['ImageId']}: {int((time.time() - start_scan_time))} seconds") 583 | log_success(f'Scan finished. Check results in s3://{s3_bucket_name}') 584 | finally: 585 | cleanup(region) 586 | 587 | 588 | if __name__ == '__main__': 589 | dig() 590 | --------------------------------------------------------------------------------