├── LICENSE.txt ├── README.rst ├── aws_assume_roles ├── __init__.py └── examples │ ├── __init__.py │ ├── check_cloudtrail_configs.py │ ├── check_for_orgaccountaccessrole.py │ ├── collect_cloudtrail_configs.py │ ├── find_admins.py │ ├── find_githubio_dns_records.py │ ├── get_account_aliases.py │ ├── get_cloudformation_regions.py │ ├── get_ec2_tags.py │ ├── get_ssh_keys.py │ ├── get_users.py │ └── show_who_can_assume_roles.py ├── setup.py └── tools └── aws_assume_role.sh /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | aws_assume_roles Python module 2 | ============================== 3 | 4 | Iterate over a set of AWS IAM roles and call an arbitrary method with each 5 | role. 6 | 7 | :: 8 | 9 | aws_assume_roles --profile myawsprofilename examples.find_githubio_dns_records.main arnlist.txt 10 | 11 | aws_assume_role bash script 12 | =========================== 13 | 14 | Generate temporary credentials for an assumed role, save those ephemeral 15 | credentials in the awscli config and set the alias of ``aaws`` to use this new 16 | ephemeral awscli profile 17 | 18 | 19 | Usage 20 | ----- 21 | :: 22 | 23 | Usage : . /home/gene/bin/aws_assume_role ROLE_ARN [PARENT_PROFILE_NAME] 24 | ^--- Note that this script must be sourced not executed 25 | 26 | Examples 27 | . /home/gene/bin/aws_assume_role arn:aws:iam::123456789012:role/ExampleRole 28 | aaws ec2 describe-instances 29 | or 30 | . /home/gene/bin/aws_assume_role arn:aws:iam::234567890123:role/ExampleRole staging 31 | aaws --region us-west-2 ec2 describe-instances -------------------------------------------------------------------------------- /aws_assume_roles/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import argparse 4 | import logging 5 | import importlib 6 | import os 7 | import sys 8 | import boto3 9 | import functools 10 | import json 11 | 12 | if 'lru_cache' in functools.__dict__: 13 | # Python 3 14 | lru_cache = functools.lru_cache 15 | else: 16 | # Python 2 17 | try: 18 | from functools32 import lru_cache 19 | except ImportError: 20 | # Make our own memoize decorator and assign it to lru_cache? 21 | raise Exception( 22 | "Unable to find lru_cache method in functools because " 23 | "this isn't Python 3 and unable to find functools32 module with " 24 | "backported lru_cache method") 25 | 26 | 27 | def type_loglevel(level): 28 | try: 29 | result = getattr(logging, level.upper()) 30 | except AttributeError: 31 | raise argparse.ArgumentTypeError( 32 | "'%s' is not a valid log level. Please use %s" % 33 | (level, [x 34 | for x 35 | in logging._levelNames.keys() 36 | if isinstance(x, str)])) 37 | return result 38 | 39 | 40 | def type_method(method): 41 | module_name = '.'.join(method.split('.')[:-1]) 42 | method_name = '.'.join(method.split('.')[-1:]) 43 | if len(module_name) == 0: 44 | raise argparse.ArgumentTypeError('%s is missing a module and method ' 45 | 'name') 46 | try: 47 | # Add the current working directory to the path 48 | sys.path.insert(0, os.getcwd()) 49 | i = importlib.import_module(module_name) 50 | except ImportError: 51 | raise argparse.ArgumentTypeError('unable to find module %s' % 52 | module_name) 53 | try: 54 | result = getattr(i, method_name) 55 | except AttributeError: 56 | raise argparse.ArgumentTypeError( 57 | 'unable to find method %s in module %s . found %s' % 58 | (method_name, module_name, dir(i))) 59 | return result 60 | 61 | 62 | @lru_cache(maxsize=32) 63 | def get_assumed_role(role_arn, 64 | profile_name=None, 65 | role_session_name='aws_assume_role', 66 | policy=None): 67 | logging.debug("Connecting to sts") 68 | try: 69 | params = {} if profile_name is None else {'profile_name': profile_name} 70 | session = boto3.Session(**params) 71 | client_sts = session.client('sts') 72 | except Exception as e: 73 | logging.error("Unable to connect to sts with exception %s" % e) 74 | raise 75 | try: 76 | params = {'RoleArn': role_arn, 77 | 'RoleSessionName': role_session_name} 78 | if policy is not None: 79 | params['Policy'] = policy 80 | response = client_sts.assume_role(**params) 81 | except Exception as e: 82 | logging.error("Unable to assume role %s due to exception %s" % 83 | (role_arn, e)) 84 | return False 85 | credentials = { 86 | 'aws_access_key_id': response['Credentials']['AccessKeyId'], 87 | 'aws_secret_access_key': response['Credentials']['SecretAccessKey'], 88 | 'aws_session_token': response['Credentials']['SessionToken']} 89 | return credentials 90 | 91 | 92 | def get_args(): 93 | parser = argparse.ArgumentParser( 94 | description='Iterate over a set of AWS IAM roles and call an ' 95 | 'arbitrary method with each role') 96 | parser.add_argument( 97 | 'method', type=type_method, help='a dot delimited method name') 98 | parser.add_argument( 99 | 'arnfile', nargs='?', type=argparse.FileType('r'), default=sys.stdin, 100 | help='a filename of a list of ARNs, one per line (default : stdin)') 101 | parser.add_argument('--profile', help='AWS credential profile name') 102 | parser.add_argument( 103 | '-l', '--loglevel', type=type_loglevel, default='INFO', 104 | help='Log level verbosity (default: INFO)') 105 | parser.add_argument( 106 | '--output', help='Filename to output to instead of stdout') 107 | args = parser.parse_args() 108 | logging.basicConfig(level=args.loglevel) 109 | # Disable boto logging 110 | logging.getLogger('boto3').setLevel(logging.ERROR) 111 | logging.getLogger('botocore').setLevel(logging.ERROR) 112 | logging.getLogger('requests').setLevel(logging.ERROR) 113 | logging.getLogger('urllib3').setLevel(logging.ERROR) 114 | 115 | return args 116 | 117 | 118 | def main(): 119 | args = get_args() 120 | results = {} 121 | for line in args.arnfile.readlines(): 122 | arn = line.split('#')[0].strip() 123 | if len(arn) == 0: 124 | continue 125 | credentials = get_assumed_role(role_arn=arn, profile_name=args.profile) 126 | if credentials: 127 | results[arn] = args.method(arn=arn, credentials=credentials) 128 | else: 129 | if 'errors' not in results: 130 | results['errors'] = [] 131 | results['errors'].append('Unable to assume_role to %s' % arn) 132 | if args.output: 133 | with open(args.output, 'w') as f: 134 | json.dump(results, f, indent=4) 135 | print('{} records collected for {}'.format(len(results[arn]), arn)) 136 | 137 | if not args.output: 138 | print(json.dumps(results, indent=4)) 139 | 140 | 141 | if __name__ == "__main__": 142 | main() 143 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gene1wood/aws_assume_roles/ee5f486c8379e5c0f57a1f5458120d27ba6c0669/aws_assume_roles/examples/__init__.py -------------------------------------------------------------------------------- /aws_assume_roles/examples/check_cloudtrail_configs.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | import boto3 4 | 5 | def main(arn, credentials={}): 6 | client = boto3.client('cloudtrail', **credentials) 7 | response = client.describe_trails( 8 | includeShadowTrails=True 9 | ) 10 | if len(response['trailList']) == 0: 11 | return "no cloudtrail" 12 | else: 13 | for trail in response['trailList']: 14 | return "%s %s" % (trail['S3BucketName'], 15 | trail['IsMultiRegionTrail']) 16 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/check_for_orgaccountaccessrole.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | import boto3 4 | import datetime 5 | 6 | 7 | def get_paginated_results(product, action, key, credentials={}, args=None): 8 | args = {} if args is None else args 9 | return [y for sublist in [x[key] for x in boto3.client(product, **credentials).get_paginator(action).paginate(**args)] for y in sublist] 10 | 11 | 12 | def main(arn='', credentials={}): 13 | """Get OrganizationAccountAccessRole""" 14 | 15 | client = boto3.client('iam', **credentials) 16 | result=None 17 | try: 18 | response = client.get_role(RoleName='OrganizationAccountAccessRole') 19 | result = response['Role']['AssumeRolePolicyDocument'] 20 | except: 21 | pass 22 | return result 23 | 24 | 25 | if __name__ == "__main__": 26 | print(main()) 27 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/collect_cloudtrail_configs.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | import boto3 4 | 5 | 6 | def main(arn='', credentials={}): 7 | client = boto3.client('cloudtrail', **credentials) 8 | response = client.describe_trails( 9 | includeShadowTrails=True 10 | ) 11 | 12 | if len(response['trailList']) == 0: 13 | return ["no cloudtrail"] 14 | else: 15 | return ["%s %s %s %s" % ( 16 | trail['S3BucketName'], 17 | trail['IsMultiRegionTrail'], 18 | trail['SnsTopicARN'] if 'SnsTopicARN' in trail else 'no-sns-topic', 19 | trail['HomeRegion']) for trail in response['trailList']] 20 | 21 | 22 | if __name__ == "__main__": 23 | print(main()) 24 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/find_admins.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | import boto3 4 | import datetime 5 | 6 | # https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces 7 | # This is an AWS product that I'm assuming no user has explicitly granted in 8 | # an IAM policy. If a user has a policy granting them access to SUPER_ESOTERIC_AWS_NAMESPACE 9 | # service, they're likely admins with *:* permissions 10 | SUPER_ESOTERIC_AWS_NAMESPACE = 'mediapackage' 11 | 12 | 13 | def get_paginated_results(product, action, key, credentials, args=None): 14 | args = {} if args is None else args 15 | return [y for sublist in [x[key] for x in boto3.client(product, **credentials).get_paginator(action).paginate(**args)] for y in sublist] 16 | 17 | 18 | def main(arn='', credentials=None): 19 | """Get all IAM users with *:* permissions""" 20 | credentials = {} if credentials is None else credentials 21 | client = boto3.client('iam', **credentials) 22 | users = get_paginated_results('iam', 'list_users', 'Users', credentials) 23 | admins = [] 24 | for user in users: 25 | response = client.list_policies_granting_service_access( 26 | Arn=user['Arn'], 27 | ServiceNamespaces=[SUPER_ESOTERIC_AWS_NAMESPACE] 28 | ) 29 | if len(response['PoliciesGrantingServiceAccess'][0]['Policies']) > 0: 30 | last_used = user.get('PasswordLastUsed', datetime.datetime.utcfromtimestamp(0)) 31 | admins.append((user['UserName'], str(last_used))) 32 | 33 | return admins 34 | 35 | 36 | if __name__ == "__main__": 37 | print(main()) 38 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/find_githubio_dns_records.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import boto3 4 | import logging 5 | 6 | logging.basicConfig(level=logging.INFO) 7 | 8 | # https://help.github.com/articles/troubleshooting-custom-domains/ 9 | GITHUBIO_IPS = ['192.30.252.153', 10 | '192.30.252.154', 11 | '185.199.108.153', 12 | '185.199.109.153', 13 | '185.199.110.153', 14 | '185.199.111.153', 15 | '207.97.227.245', 16 | '204.232.175.78' 17 | ] 18 | GITHUBIO_SUFFIX = '.github.io.' 19 | 20 | 21 | def main(arn='', credentials={}): 22 | client = boto3.client('route53', **credentials) 23 | results = [] 24 | hosted_zone_ids = [] 25 | 26 | paginator = client.get_paginator('list_hosted_zones') 27 | response_iterator = paginator.paginate() 28 | 29 | for page in response_iterator: 30 | hosted_zone_ids.extend([x['Id'] for x in page['HostedZones']]) 31 | 32 | for hosted_zone_id in hosted_zone_ids: 33 | paginator = client.get_paginator('list_resource_record_sets') 34 | response_iterator = paginator.paginate( 35 | HostedZoneId=hosted_zone_id 36 | ) 37 | for page in response_iterator: 38 | if 'ResourceRecordSets' not in page: 39 | logging.debug("'ResourceRecordSets' not found in %s" % page) 40 | raise Exception() 41 | for record in page['ResourceRecordSets']: 42 | logging.info('Checking %s' % record['Name']) 43 | if record['Type'] == 'CNAME': 44 | if 'ResourceRecords' not in record: 45 | logging.debug("'ResourceRecords' not found in %s" % 46 | record) 47 | continue # Previously we raised an Exception here but I'm not sure why 48 | for value in [x['Value'] 49 | for x 50 | in record['ResourceRecords']]: 51 | if value.endswith(GITHUBIO_SUFFIX): 52 | results.append({'HostedZoneId': hosted_zone_id, 53 | 'Name': record['Name'], 54 | 'Type': record['Type'], 55 | 'Value': value}) 56 | elif record['Type'] == 'A': 57 | if 'ResourceRecords' not in record: 58 | logging.debug("'ResourceRecords' not found in %s" % 59 | record) 60 | continue 61 | for value in [x['Value'] 62 | for x 63 | in record['ResourceRecords']]: 64 | if value in GITHUBIO_IPS: 65 | results.append({'HostedZoneId': hosted_zone_id, 66 | 'Name': record['Name'], 67 | 'Type': record['Type'], 68 | 'Value': value}) 69 | 70 | return results 71 | 72 | 73 | if __name__ == "__main__": 74 | print(main()) 75 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/get_account_aliases.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | import boto3 4 | 5 | 6 | def main(arn='', credentials=None): 7 | """Get account aliases""" 8 | credentials = {} if credentials is None else credentials 9 | client = boto3.client('iam', **credentials) 10 | aliases = client.list_account_aliases() 11 | return aliases['AccountAliases'] 12 | 13 | 14 | if __name__ == "__main__": 15 | print(main()) 16 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/get_cloudformation_regions.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | import boto3 4 | 5 | 6 | def get_paginated_results(product, action, key, region_name, credentials): 7 | return [y for sublist in [x[key] for x in boto3.client(product, region_name=region_name, **credentials).get_paginator(action).paginate()] for y in sublist] 8 | 9 | 10 | def main(arn='', credentials={}): 11 | """Count the number of CloudFormation stacks in each region""" 12 | result = {} 13 | regions = boto3.session.Session().get_available_regions('cloudformation') 14 | for region in regions: 15 | stacks = get_paginated_results('cloudformation', 'list_stacks', 'StackSummaries', region, credentials) 16 | result[region] = len(stacks) 17 | return result 18 | 19 | 20 | if __name__ == "__main__": 21 | print(main()) 22 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/get_ec2_tags.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | import boto3 4 | 5 | 6 | def main(arn='', credentials={}): 7 | result = [] 8 | ec2c = boto3.client('ec2', **credentials) 9 | regions = [x['RegionName'] for x in ec2c.describe_regions()['Regions']] 10 | for region in regions: 11 | client = boto3.client('ec2', region_name=region, **credentials) 12 | paginator = client.get_paginator('describe_instances') 13 | page_iterator = paginator.paginate() 14 | for page in page_iterator: 15 | for reservation in page['Reservations']: 16 | for instance in reservation['Instances']: 17 | result.append({ 18 | 'Region': region, 19 | 'InstanceId': instance['InstanceId'], 20 | 'Tags': dict([(x['Key'], x['Value']) for 21 | x in (instance['Tags'] if 'Tags' in 22 | instance else [])])}) 23 | return result 24 | 25 | 26 | if __name__ == "__main__": 27 | print(main()) 28 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/get_ssh_keys.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | import boto3 4 | 5 | 6 | def main(arn='', credentials={}): 7 | result = [] 8 | regions = boto3.session.Session().get_available_regions('ec2') 9 | for region in regions: 10 | client = boto3.client('ec2', region_name=region, **credentials) 11 | response = client.describe_key_pairs() 12 | result.extend( 13 | ['%s (%s)' % (x['KeyName'], region) for x in response['KeyPairs']]) 14 | 15 | return result 16 | 17 | 18 | if __name__ == "__main__": 19 | print(main()) 20 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/get_users.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | import boto3 4 | import datetime 5 | 6 | 7 | def get_paginated_results(product, action, key, credentials, args=None): 8 | args = {} if args is None else args 9 | return [y for sublist in [x[key] for x in boto3.client(product, **credentials).get_paginator(action).paginate(**args)] for y in sublist] 10 | 11 | 12 | def main(arn='', credentials=None): 13 | """Get users, the last time they logged in with a password and each of 14 | their API keys and the last time those keys were used 15 | 16 | :param arn: 17 | :param credentials: 18 | :return: A 3-tuple of 19 | IAM username 20 | the datetime that the password was last used for login 21 | a list of 2-tuples one for each API key with values of 22 | The access key id (public key) 23 | The datetime that the key was last used 24 | """ 25 | credentials = {} if credentials is None else credentials 26 | 27 | client = boto3.client('iam', **credentials) 28 | result = [] 29 | users = get_paginated_results('iam', 'list_users', 'Users', credentials) 30 | for user in users: 31 | last_used_password = user.get('PasswordLastUsed', 32 | datetime.datetime.utcfromtimestamp(0)) 33 | access_keys = get_paginated_results( 34 | 'iam', 'list_access_keys', 'AccessKeyMetadata', credentials, 35 | args={'UserName': user['UserName']}) 36 | keys = [] 37 | for access_key in access_keys: 38 | response = client.get_access_key_last_used( 39 | AccessKeyId=access_key['AccessKeyId'] 40 | ) 41 | last_used_access_key = response['AccessKeyLastUsed'].get( 42 | 'LastUsedDate', datetime.datetime.utcfromtimestamp(0)) 43 | keys.append((access_key['AccessKeyId'], str(last_used_access_key))) 44 | 45 | result.append((user['UserName'], str(last_used_password), keys)) 46 | 47 | return result 48 | 49 | 50 | if __name__ == "__main__": 51 | print(main()) 52 | -------------------------------------------------------------------------------- /aws_assume_roles/examples/show_who_can_assume_roles.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | import boto3 4 | 5 | 6 | def get_paginated_results(product, action, key, credentials={}, args={}): 7 | return [y for sublist in [x[key] for x in boto3.client(product, **credentials).get_paginator(action).paginate(**args)] for y in sublist] 8 | 9 | 10 | def simulate_policy(arn, credentials): 11 | """Given an IAM user/role, determine if it has rights to iam:AssumeRole""" 12 | args = {'PolicySourceArn': arn, 13 | 'ActionNames': ['iam:AssumeRole']} 14 | results = [ 15 | "%s %s %s %s %s %s" % ( 16 | arn, 17 | x['EvalActionName'], 18 | x['EvalResourceName'], 19 | x['EvalDecision'], 20 | x['MatchedStatements'], 21 | x['EvalDecisionDetails']) for x in 22 | get_paginated_results('iam', 'simulate_principal_policy', 23 | 'EvaluationResults', credentials, args)] 24 | return results 25 | 26 | 27 | def main(arn='', credentials={}): 28 | """Determine which IAM users and roles can iam:AssumeRole""" 29 | results = [] 30 | 31 | for user in get_paginated_results('iam', 'list_users', 'Users', credentials): 32 | results.extend(simulate_policy(user['Arn'], credentials)) 33 | 34 | for role in get_paginated_results('iam', 'list_roles', 'Roles', credentials): 35 | results.extend(simulate_policy(role['Arn'], credentials)) 36 | 37 | return results 38 | 39 | 40 | if __name__ == "__main__": 41 | print(main()) 42 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | 3 | setup( 4 | name='aws_assume_roles', 5 | version='0.2', 6 | author='Gene Wood', 7 | author_email='gene_wood@cementhorizon.com', 8 | packages=['aws_assume_roles'], 9 | entry_points={ 10 | 'console_scripts': [ 11 | 'aws_assume_roles = aws_assume_roles:main' 12 | ] 13 | }, 14 | url='http://pypi.python.org/pypi/aws_assume_roles/', 15 | license='LICENSE.txt', 16 | description='Iterate over a set of AWS IAM roles and call an arbitrary ' 17 | 'method with each role', 18 | long_description=open('README.rst').read(), 19 | install_requires=['boto3'], 20 | ) 21 | -------------------------------------------------------------------------------- /tools/aws_assume_role.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | usage () { 4 | cat <