├── .gitignore ├── LICENSE ├── README.md ├── all-regions.sh ├── api_gateway_enum.py ├── cognito_get_credentials.py ├── cognito_identity_pools.py ├── ec2_instance_profile_permissions.py ├── ec2_snapshots.py ├── enrich_detect_secrets.py ├── guardduty_findings.py ├── iam_access_key_owner.py ├── iam_role_trust_policies.py ├── iam_role_trust_policies_filter.py ├── iam_simulate_action.py ├── kms_grant_audit.py ├── lambda_dump.py ├── lambda_last_used.py ├── permission-bruteforce ├── README.md └── enumerate-iam.py ├── rds_snapshots.py ├── rds_snapshots_filter.py ├── regions_in_use.py ├── requirements.txt ├── route53_dump.py ├── s3_last_used.py ├── s3_versioning_cost.py ├── utils ├── __init__.py ├── boto_error_handling.py ├── get_user_name.py ├── json_encoder.py ├── json_printer.py ├── json_writer.py ├── regions.py ├── remove_metadata.py └── session.py ├── vpc_security_group_usage.py └── whoami.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | .idea/ 107 | 108 | *.json -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | This repository contains tools, scripts and other resources used during AWS Cloud 3 | security assessments. 4 | 5 | ## Documentation 6 | No documentation is provided, some scripts might have a `--help` you can use do 7 | better understand what the tool does, but in general I recommend reading the 8 | source code. 9 | 10 | 11 | -------------------------------------------------------------------------------- /all-regions.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | for region in `aws ec2 describe-regions --output text | cut -f3` 4 | do 5 | echo -e "\nListing Instances in region:'$region'..." 6 | aws ec2 describe-instances --region $region 7 | done 8 | -------------------------------------------------------------------------------- /api_gateway_enum.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import boto3 4 | 5 | from utils.json_encoder import json_encoder 6 | from utils.json_writer import json_writer 7 | from utils.json_printer import json_printer 8 | from utils.session import get_session 9 | from utils.regions import get_all_regions 10 | from utils.boto_error_handling import yield_handling_errors 11 | 12 | 13 | def get_api_gateways_for_region(client): 14 | for rest_api in client.get_rest_apis()['items']: 15 | yield rest_api 16 | 17 | 18 | def get_authorizers(client, api_id): 19 | return client.get_authorizers(restApiId=api_id)['items'] 20 | 21 | 22 | def main(): 23 | all_data = {} 24 | session = get_session() 25 | 26 | for region in get_all_regions(session): 27 | all_data[region] = {} 28 | client = session.client('apigateway', region_name=region) 29 | 30 | iterator = yield_handling_errors(get_api_gateways_for_region, client) 31 | 32 | for rest_api in iterator: 33 | api_id = rest_api['id'] 34 | print('Region: %s / API ID: %s' % (region, api_id)) 35 | 36 | try: 37 | authorizers = get_authorizers(client, api_id) 38 | except Exception as e: 39 | msg = 'Failed to retrieve authorizers for %s @ %s. Error: "%s"' 40 | args = (api_id, region, e) 41 | print(msg % args) 42 | 43 | authorizers = {} 44 | 45 | all_data[region][api_id] = {} 46 | all_data[region][api_id]['main'] = rest_api 47 | all_data[region][api_id]['authorizers'] = authorizers 48 | 49 | else: 50 | print('Region: %s / No API gateways' % region) 51 | 52 | os.makedirs('output', exist_ok=True) 53 | json_writer('output/api-gateways.json', all_data) 54 | json_printer(all_data) 55 | 56 | 57 | if __name__ == '__main__': 58 | main() 59 | -------------------------------------------------------------------------------- /cognito_get_credentials.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | # Enable logging 4 | # boto3.set_stream_logger(name='botocore') 5 | 6 | client = boto3.client('cognito-identity', region_name='us-east-1') 7 | 8 | _id = client.get_id(IdentityPoolId='us-east-1:XXXXXX-XXXXXXXXX-XXXXXXX-XXXXXX') 9 | _id = _id['IdentityId'] 10 | print(_id) 11 | 12 | print client.get_credentials_for_identity(IdentityId=_id) 13 | -------------------------------------------------------------------------------- /cognito_identity_pools.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import boto3 4 | 5 | from utils.json_encoder import json_encoder 6 | from utils.json_writer import json_writer 7 | from utils.json_printer import json_printer 8 | from utils.session import get_session 9 | from utils.regions import get_all_regions 10 | from botocore.exceptions import EndpointConnectionError 11 | 12 | 13 | def get_id_pools(client): 14 | try: 15 | id_pools = client.list_identity_pools(MaxResults=60)['IdentityPools'] 16 | except EndpointConnectionError: 17 | print('Cognito is not supported in this region') 18 | return 19 | 20 | for id_pool in id_pools: 21 | yield id_pool 22 | 23 | def main(): 24 | session = get_session() 25 | 26 | all_data = {} 27 | 28 | for region in get_all_regions(session): 29 | all_data[region] = {} 30 | client = session.client('cognito-identity', region_name=region) 31 | 32 | print('Processing region: %s' % region) 33 | 34 | for i, id_pool in enumerate(get_id_pools(client)): 35 | id_pool_id = id_pool['IdentityPoolId'] 36 | 37 | id_pool = client.describe_identity_pool(IdentityPoolId=id_pool_id) 38 | pool_roles = client.get_identity_pool_roles(IdentityPoolId=id_pool_id) 39 | 40 | all_data[region][id_pool_id] = {} 41 | all_data[region][id_pool_id]['describe'] = id_pool 42 | all_data[region][id_pool_id]['roles'] = pool_roles 43 | 44 | sys.stdout.write('.') 45 | sys.stdout.flush() 46 | 47 | os.makedirs('output', exist_ok=True) 48 | json_writer('output/cognito-id-pools.json', all_data) 49 | json_printer(all_data) 50 | 51 | 52 | if __name__ == '__main__': 53 | main() 54 | -------------------------------------------------------------------------------- /ec2_instance_profile_permissions.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import sys 4 | 5 | import boto3 6 | 7 | from utils.json_encoder import json_encoder 8 | from utils.json_writer import json_writer 9 | from utils.json_printer import json_printer 10 | from utils.session import get_session 11 | from utils.regions import get_all_regions 12 | from utils.boto_error_handling import yield_handling_errors 13 | 14 | 15 | def get_instance_profiles(ec2_client, iam_client): 16 | 17 | paginator = ec2_client.get_paginator('describe_instances') 18 | 19 | for page in paginator.paginate(): 20 | for reservation in page['Reservations']: 21 | for instance in reservation['Instances']: 22 | if 'IamInstanceProfile' not in instance: 23 | continue 24 | 25 | if 'Arn' not in instance['IamInstanceProfile']: 26 | continue 27 | 28 | instance_profile_arn = instance['IamInstanceProfile']['Arn'] 29 | instance_profile_name = instance_profile_arn.split('/')[-1] 30 | 31 | instance_profile = iam_client.get_instance_profile(InstanceProfileName=instance_profile_name)['InstanceProfile'] 32 | role_name = instance_profile['Roles'][0]['RoleName'] 33 | 34 | role_policies = iam_client.list_role_policies(RoleName=role_name)['PolicyNames'] 35 | 36 | for policy_name in role_policies: 37 | response = iam_client.get_role_policy(RoleName=role_name, PolicyName=policy_name) 38 | response['IamInstanceProfile'] = instance_profile_arn 39 | response['Instance'] = instance 40 | yield response 41 | 42 | 43 | 44 | def main(): 45 | session = get_session() 46 | 47 | all_data = {} 48 | iam_client = session.client('iam') 49 | 50 | for region in get_all_regions(session): 51 | all_data[region] = {} 52 | ec2_client = session.client('ec2', region_name=region) 53 | 54 | print('Processing region: %s' % region) 55 | 56 | iterator = yield_handling_errors(get_instance_profiles, ec2_client, iam_client) 57 | iterator = enumerate(iterator) 58 | 59 | for i, instance_profile_policy in iterator: 60 | all_data[region][i] = instance_profile_policy 61 | 62 | sys.stdout.write('.') 63 | sys.stdout.flush() 64 | 65 | os.makedirs('output', exist_ok=True) 66 | json_writer('output/instance_profile_policies.json', all_data) 67 | json_printer(all_data) 68 | 69 | 70 | if __name__ == '__main__': 71 | main() 72 | -------------------------------------------------------------------------------- /ec2_snapshots.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import sys 4 | 5 | import boto3 6 | 7 | from utils.json_encoder import json_encoder 8 | from utils.json_writer import json_writer 9 | from utils.json_printer import json_printer 10 | from utils.session import get_session 11 | from utils.regions import get_all_regions 12 | from utils.boto_error_handling import yield_handling_errors 13 | 14 | 15 | def get_snapshots(ec2_client): 16 | paginator = ec2_client.get_paginator('describe_snapshots') 17 | 18 | response_iterator = paginator.paginate(DryRun=False, 19 | OwnerIds=['self'], 20 | PaginationConfig={'MaxItems': 5000, 'PageSize': 100}) 21 | 22 | for snapshots_page in response_iterator: 23 | snapshots = snapshots_page['Snapshots'] 24 | 25 | for snapshot in snapshots: 26 | perms = ec2_client.describe_snapshot_attribute(Attribute='createVolumePermission', 27 | SnapshotId=snapshot['SnapshotId'])['CreateVolumePermissions'] 28 | 29 | # The permissions for a snapshot are specified using the 30 | # createVolumePermission attribute of the snapshot. 31 | # 32 | # To make a snapshot public, set the group to all. 33 | # To share a snapshot with a specific AWS account, 34 | # set the user to the ID of the AWS account. 35 | # 36 | # https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html 37 | snapshot['CreateVolumePermissions'] = perms 38 | 39 | if perms: 40 | print('Shared snapshot found: %s !' % snapshot['SnapshotId']) 41 | shapshot['shared'] = True 42 | else: 43 | shapshot['shared'] = False 44 | 45 | yield snapshot 46 | 47 | 48 | def main(): 49 | session = get_session() 50 | 51 | all_data = {} 52 | 53 | for region in get_all_regions(session): 54 | ec2_client = session.client('ec2', region) 55 | all_data[region] = {} 56 | 57 | print('Processing region: %s' % region) 58 | 59 | iterator = yield_handling_errors(get_snapshots, ec2_client) 60 | iterator = enumerate(iterator) 61 | 62 | for i, snapshot in iterator: 63 | all_data[region][i] = snapshot 64 | 65 | sys.stdout.write('.') 66 | sys.stdout.flush() 67 | 68 | if all_data[region]: 69 | print('\n') 70 | 71 | os.makedirs('output', exist_ok=True) 72 | json_writer('output/ec2_snapshots.json', all_data) 73 | json_printer(all_data) 74 | 75 | 76 | if __name__ == '__main__': 77 | main() 78 | -------------------------------------------------------------------------------- /enrich_detect_secrets.py: -------------------------------------------------------------------------------- 1 | USAGE = """\ 2 | Enrich the output of detect-secrets to include the secret and context. 3 | 4 | ./enrich-detect-secrets.py detect-secrets-output.json scanned-file.json 5 | """ 6 | 7 | import sys 8 | import json 9 | import os 10 | 11 | 12 | def parse_arguments(): 13 | if len(sys.argv) != 3: 14 | print(USAGE) 15 | sys.exit(1) 16 | 17 | ds_output = sys.argv[1] 18 | scanned_file = sys.argv[2] 19 | 20 | if not os.path.exists(ds_output): 21 | print(USAGE) 22 | sys.exit(2) 23 | 24 | if not os.path.exists(scanned_file): 25 | print(USAGE) 26 | sys.exit(2) 27 | 28 | return ds_output, scanned_file 29 | 30 | 31 | def get_lines(scanned_file, line_number): 32 | line_numbers = [line_number - 3, 33 | line_number - 2, 34 | line_number - 1, 35 | line_number, 36 | line_number + 1, 37 | line_number + 2, 38 | line_number + 3,] 39 | 40 | output = [] 41 | 42 | for i, line in enumerate(open(scanned_file)): 43 | if i + 1 in line_numbers: 44 | output.append(line[:-1]) 45 | 46 | return output 47 | 48 | 49 | def enrich(ds_output, scanned_file): 50 | detected_secrets = json.loads(open(ds_output).read()) 51 | 52 | results = detected_secrets.get('results', {}) 53 | 54 | if len(results) != 1: 55 | print('Can only handle detect-secrets output with one filename.') 56 | sys.exit(1) 57 | 58 | for filename in results: 59 | for result in results[filename]: 60 | line_number = result['line_number'] 61 | lines = get_lines(scanned_file, line_number) 62 | 63 | result['context'] = lines 64 | 65 | json_data = json.dumps(detected_secrets, indent=4) 66 | output = open(ds_output, 'w') 67 | output.write(json_data) 68 | 69 | if __name__ == '__main__': 70 | ds_output, scanned_file = parse_arguments() 71 | enrich(ds_output, scanned_file) 72 | -------------------------------------------------------------------------------- /guardduty_findings.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import json 4 | import boto3 5 | 6 | from utils.session import get_session 7 | from utils.regions import get_all_regions 8 | from utils.json_encoder import json_encoder 9 | from utils.json_writer import json_writer 10 | from utils.json_printer import json_printer 11 | 12 | 13 | def get_findings(session, region): 14 | """ 15 | Identify configured detectors, and retrieve findings. 16 | """ 17 | gd_client = session.client("guardduty", region) 18 | 19 | detectors = gd_client.list_detectors() 20 | detectors = detectors['DetectorIds'] 21 | 22 | if not detectors: 23 | print('%s has no detectors' % region) 24 | 25 | findings = [] 26 | 27 | for detector in detectors: 28 | # TODO: Handle findings pagination 29 | finding_ids = gd_client.list_findings(DetectorId=detector) 30 | finding_ids = finding_ids['FindingIds'] 31 | 32 | findings = gd_client.get_findings( 33 | DetectorId=detector, 34 | FindingIds=finding_ids 35 | ) 36 | findings = findings['Findings'] 37 | 38 | for f in findings: 39 | f['DetectorId'] = detector 40 | 41 | findings.extend(findings) 42 | 43 | return findings 44 | 45 | 46 | def main(): 47 | session = get_session() 48 | 49 | all_data = {} 50 | 51 | for region in get_all_regions(session): 52 | all_data[region] = get_findings(session, region) 53 | 54 | os.makedirs('output', exist_ok=True) 55 | json_writer('output/guardduty.json', all_data) 56 | json_printer(all_data) 57 | 58 | 59 | if __name__ == '__main__': 60 | main() 61 | -------------------------------------------------------------------------------- /iam_access_key_owner.py: -------------------------------------------------------------------------------- 1 | # Find the IAM username belonging to one access key 2 | 3 | import argparse 4 | import boto3 5 | import sys 6 | 7 | from botocore.exceptions import ClientError 8 | 9 | 10 | def get_session(): 11 | parser = argparse.ArgumentParser() 12 | parser.add_argument( 13 | '--profile', 14 | help='AWS profile from ~/.aws/credentials', 15 | required=False, 16 | default='default' 17 | ) 18 | 19 | parser.add_argument( 20 | '--access-key', 21 | help='AWS IAM access key', 22 | required=True 23 | ) 24 | 25 | args = parser.parse_args() 26 | 27 | try: 28 | session = boto3.Session(profile_name=args.profile) 29 | except Exception as e: 30 | print('%s' % e) 31 | sys.exit(1) 32 | 33 | return session, args.access_key 34 | 35 | 36 | def find_user(session, access_key): 37 | iam_client = session.client('iam') 38 | 39 | try: 40 | key_info = iam_client.get_access_key_last_used(AccessKeyId=access_key) 41 | return key_info['UserName'] 42 | except ClientError as e: 43 | print("Received error: %s" % e) 44 | 45 | if e.response['Error']['Code'] == 'AccessDenied': 46 | return "Key does not exist in target account" 47 | 48 | 49 | def main(): 50 | session, access_key = get_session() 51 | 52 | user = find_user(session, access_key) 53 | print(user) 54 | 55 | 56 | if __name__ == '__main__': 57 | main() 58 | -------------------------------------------------------------------------------- /iam_role_trust_policies.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | 4 | import boto3 5 | 6 | from utils.session import get_session 7 | from utils.regions import get_all_regions 8 | from utils.json_encoder import json_encoder 9 | from utils.json_writer import json_writer 10 | from utils.json_printer import json_printer 11 | 12 | 13 | def get_role_names(client): 14 | paginator = client.get_paginator('list_roles') 15 | page_iterator = paginator.paginate(MaxItems=200) 16 | 17 | for page in page_iterator: 18 | for role in page['Roles']: 19 | yield role['RoleName'] 20 | 21 | 22 | def get_role_details(client, role_name): 23 | role = client.get_role(RoleName=role_name)['Role'] 24 | return role 25 | 26 | 27 | def main(): 28 | session = get_session() 29 | 30 | all_data = {} 31 | 32 | client = session.client('iam') 33 | 34 | for role_name in get_role_names(client): 35 | print('RoleName: %s' % (role_name,)) 36 | 37 | roles = [] 38 | 39 | try: 40 | role_details = get_role_details(client, role_name) 41 | except Exception as e: 42 | msg = 'Failed to retrieve role for %s. Error: "%s"' 43 | args = (role_name, e) 44 | print(msg % args) 45 | 46 | all_data[role_name] = role_details 47 | 48 | os.makedirs('output', exist_ok=True) 49 | json_writer('output/role-details.json', all_data) 50 | json_printer(all_data) 51 | 52 | 53 | if __name__ == '__main__': 54 | main() 55 | -------------------------------------------------------------------------------- /iam_role_trust_policies_filter.py: -------------------------------------------------------------------------------- 1 | import json 2 | import pprint 3 | 4 | data = json.loads(open('output/role-details.json').read()) 5 | 6 | for role in data: 7 | role_data = data[role] 8 | 9 | if 'AssumeRolePolicyDocument' not in role_data: 10 | continue 11 | 12 | statements = role_data['AssumeRolePolicyDocument']['Statement'] 13 | 14 | if len(statements) > 1: 15 | print(role) 16 | pprint.pprint(statements) 17 | continue 18 | 19 | # "Action": "sts:AssumeRoleWithSAML", 20 | first_statement = statements[0] 21 | 22 | if first_statement['Action'] == 'sts:AssumeRoleWithSAML': 23 | continue 24 | 25 | should_continue = True 26 | 27 | principals = first_statement['Principal'] 28 | if 'Service' not in principals: 29 | print(role) 30 | pprint.pprint(statements) 31 | continue 32 | 33 | services = first_statement['Principal']['Service'] 34 | if isinstance(services, str): 35 | services = [services] 36 | 37 | for service in services: 38 | if not service.endswith('.amazonaws.com'): 39 | should_continue = False 40 | break 41 | 42 | if should_continue: 43 | continue 44 | 45 | print(role) 46 | pprint.pprint(statements) 47 | -------------------------------------------------------------------------------- /iam_simulate_action.py: -------------------------------------------------------------------------------- 1 | # 2 | # Find which principals can run a specific API method: 3 | # 4 | # python iam_simulate_action.py lambda:GetFunction 5 | # 6 | import os 7 | import sys 8 | import json 9 | import itertools 10 | 11 | import boto3 12 | 13 | from utils.session import get_session 14 | from utils.regions import get_all_regions 15 | from utils.json_encoder import json_encoder 16 | from utils.json_writer import json_writer 17 | from utils.json_printer import json_printer 18 | 19 | 20 | def get_users(client): 21 | """ 22 | :return: ARN for all IAM users 23 | """ 24 | return [u['Arn'] for u in client.list_users(MaxItems=1000)['Users']] 25 | 26 | 27 | def get_groups(client): 28 | """ 29 | :return: ARN for all IAM groups 30 | """ 31 | return [g['Arn'] for g in client.list_groups(MaxItems=1000)['Groups']] 32 | 33 | 34 | def get_roles(client): 35 | """ 36 | :return: ARN for all IAM roles 37 | """ 38 | return [r['Arn'] for r in client.list_roles(MaxItems=1000)['Roles']] 39 | 40 | 41 | def main(): 42 | session = get_session() 43 | actions = [ 44 | 'sts:AssumeRole' 45 | ] 46 | 47 | iam_client = session.client('iam') 48 | 49 | all_principals = itertools.chain( 50 | get_users(iam_client), 51 | get_groups(iam_client), 52 | get_roles(iam_client), 53 | ) 54 | 55 | allowed_principals = [] 56 | 57 | for principal in all_principals: 58 | evaluation_result = iam_client.simulate_principal_policy( 59 | PolicySourceArn=principal, 60 | ActionNames=actions 61 | ) 62 | 63 | if evaluation_result['EvaluationResults'][0]['EvalDecision'] == 'allowed': 64 | allowed_principals.append(principal) 65 | sys.stdout.write('A') 66 | sys.stdout.flush() 67 | else: 68 | sys.stdout.write('.') 69 | sys.stdout.flush() 70 | 71 | print('\n') 72 | 73 | print('These principals are allowed to %s:' % actions) 74 | print('\n'.join([' - %s' % ap for ap in allowed_principals])) 75 | 76 | if __name__ == '__main__': 77 | main() 78 | -------------------------------------------------------------------------------- /kms_grant_audit.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | 4 | import boto3 5 | 6 | from utils.session import get_session 7 | from utils.regions import get_all_regions 8 | from utils.json_encoder import json_encoder 9 | from utils.json_writer import json_writer 10 | from utils.json_printer import json_printer 11 | 12 | 13 | def get_keys_for_region(client): 14 | region_keys = client.list_keys(Limit=1000)['Keys'] 15 | return [k['KeyId'] for k in region_keys] 16 | 17 | 18 | def get_key_grants(client, key_id): 19 | grants = client.list_grants(KeyId=key_id)['Grants'] 20 | return grants 21 | 22 | 23 | def get_key_policies(client, key_id): 24 | policies = [] 25 | 26 | for policy in client.list_key_policies(KeyId=key_id)['PolicyNames']: 27 | policy_json = client.get_key_policy(KeyId=key_id, PolicyName=policy) 28 | policy_json = json.loads(policy_json['Policy']) 29 | policies.append(policy_json) 30 | 31 | return policies 32 | 33 | 34 | def main(): 35 | session = get_session() 36 | 37 | all_data = {} 38 | 39 | for region in get_all_regions(session): 40 | all_data[region] = {} 41 | client = session.client('kms', region_name=region) 42 | 43 | keys_for_region = get_keys_for_region(client) 44 | 45 | if not keys_for_region: 46 | print('Region: %s / No KMS keys' % region) 47 | continue 48 | 49 | for key in keys_for_region: 50 | print('Region: %s / KeyId: %s' % (region, key)) 51 | 52 | grants = [] 53 | policies = [] 54 | 55 | try: 56 | grants = get_key_grants(client, key) 57 | except Exception as e: 58 | msg = 'Failed to retrieve grants for %s @ %s. Error: "%s"' 59 | args = (key, region, e) 60 | print(msg % args) 61 | 62 | try: 63 | policies = get_key_policies(client, key) 64 | except Exception as e: 65 | msg = 'Failed to retrieve policies for %s @ %s. Error: "%s"' 66 | args = (key, region, e) 67 | print(msg % args) 68 | 69 | all_data[region][key] = {} 70 | all_data[region][key]['grants'] = grants 71 | all_data[region][key]['policies'] = policies 72 | 73 | os.makedirs('output', exist_ok=True) 74 | json_writer('output/key-grants.json', all_data) 75 | json_printer(all_data) 76 | 77 | 78 | if __name__ == '__main__': 79 | main() 80 | -------------------------------------------------------------------------------- /lambda_dump.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | 4 | import boto3 5 | 6 | from utils.session import get_session 7 | from utils.regions import get_all_regions 8 | from utils.json_writer import json_writer 9 | from utils.json_printer import json_printer 10 | from utils.boto_error_handling import yield_handling_errors 11 | 12 | 13 | def get_lambda_functions_for_region(client): 14 | for lambda_function in client.list_functions()['Functions']: 15 | yield lambda_function 16 | 17 | 18 | def get_function(client, function_name): 19 | try: 20 | function_details = client.get_function(FunctionName=function_name) 21 | except Exception as e: 22 | msg = 'Failed to retrieve function details for %s. Error: "%s"' 23 | args = (function_name, e) 24 | print(msg % args) 25 | 26 | function_details = {} 27 | 28 | return function_details 29 | 30 | 31 | def get_policy(client, function_name): 32 | try: 33 | function_policy = client.get_policy(FunctionName=function_name) 34 | except Exception as e: 35 | msg = 'Failed to retrieve function policy for %s. Error: "%s"' 36 | args = (function_name, e) 37 | print(msg % args) 38 | 39 | function_policy = {} 40 | else: 41 | function_policy = json.loads(function_policy['Policy']) 42 | 43 | return function_policy 44 | 45 | 46 | def main(): 47 | session = get_session() 48 | 49 | all_data = {} 50 | 51 | for region in get_all_regions(session): 52 | 53 | all_data[region] = {} 54 | client = session.client('lambda', region_name=region) 55 | 56 | iterator = yield_handling_errors(get_lambda_functions_for_region, client) 57 | 58 | for lambda_function in iterator: 59 | function_name = lambda_function['FunctionName'] 60 | print('Region: %s / Lambda function: %s' % (region, function_name)) 61 | 62 | function_details = get_function(client, function_name) 63 | function_policy = get_policy(client, function_name) 64 | 65 | all_data[region][function_name] = {} 66 | all_data[region][function_name]['main'] = lambda_function 67 | all_data[region][function_name]['details'] = function_details 68 | all_data[region][function_name]['policy'] = function_policy 69 | 70 | if not all_data[region]: 71 | print('Region %s / No Lambda functions' % region) 72 | continue 73 | 74 | os.makedirs('output', exist_ok=True) 75 | json_writer('output/lambda-functions.json', all_data) 76 | json_printer(all_data) 77 | 78 | 79 | if __name__ == '__main__': 80 | main() 81 | -------------------------------------------------------------------------------- /lambda_last_used.py: -------------------------------------------------------------------------------- 1 | """ 2 | Identify when a lambda function was last modified or invoked. This script 3 | helps identify lambda functions which can be removed from the AWS account 4 | because nobody is using them. 5 | 6 | This script is different from the others because it has a lot of external 7 | dependencies and manual steps that need to be done before running it. 8 | 9 | Requirements 10 | 11 | 1. Enable CloudTrail logging to an S3 bucket 12 | 13 | 2. Enable Lambda detailed logging in CloudTrail to get the Invoke calls 14 | 15 | 3. Run cloudtrail-partitioner [0], no need to install it, just run the tool 16 | to get 90 day visibility. 17 | 18 | 4. Use Athena to query the events and download the result as CSV. Use the 19 | this Athena query [1] to get all the data from the previously created 20 | partitions. Make sure you adjust the dates. 21 | 22 | 5. Run this tool 23 | 24 | [0] https://github.com/duo-labs/cloudtrail-partitioner/ 25 | [1] https://gist.github.com/andresriancho/512bfbae1ad8b175a36d6fdc32b8ccef 26 | """ 27 | import os 28 | import sys 29 | import csv 30 | import json 31 | import argparse 32 | import boto3 33 | 34 | from dateutil.parser import parse 35 | from datetime import datetime, timezone 36 | 37 | from utils.regions import get_all_regions 38 | from lambda_dump import get_lambda_functions_for_region 39 | from utils.boto_error_handling import yield_handling_errors 40 | 41 | 42 | DEFAULT_DATE = datetime(1970, 1, 1, tzinfo=timezone.utc) 43 | 44 | 45 | def parse_arguments(): 46 | parser = argparse.ArgumentParser() 47 | 48 | parser.add_argument( 49 | '--input', 50 | help='Athena-generated CSV file', 51 | required=True 52 | ) 53 | 54 | parser.add_argument( 55 | '--profile', 56 | help='AWS profile from ~/.aws/credentials', 57 | required=True 58 | ) 59 | 60 | args = parser.parse_args() 61 | 62 | try: 63 | session = boto3.Session(profile_name=args.profile) 64 | except Exception as e: 65 | print('%s' % e) 66 | sys.exit(1) 67 | 68 | csv_file = args.input 69 | 70 | if not os.path.exists(csv_file): 71 | print('%s is not a file' % csv_file) 72 | sys.exit(1) 73 | 74 | return csv_file, session 75 | 76 | 77 | class LambdaData(object): 78 | def __init__(self, event_time, request_parameters, aws_region, event_source): 79 | self.event_time = event_time 80 | self.request_parameters = request_parameters 81 | self.aws_region = aws_region 82 | self.event_source = event_source 83 | 84 | 85 | def parse_csv(csv_file): 86 | lambda_last_used_data = dict() 87 | 88 | with open(csv_file, newline='') as csv_file: 89 | reader = csv.reader(csv_file) 90 | headers = next(reader, None) 91 | 92 | for row in reader: 93 | (event_time, event_name, request_parameters, aws_region, event_source, resources) = row 94 | request_parameters = json.loads(request_parameters) 95 | event_time = parse(event_time) 96 | 97 | lambda_function_arn = request_parameters['functionName'] 98 | 99 | if lambda_function_arn in lambda_last_used_data: 100 | # Might need to update the last used time 101 | if event_time > lambda_last_used_data[lambda_function_arn].event_time: 102 | lambda_last_used_data[lambda_function_arn] = LambdaData(event_time, 103 | request_parameters, 104 | aws_region, 105 | event_source) 106 | else: 107 | # New lambda function 108 | lambda_last_used_data[lambda_function_arn] = LambdaData(event_time, 109 | request_parameters, 110 | aws_region, 111 | event_source) 112 | 113 | return lambda_last_used_data 114 | 115 | 116 | def sort_key(item): 117 | return item[1] 118 | 119 | 120 | def print_output(lambda_last_used_data): 121 | data = [] 122 | 123 | for lambda_function_arn, lambda_data in lambda_last_used_data.items(): 124 | item = (lambda_function_arn, lambda_data.event_time,) 125 | data.append(item) 126 | 127 | data.sort(key=sort_key, reverse=True) 128 | 129 | for lambda_function_arn, event_time in data: 130 | if event_time is DEFAULT_DATE: 131 | msg = '%s NOT used during the tracking period' 132 | args = (lambda_function_arn,) 133 | print(msg % args) 134 | 135 | else: 136 | days_ago = datetime.now() - event_time.replace(tzinfo=None) 137 | days_ago = days_ago.days 138 | 139 | msg = '%s was last used %s days ago' 140 | args = (lambda_function_arn, days_ago) 141 | print(msg % args) 142 | 143 | 144 | def dump_lambda_functions(session): 145 | all_lambda_functions = [] 146 | 147 | for region in get_all_regions(session): 148 | 149 | client = session.client('lambda', region_name=region) 150 | 151 | iterator = yield_handling_errors(get_lambda_functions_for_region, client) 152 | 153 | for lambda_function in iterator: 154 | function_name = lambda_function['FunctionArn'] 155 | all_lambda_functions.append(function_name) 156 | 157 | return all_lambda_functions 158 | 159 | 160 | def merge_all_functions(lambda_last_used_data, all_lambda_functions): 161 | for lambda_function_arn in all_lambda_functions: 162 | if lambda_function_arn not in lambda_last_used_data: 163 | lambda_last_used_data[lambda_function_arn] = LambdaData(DEFAULT_DATE, 164 | None, 165 | None, 166 | None) 167 | 168 | return lambda_last_used_data 169 | 170 | 171 | def main(): 172 | csv_file, session = parse_arguments() 173 | 174 | print('Parsing CSV file...') 175 | lambda_last_used_data = parse_csv(csv_file) 176 | 177 | print('Getting all existing AWS Lambda functions...') 178 | all_lambda_functions = dump_lambda_functions(session) 179 | 180 | lambda_last_used_data = merge_all_functions(lambda_last_used_data, all_lambda_functions) 181 | 182 | print('') 183 | print('Result:') 184 | print('') 185 | print_output(lambda_last_used_data) 186 | 187 | 188 | if __name__ == '__main__': 189 | main() 190 | -------------------------------------------------------------------------------- /permission-bruteforce/README.md: -------------------------------------------------------------------------------- 1 | # Enumerate IAM 2 | 3 | The following code will attempt to enumerate operations that a given set of AWS AccessKeys 4 | can perform. 5 | 6 | # Source 7 | 8 | The original version of this script was found at in [this gist](https://gist.github.com/darkarnium/1df59865f503355ef30672168063da4e) 9 | and developed by [darkarnium](https://gist.github.com/darkarnium). 10 | 11 | ## Usage 12 | ``` 13 | Usage: enumerate-iam.py [OPTIONS] 14 | 15 | IAM Account Enumerator. 16 | 17 | This code provides a mechanism to attempt to validate the permissions 18 | assigned to a given set of AWS tokens. 19 | 20 | Options: 21 | --access-key TEXT An AWS Access Key Id to check 22 | --secret-key TEXT An AWS Secret Access Key to check 23 | --session-token TEXT An AWS Session Token to check 24 | --help Show this message and exit. 25 | ``` 26 | 27 | ## Example 28 | 29 | ``` 30 | $ python enumerate-iam.py --access-key --secret-key 31 | 2017-05-06 00:16:05,164 - 5692 - [INFO] Starting scrape for access-key-id "" 32 | 2017-05-06 00:16:06,107 - 5692 - [ERROR] Failed to get everything at once (get_account_authorization_details) :( 33 | 2017-05-06 00:16:06,210 - 5692 - [INFO] -- Account ARN : arn:aws:iam::NNNNNNNNNNN:user/some-other-user 34 | 2017-05-06 00:16:06,210 - 5692 - [INFO] -- Account Id : NNNNNNNNNNN 35 | 2017-05-06 00:16:06,210 - 5692 - [INFO] -- Account Path: user/some-other-user 36 | 2017-05-06 00:16:06,321 - 5692 - [INFO] User "some-other-user" has 1 attached policies 37 | 2017-05-06 00:16:06,321 - 5692 - [INFO] -- Policy "some-policy" (arn:aws:iam::NNNNNNNNNNN:policy/some-policy) 38 | 2017-05-06 00:16:06,436 - 5692 - [INFO] User "some-other-user" has 1 inline policies 39 | 2017-05-06 00:16:06,436 - 5692 - [INFO] -- Policy "policygen-some-other-user-201705060014" 40 | 2017-05-06 00:16:06,543 - 5692 - [INFO] User "some-other-user" has 0 groups associated 41 | 2017-05-06 00:16:06,543 - 5692 - [INFO] Attempting common-service describe / list bruteforce. 42 | ... 43 | ``` 44 | 45 | ``` 46 | $ python enumerate-iam.py --access-key --secret-key 47 | 2017-05-05 23:52:27,194 - 3060 - [INFO] Starting scrape for access-key-id "" 48 | 2017-05-05 23:52:28,206 - 3060 - [ERROR] Failed to get everything at once (get_account_authorization_details) :( 49 | 2017-05-05 23:52:28,293 - 3060 - [ERROR] Failed to retrieve any IAM data for this key. 50 | 2017-05-05 23:52:28,293 - 3060 - [INFO] -- Account ARN : arn:aws:iam::NNNNNNNNNNN:user/some-user 51 | 2017-05-05 23:52:28,293 - 3060 - [INFO] -- Account Id : NNNNNNNNNNN 52 | 2017-05-05 23:52:28,293 - 3060 - [INFO] -- Account Path: user/some-user 53 | 2017-05-05 23:52:28,293 - 3060 - [INFO] Attempting common-service describe / list bruteforce. 54 | 2017-05-05 23:52:28,301 - 3060 - [INFO] Checking ACM (Certificate Manager) 55 | 2017-05-05 23:52:28,737 - 3060 - [ERROR] -- list_certificates() failed 56 | 2017-05-05 23:52:28,762 - 3060 - [INFO] Checking CFN (CloudFormation) 57 | 2017-05-05 23:52:29,184 - 3060 - [ERROR] -- describe_stacks() failed 58 | 2017-05-05 23:52:29,193 - 3060 - [INFO] Checking CloudHSM 59 | 2017-05-05 23:52:29,611 - 3060 - [ERROR] -- list_hsms() failed 60 | 2017-05-05 23:52:29,625 - 3060 - [INFO] Checking CloudSearch 61 | 2017-05-05 23:52:30,069 - 3060 - [ERROR] -- list_domain_names() failed 62 | 2017-05-05 23:52:30,078 - 3060 - [INFO] Checking CloudTrail 63 | 2017-05-05 23:52:30,529 - 3060 - [ERROR] -- describe_trails() failed 64 | 2017-05-05 23:52:30,536 - 3060 - [INFO] Checking CloudWatch 65 | 2017-05-05 23:52:30,926 - 3060 - [ERROR] -- describe_alarm_history() failed 66 | 2017-05-05 23:52:30,936 - 3060 - [INFO] Checking CodeCommit 67 | 2017-05-05 23:52:31,338 - 3060 - [ERROR] -- list_repositories() failed 68 | 2017-05-05 23:52:31,374 - 3060 - [INFO] Checking CodeDeploy 69 | 2017-05-05 23:52:31,782 - 3060 - [ERROR] -- list_applications() failed 70 | 2017-05-05 23:52:31,881 - 3060 - [ERROR] -- list_deployments() failed 71 | 2017-05-05 23:52:31,953 - 3060 - [INFO] Checking EC2 (Elastic Compute) 72 | 2017-05-05 23:52:32,345 - 3060 - [ERROR] -- describe_instances() failed 73 | 2017-05-05 23:52:32,440 - 3060 - [ERROR] -- describe_images() failed 74 | 2017-05-05 23:52:32,539 - 3060 - [ERROR] -- describe_addresses() failed 75 | 2017-05-05 23:52:32,630 - 3060 - [ERROR] -- describe_hosts() failed 76 | 2017-05-05 23:52:32,721 - 3060 - [ERROR] -- describe_nat_gateways() failed 77 | 2017-05-05 23:52:32,819 - 3060 - [ERROR] -- describe_key_pairs() failed 78 | 2017-05-05 23:52:32,917 - 3060 - [ERROR] -- describe_snapshots() failed 79 | 2017-05-05 23:52:33,013 - 3060 - [ERROR] -- describe_volumes() failed 80 | 2017-05-05 23:52:33,111 - 3060 - [ERROR] -- describe_tags() failed 81 | 2017-05-05 23:52:33,207 - 3060 - [ERROR] -- describe_tags() failed 82 | 2017-05-05 23:52:33,305 - 3060 - [ERROR] -- describe_vpcs() failed 83 | 2017-05-05 23:52:33,319 - 3060 - [INFO] Checking ECS (DOCKER DOCKER DOCKER DOCKER ...) 84 | 2017-05-05 23:52:33,713 - 3060 - [ERROR] -- describe_clusters() failed 85 | 2017-05-05 23:52:33,730 - 3060 - [INFO] Checking ElasticBeanstalk 86 | 2017-05-05 23:52:34,167 - 3060 - [INFO] -- describe_applications() worked! 87 | 2017-05-05 23:52:34,352 - 3060 - [INFO] -- describe_environments() worked! 88 | 2017-05-05 23:52:34,365 - 3060 - [INFO] Checking ELB (Elastic Load Balancing) 89 | 2017-05-05 23:52:34,749 - 3060 - [ERROR] -- describe_load_balancers() failed 90 | 2017-05-05 23:52:34,763 - 3060 - [INFO] Checking ELBv2 (Elastic Load Balancing) 91 | 2017-05-05 23:52:35,135 - 3060 - [ERROR] -- describe_load_balancers() failed 92 | 2017-05-05 23:52:35,151 - 3060 - [INFO] Checking ElasticTranscoder 93 | 2017-05-05 23:52:35,561 - 3060 - [ERROR] -- list_pipelines() failed 94 | 2017-05-05 23:52:35,572 - 3060 - [INFO] Checking DynamoDB 95 | 2017-05-05 23:52:35,960 - 3060 - [ERROR] -- list_tables() failed 96 | 2017-05-05 23:52:36,003 - 3060 - [INFO] Checking IoT 97 | 2017-05-05 23:52:36,217 - 3060 - [ERROR] -- list_things() failed 98 | 2017-05-05 23:52:36,331 - 3060 - [ERROR] -- describe_endpoint() failed 99 | 2017-05-05 23:52:36,342 - 3060 - [INFO] Checking Kinesis 100 | 2017-05-05 23:52:36,733 - 3060 - [ERROR] -- list_streams() failed 101 | 2017-05-05 23:52:36,806 - 3060 - [INFO] Checking KMS (Key Management Service) 102 | 2017-05-05 23:52:37,229 - 3060 - [ERROR] -- list_keys() failed 103 | 2017-05-05 23:52:37,255 - 3060 - [INFO] Checking Lambda 104 | 2017-05-05 23:52:37,663 - 3060 - [ERROR] -- list_functions() failed 105 | 2017-05-05 23:52:37,701 - 3060 - [INFO] Checking OpsWorks 106 | 2017-05-05 23:52:38,197 - 3060 - [INFO] -- describe_stacks() worked! 107 | 2017-05-05 23:52:38,252 - 3060 - [INFO] Checking RDS (Relational Database Service) 108 | 2017-05-05 23:52:38,726 - 3060 - [ERROR] -- describe_db_clusters() failed 109 | 2017-05-05 23:52:38,821 - 3060 - [ERROR] -- describe_db_instances() failed 110 | 2017-05-05 23:52:38,858 - 3060 - [INFO] Checking Route53 (DNS) 111 | 2017-05-05 23:52:39,250 - 3060 - [ERROR] -- list_hosted_zones() failed 112 | 2017-05-05 23:52:39,539 - 3060 - [INFO] Checking S3 (Simple Storage Service) 113 | 2017-05-05 23:52:39,928 - 3060 - [ERROR] -- list_buckets() failed 114 | 2017-05-05 23:52:39,956 - 3060 - [INFO] Checking SES (Simple Email Service) 115 | 2017-05-05 23:52:40,344 - 3060 - [ERROR] -- list_identities() failed 116 | 2017-05-05 23:52:40,361 - 3060 - [INFO] Checking SNS (Simple Notification Service) 117 | 2017-05-05 23:52:40,750 - 3060 - [ERROR] -- list_topics() failed 118 | 2017-05-05 23:52:40,767 - 3060 - [INFO] Checking SQS (Simple Queue Service) 119 | 2017-05-05 23:52:41,151 - 3060 - [ERROR] -- list_queues() failed 120 | 2017-05-05 23:52:41,171 - 3060 - [INFO] Checking Support 121 | 2017-05-05 23:52:41,571 - 3060 - [ERROR] -- describe_cases() failed 122 | ``` 123 | -------------------------------------------------------------------------------- /permission-bruteforce/enumerate-iam.py: -------------------------------------------------------------------------------- 1 | """IAM Account Enumerator. 2 | 3 | This code provides a mechanism to attempt to validate the permissions assigned 4 | to a given set of AWS tokens. 5 | """ 6 | import re 7 | import sys 8 | import logging 9 | import boto3 10 | import botocore 11 | import click 12 | 13 | from botocore.config import Config 14 | 15 | config = Config( 16 | retries=dict( 17 | max_attempts=10 18 | ) 19 | ) 20 | 21 | 22 | def report_arn(candidate): 23 | """ Attempt to extract and slice up an ARN from the input string. """ 24 | logger = logging.getLogger() 25 | arn_search = re.search(r'.*(arn:aws:.*:.*:.*:.*)\s*.*$', candidate) 26 | if arn_search: 27 | arn = arn_search.group(1) 28 | logger.info('-- Account ARN : %s', arn) 29 | logger.info('-- Account Id : %s', arn.split(':')[4]) 30 | logger.info('-- Account Path: %s', arn.split(':')[5]) 31 | 32 | 33 | # This is lame and won't work with federated policies and a bunch of other cases. 34 | def build_arn(user_arn, policy_name, path='policy'): 35 | """ Chops up the user ARN and attempts and builds a policy ARN. """ 36 | return '{}:{}/{}'.format(':'.join(user_arn.split(':')[0:5]), path, policy_name) 37 | 38 | 39 | def brute(access_key, secret_key, session_token): 40 | """ Attempt to brute-force common describe calls. """ 41 | logger = logging.getLogger() 42 | logger.info('Attempting common-service describe / list bruteforce.') 43 | 44 | # ACM 45 | acm = boto3.client( 46 | 'acm', 47 | aws_access_key_id=access_key, 48 | aws_secret_access_key=secret_key, 49 | aws_session_token=session_token 50 | ) 51 | logger.info('Checking ACM (Certificate Manager)') 52 | 53 | try: 54 | acm.list_certificates() 55 | logger.info('-- list_certificates() worked!') 56 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 57 | logger.error('-- list_certificates() failed') 58 | 59 | # CloudFormation 60 | cfn = boto3.client( 61 | 'cloudformation', 62 | aws_access_key_id=access_key, 63 | aws_secret_access_key=secret_key, 64 | aws_session_token=session_token 65 | ) 66 | logger.info('Checking CFN (CloudFormation)') 67 | 68 | try: 69 | cfn.describe_stacks() 70 | logger.info('-- describe_stacks() worked!') 71 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 72 | logger.error('-- describe_stacks() failed') 73 | 74 | # CloudHSM 75 | cloudhsm = boto3.client( 76 | 'cloudhsm', 77 | aws_access_key_id=access_key, 78 | aws_secret_access_key=secret_key, 79 | aws_session_token=session_token 80 | ) 81 | logger.info('Checking CloudHSM') 82 | 83 | try: 84 | cloudhsm.list_hsms() 85 | logger.info('-- list_hsms() worked!') 86 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 87 | logger.error('-- list_hsms() failed') 88 | 89 | # CloudSearch 90 | cloudsearch = boto3.client( 91 | 'cloudsearch', 92 | aws_access_key_id=access_key, 93 | aws_secret_access_key=secret_key, 94 | aws_session_token=session_token 95 | ) 96 | logger.info('Checking CloudSearch') 97 | 98 | try: 99 | cloudsearch.list_domain_names() 100 | logger.info('-- list_domain_names() worked!') 101 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 102 | logger.error('-- list_domain_names() failed') 103 | 104 | # CloudTrail 105 | cloudtrail = boto3.client( 106 | 'cloudtrail', 107 | aws_access_key_id=access_key, 108 | aws_secret_access_key=secret_key, 109 | aws_session_token=session_token 110 | ) 111 | logger.info('Checking CloudTrail') 112 | 113 | try: 114 | cloudtrail.describe_trails() 115 | logger.info('-- describe_trails() worked!') 116 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 117 | logger.error('-- describe_trails() failed') 118 | 119 | # CloudWatch 120 | cloudwatch = boto3.client( 121 | 'cloudwatch', 122 | aws_access_key_id=access_key, 123 | aws_secret_access_key=secret_key, 124 | aws_session_token=session_token 125 | ) 126 | logger.info('Checking CloudWatch') 127 | 128 | try: 129 | cloudwatch.describe_alarm_history() 130 | logger.info('-- describe_alarm_history() worked!') 131 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 132 | logger.error('-- describe_alarm_history() failed') 133 | 134 | # CodeCommit 135 | codecommit = boto3.client( 136 | 'codecommit', 137 | aws_access_key_id=access_key, 138 | aws_secret_access_key=secret_key, 139 | aws_session_token=session_token 140 | ) 141 | logger.info('Checking CodeCommit') 142 | 143 | try: 144 | codecommit.list_repositories() 145 | logger.info('-- list_repositories() worked!') 146 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 147 | logger.error('-- list_repositories() failed') 148 | 149 | # CodeDeploy 150 | codedeploy = boto3.client( 151 | 'codedeploy', 152 | aws_access_key_id=access_key, 153 | aws_secret_access_key=secret_key, 154 | aws_session_token=session_token 155 | ) 156 | logger.info('Checking CodeDeploy') 157 | 158 | try: 159 | codedeploy.list_applications() 160 | logger.info('-- list_applications() worked!') 161 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 162 | logger.error('-- list_applications() failed') 163 | 164 | try: 165 | codedeploy.list_deployments() 166 | logger.info('-- list_deployments() worked!') 167 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 168 | logger.error('-- list_deployments() failed') 169 | 170 | # EC2 171 | ec2 = boto3.client( 172 | 'ec2', 173 | aws_access_key_id=access_key, 174 | aws_secret_access_key=secret_key, 175 | aws_session_token=session_token 176 | ) 177 | logger.info('Checking EC2 (Elastic Compute)') 178 | 179 | try: 180 | ec2.describe_instances() 181 | logger.info('-- describe_instances() worked!') 182 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 183 | logger.error('-- describe_instances() failed') 184 | 185 | try: 186 | ec2.describe_images() 187 | logger.info('-- describe_images() worked!') 188 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 189 | logger.error('-- describe_images() failed') 190 | 191 | try: 192 | ec2.describe_addresses() 193 | logger.info('-- describe_addresses() worked!') 194 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 195 | logger.error('-- describe_addresses() failed') 196 | 197 | try: 198 | ec2.describe_hosts() 199 | logger.info('-- describe_hosts() worked!') 200 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 201 | logger.error('-- describe_hosts() failed') 202 | 203 | try: 204 | ec2.describe_nat_gateways() 205 | logger.info('-- describe_nat_gateways() worked!') 206 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 207 | logger.error('-- describe_nat_gateways() failed') 208 | 209 | try: 210 | ec2.describe_key_pairs() 211 | logger.info('-- describe_key_pairs() worked!') 212 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 213 | logger.error('-- describe_key_pairs() failed') 214 | 215 | try: 216 | ec2.describe_snapshots() 217 | logger.info('-- describe_snapshots() worked!') 218 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 219 | logger.error('-- describe_snapshots() failed') 220 | 221 | try: 222 | ec2.describe_volumes() 223 | logger.info('-- describe_volumes() worked!') 224 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 225 | logger.error('-- describe_volumes() failed') 226 | 227 | try: 228 | ec2.describe_tags() 229 | logger.info('-- describe_tags() worked!') 230 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 231 | logger.error('-- describe_tags() failed') 232 | 233 | try: 234 | ec2.describe_tags() 235 | logger.info('-- describe_tags() worked!') 236 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 237 | logger.error('-- describe_tags() failed') 238 | 239 | try: 240 | ec2.describe_vpcs() 241 | logger.info('-- describe_vpcs() worked!') 242 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 243 | logger.error('-- describe_vpcs() failed') 244 | 245 | # ECS 246 | ecs = boto3.client( 247 | 'ecs', 248 | aws_access_key_id=access_key, 249 | aws_secret_access_key=secret_key, 250 | aws_session_token=session_token 251 | ) 252 | logger.info('Checking ECS (DOCKER DOCKER DOCKER DOCKER ...)') 253 | 254 | try: 255 | ecs.describe_clusters() 256 | logger.info('-- describe_clusters() worked!') 257 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 258 | logger.error('-- describe_clusters() failed') 259 | 260 | # Elastic Beanstalk 261 | beanstalk = boto3.client( 262 | 'elasticbeanstalk', 263 | aws_access_key_id=access_key, 264 | aws_secret_access_key=secret_key, 265 | aws_session_token=session_token 266 | ) 267 | logger.info('Checking ElasticBeanstalk') 268 | 269 | try: 270 | beanstalk.describe_applications() 271 | logger.info('-- describe_applications() worked!') 272 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 273 | logger.error('-- describe_applications() failed') 274 | 275 | try: 276 | beanstalk.describe_environments() 277 | logger.info('-- describe_environments() worked!') 278 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 279 | logger.error('-- describe_environments() failed') 280 | 281 | # ELB 282 | elb = boto3.client( 283 | 'elb', 284 | aws_access_key_id=access_key, 285 | aws_secret_access_key=secret_key, 286 | aws_session_token=session_token 287 | ) 288 | logger.info('Checking ELB (Elastic Load Balancing)') 289 | 290 | try: 291 | elb.describe_load_balancers() 292 | logger.info('-- describe_load_balancers() worked!') 293 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 294 | logger.error('-- describe_load_balancers() failed') 295 | 296 | # ELBv2 297 | elbv2 = boto3.client( 298 | 'elbv2', 299 | aws_access_key_id=access_key, 300 | aws_secret_access_key=secret_key, 301 | aws_session_token=session_token 302 | ) 303 | logger.info('Checking ELBv2 (Elastic Load Balancing)') 304 | 305 | try: 306 | elbv2.describe_load_balancers() 307 | logger.info('-- describe_load_balancers() worked!') 308 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 309 | logger.error('-- describe_load_balancers() failed') 310 | 311 | # ElasticTranscoder 312 | elastictranscoder = boto3.client( 313 | 'elastictranscoder', 314 | aws_access_key_id=access_key, 315 | aws_secret_access_key=secret_key, 316 | aws_session_token=session_token 317 | ) 318 | logger.info('Checking ElasticTranscoder') 319 | 320 | try: 321 | elastictranscoder.list_pipelines() 322 | logger.info('-- list_pipelines() worked!') 323 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 324 | logger.error('-- list_pipelines() failed') 325 | 326 | # DynomoDB 327 | dynamodb = boto3.client( 328 | 'dynamodb', 329 | aws_access_key_id=access_key, 330 | aws_secret_access_key=secret_key, 331 | aws_session_token=session_token 332 | ) 333 | logger.info('Checking DynamoDB') 334 | 335 | try: 336 | dynamodb.list_tables() 337 | logger.info('-- list_tables() worked!') 338 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 339 | logger.error('-- list_tables() failed') 340 | 341 | # IoT 342 | iot = boto3.client( 343 | 'iot', 344 | aws_access_key_id=access_key, 345 | aws_secret_access_key=secret_key, 346 | aws_session_token=session_token 347 | ) 348 | logger.info('Checking IoT') 349 | 350 | try: 351 | iot.list_things() 352 | logger.info('-- list_things() worked!') 353 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 354 | logger.error('-- list_things() failed') 355 | 356 | try: 357 | iot.describe_endpoint() 358 | logger.info('-- describe_endpoint() worked!') 359 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 360 | logger.error('-- describe_endpoint() failed') 361 | 362 | # Kinesis 363 | kinesis = boto3.client( 364 | 'kinesis', 365 | aws_access_key_id=access_key, 366 | aws_secret_access_key=secret_key, 367 | aws_session_token=session_token 368 | ) 369 | logger.info('Checking Kinesis') 370 | 371 | try: 372 | kinesis.list_streams() 373 | logger.info('-- list_streams() worked!') 374 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 375 | logger.error('-- list_streams() failed') 376 | 377 | # KMS 378 | kms = boto3.client( 379 | 'kms', 380 | aws_access_key_id=access_key, 381 | aws_secret_access_key=secret_key, 382 | aws_session_token=session_token 383 | ) 384 | logger.info('Checking KMS (Key Management Service)') 385 | 386 | try: 387 | kms.list_keys() 388 | logger.info('-- list_keys() worked!') 389 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 390 | logger.error('-- list_keys() failed') 391 | 392 | # Lambda 393 | lmb = boto3.client( 394 | 'lambda', 395 | aws_access_key_id=access_key, 396 | aws_secret_access_key=secret_key, 397 | aws_session_token=session_token 398 | ) 399 | logger.info('Checking Lambda') 400 | 401 | try: 402 | lmb.list_functions() 403 | logger.info('-- list_functions() worked!') 404 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 405 | logger.error('-- list_functions() failed') 406 | 407 | # OpsWorks 408 | opsworks = boto3.client( 409 | 'opsworks', 410 | aws_access_key_id=access_key, 411 | aws_secret_access_key=secret_key, 412 | aws_session_token=session_token 413 | ) 414 | logger.info('Checking OpsWorks') 415 | 416 | try: 417 | opsworks.describe_stacks() 418 | logger.info('-- describe_stacks() worked!') 419 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 420 | logger.error('-- describe_stacks() failed') 421 | 422 | # RDS 423 | rds = boto3.client( 424 | 'rds', 425 | aws_access_key_id=access_key, 426 | aws_secret_access_key=secret_key, 427 | aws_session_token=session_token 428 | ) 429 | logger.info('Checking RDS (Relational Database Service)') 430 | 431 | try: 432 | rds.describe_db_clusters() 433 | logger.info('-- describe_db_clusters() worked!') 434 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 435 | logger.error('-- describe_db_clusters() failed') 436 | 437 | try: 438 | rds.describe_db_instances() 439 | logger.info('-- describe_db_instances() worked!') 440 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 441 | logger.error('-- describe_db_instances() failed') 442 | 443 | # Route53 444 | route53 = boto3.client( 445 | 'route53', 446 | aws_access_key_id=access_key, 447 | aws_secret_access_key=secret_key, 448 | aws_session_token=session_token 449 | ) 450 | logger.info('Checking Route53 (DNS)') 451 | 452 | try: 453 | route53.list_hosted_zones() 454 | logger.info('-- list_hosted_zones() worked!') 455 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 456 | logger.error('-- list_hosted_zones() failed') 457 | 458 | # S3 459 | s3 = boto3.client( 460 | 's3', 461 | aws_access_key_id=access_key, 462 | aws_secret_access_key=secret_key, 463 | aws_session_token=session_token 464 | ) 465 | logger.info('Checking S3 (Simple Storage Service)') 466 | 467 | try: 468 | s3.list_buckets() 469 | logger.info('-- list_buckets() worked!') 470 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 471 | logger.error('-- list_buckets() failed') 472 | 473 | # SES 474 | ses = boto3.client( 475 | 'ses', 476 | aws_access_key_id=access_key, 477 | aws_secret_access_key=secret_key, 478 | aws_session_token=session_token 479 | ) 480 | logger.info('Checking SES (Simple Email Service)') 481 | 482 | try: 483 | ses.list_identities() 484 | logger.info('-- list_identities() worked!') 485 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 486 | logger.error('-- list_identities() failed') 487 | 488 | # sns 489 | sns = boto3.client( 490 | 'sns', 491 | aws_access_key_id=access_key, 492 | aws_secret_access_key=secret_key, 493 | aws_session_token=session_token 494 | ) 495 | logger.info('Checking SNS (Simple Notification Service)') 496 | 497 | try: 498 | sns.list_topics() 499 | logger.info('-- list_topics() worked!') 500 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 501 | logger.error('-- list_topics() failed') 502 | 503 | # SQS 504 | sqs = boto3.client( 505 | 'sqs', 506 | aws_access_key_id=access_key, 507 | aws_secret_access_key=secret_key, 508 | aws_session_token=session_token 509 | ) 510 | logger.info('Checking SQS (Simple Queue Service)') 511 | 512 | try: 513 | sqs.list_queues() 514 | logger.info('-- list_queues() worked!') 515 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 516 | logger.error('-- list_queues() failed') 517 | 518 | # support 519 | support = boto3.client( 520 | 'support', 521 | aws_access_key_id=access_key, 522 | aws_secret_access_key=secret_key, 523 | aws_session_token=session_token 524 | ) 525 | logger.info('Checking Support') 526 | 527 | try: 528 | support.describe_cases() 529 | logger.info('-- describe_cases() worked!') 530 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 531 | logger.error('-- describe_cases() failed') 532 | 533 | @click.command() 534 | @click.option('--access-key', help='An AWS Access Key Id to check') 535 | @click.option('--secret-key', help='An AWS Secret Access Key to check') 536 | @click.option('--session-token', help='An AWS Session Token to check') 537 | def main(access_key, secret_key, session_token): 538 | """IAM Account Enumerator. 539 | 540 | This code provides a mechanism to attempt to validate the permissions assigned 541 | to a given set of AWS tokens. 542 | """ 543 | logging.basicConfig( 544 | level=logging.INFO, 545 | format='%(asctime)s - %(process)d - [%(levelname)s] %(message)s', 546 | ) 547 | logger = logging.getLogger() 548 | 549 | # Suppress boto INFO. 550 | logging.getLogger('boto3').setLevel(logging.WARNING) 551 | logging.getLogger('botocore').setLevel(logging.WARNING) 552 | logging.getLogger('nose').setLevel(logging.WARNING) 553 | 554 | # Ensure requires parameters are set. 555 | if access_key is None: 556 | logger.fatal('No access-key provided, cannot continue.') 557 | sys.exit(-1) 558 | if secret_key is None: 559 | logger.fatal('No secret-key provided, cannot continue.') 560 | sys.exit(-1) 561 | 562 | # Connect to the IAM API and start testing. 563 | logger.info('Starting scrape for access-key-id "%s"', access_key) 564 | iam = boto3.client( 565 | 'iam', 566 | aws_access_key_id=access_key, 567 | aws_secret_access_key=secret_key, 568 | aws_session_token=session_token 569 | ) 570 | 571 | # Try for the kitchen sink. 572 | try: 573 | everything = iam.get_account_authorization_details() 574 | logger.info('Run for the hills, get_account_authorization_details worked!') 575 | logger.info('-- %s', everything) 576 | except (botocore.exceptions.ClientError, botocore.exceptions.EndpointConnectionError): 577 | logger.error('Failed to get everything at once (get_account_authorization_details) :(') 578 | 579 | # Attempt to get user to start. 580 | try: 581 | user = iam.get_user() 582 | report_arn(user['User']['Arn']) 583 | except botocore.exceptions.ClientError as err: 584 | logger.error('Failed to retrieve any IAM data for this key.') 585 | report_arn(str(err)) 586 | brute(access_key=access_key, secret_key=secret_key, session_token=session_token) 587 | sys.exit(0) 588 | 589 | # Attempt to get policies attached to this user. 590 | try: 591 | user_policies = iam.list_attached_user_policies(UserName=user['User']['UserName']) 592 | logger.info( 593 | 'User "%s" has %0d attached policies', 594 | user['User']['UserName'], 595 | len(user_policies['AttachedPolicies']) 596 | ) 597 | 598 | # List all policies, if present. 599 | for policy in user_policies['AttachedPolicies']: 600 | logger.info('-- Policy "%s" (%s)', policy['PolicyName'], policy['PolicyArn']) 601 | except botocore.exceptions.ClientError as err: 602 | logger.error( 603 | 'Unable to query for user policies for "%s" (list_attached_user_policies): %s', 604 | user['User']['UserName'], 605 | err 606 | ) 607 | 608 | # Attempt to get inline policies for this user. 609 | try: 610 | user_policies = iam.list_user_policies(UserName=user['User']['UserName']) 611 | logger.info( 612 | 'User "%s" has %0d inline policies', 613 | user['User']['UserName'], 614 | len(user_policies['PolicyNames']) 615 | ) 616 | 617 | # List all policies, if present. 618 | for policy in user_policies['PolicyNames']: 619 | logger.info('-- Policy "%s"', policy) 620 | 621 | except botocore.exceptions.ClientError as err: 622 | logger.error( 623 | 'Unable to query for user policies for "%s" (list_user_policies): %s', 624 | user['User']['UserName'], 625 | err 626 | ) 627 | 628 | # Attempt to get the groups attached to this user. 629 | try: 630 | user_groups = iam.list_groups_for_user(UserName=user['User']['UserName']) 631 | logger.info( 632 | 'User "%s" has %0d groups associated', 633 | user['User']['UserName'], 634 | len(user_groups['Groups']) 635 | ) 636 | 637 | # List all groups, if present. 638 | for group in user_groups['Groups']: 639 | try: 640 | group_policy = iam.list_group_policies(GroupName=group['GroupName']) 641 | logger.info( 642 | '-- Group "%s" has %0d inline policies', 643 | group['GroupName'], 644 | len(group_policy['PolicyNames']) 645 | ) 646 | 647 | # List all group policy names. 648 | for policy in group_policy['PolicyNames']: 649 | logger.info('---- Policy "%s"', policy) 650 | except botocore.exceptions.ClientError as err: 651 | logger.error( 652 | '---- Failed to get policies for group "%s" (list_group_policies): %s', 653 | group['GroupName'], 654 | err 655 | ) 656 | except botocore.exceptions.ClientError as err: 657 | logger.error( 658 | 'Unable to query for groups for %s (list_groups_for_user): %s', 659 | user['User']['UserName'], 660 | err 661 | ) 662 | 663 | # Try a brute-force approach. 664 | brute(access_key=access_key, secret_key=secret_key, session_token=session_token) 665 | 666 | 667 | if __name__ == '__main__': 668 | main() 669 | -------------------------------------------------------------------------------- /rds_snapshots.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | 4 | import boto3 5 | 6 | from utils.session import get_session 7 | from utils.regions import get_all_regions 8 | from utils.json_encoder import json_encoder 9 | from utils.json_writer import json_writer 10 | from utils.json_printer import json_printer 11 | 12 | 13 | def get_shapshots_for_region(client): 14 | paginator = client.get_paginator('describe_db_snapshots') 15 | 16 | for page in paginator.paginate(): 17 | for shapshot in page['DBSnapshots']: 18 | yield shapshot 19 | 20 | 21 | def get_snapshot_attributes(client, snapshot_id): 22 | return client.describe_db_snapshot_attributes(DBSnapshotIdentifier=snapshot_id)['DBSnapshotAttributesResult'] 23 | 24 | 25 | def main(): 26 | session = get_session() 27 | 28 | all_data = {} 29 | 30 | for region in get_all_regions(session): 31 | all_data[region] = {} 32 | client = session.client('rds', region_name=region) 33 | 34 | for snapshot in get_shapshots_for_region(client): 35 | snapshot_id = snapshot['DBSnapshotIdentifier'] 36 | print('Region: %s / Snapshot: %s' % (region, snapshot_id)) 37 | 38 | try: 39 | attributes = get_snapshot_attributes(client, snapshot_id) 40 | except Exception as e: 41 | msg = 'Failed to retrieve attributes for %s @ %s. Error: "%s"' 42 | args = (snapshot_id, region, e) 43 | print(msg % args) 44 | 45 | attributes = {} 46 | 47 | all_data[region][snapshot_id] = {} 48 | all_data[region][snapshot_id]['main'] = snapshot 49 | all_data[region][snapshot_id]['attributes'] = attributes 50 | else: 51 | print('Region: %s / No snapshots found' % (region,)) 52 | 53 | os.makedirs('output', exist_ok=True) 54 | json_writer('output/rds-snapshots.json', all_data) 55 | json_printer(all_data) 56 | 57 | 58 | if __name__ == '__main__': 59 | main() 60 | -------------------------------------------------------------------------------- /rds_snapshots_filter.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | rds_snapshots = json.loads(open('output/rds-snapshots.json').read()) 4 | 5 | for region in rds_snapshots: 6 | 7 | for snapshot in rds_snapshots[region]: 8 | 9 | db_attrs = rds_snapshots[region][snapshot]['attributes']['DBSnapshotAttributes'] 10 | 11 | if len(db_attrs) > 1: 12 | print(snapshot) 13 | continue 14 | 15 | if db_attrs[0]['AttributeName'] != 'restore': 16 | print(snapshot) 17 | continue 18 | 19 | if db_attrs[0]['AttributeValues'] != []: 20 | print(snapshot) 21 | continue 22 | -------------------------------------------------------------------------------- /regions_in_use.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script receives a CSV export from the "Tag Editor" [0] and returns 3 | a list of regions where resources are found. 4 | 5 | Default resources such as the default security group for RDS, default VPC, etc. 6 | are ignored. These are some examples of ignored resources: 7 | 8 | EC2 DHCPOptions dopt-a1f31ac8 9 | EC2 InternetGateway igw-e0f01c89 10 | EC2 NetworkAcl acl-cf39d0a6 11 | EC2 RouteTable rtb-7348a11a 12 | EC2 SecurityGroup sg-9117ddf8 13 | EC2 Subnet subnet-ec36d985 14 | EC2 Subnet subnet-78062e32 15 | EC2 Subnet subnet-289f9150 16 | EC2 VPC vpc-df48a6b6 17 | RDS DBSecurityGroup default 18 | 19 | For each region the script ignores one VPC, three subnets, one route table, etc. 20 | If there are more resources of this type they were created by the user and that 21 | will mark the region as used. 22 | 23 | [0] https://us-west-2.console.aws.amazon.com/resource-groups/tag-editor/find-resources?region=us-west-2 24 | """ 25 | 26 | import os 27 | import csv 28 | import sys 29 | 30 | from utils.json_writer import json_writer 31 | from utils.json_printer import json_printer 32 | 33 | RESOURCES_TO_IGNORE_PER_REGION = { 34 | 'dopt': 1, 35 | 'igw': 1, 36 | 'acl': 1, 37 | 'rtb': 1, 38 | 'sg': 1, 39 | 'subnet': 3, 40 | 'vpc': 1, 41 | 'default': 1 42 | } 43 | 44 | 45 | class Resource(object): 46 | def __init__(self, name, service, _type, region, _id): 47 | self.name = name 48 | self.service = service 49 | self.type = _type 50 | self.region = region 51 | self.id = _id 52 | self.id_start = self.id.split('-')[0] 53 | 54 | @classmethod 55 | def from_row(cls, row): 56 | """ 57 | Create a new Resource from a row. Rows are list that contain these items: 58 | 59 | RDS DBSecurityGroup default,RDS,DBSecurityGroup,ap-south-1,default,-,-,-,-,-,-,-,- 60 | 61 | :param row: A list with the previously documented items 62 | :return: A new Resource instance 63 | """ 64 | name, service, _type, region, _id, _, _, _, _, _, _, _, _ = row 65 | 66 | return Resource(name, 67 | service, 68 | _type, 69 | region, 70 | _id) 71 | 72 | def to_dict(self): 73 | return { 74 | 'name': self.name, 75 | 'service': self.service, 76 | 'type': self.type, 77 | 'region': self.region, 78 | 'id': self.id, 79 | 'id_start': self.id_start, 80 | } 81 | 82 | def __str__(self): 83 | return '' % (self.id, self.region) 84 | 85 | def __repr__(self): 86 | return '' % (self.id, self.region) 87 | 88 | 89 | def get_resources(input_filename): 90 | with open(input_filename, newline='') as csv_file: 91 | reader = csv.reader(csv_file) 92 | for row in reader: 93 | resource = Resource.from_row(row) 94 | 95 | # Ignore the first row which holds the column names 96 | if resource.region == 'Region': 97 | continue 98 | 99 | yield resource 100 | 101 | 102 | def get_input_csv_filename(): 103 | try: 104 | csv_filename = sys.argv[1] 105 | except IndexError: 106 | print('regions_in_use.py resources.csv') 107 | sys.exit(1) 108 | 109 | return csv_filename 110 | 111 | 112 | def resource_matches_to_ignore_id(resource): 113 | for to_ignore_id_start in RESOURCES_TO_IGNORE_PER_REGION: 114 | if resource.id_start == to_ignore_id_start: 115 | return True 116 | 117 | return False 118 | 119 | 120 | def should_ignore_resource(resource, ignored_resources_per_region): 121 | # 122 | # The resource doesn't have a name we ignore 123 | # 124 | if not resource_matches_to_ignore_id(resource): 125 | return False 126 | 127 | # 128 | # The resource is in a region where nothing has been ignored yet, we don't 129 | # need to count if there are other resources of the same type 130 | # 131 | if resource.region not in ignored_resources_per_region: 132 | ignored_resources_per_region[resource.region] = [resource] 133 | # print('Ignoring %s' % resource.id) 134 | return True 135 | 136 | current_ignore_count = {} 137 | 138 | for already_ignored_resource in ignored_resources_per_region[resource.region]: 139 | if already_ignored_resource.id_start in current_ignore_count: 140 | current_ignore_count[already_ignored_resource.id_start] += 1 141 | else: 142 | current_ignore_count[already_ignored_resource.id_start] = 1 143 | 144 | if resource.id_start not in current_ignore_count: 145 | # print('Ignoring %s' % resource.id) 146 | ignored_resources_per_region[resource.region].append(resource) 147 | return True 148 | 149 | if current_ignore_count[resource.id_start] < RESOURCES_TO_IGNORE_PER_REGION[resource.id_start]: 150 | # print('Ignoring %s' % resource.id) 151 | return True 152 | 153 | return False 154 | 155 | 156 | def main(): 157 | csv_filename = get_input_csv_filename() 158 | 159 | resources_per_region = {} 160 | ignored_resources_per_region = {} 161 | 162 | # 163 | # Filter out the default resources 164 | # 165 | for resource in get_resources(csv_filename): 166 | if should_ignore_resource(resource, ignored_resources_per_region): 167 | continue 168 | 169 | if resource.region in resources_per_region: 170 | resources_per_region[resource.region].append(resource) 171 | else: 172 | resources_per_region[resource.region] = [resource] 173 | 174 | # 175 | # Make the output printable in JSON 176 | # 177 | resources_per_region_json = {} 178 | 179 | for region in resources_per_region: 180 | for resource in resources_per_region[region]: 181 | if region in resources_per_region_json: 182 | resources_per_region_json[region].append(resource.to_dict()) 183 | else: 184 | resources_per_region_json[region] = [resource.to_dict()] 185 | 186 | used_regions = list(resources_per_region_json.keys()) 187 | used_regions.sort() 188 | used_regions.append('global') 189 | 190 | # Global is always in use 191 | resources_per_region_json['global'] = ['iam'] 192 | 193 | os.makedirs('output', exist_ok=True) 194 | json_writer('output/regions-in-use.json', used_regions) 195 | json_writer('output/resources-by-region.json', resources_per_region_json) 196 | 197 | json_printer(used_regions) 198 | 199 | 200 | if __name__ == '__main__': 201 | main() 202 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pygments 2 | boto3 3 | click 4 | python-dateutil 5 | tqdm -------------------------------------------------------------------------------- /route53_dump.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dump all route53 records 3 | """ 4 | 5 | from utils.json_printer import json_printer 6 | from utils.json_writer import json_writer 7 | from utils.session import get_session 8 | 9 | PRINT_NAMES = ('A', 'CNAME') 10 | 11 | 12 | def print_interesting(record): 13 | record_name = record.get('Name', None) 14 | 15 | if record.get('Type') not in PRINT_NAMES: 16 | return 17 | 18 | if record_name.endswith('internal'): 19 | return 20 | 21 | # replace the * at the beginning of the record name 22 | record_name = record_name.replace('*', 'www') 23 | 24 | print(record_name) 25 | 26 | 27 | def dump_route53_records(route53_client, zone_name, zone_id, all_data): 28 | pager = route53_client.get_paginator('list_resource_record_sets') 29 | 30 | for page in pager.paginate(HostedZoneId=zone_id): 31 | for record in page['ResourceRecordSets']: 32 | record_name = record.get('Name', None) 33 | 34 | if record_name is None: 35 | continue 36 | 37 | if record_name in all_data: 38 | continue 39 | 40 | record_name = record_name.replace('\\052', '*') 41 | record_name = record_name[:-1] 42 | record['Name'] = record_name 43 | 44 | if zone_name not in all_data: 45 | all_data[zone_name] = list() 46 | 47 | all_data[zone_name].append(record) 48 | print_interesting(record) 49 | 50 | return all_data 51 | 52 | 53 | def main(): 54 | session = get_session() 55 | route53_client = session.client('route53') 56 | 57 | zone_info = route53_client.list_hosted_zones() 58 | 59 | all_data = dict() 60 | 61 | for zone in zone_info.get('HostedZones'): 62 | zone_name = zone['Name'] 63 | zone_id = zone['Id'] 64 | 65 | # remove trailing dot 66 | zone_name = zone_name[:-1] 67 | 68 | dump_route53_records(route53_client, zone_name, zone_id, all_data) 69 | 70 | json_writer('output/route53_dump.json', all_data) 71 | return all_data 72 | 73 | 74 | if __name__ == '__main__': 75 | all_data = main() 76 | # json_printer(all_data) 77 | -------------------------------------------------------------------------------- /s3_last_used.py: -------------------------------------------------------------------------------- 1 | """ 2 | Identify when an S3 bucket was last used. This script helps identify S3 buckets 3 | which can be removed from the AWS account because nobody is using them. 4 | 5 | An S3 bucket is considered as used when there are calls to: 6 | * PutObject 7 | * GetObject 8 | * ListObjects 9 | 10 | This script is different from the others in this repository because it has a 11 | lot of external dependencies and manual steps that need to be done before 12 | running it. 13 | 14 | Requirements 15 | 16 | 1. Enable CloudTrail logging to an S3 bucket 17 | 18 | 2. Enable S3 detailed logging in CloudTrail to get the data API calls 19 | 20 | 3. Run cloudtrail-partitioner [0], no need to install the CDK application in 21 | the account, just run the tool to get 90 day visibility in Athena. 22 | 23 | 4. Use Athena to query the events and download the result as CSV. Use the 24 | this Athena query [1] to get all the data from the previously created 25 | partitions. Make sure you adjust the dates. 26 | 27 | 5. Run this tool 28 | 29 | [0] https://github.com/duo-labs/cloudtrail-partitioner/ 30 | [1] https://gist.github.com/andresriancho/2a85070593d70f48430ea132e08c1ad9 31 | """ 32 | import os 33 | import sys 34 | import csv 35 | import json 36 | import argparse 37 | import boto3 38 | 39 | from dateutil.parser import parse 40 | from datetime import datetime, timezone 41 | from tqdm import tqdm 42 | 43 | from utils.boto_error_handling import yield_handling_errors 44 | 45 | 46 | DEFAULT_DATE = datetime(1970, 1, 1, tzinfo=timezone.utc) 47 | 48 | 49 | def parse_arguments(): 50 | parser = argparse.ArgumentParser() 51 | 52 | parser.add_argument( 53 | '--input', 54 | help='Athena-generated CSV file', 55 | required=True 56 | ) 57 | 58 | parser.add_argument( 59 | '--profile', 60 | help='AWS profile from ~/.aws/credentials', 61 | required=True 62 | ) 63 | 64 | args = parser.parse_args() 65 | 66 | try: 67 | session = boto3.Session(profile_name=args.profile) 68 | except Exception as e: 69 | print('%s' % e) 70 | sys.exit(1) 71 | 72 | csv_file = args.input 73 | 74 | if not os.path.exists(csv_file): 75 | print('%s is not a file' % csv_file) 76 | sys.exit(1) 77 | 78 | return csv_file, session 79 | 80 | 81 | class S3Data(object): 82 | def __init__(self, event_time, request_parameters, aws_region, event_source): 83 | self.event_time = event_time 84 | self.request_parameters = request_parameters 85 | self.aws_region = aws_region 86 | self.event_source = event_source 87 | 88 | 89 | def parse_csv(csv_file): 90 | s3_last_used_data = dict() 91 | 92 | with open(csv_file, newline='') as csv_file: 93 | reader = csv.reader(csv_file) 94 | headers = next(reader, None) 95 | 96 | for row in tqdm(reader): 97 | (event_time, event_name, request_parameters, aws_region, event_source, resources) = row 98 | request_parameters = json.loads(request_parameters) 99 | event_time = parse(event_time) 100 | 101 | bucket_name = request_parameters['bucketName'] 102 | 103 | if bucket_name in s3_last_used_data: 104 | # Might need to update the last used time 105 | if event_time > s3_last_used_data[bucket_name].event_time: 106 | s3_last_used_data[bucket_name] = S3Data(event_time, 107 | request_parameters, 108 | aws_region, 109 | event_source) 110 | else: 111 | # New lambda function 112 | s3_last_used_data[bucket_name] = S3Data(event_time, 113 | request_parameters, 114 | aws_region, 115 | event_source) 116 | 117 | return s3_last_used_data 118 | 119 | 120 | def sort_key(item): 121 | return item[1] 122 | 123 | 124 | def print_output(s3_last_used_data): 125 | data = [] 126 | 127 | for bucket_name, s3_data in s3_last_used_data.items(): 128 | item = (bucket_name, s3_data.event_time,) 129 | data.append(item) 130 | 131 | data.sort(key=sort_key, reverse=True) 132 | 133 | for bucket_name, event_time in data: 134 | if event_time is DEFAULT_DATE: 135 | msg = '%s NOT used during the tracking period' 136 | args = (bucket_name,) 137 | print(msg % args) 138 | 139 | else: 140 | days_ago = datetime.now() - event_time.replace(tzinfo=None) 141 | days_ago = days_ago.days 142 | 143 | msg = '%s was last used %s days ago' 144 | args = (bucket_name, days_ago) 145 | print(msg % args) 146 | 147 | 148 | def get_all_buckets(session): 149 | client = session.client('s3') 150 | response = client.list_buckets() 151 | 152 | for bucket in response['Buckets']: 153 | yield bucket['Name'] 154 | 155 | 156 | def dump_s3_buckets(session): 157 | all_s3_buckets = [] 158 | 159 | iterator = yield_handling_errors(get_all_buckets, session) 160 | 161 | for bucket_name in iterator: 162 | all_s3_buckets.append(bucket_name) 163 | 164 | return all_s3_buckets 165 | 166 | 167 | def merge_all_buckets(s3_last_used_data, all_s3_buckets): 168 | for bucket_name in all_s3_buckets: 169 | if bucket_name not in s3_last_used_data: 170 | s3_last_used_data[bucket_name] = S3Data(DEFAULT_DATE, 171 | None, 172 | None, 173 | None) 174 | 175 | return s3_last_used_data 176 | 177 | 178 | def main(): 179 | csv_file, session = parse_arguments() 180 | 181 | print('Getting all existing S3 buckets...') 182 | all_s3_buckets = dump_s3_buckets(session) 183 | 184 | print('Parsing CSV file...') 185 | s3_last_used_data = parse_csv(csv_file) 186 | 187 | s3_last_used_data = merge_all_buckets(s3_last_used_data, all_s3_buckets) 188 | 189 | print('') 190 | print('Result:') 191 | print('') 192 | print_output(s3_last_used_data) 193 | 194 | 195 | if __name__ == '__main__': 196 | main() 197 | -------------------------------------------------------------------------------- /s3_versioning_cost.py: -------------------------------------------------------------------------------- 1 | """ 2 | Get the total number of bytes used to store non-current versions 3 | of S3 objects in a bucket. 4 | 5 | The result of this tool needs to be multiplied by the S3 pricing 6 | associated with your bucket. 7 | 8 | https://aws.amazon.com/s3/pricing/ 9 | """ 10 | import sys 11 | import argparse 12 | import boto3 13 | 14 | 15 | def parse_arguments(): 16 | parser = argparse.ArgumentParser() 17 | 18 | parser.add_argument( 19 | '--bucket', 20 | help='S3 bucket name', 21 | required=True 22 | ) 23 | 24 | parser.add_argument( 25 | '--profile', 26 | help='AWS profile from ~/.aws/credentials', 27 | required=True 28 | ) 29 | 30 | args = parser.parse_args() 31 | 32 | try: 33 | session = boto3.Session(profile_name=args.profile) 34 | except Exception as e: 35 | print('%s' % e) 36 | sys.exit(1) 37 | 38 | return args.bucket, session 39 | 40 | 41 | def get_size_for_previous_versions(session, bucket): 42 | total_size = 0 43 | iter_count = 0 44 | version_count = 0 45 | non_current_versions = 0 46 | 47 | s3 = session.client('s3') 48 | paginator = s3.get_paginator('list_object_versions') 49 | 50 | response_iterator = paginator.paginate(Bucket=bucket) 51 | 52 | for response in response_iterator: 53 | 54 | versions = response.get('Versions') 55 | if versions is None: 56 | continue 57 | 58 | iter_count += 1 59 | 60 | if iter_count % 50 == 0: 61 | stats = { 62 | 'analyzed_objects': version_count, 63 | 'non_current_objects': non_current_versions, 64 | 'non_current_objects_size_bytes': total_size 65 | } 66 | print(stats) 67 | 68 | for version in versions: 69 | version_count += 1 70 | 71 | if version['IsLatest']: 72 | # We just want the cost for the previous versions 73 | continue 74 | 75 | total_size += version['Size'] 76 | non_current_versions += 1 77 | 78 | return total_size 79 | 80 | 81 | def main(): 82 | bucket, session = parse_arguments() 83 | 84 | total = get_size_for_previous_versions(session, bucket) 85 | print(total) 86 | 87 | 88 | if __name__ == '__main__': 89 | main() 90 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andresriancho/aws-audit-automation/4180fa5fade49df1904e330a00a62efab300c0a0/utils/__init__.py -------------------------------------------------------------------------------- /utils/boto_error_handling.py: -------------------------------------------------------------------------------- 1 | from botocore.exceptions import ClientError 2 | 3 | UNAUTH_ERRORS = ('UnauthorizedOperation', 4 | 'AccessDeniedException') 5 | 6 | 7 | def yield_handling_errors(func, *args, **kwargs): 8 | try: 9 | for result in func(*args, **kwargs): 10 | yield result 11 | except ClientError as e: 12 | if e.response['Error']['Code'] in UNAUTH_ERRORS: 13 | print("%s" % e) 14 | else: 15 | print("Unexpected error: %s" % e) 16 | -------------------------------------------------------------------------------- /utils/get_user_name.py: -------------------------------------------------------------------------------- 1 | def get_principal_name(sts_caller_identity_output): 2 | # arn:aws:iam::231051035917:user/s3user 3 | arn = sts_caller_identity_output['Arn'] 4 | type_name = arn.split(':')[5] 5 | return type_name.split('/') 6 | -------------------------------------------------------------------------------- /utils/json_encoder.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | 4 | def json_encoder(o): 5 | if type(o) is datetime.date or type(o) is datetime.datetime: 6 | return o.isoformat() 7 | -------------------------------------------------------------------------------- /utils/json_printer.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from pygments import highlight 4 | from pygments.lexers import JsonLexer 5 | from pygments.formatters import TerminalFormatter 6 | 7 | from utils.json_encoder import json_encoder 8 | 9 | 10 | def json_printer(data): 11 | json_str = json.dumps(data, 12 | indent=4, 13 | sort_keys=True, 14 | default=json_encoder) 15 | 16 | print(highlight(json_str, JsonLexer(), TerminalFormatter())) 17 | -------------------------------------------------------------------------------- /utils/json_writer.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | 4 | from utils.json_encoder import json_encoder 5 | 6 | 7 | def json_writer(filename, data): 8 | os.makedirs('output', exist_ok=True) 9 | 10 | data_str = json.dumps(data, 11 | indent=4, 12 | sort_keys=True, 13 | default=json_encoder) 14 | 15 | open(filename, 'w').write(data_str) 16 | -------------------------------------------------------------------------------- /utils/regions.py: -------------------------------------------------------------------------------- 1 | def get_all_regions(session): 2 | client = session.client('ec2', 'us-east-1') 3 | 4 | for region in client.describe_regions()['Regions']: 5 | yield region['RegionName'] 6 | -------------------------------------------------------------------------------- /utils/remove_metadata.py: -------------------------------------------------------------------------------- 1 | def remove_metadata(boto_response): 2 | boto_response.pop('ResponseMetadata', None) 3 | return boto_response 4 | -------------------------------------------------------------------------------- /utils/session.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import boto3 3 | import sys 4 | 5 | 6 | def get_session(): 7 | parser = argparse.ArgumentParser() 8 | parser.add_argument( 9 | '--profile', 10 | help='AWS profile from ~/.aws/credentials', 11 | required=False, 12 | default='default' 13 | ) 14 | 15 | args = parser.parse_args() 16 | 17 | try: 18 | session = boto3.Session(profile_name=args.profile) 19 | except Exception as e: 20 | print('%s' % e) 21 | sys.exit(1) 22 | 23 | return session 24 | -------------------------------------------------------------------------------- /vpc_security_group_usage.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import sys 4 | 5 | import boto3 6 | 7 | from utils.json_printer import json_printer 8 | from utils.session import get_session 9 | 10 | 11 | def main(): 12 | session = get_session() 13 | 14 | # TODO: Change this to a command line parameters 15 | security_group_id = 'sg-0ea...' 16 | region_name = 'us-west-2' 17 | 18 | ec2_client = session.client('ec2', region_name=region_name) 19 | 20 | filters = [{'Name': 'group-id', 21 | 'Values': [security_group_id]}] 22 | result = ec2_client.describe_network_interfaces(Filters=filters) 23 | 24 | result.pop('ResponseMetadata') 25 | 26 | json_printer(result) 27 | 28 | 29 | if __name__ == '__main__': 30 | main() 31 | -------------------------------------------------------------------------------- /whoami.py: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | 3 | """ 4 | Calls these (from boto) to get an idea of who's behind a set of credentials 5 | 6 | aws sts get-caller-identity 7 | aws iam get-account-authorization-details 8 | aws iam list-attached-user-policies --user-name=... 9 | aws iam list-groups-for-user --user-name=... 10 | aws iam list-attached-group-policies --group-name ... 11 | """ 12 | import os 13 | import boto3 14 | 15 | from utils.json_writer import json_writer 16 | from utils.json_printer import json_printer 17 | from utils.remove_metadata import remove_metadata 18 | from utils.get_user_name import get_principal_name 19 | from utils.session import get_session 20 | 21 | 22 | def get_policy(session, policy_arn): 23 | iam_client = session.client('iam') 24 | 25 | policy = iam_client.get_policy( 26 | PolicyArn=policy_arn 27 | ) 28 | 29 | policy_version = iam_client.get_policy_version( 30 | PolicyArn=policy_arn, 31 | VersionId=policy['Policy']['DefaultVersionId'] 32 | ) 33 | 34 | output = dict() 35 | output['document'] = policy_version['PolicyVersion']['Document'] 36 | output['statement'] = policy_version['PolicyVersion']['Document']['Statement'] 37 | return output 38 | 39 | 40 | def main(): 41 | session = get_session() 42 | 43 | output = {} 44 | 45 | sts_client = session.client('sts') 46 | sts_data = sts_client.get_caller_identity() 47 | sts_data = remove_metadata(sts_data) 48 | 49 | output['sts'] = sts_data 50 | 51 | principal_type, name, session_name = get_principal_name(sts_data) 52 | 53 | output['principal_type'] = principal_type 54 | output['principal_name'] = name 55 | 56 | os.makedirs('output', exist_ok=True) 57 | json_writer('output/whoami.json', output) 58 | json_printer(output) 59 | 60 | 61 | if __name__ == '__main__': 62 | main() 63 | --------------------------------------------------------------------------------