def get_environment_credentials(self): """Get session credentials from the environment.""" aws_region = 'us-east-1' if 'AWS_PROFILE' in os.environ: credentials_profiles = awsumepy.read_ini_file(awsumepy.AWS_CREDENTIALS_FILE) auto_profile = credentials_profiles[os.environ['AWS_PROFILE']] temp_credentials = { 'sessionId': auto_profile['aws_access_key_id'], 'sessionKey': auto_profile['aws_secret_access_key'], 'sessionToken': auto_profile['aws_session_token'] } if auto_profile.get('aws_region'): aws_region = auto_profile.get('aws_region') elif os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY') and os.environ.get('AWS_SESSION_TOKEN'): temp_credentials = { 'sessionId': os.environ['AWS_ACCESS_KEY_ID'], 'sessionKey': os.environ['AWS_SECRET_ACCESS_KEY'], 'sessionToken': os.environ['AWS_SESSION_TOKEN'] } if os.environ.get('AWS_REGION'): aws_region = os.environ['AWS_REGION'] else: awsumepy.safe_print('Cannot use these credentials to open the AWS Console.') exit(0) json_temp_credentials = json.dumps(temp_credentials) return json_temp_credentials, aws_region
def post_awsume(self, app, args, profiles, user_session, role_session): """Open the console using the currently AWSume'd credentials.""" if args.open_console is True: if not role_session: awsumepy.safe_print('Cannot use these credentials to open the AWS Console.') return credentials, region = self.get_session_temp_credentials(role_session) response = self.make_aws_federation_request(credentials) signin_token = self.get_signin_token(response) console_url = self.get_console_url(signin_token, region) self.open_browser_to_url(console_url, args)
def get_session_temp_credentials(self, session): """Create a properly formatted json string of the given session. Return the session and the region to use.""" if session.get('AccessKeyId') and session.get('SecretAccessKey') and session.get('SessionToken'): aws_region = 'us-east-1' temp_credentials = { 'sessionId': session['AccessKeyId'], 'sessionKey': session['SecretAccessKey'], } if 'SessionToken' in session: temp_credentials['sessionToken'] = session['SessionToken'] if session.get('region'): aws_region = session['region'] #format the credentials into a json formatted string json_temp_credentials = json.dumps(temp_credentials) return json_temp_credentials, aws_region awsumepy.safe_print('Cannot use these credentials to open the AWS Console.') exit(0)
def post_add_arguments(config: dict, arguments: argparse.Namespace, parser: argparse.ArgumentParser): get_url, open_browser, print_url, service = parse_args(arguments, config) if get_url is True and arguments.profile_name is None and arguments.role_arn is None and sys.stdin.isatty( ) and not arguments.json: logger.debug('Openning console with current credentials') session = boto3.session.Session() creds = session.get_credentials() if not creds: raise exceptions.NoCredentialsError( 'No credentials to open the console with') url = get_console_url( { 'AccessKeyId': creds.access_key, 'SecretAccessKey': creds.secret_key, 'SessionToken': creds.token, 'Region': session.region_name, }, service) if config.get('console', {}).get('ext_container'): url = 'ext+container:name=%s&url=' % arguments.target_profile_name + urllib.parse.quote_plus( url) if print_url: safe_print(url) elif open_browser: try: open_url(config, arguments, url) except Exception as e: safe_print('Cannot open browser: {}'.format(e)) safe_print('Here is the link: {}'.format(url)) exit(0)
def open_browser_to_url(self, url, args): """Open the default browser to the given url. If that fails, display the url.""" if args.open_console_link: awsumepy.safe_print(url) else: try: webbrowser.open(url) except Exception: awsumepy.safe_print('Cannot open browser, here is the link:') awsumepy.safe_print(url)
def post_get_credentials(config: dict, arguments: argparse.Namespace, profiles: dict, credentials: dict): get_url, open_browser, print_url, service = parse_args(arguments, config) if get_url: logger.debug('Opening console with awsume\'d credentials') url = get_console_url(credentials, service) logger.debug('URL: {}'.format(url)) if print_url: safe_print(url) elif open_browser: try: open_url(config, arguments, url) except Exception as e: safe_print('Cannot open browser: {}'.format(e)) safe_print('Here is the link: {}'.format(url))
def post_get_credentials(config: dict, arguments: argparse.Namespace, profiles: dict, credentials: dict): get_url, open_browser, print_url, service = parse_args(arguments, config) if get_url: logger.debug('Openning console with awsume\'d credentials') url = get_console_url(credentials, service) if config.get('console', {}).get('ext_container'): url = 'ext+container:name=%s&url=' % arguments.target_profile_name + urllib.parse.quote_plus( url) logger.debug('URL: {}'.format(url)) if print_url: safe_print(url) elif open_browser: try: open_url(config, arguments, url) except Exception as e: safe_print('Cannot open browser: {}'.format(e)) safe_print('Here is the link: {}'.format(url))
def pre_get_credentials(config: dict, arguments: argparse.Namespace, profiles: dict): safe_print('Before getting credentials')
def display_access_keys(session: boto3.Session): target_key = session.get_credentials().access_key iam = session.client('iam') response = iam.list_access_keys()['AccessKeyMetadata'] safe_print('Displaying Access Keys'.center(45, '=')) safe_print('ACCESS KEY ID'.ljust(20), end=' ') safe_print('STATUS'.ljust(10), end=' ') safe_print('CREATE DATE'.ljust(10)) for key_metadata in response: color = None if target_key != key_metadata.get( 'AccessKeyId') else colorama.Fore.MAGENTA safe_print(key_metadata.get('AccessKeyId'), end=' ', color=color) safe_print('[{}]'.format(key_metadata.get('Status')).ljust(10), end=' ', color=color) safe_print('{}'.format( key_metadata.get('CreateDate').strftime('%d/%M/%Y')).ljust(10), color=color) safe_print(''.center(45, '='))
def post_get_credentials(config: dict, arguments: argparse.Namespace, profiles: dict, credentials: dict): safe_print('After getting credentials')
def catch_profile_not_found_exception(config: dict, arguments: argparse.Namespace, profiles: dict, error: Exception): safe_print('Uh oh, a profile was not found')
def catch_invalid_profile_exception(config: dict, arguments: argparse.Namespace, profiles: dict, error: Exception): safe_print('Uh oh, a profile was invalid')
def __get_accounts_from_appsync(plugin_config: dict): """Make the call to get the aws accounts.""" endpoint = plugin_config.get('appsync_url', None) if endpoint is None or endpoint == '': safe_print( 'AppSync URL Not Configured. Cheack the README for instructions.') return {} query = 'query {listAccounts {items {id name}}}' headers = {"Content-Type": "application/json"} payload = {"query": query} service = 'appsync' appsync_region = __parse_region_from_url(endpoint) or region auth = AWSV4Sign(credentials, appsync_region, service) try: appsync_accounts = requests.post(endpoint, auth=auth, json=payload, headers=headers).json() if 'errors' in appsync_accounts: safe_print('Error attempting to query AppSync', color=ERROR_COLOR) err = appsync_accounts['errors'][0] if 'errorType' in err and 'message' in err: errorType = err['errorType'] errorMessage = err['message'] safe_print(f'\t{errorType}: {errorMessage}', color=ERROR_COLOR) return {} else: appsync_accounts = appsync_accounts['data']['listAccounts'][ 'items'] if appsync_accounts is not None: __write_cache(appsync_accounts) except Exception as exception: appsync_accounts = {} safe_print("Cannot make the request to AppSync: ") safe_print(str(exception)) safe_print("Make sure you are authorized to make the request") return appsync_accounts
def catch_role_authentication_error(config: dict, arguments: argparse.Namespace, profiles: dict, error: Exception): safe_print('Uh oh, could not authenticate the role')
def pre_add_arguments(config: dict): safe_print('Before adding arguments')
def post_add_arguments(config: dict, arguments: argparse.Namespace, parser: argparse.ArgumentParser): if arguments.rotate_access_keys or arguments.force_rotate_access_keys: _, credentials_file = get_aws_files(arguments, config) profiles = read_aws_file(credentials_file) target_profile = profiles.get(arguments.target_profile_name) if not target_profile: safe_print('Profile {} not found'.format( arguments.target_profile_name), color=colorama.Fore.RED) exit(1) if 'aws_access_key_id' not in target_profile or 'aws_secret_access_key' not in target_profile: safe_print('Cannot rotate {}, must have keys to rotate'.format( arguments.target_profile_name), color=colorama.Fore.RED) exit(1) if 'aws_session_token' in target_profile: safe_print('Cannot rotate {}, must be a user profile'.format( arguments.target_profile_name), color=colorama.Fore.RED) exit(1) session = boto3.Session( aws_access_key_id=target_profile.get('aws_access_key_id'), aws_secret_access_key=target_profile.get('aws_secret_access_key'), ) display_access_keys(session) if not arguments.force_rotate_access_keys: safe_print( 'Are you sure you want to rotate access key [{}] for profile {} (y/N)?\n> ' .format( target_profile.get('aws_access_key_id'), arguments.target_profile_name, ), end='', ) choice = input() if choice.lower() != 'y': exit(0) safe_print('Rotating access keys for profile: {}'.format( arguments.target_profile_name), color=colorama.Fore.YELLOW) safe_print('Creating a new set of access keys...', color=colorama.Fore.GREEN) # todo safe_print('Updating credentials file {}...'.format(credentials_file), color=colorama.Fore.GREEN) # todo # also, update profiles that share the same key, but prompt each time safe_print('Deleting previous keys...', color=colorama.Fore.GREEN) # todo exit(0)
def post_collect_aws_profiles(config: dict, arguments: argparse.Namespace, profiles: dict): safe_print('After collecting aws profiles')
def pre_collect_aws_profiles(config: dict, arguments: argparse.Namespace, credentials_file: str, config_file: str): safe_print('Before collecting aws profiles')
def post_add_arguments(config: dict, arguments: argparse.Namespace, parser: argparse.ArgumentParser): if arguments.test: safe_print('Custom flag was triggered')