Пример #1
0
def make_aws_credentials(config, role_arn=None, role_name=None):
    if role_arn:
        try:
            sts_connection = STSConnection()
            assumedRoleObject = sts_connection.assume_role(
                role_arn=role_arn,
                role_session_name=role_name
            )
        except:
            out("Oops! something went wrong trying to assume the specified role")
        else:
            # create credentials for switching roles
            aws = AwsCredentials(
                assumedRoleObject.credentials.access_key,
                assumedRoleObject.credentials.secret_key,
                assumedRoleObject.credentials.session_token,
                get(config, 'aws.region',           os.environ.get('AWS_DEFAULT_REGION')),
                get(config, 'aws.bucket',           os.environ.get('AWS_BEANSTALK_BUCKET_NAME')),
                get(config, 'aws.bucket_path',      os.environ.get('AWS_BEANSTALK_BUCKET_NAME_PATH')))
            out("Using Role: "+role_name)
    else:
        # create credentials
        aws = AwsCredentials(
            get(config, 'aws.access_key',       os.environ.get('AWS_ACCESS_KEY_ID')),
            get(config, 'aws.secret_key',       os.environ.get('AWS_SECRET_ACCESS_KEY')),
            get(config, 'aws.secret_token',     os.environ.get('AWS_SECRET_TOKEN')),
            get(config, 'aws.region',           os.environ.get('AWS_DEFAULT_REGION')),
            get(config, 'aws.bucket',           os.environ.get('AWS_BEANSTALK_BUCKET_NAME')),
            get(config, 'aws.bucket_path',      os.environ.get('AWS_BEANSTALK_BUCKET_NAME_PATH')))
    return aws
Пример #2
0
def oauth_authorized(resp):
    facebook_graph = facebook.GraphAPI(resp.get('access_token'))
    email = facebook_graph.get_object("me")['email']
    sts_connection = STSConnection()
    role = sts_connection.assume_role(
        role_arn="arn:aws:iam::054060359478:role/facebook-login",
        role_session_name=email
    )
    creds = {
        'sessionId': role.credentials.access_key,
        'sessionKey': role.credentials.secret_key,
        'sessionToken': role.credentials.session_token
    }
    params = {
        'Action': 'getSigninToken',
        'Session': json.dumps(creds),
    }
    auth_url = "https://signin.aws.amazon.com/federation"
    r = requests.get(auth_url, params=params)
    signin_token = json.loads(r.text).get('SigninToken')
    params.update({
        'Action': 'login',
        'Issuer': 'ranman.org',
        'Destination': 'https://console.aws.amazon.com/',
        'SigninToken': signin_token
    })
    url = requests.Request('GET', auth_url, params=params).prepare().url
    return redirect(url)
 def get_aws_credentials(self, account_alias, role):
     """Get temporary credentials from AWS"""
     self.check_user_permissions(account_alias, role)
     try:
         account_id = self.account_config[account_alias]['id']
     except Exception:
         message = "No Configuration for account '{account}'."
         raise ConfigurationError(message.format(account=account_alias))
     arn = "arn:aws:iam::{account_id}:role/{role}".format(
         account_id=account_id, role=role)
     key_id = self.application_config['aws']['access_key']
     secret_key = self.application_config['aws']['secret_key']
     try:
         sts_connection = STSConnection(
             aws_access_key_id=key_id,
             aws_secret_access_key=secret_key)
         assumed_role_object = sts_connection.assume_role(
             role_arn=arn,
             role_session_name=self.user)
     except Exception as error:
         if getattr(error, 'status', None) == 403:
             raise PermissionError(str(error))
         self.logger.exception("AWS STS failed with: {exc_vars}".format(
             exc_vars=vars(error)))
         raise AWSError(str(error))
     return assumed_role_object.credentials
Пример #4
0
 def get_connection(self):
     ret = None
     if self._cross_account_number and self._cross_account_role:
         self._info(
             subject=_status.parse_status('cross_account_connect', (self._cross_account_number, self._cross_account_role, self._region)), 
             src_account=self._cross_account_number,
             src_role=self._cross_account_role,
             category='connection')
         from boto.sts import STSConnection
         import boto
         try:
             role_arn = 'arn:aws:iam::%s:role/%s' % (self._cross_account_number, self._cross_account_role)
             sts = STSConnection()
             assumed_role = sts.assume_role(role_arn=role_arn, role_session_name='AssumeRoleSession')
             ret = ec2.connect_to_region(
                 self._region,
                 aws_access_key_id=assumed_role.credentials.access_key,
                 aws_secret_access_key=assumed_role.credentials.secret_key,
                 security_token=assumed_role.credentials.session_token
             )
         except BotoServerError, e:
             raise BackupMonkeyException('%s: %s' % (_status.parse_status('cross_account_error'), e.message),
                 subject=_status.parse_status('cross_account_error'),
                 body=e.message,
                 src_account=self._cross_account_number,
                 src_role=self._cross_account_role,
                 category='connection')
Пример #5
0
def get_sts(duration, mfa_serial, mfa_device_name,
            long_term, short_term, assume_role_arn=None):
    if boto.config.get(long_term, 'aws_access_key_id') is None:
        logger.error('aws_access_key_id is missing from section %s'
                     'or config file is missing.' % (long_term,))
        sys.exit(1)
    else:
        long_term_id = boto.config.get(long_term, 'aws_access_key_id')

    if boto.config.get(long_term, 'aws_secret_access_key') is None:
        logger.error('aws_secret_access_key is missing from section '
                     'or config file is missing.' % (long_term,))
        sys.exit(1)
    else:
        long_term_secret = boto.config.get(long_term, 'aws_secret_access_key')

    if boto.config.has_section(short_term):
        boto.config.remove_option(short_term, 'aws_security_token')

    mfa_TOTP = raw_input('Enter AWS MFA code for user %s '
                         '(renewing for %s seconds):' %
                         (mfa_device_name, duration))
    try:
        sts_connection = STSConnection(aws_access_key_id=long_term_id,
                                       aws_secret_access_key=long_term_secret)
        if assume_role_arn is None:
            tempCredentials = sts_connection.get_session_token(
                duration=duration,
                mfa_serial_number=mfa_serial,
                mfa_token=mfa_TOTP)
            assumed_role = 'False'
        else:
            role_session_name = assume_role_arn.split('/')[-1]
            assumedRole = sts_connection.assume_role(
                assume_role_arn, role_session_name,
                duration_seconds=duration,
                mfa_serial_number=mfa_serial,
                mfa_token=mfa_TOTP)
            tempCredentials = assumedRole.credentials
            assumed_role = 'True'

        default_options = [
            ('aws_access_key_id', tempCredentials.access_key),
            ('aws_secret_access_key', tempCredentials.secret_key),
            ('aws_security_token', tempCredentials.session_token),
            ('expiration', tempCredentials.expiration),
            ('assumed_role', assumed_role)
        ]

        for option, value in default_options:
            boto.config.save_user_option(
                short_term,
                option,
                value
            )

    except boto.exception.BotoServerError as e:
        message = '%s - Please try again.' % (e.message)
        logger.error(message)
        sys.exit(1)
Пример #6
0
 def get_conn(self):
     """
     Returns the boto S3Connection object.
     """
     if self._creds_in_config_file:
         a_key, s_key = _parse_s3_config(self.s3_config_file,
                                         self.s3_config_format,
                                         self.profile)
     else:
         a_key = self._a_key
         s_key = self._s_key
     if self._sts_conn_required:
         sts_connection = STSConnection(aws_access_key_id=a_key,
                                        aws_secret_access_key=s_key,
                                        profile_name=self.profile)
         assumed_role_object = sts_connection.assume_role(
             role_arn=self.role_arn,
             role_session_name="Airflow_" + self.s3_conn_id
             )
         creds = assumed_role_object.credentials
         connection = S3Connection(
             aws_access_key_id=creds.access_key,
             aws_secret_access_key=creds.secret_key,
             security_token=creds.session_token
             )
     else:
         connection = S3Connection(aws_access_key_id=a_key,
                                   aws_secret_access_key=s_key)
     return connection
Пример #7
0
 def assume(self):
     """Assume a role a collect the AWS keys for that role.  This will set
     the environment variables AND will print the results.  It returns the
     credentials object from the assume_role function.
     """
     self._clear_expired()
     try:
         sts = STSConnection()
     except boto.exception.NoAuthHandlerFound:
         sys.stderr.write(
             "Please ensure that your AWS keys can "
             "assume roles.\n"
         )
         sys.exit(1)
     output = sts.assume_role(self.get_role_arn(), self.session_name)
     for source, dest in self.map_.items():
         # SVC-4728 - Add security_token support
         if source is 'security_token':
             source = 'session_token'
         value = getattr(output.credentials, source)
         self.set_env(dest, value)
     self.credentials = output.credentials
     if self.save:
         self._save()
     return self.credentials
Пример #8
0
    def __init__(self):
        ''' Main execution path '''

        # Inventory grouped by instance IDs, tags, security groups, regions, elbs and availability zones
        self.inventory = self._empty_inventory()

        # Index of hostname (address) to instance ID
        #self.index = {}

        # Read settings and parse CLI arguments
        self.read_settings()
        self.parse_cli_args()

        #Initiate the STS connection:                             
        sts_connection = STSConnection( )

        data_to_print = {}
        for i in self.aws_creds.keys():
           
              # Creating the object from the sts_connection
              assumedRoleObject = sts_connection.assume_role(
                  role_arn=self.aws_creds[i]["arn"],
                  role_session_name="AssumeRoleSession")

              # Index of hostname (address) to instance ID
              self.index = {}

              self.creds = self.aws_creds[i]
              
              # Cache Setup
              self.cache_path_cache = self.cache_dir + "/ansible-%s.cache" % i
              self.cache_path_index = self.cache_dir + "/ansible-%s.index" % i

              # Cache
              if self.args.refresh_cache:
                self.do_api_calls_update_cache(assumedRoleObject)
              elif not self.is_cache_valid():
                self.do_api_calls_update_cache(assumedRoleObject)

              # Data to print
              if self.args.host:
                data_to_print = self.get_host_info()

              elif self.args.list:
                # Display list of instances for inventory
                if self.inventory == self._empty_inventory():
                    data_to_print = self.get_inventory_from_cache()
                else:
                    data_to_print = self.json_format_dict(self.inventory, True)

        print(data_to_print)
Пример #9
0
    def get_conn(self):
        """
        Returns the boto S3Connection object.
        """
        if self._default_to_boto:
            return S3Connection(profile_name=self.profile)
        a_key = s_key = None
        if self._creds_in_config_file:
            a_key, s_key, calling_format = _parse_s3_config(self.s3_config_file,
                                                self.s3_config_format,
                                                self.profile)
        elif self._creds_in_conn:
            a_key = self._a_key
            s_key = self._s_key
            calling_format = self.calling_format
            s3_host = self.s3_host

        if calling_format is None:
            calling_format = 'boto.s3.connection.SubdomainCallingFormat'

        if s3_host is None:
            s3_host = NoHostProvided

        if self._sts_conn_required:
            sts_connection = STSConnection(aws_access_key_id=a_key,
                                           aws_secret_access_key=s_key,
                                           profile_name=self.profile)
            assumed_role_object = sts_connection.assume_role(
                role_arn=self.role_arn,
                role_session_name="Airflow_" + self.s3_conn_id
                )
            creds = assumed_role_object.credentials
            connection = S3Connection(
                aws_access_key_id=creds.access_key,
                aws_secret_access_key=creds.secret_key,
                calling_format=calling_format,
                security_token=creds.session_token
                )
        else:
            connection = S3Connection(aws_access_key_id=a_key,
                                      aws_secret_access_key=s_key,
                                      calling_format=calling_format,
                                      host=s3_host,
                                      profile_name=self.profile)
        return connection
Пример #10
0
def assumeRole(credentials, arn):
    sts_connection = STSConnection(
        aws_access_key_id=credentials['AWS_ACCESS_KEY_ID'],
        aws_secret_access_key=credentials['AWS_SECRET_ACCESS_KEY'])

    sessionName = "awsudo-%08x" % (random.randint(0, 0xffffffff),)

    response = sts_connection.assume_role(
        role_arn=arn,
        role_session_name=sessionName)

    credentials = response.credentials

    return {
        'AWS_ACCESS_KEY_ID': credentials.access_key,
        'AWS_SECRET_ACCESS_KEY': credentials.secret_key,
        'AWS_SESSION_TOKEN': credentials.session_token,
    }
Пример #11
0
 def get_connection(self):
     ret = None
     if self._cross_account_number and self._cross_account_role:
         from boto.sts import STSConnection
         import boto
         try:
             role_arn = 'arn:aws:iam::%s:role/%s' % (self._cross_account_number, self._cross_account_role)
             sts = STSConnection()
             assumed_role = sts.assume_role(role_arn=role_arn, role_session_name='AssumeRoleSession')
             ret = ec2.connect_to_region(
                 self._region,
                 aws_access_key_id=assumed_role.credentials.access_key, 
                 aws_secret_access_key=assumed_role.credentials.secret_key, 
                 security_token=assumed_role.credentials.session_token
             )
         except Exception,e:
             print e
             raise BackupMonkeyException('Cannot complete cross account access')
    def get_conn(self):
        """
        Returns the boto S3Connection object.
        """
        if self._default_to_boto:
            return S3Connection(profile_name=self.profile)
        a_key = s_key = None
        if self._creds_in_config_file:
            a_key, s_key, calling_format = _parse_s3_config(
                self.s3_config_file, self.s3_config_format, self.profile)
        elif self._creds_in_conn:
            a_key = self._a_key
            s_key = self._s_key
            calling_format = self.calling_format
            s3_host = self.s3_host

        if calling_format is None:
            calling_format = 'boto.s3.connection.SubdomainCallingFormat'

        if s3_host is None:
            s3_host = NoHostProvided

        if self._sts_conn_required:
            sts_connection = STSConnection(aws_access_key_id=a_key,
                                           aws_secret_access_key=s_key,
                                           profile_name=self.profile)
            assumed_role_object = sts_connection.assume_role(
                role_arn=self.role_arn,
                role_session_name="Airflow_" + self.s3_conn_id)
            creds = assumed_role_object.credentials
            connection = S3Connection(aws_access_key_id=creds.access_key,
                                      aws_secret_access_key=creds.secret_key,
                                      calling_format=calling_format,
                                      security_token=creds.session_token)
        else:
            connection = S3Connection(aws_access_key_id=a_key,
                                      aws_secret_access_key=s_key,
                                      calling_format=calling_format,
                                      host=s3_host,
                                      profile_name=self.profile)
        return connection
Пример #13
0
def connect_sts(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
    """
    :type aws_access_key_id: string
    :param aws_access_key_id: Your AWS Access Key ID

    :type aws_secret_access_key: string
    :param aws_secret_access_key: Your AWS Secret Access Key

    :rtype: :class:`boto.sts.STSConnection`
    :return: A connection to Amazon's STS
    """
    from boto.sts import STSConnection
    return STSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
Пример #14
0
    def _add_assumed_role(self, config):
        c = {}
        c['region_name'] = config['region_name']

        assumedRoleObject = STSConnection().assume_role(
            role_arn=config["assumed_role_arn"],
            role_session_name="assumeRole_" + uuid.uuid4().urn[-12:])

        c["aws_access_key_id"] = assumedRoleObject.credentials.access_key
        c["aws_secret_access_key"] = assumedRoleObject.credentials.secret_key
        c["security_token"] = assumedRoleObject.credentials.session_token

        return c
Пример #15
0
def sync(name=None):
    if not name:
        name = get_default_name()

    credentials = get_credentials(name)
    if not credentials.mfa_serial:
        # Nothing to do here.
        return

    # Have temporary credentials and they aren't expired yet, so no need to
    # get new ones.
    if (credentials.temporary_credentials and
        credentials.temporary_credentials.time_until_expiration() > 0):
        return 

    import boto
    from boto.sts import STSConnection

    mfa_TOTP = getpass("Enter the MFA code: ")

    sts_connection = STSConnection(
        aws_access_key_id=credentials.access_key_id,
        aws_secret_access_key=credentials.secret_access_key
    )

    temporary_credentials = sts_connection.get_session_token(
        duration=SESSION_DURATION,
        mfa_serial_number=credentials.mfa_serial,
        mfa_token=mfa_TOTP,
    )

    details = TemporaryCredentials(
        temporary_access_key=temporary_credentials.access_key,
        temporary_secret_key=temporary_credentials.secret_key,
        session_token=temporary_credentials.session_token,
        expiration=temporary_credentials.expiration
    )

    keyring.set_password('aws-keyring-temporary-credentials', name, str(details))
Пример #16
0
def assumed_role(debug, OTP, mfa_serial, sts_duration, roleArn, SessionName):

    try:
        sts_connection = STSConnection()

        # Use the appropriate device ID (serial number for hardware device or ARN for virtual device).
        # Replace ACCOUNT-NUMBER-WITHOUT-HYPHENS and MFA-DEVICE-ID with appropriate values.
        #OTP = input("Enter OTP: ")
        #debug is used if you want assume-role print credentials

        tempCredentials = sts_connection.get_session_token(
            duration=sts_duration,
            mfa_serial_number=
            mfa_serial,  #"arn:aws:iam::101549811061:mfa/SecurityAuditUser",
            mfa_token=OTP)

        STSsession = boto3.client(
            'sts',
            aws_access_key_id=tempCredentials.access_key,
            aws_secret_access_key=tempCredentials.secret_key,
            aws_session_token=tempCredentials.session_token)

        assumed_role_object = STSsession.assume_role(
            RoleArn=roleArn,  #"arn:aws:iam::072979390894:role/read",
            RoleSessionName=SessionName  #"SecurityAuditSession"
        )

        credentials = assumed_role_object['Credentials']
    except (ValueError, IOError) as e:
        raise ("Error Processing your information for Assuming a role")
        credentials = ""

    if (debug):
        print(credentials['AccessKeyId'])
        print(credentials['SecretAccessKey'])
        print(credentials['SessionToken'])

    return credentials
Пример #17
0
def get_sts(duration):
    os.environ['AWS_ACCESS_KEY_ID'] = boto.config.get(
        'long-term',
        'aws_access_key_id')
    os.environ['AWS_SECRET_ACCESS_KEY'] = boto.config.get(
        'long-term',
        'aws_secret_access_key')
    boto.config.remove_option('Credentials', 'aws_security_token')
    try:
        del os.environ['AWS_SECURITY_TOKEN']
    except:
        pass
    mfa_TOTP = raw_input("Enter AWS MFA code for user %s:" % mfa_device_name)
    try:
        sts_connection = STSConnection()
        tempCredentials = sts_connection.get_session_token(
            duration=duration,
            mfa_serial_number=mfa_serial,
            mfa_token=mfa_TOTP)
        boto.config.save_user_option(
            'Credentials',
            'aws_access_key_id',
            tempCredentials.access_key)
        boto.config.save_user_option(
            'Credentials',
            'aws_secret_access_key',
            tempCredentials.secret_key)
        boto.config.save_user_option(
            'Credentials',
            'aws_security_token',
            tempCredentials.session_token)
        boto.config.save_user_option(
            'Credentials',
            'expiration',
            tempCredentials.expiration)
    except boto.exception.BotoServerError as e:
        message = '%s - Please try again.' % (e.message)
        sys.exit(message)
Пример #18
0
def get_session_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project_name, environment_name, role_name, token_expiration, session_token_expiration):
    try:

        if not args.nomfa:
            mfa_token = raw_input("Enter the MFA code: ")
            sts_session = sts_connection.get_session_token(
                duration=session_token_expiration,
                mfa_serial_number=mfa_serial_number,
                mfa_token=mfa_token
            )

            session_sts_connection = STSConnection(aws_access_key_id=sts_session.access_key,
                                                   aws_secret_access_key=sts_session.secret_key,
                                                   security_token=sts_session.session_token)

            if args.externalid:
                assumed_role_object = session_sts_connection.assume_role(
                    role_arn=role_arn,

                    role_session_name=role_session_name,
                    duration_seconds=token_expiration,
                    external_id=externalid
                )
            else:
                assumed_role_object = session_sts_connection.assume_role(
                    role_arn=role_arn,
                    role_session_name=role_session_name,
                    duration_seconds=token_expiration,
                )
        else:
             colormsg ("When using get_session you must use MFA", "error")
             exit(1)

    except Exception, e:
        colormsg ("There was an error assuming role", "error")
        verbose(e)
        exit(1)
Пример #19
0
def get_session_token(sts_connection, role_arn, mfa_serial_number,
                      role_session_name, project_name, environment_name,
                      role_name, token_expiration, session_token_expiration):
    try:

        if not args.nomfa:
            mfa_token = raw_input("Enter the MFA code: ")
            sts_session = sts_connection.get_session_token(
                duration=session_token_expiration,
                mfa_serial_number=mfa_serial_number,
                mfa_token=mfa_token)

            session_sts_connection = STSConnection(
                aws_access_key_id=sts_session.access_key,
                aws_secret_access_key=sts_session.secret_key,
                security_token=sts_session.session_token)

            if args.externalid:
                assumed_role_object = session_sts_connection.assume_role(
                    role_arn=role_arn,
                    role_session_name=role_session_name,
                    duration_seconds=token_expiration,
                    external_id=externalid)
            else:
                assumed_role_object = session_sts_connection.assume_role(
                    role_arn=role_arn,
                    role_session_name=role_session_name,
                    duration_seconds=token_expiration,
                )
        else:
            colormsg("When using get_session you must use MFA", "error")
            exit(1)

    except Exception, e:
        colormsg("There was an error assuming role", "error")
        verbose(e)
        exit(1)
Пример #20
0
def make_aws_credentials(config, role_arn=None, role_name=None):
    if role_arn:
        try:
            sts_connection = STSConnection()
            assumedRoleObject = sts_connection.assume_role(
                role_arn=role_arn, role_session_name=role_name)
        except:
            out("Oops! something went wrong trying to assume the specified role"
                )
        else:
            # create credentials for switching roles
            aws = AwsCredentials(
                assumedRoleObject.credentials.access_key,
                assumedRoleObject.credentials.secret_key,
                assumedRoleObject.credentials.session_token,
                get(config, 'aws.region',
                    os.environ.get('AWS_DEFAULT_REGION')),
                get(config, 'aws.bucket',
                    os.environ.get('AWS_BEANSTALK_BUCKET_NAME')),
                get(config, 'aws.bucket_path',
                    os.environ.get('AWS_BEANSTALK_BUCKET_NAME_PATH')))
            out("Using Role: " + role_name)
    else:
        # create credentials
        aws = AwsCredentials(
            get(config, 'aws.access_key', os.environ.get('AWS_ACCESS_KEY_ID')),
            get(config, 'aws.secret_key',
                os.environ.get('AWS_SECRET_ACCESS_KEY')),
            get(config, 'aws.secret_token',
                os.environ.get('AWS_SECRET_TOKEN')),
            get(config, 'aws.region', os.environ.get('AWS_DEFAULT_REGION')),
            get(config, 'aws.bucket',
                os.environ.get('AWS_BEANSTALK_BUCKET_NAME')),
            get(config, 'aws.bucket_path',
                os.environ.get('AWS_BEANSTALK_BUCKET_NAME_PATH')))
    return aws
Пример #21
0
def get_sts_keys(default_keys):
    from boto.sts import STSConnection

    baseline_keys = load_keys(args.profile + ".credentials")
    conn = STSConnection(default_keys["aws_access_key_id"], default_keys["aws_secret_access_key"])
    mfaArn = "arn:aws:iam::{0}:mfa/{1}".format(args.accountId, args.userName)
    log("mfa device = %s" % mfaArn)
    try:
        creds = conn.get_session_token(args.duration, args.force_new, mfaArn, args.mfaToken)
        log("Session will expire at %s" % creds.expiration)
        return {
            "aws_access_key_id": creds.access_key,
            "aws_secret_access_key": creds.secret_key,
            "aws_session_token": creds.session_token,
        }
    except boto.exception.BotoServerError, e:
        if "MultiFactorAuthentication failed" in str(e):
            log("Invalid MFA token, resetting default keys")
            return default_keys
        elif "InvalidClientTokenId" in str(e):
            log("Invalid default credentials")
            return None
        else:
            raise e
Пример #22
0
def awsTVMUpload(archiveFile=None,bucket=None,aws_key=None,aws_secret=None,foldername=None):
    if not aws_key:
        aws_key=settings.BUCKETS[bucket]["AWS_KEY_ID"]
    if not aws_secret:
        aws_secret=settings.BUCKETS[bucket]["AWS_SECRET"]

    stsconn = STSConnection(aws_access_key_id=aws_key, aws_secret_access_key=aws_secret)

    policydict={
                "Statement": [
                {
                  "Action": [
                    "s3:*"
                  ],
                  "Resource": [
                    "arn:aws:s3:::%s/%s/*" % (bucket,foldername)
                  ],
                  "Effect": "Allow"
            },{
                  "Action": [
                    "s3:PutObject"
                  ],
                  "Resource": [
                    "arn:aws:s3:::%s*" % (bucket)
                  ],
                  "Effect": "Allow"
            }                              
        ] }

    policystring = json.dumps(policydict)
    ststoken = stsconn.get_federation_token("sys_upload", 24*3600, policystring)
    jsonoutput={}
    jsonoutput["SecretAccessKey"]=ststoken.credentials.secret_key
    jsonoutput["AccessKeyId"]=ststoken.credentials.access_key
    jsonoutput["SessionToken"]=ststoken.credentials.session_token
    return jsonoutput
Пример #23
0
 def get_aws_credentials(self, account_alias, role):
     """Get temporary credentials from AWS"""
     self.check_user_permissions(account_alias, role)
     try:
         account_id = self.account_config[account_alias]['id']
     except Exception:
         message = "No Configuration for account '{account}'."
         raise ConfigurationError(message.format(account=account_alias))
     arn = "arn:aws:iam::{account_id}:role/{role}".format(
         account_id=account_id, role=role)
     key_id = self.application_config['aws']['access_key']
     secret_key = self.application_config['aws']['secret_key']
     try:
         sts_connection = STSConnection(aws_access_key_id=key_id,
                                        aws_secret_access_key=secret_key)
         assumed_role_object = sts_connection.assume_role(
             role_arn=arn, role_session_name=self.user)
     except Exception as error:
         if getattr(error, 'status', None) == 403:
             raise PermissionError(str(error))
         self.logger.exception(
             "AWS STS failed with: {exc_vars}".format(exc_vars=vars(error)))
         raise AWSError(str(error))
     return assumed_role_object.credentials
Пример #24
0
def connect_sts(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
    """
    :type aws_access_key_id: string
    :param aws_access_key_id: Your AWS Access Key ID

    :type aws_secret_access_key: string
    :param aws_secret_access_key: Your AWS Secret Access Key

    :rtype: :class:`boto.sts.STSConnection`
    :return: A connection to Amazon's STS
    """
    access_key, secret_key = get_govcloud_creds(aws_access_key_id,
                                                aws_secret_access_key)
    from boto.sts import STSConnection
    region = RegionInfo(name='govcloud',
                        endpoint='ec2.us-gov-west-1.amazonaws.com')
    return STSConnection(access_key, secret_key,
                         region=region, **kwargs)
Пример #25
0
from pprint import pprint

appId ="{{ priam_cluster_name }}"

def put_record(domain, prop, val):
  print"Inserting into %s: %s -> %s" % (domain, prop, val)
  itemname ="%s.%s" % (appId, prop)
  sdb.put_attributes(domain, itemname, {"appId" : appId,"property" : prop,"value" : val})
  return

roleArn = '{{ priam_assume_role_arn|default('None') }}'

if roleArn == 'None':
    sdb = boto.sdb.connect_to_region("us-east-1")
else:
    sts = STSConnection()
    assumed = sts.assume_role(roleArn, 'sdb_script')
    sdb = boto.sdb.connect_to_region('us-east-1', aws_access_key_id=assumed.credentials.access_key, aws_secret_access_key=assumed.credentials.secret_key, security_token=assumed.credentials.session_token)

ii = sdb.lookup("InstanceIdentity", validate=True)
if ii is None:
  print"No InstanceIdentity, creating."
  ii = sdb.create_domain("InstanceIdentity")

pp = sdb.lookup("PriamProperties", validate=True)
if pp is None:
  print"No PriamProperties, creating."
  pp = sdb.create_domain("PriamProperties")

put_record("PriamProperties","priam.s3.bucket","{{ priam_s3_bucket }}")
put_record("PriamProperties","priam.s3.base_dir","{{ priam_s3_base_dir }}")
Пример #26
0
def get_session_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project_name, environment_name, role_name, token_expiration, session_token_expiration, args):
    global access_key
    global session_key
    global session_token

    try:

        if not args.nomfa:
            mfa_token = input("Enter the MFA code: ")
            sts_session = sts_connection.get_session_token(
                duration=session_token_expiration,
                mfa_serial_number=mfa_serial_number,
                mfa_token=mfa_token
            )

            session_sts_connection = STSConnection(aws_access_key_id=sts_session.access_key,
                                                   aws_secret_access_key=sts_session.secret_key,
                                                   security_token=sts_session.session_token)

            if args.externalid:
                assumed_role_object = session_sts_connection.assume_role(
                    role_arn=role_arn,
                    role_session_name=role_session_name,
                    duration_seconds=token_expiration,
                    external_id=externalid
                )
            else:
                assumed_role_object = session_sts_connection.assume_role(
                    role_arn=role_arn,
                    role_session_name=role_session_name,
                    duration_seconds=token_expiration,
                )
        else:
             colormsg("When using get_session you must use MFA", "error")
             exit(1)

    except Exception as e:
        colormsg("There was an error assuming role", "error")
        verbose(str(e))
        exit(1)

    colormsg ("Assumed the role successfully", "ok")

    # Format resulting temporary credentials into a JSON block using
    # known field names.
    access_key = sts_session.access_key
    session_key = sts_session.secret_key
    session_token = sts_session.session_token
    expiration = sts_session.expiration

    login_to_fedaccount(access_key, session_key, session_token, role_session_name, args=args)

    if not args.profile:
        credential_profile = 'default'
    else:
        credential_profile = args.profile

    save_credentials(access_key, session_key, session_token, role_session_name, 'corp', 'session', credential_profile, region)

    # save_credentials(access_key, session_key, session_token, role_session_name, project_name, environment_name, role_name, region)
    # and save them on the CLI config file .aws/credentials

    save_cli_credentials(access_key, session_key, session_token, '-'.join(['corp','session',credential_profile]), region)

    if args.stdout:
        print("")
        print("If you want to use your credentials from the environment with an external Tool (for instance, Terraform), you can use the following instructions:")
        print("WARNING: If you use it in the same shell as anwbis exported variables takes precedence over the .aws/credentials, so use it carefully")
        print("")
        print("export AWS_ACCESS_KEY_ID='%s'" % access_key)
        print("export AWS_SECRET_ACCESS_KEY='%s'" % session_key)
        print("export AWS_SESSION_TOKEN='%s'" % session_token)
        print("export AWS_DEFAULT_REGION='%s'" % region)
        print("Expiration='%s'" % expiration)
        print("")

    return {'access_key': access_key,
            'session_key': session_key,
            'session_token': session_token,
            'role_session_name': role_session_name}
Пример #27
0
import hashlib
import sys


import boto
from boto.sts import STSConnection
from boto.s3.connection import S3Connection

print ('Assuming role to access S3 on a different account')
ROLE_ARN = os.environ['ROLE_ARN']
ROLE_SESS_NAME = os.environ['ROLE_SESS_NAME']
FILE_ROOT = os.environ['WORKSPACE'] + '/project/deploy/'
BUCKET_PARAM = os.environ['BUCKET_NAME']
CF_DIST_ID = os.environ['CF_DIST_ID']

sts_connection = STSConnection()
assumedRoleObject = sts_connection.assume_role(
    role_arn=ROLE_ARN,
    role_session_name=ROLE_SESS_NAME
)

ACCESS_KEY = assumedRoleObject.credentials.access_key
SECRET_KEY = assumedRoleObject.credentials.secret_key
TOKEN = assumedRoleObject.credentials.session_token

# Use the temporary credentials returned by AssumeRole to call Amazon S3
connection = S3Connection(
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY,
    security_token=TOKEN,
    calling_format=boto.s3.connection.OrdinaryCallingFormat()
Пример #28
0
                mfa_serial_number = mfa_devices_r.list_mfa_devices_response.list_mfa_devices_result.mfa_devices[
                    0].serial_number
            else:
                colormsg("You don't have MFA devices associated with our user",
                         "error")
                exit(1)
        else:
            mfa_serial_number = "arn:aws:iam::" + account_id + ":mfa/" + role_session_name

        # Create an ARN out of the information provided by the user.
        role_arn = "arn:aws:iam::" + account_id_from_user + ":role/"
        role_arn += role_name_from_user

        # Connect to AWS STS and then call AssumeRole. This returns temporary security credentials.
        if args.profile:
            sts_connection = STSConnection(profile_name=args.profile)
        else:
            sts_connection = STSConnection()

        # Assume the role
        if not args.nomfa:
            verbose("Assuming role " + role_arn + " using MFA device " +
                    mfa_serial_number + "...")
            if args.project:
                colormsg(
                    "Assuming role " + role + " from project " + project +
                    " using MFA device from user " + role_session_name + "...",
                    "normal")
            elif args.iam_delegated_role:
                colormsg(
                    "Assuming role " + role + " using MFA device from user " +
Пример #29
0
def signedUrlUpload(archiveFile=None,
                    bucket=None,
                    aws_key=None,
                    aws_secret=None):
    '''
    This method returns data required for a pre-signed PUT operation for uploading
    a file to the S3 bucket directly.

    Note: This method depends on STS permissions and thus an IAM user configured and
          will be removed soon as a result. Moving forward it is best to use the
          pre-signed POSTs returned from the Filemaster API.
    :param archiveFile:
    :param bucket:
    :param aws_key:
    :param aws_secret:
    :return: dict
    '''
    if not bucket:
        bucket = settings.S3_DEFAULT_BUCKET

    foldername = str(uuid.uuid4())
    key = foldername + "/" + archiveFile.filename

    try:
        if not aws_key:
            aws_key = settings.BUCKET_CREDENTIALS.get(bucket,
                                                      {}).get("AWS_KEY_ID")
        if not aws_secret:
            aws_secret = settings.BUCKET_CREDENTIALS.get(bucket,
                                                         {}).get('AWS_SECRET')

        conn = S3Connection(aws_key,
                            aws_secret,
                            is_secure=True,
                            host=S3Connection.DefaultHost)
        url = "S3://{bucket}/{key}".format(bucket=bucket, key=key)

        # register file
        fl = FileLocation(url=url, storagetype='s3')
        fl.save()
        archiveFile.locations.add(fl)

        url = conn.generate_url(3600 * 24 * 7,
                                'PUT',
                                bucket=bucket,
                                key=foldername + "/" + archiveFile.filename,
                                force_http=False)

        stsconn = STSConnection(aws_access_key_id=aws_key,
                                aws_secret_access_key=aws_secret)

        policydict = {
            "Statement": [{
                "Action": ["s3:*"],
                "Resource": [
                    "arn:aws:s3:::{bucket}/{foldername}/*".format(
                        bucket=bucket, foldername=foldername)
                ],
                "Effect":
                "Allow"
            }, {
                "Action": ["s3:PutObject"],
                "Resource": ["arn:aws:s3:::{bucket}*".format(bucket=bucket)],
                "Effect":
                "Allow"
            }]
        }

        policystring = json.dumps(policydict)
        ststoken = stsconn.get_federation_token("sys_upload", 24 * 3600,
                                                policystring)

        jsonoutput = {
            "url": url,
            "location": "s3://{bucket}/{key}/".format(bucket=bucket, key=key),
            "locationid": fl.id,
            "bucket": bucket,
            "foldername": foldername,
            "filename": archiveFile.filename,
            "secretkey": ststoken.credentials.secret_key,
            "accesskey": ststoken.credentials.access_key,
            "sessiontoken": ststoken.credentials.session_token,
        }

        return jsonoutput

    except Exception as exc:
        log.error("Error: %s" % exc)
        return {}
def main():

    import logging
    from boto.s3.connection import S3Connection
    from boto.sts import STSConnection

    # Prompt for token code
    mfa = raw_input("Enter the mfa authcode for ec2-dev: ")

    #
    sts_connection = STSConnection()

    # Use the appropriate device ID (serial number for hardware device or ARN for virtual device).
    # Replace ACCOUNT-NUMBER-WITHOUT-HYPHENS and MFA-DEVICE-ID with appropriate values.

    tempCredentials = sts_connection.get_session_token(
        duration=3600,
        mfa_serial_number="arn:aws:iam::231871078230:mfa/ec2-dev",
        mfa_token=mfa
    )

    # Use the temporary credentials to list the contents of an S3 bucket
    s3_connection = S3Connection(
        aws_access_key_id=tempCredentials.access_key,
        aws_secret_access_key=tempCredentials.secret_key,
        security_token=tempCredentials.session_token
    )


    # Set up logging
    logging.basicConfig(filename='ec2-termination.log',
            format='%(asctime)s = %(levelname)s: %(message)s',
            level=logging.DEBUG)

    # List comprehension for regions
    ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]

    # tag values to ignore
    tag_value = ['openshift-node','openshift-master']

    for region in ec2_regions:
        #sets current working region
        print("Currently process instances in %s" % region)
        region_id = boto3.resource('ec2',region_name=region)
        # Gets a list of EC2 instances which are running
        instances = region_id.instances.filter(
                    Filters=[{'Name': 'instance-state-name', 'Values': ['running','stopped']}])

        flag = True
        for instance in instances:
            for tag in instance.tags:
                if tag['Key'] == 'Name':
                    name = tag['Value']
                if name in tag_value:
                    flag = False
            try:
                logging.info("Deleting instance %s "% instance.id)
                if flag:
                #disableAPIProtection(instance.id)
                #response = instance.terminate()
                    print("Instance %s termination"  % instance.id)
                else:
                    pass
                    #print("Instance %s termination"  % name)
            except botocore.exceptions.ClientError as e:
                logging.error(e.response['Error']['Code'])
import boto3
from boto.sts import STSConnection
from boto.s3.connection import S3Connection
from boto3 import client

# Prompt for MFA time-based one-time password (TOTP)
mfa_TOTP = raw_input("Enter the MFA code: ")

# The calls to AWS STS GetSessionToken must be signed with the access key ID and secret
# access key of an IAM user. The credentials can be in environment variables or in
# a configuration file and will be discovered automatically
# by the STSConnection() function. For more information, see the Python SDK
# documentation: http://boto.readthedocs.org/en/latest/boto_config_tut.html

sts_connection = STSConnection(
    aws_access_key_id="AKIAJEGDPRSEOJMV46ZA",
    aws_secret_access_key="RHrGRGJrpb8mWAq6zRXTwmX1TmvjfQZTOevPatg9")

# Use the appropriate device ID (serial number for hardware device or ARN for virtual device).
# Replace ACCOUNT-NUMBER-WITHOUT-HYPHENS and MFA-DEVICE-ID with appropriate values.

tempCredentials = sts_connection.get_session_token(
    duration=2800,
    mfa_serial_number="arn:aws:iam::186502235371:mfa/sthathamsetty",
    mfa_token=mfa_TOTP)

print(tempCredentials.access_key)
print(tempCredentials.secret_key)
print("\n" + tempCredentials.session_token)

sts_connection1 = STSConnection(
Пример #32
0
        secret_access_key = raw_input("Enter your AWS Secret Access Key: ")
        config.set(profile, AWS_SECRET_ACCESS_KEY, secret_access_key)
        write_config = True

    if config.has_option(profile, AWS_MFA_DEVICE) == False:
        mfa_device = raw_input("Enter your username: "******"arn:aws:iam::973692506099:mfa/" + mfa_device

    # use the passed in code if any
    mfa_TOTP = args.code
    if args.code is None:
        mfa_TOTP = raw_input("Enter your MFA code: ")

    # Get temp credentials
    tempCredentials = sts_connection.get_session_token(
        duration=28800,
        mfa_serial_number=serial_number,
        mfa_token=mfa_TOTP
Пример #33
0
import json
import boto
import boto3
import os
import commands
import boto.ec2
from boto import ec2
from boto.sts import STSConnection
import sys

arn=str(sys.argv[1])
print  arn
sts_connection = STSConnection()
assumed_role_object = sts_connection.assume_role(
role_arn=arn,
role_session_name="run-script"
)
os.environ["AWS_ACCESS_KEY_ID"] =assumed_role_object.credentials.access_key
os.environ["AWS_SECRET_ACCESS_KEY"] = assumed_role_object.credentials.secret_key
os.environ["AWS_SESSION_TOKEN"] = assumed_role_object.credentials.session_token

############ Get Account name & ID #############################################
accountname=commands.getoutput("aws iam list-account-aliases | awk {'print $2'}")
accountid=(boto3.client('sts').get_caller_identity()['Account'])
print accountname
f1=open('/tmp/email_output.html', 'a')
f1.write("<h2 style='color:#0066cc;'>"+accountname+" ["+accountid+"]</h2><hr>\n<h4>Security Group Ports Summary for EC2 Instances</h4>\n<table style=\'width:100%\', border=\'1\'>\n<thead><th>Instance Name</th><th>Instance Type</th><th>VPC</th><th>Security Group</th><th>Ports Opened</th></thead>\n<tbody>\n")

############# EC2 instance INFo with attached security group name/ID ###########
def get_name(instance):
	if instance.tags:
Пример #34
0
    def run(self,
            conn,
            tmp,
            module_name,
            module_args,
            inject,
            complex_args=None,
            **kwargs):
        try:
            args = {}
            if complex_args:
                args.update(complex_args)
            args.update(parse_kv(module_args))

            # get starting credentials
            # from environment:
            #   AWS_ACCESS_KEY_ID
            #   AWS_SECRET_ACCESS_KEY

            # use get started credentials to do the roles dance and obtain
            # temporary credentials in target account

            #target_role_name = 'init-test3-shoppertrak-NucleatorCageBuilder-1I5ZOAYRJLS8Z'

            data = {}
            data.update(inject)

            # TODO use nucleator facts instead
            source_role_name = data[
                'nucleator_builder_role_name']  # TODO - RHS var here could have names in better alignment with current conventions
            target_role_name = data[
                'cage_builder_role_name']  # TODO - RHS var here could have names in better alignment with current conventions

            print "Target Role Name: ", target_role_name
            print "Source Role Name: ", source_role_name

            source_account_id = data['source_account_number']
            target_account_id = data['target_account_number']

            print "Target Account Number: ", target_account_id
            print "Source Account Number: ", source_account_id

            try:
                envdict = {}
                if self.runner.environment:
                    env = template.template(self.runner.basedir,
                                            self.runner.environment,
                                            inject,
                                            convert_bare=True)
                    env = utils.safe_eval(env)

                aws_access_key_id = env.get("AWS_ACCESS_KEY_ID")
                aws_secret_access_key = env.get("AWS_SECRET_ACCESS_KEY")
                security_token = env.get("AWS_SECURITY_TOKEN")

                aws_access_key_id = aws_access_key_id if aws_access_key_id else None
                aws_secret_access_key = aws_secret_access_key if aws_secret_access_key else None
                security_token = security_token if security_token else None

                sts_connection = STSConnection(
                    aws_access_key_id=aws_access_key_id,
                    aws_secret_access_key=aws_secret_access_key,
                    security_token=security_token)
                source_role = sts_connection.assume_role(
                    role_arn='arn:aws:iam::{0}:role/{1}'.format(
                        source_account_id, source_role_name),
                    role_session_name='SourceRoleSession')
                vv("Successfully assumed {0} role in account {1}".format(
                    source_role_name, source_account_id))

            except Exception, e:
                result = dict(
                    failed=True,
                    msg=type(e).__name__ +
                    ": Failed to obtain temporary credentials for role " +
                    source_role_name + " in target account " +
                    source_account_id + ", message: '" + str(e))
                return ReturnData(conn=conn, comm_ok=False, result=result)

            try:
                sts_connection = STSConnection(
                    aws_access_key_id=source_role.credentials.access_key,
                    aws_secret_access_key=source_role.credentials.secret_key,
                    security_token=source_role.credentials.session_token)
                target_role = sts_connection.assume_role(
                    role_arn='arn:aws:iam::{0}:role/{1}'.format(
                        target_account_id, target_role_name),
                    role_session_name='TargetRoleSession')
                vv("Successfully assumed {0} role in account {1}".format(
                    target_role_name, target_account_id))

            except Exception, e:
                # deal with failure gracefully
                result = dict(
                    failed=True,
                    msg=type(e).__name__ +
                    ": Failed to obtain temporary credentials for role " +
                    target_role_name + " in target account " +
                    target_account_id + ", message: '" + str(e) +
                    " Security_Token: " +
                    source_role.credentials.session_token)
                return ReturnData(conn=conn, comm_ok=False, result=result)
Пример #35
0
from io import StringIO
import hashlib
import sys

import boto
from boto.sts import STSConnection
from boto.s3.connection import S3Connection

print('Assuming role to access S3 on a different account')
ROLE_ARN = os.environ['ROLE_ARN']
ROLE_SESS_NAME = os.environ['ROLE_SESS_NAME']
FILE_ROOT = os.environ['WORKSPACE'] + '/project/deploy/'
BUCKET_PARAM = os.environ['BUCKET_NAME']
CF_DIST_ID = os.environ['CF_DIST_ID']

sts_connection = STSConnection()
assumedRoleObject = sts_connection.assume_role(
    role_arn=ROLE_ARN, role_session_name=ROLE_SESS_NAME)

ACCESS_KEY = assumedRoleObject.credentials.access_key
SECRET_KEY = assumedRoleObject.credentials.secret_key
TOKEN = assumedRoleObject.credentials.session_token

# Use the temporary credentials returned by AssumeRole to call Amazon S3
connection = S3Connection(
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY,
    security_token=TOKEN,
    calling_format=boto.s3.connection.OrdinaryCallingFormat())

print('File Root: ', FILE_ROOT)
Пример #36
0
#           "aws:MultiFactorAuthAge": false #mfa condition is optional
#         }
#       }
#     }
#   ]
# }
# And appropriate IAM policy
roleArn = "arn:aws:iam::<YOUR_ACCOUNT_ID>:role/<NAME_OF_EXISTING_ROLE>"

###########################################
### Create preSigned URL
###########################################

# Taken from : http://docs.aws.amazon.com/STS/latest/UsingSTS/STSMgmtConsole-manualURL.html#STSConsoleLink_programPython

sts_connection = STSConnection()

assumed_role_object = sts_connection.assume_role(
    role_arn=roleArn,
    role_session_name="ConsoleSSOSession",
    duration_seconds=1800
)

# Step 3: Format resulting temporary credentials into JSON
json_string_with_temp_credentials = '{'
json_string_with_temp_credentials += '"sessionId":"' + assumed_role_object.credentials.access_key + '",'
json_string_with_temp_credentials += '"sessionKey":"' + assumed_role_object.credentials.secret_key + '",'
json_string_with_temp_credentials += '"sessionToken":"' + assumed_role_object.credentials.session_token + '"'
json_string_with_temp_credentials += '}'

# Step 4. Make request to AWS federation endpoint to get sign-in token. Pass
Пример #37
0
def get_aws_connection_info(module):
    ec2_url = module.params.get('ec2_url')
    access_key = module.params.get('aws_access_key')
    secret_key = module.params.get('aws_secret_key')
    security_token = module.params.get('security_token')
    region = module.params.get('region')
    aws_profile = module.params.get('aws_profile')
    validate_certs = module.params.get('validate_certs')

    profile_dict = {}

    if not ec2_url:
        if 'EC2_URL' in os.environ:
            ec2_url = os.environ['EC2_URL']
        elif 'AWS_URL' in os.environ:
            ec2_url = os.environ['AWS_URL']

    if not region:
        if 'EC2_REGION' in os.environ:
            region = os.environ['EC2_REGION']
        elif 'AWS_REGION' in os.environ:
            region = os.environ['AWS_REGION']
        else:
            # boto.config.get returns None if config not found
            region = boto.config.get('Boto', 'aws_region')
            if not region:
                region = boto.config.get('Boto', 'ec2_region')

    if aws_profile:
        # sanity checks
        if aws_profile != "default":
            if "HOME" not in os.environ:
                module.fail_json(
                    msg=
                    "No $HOME environment variable could be detected. Do you even UNIX bro?"
                )

            aws_config_file = os.path.join(os.environ["HOME"], ".aws/config")
            if not os.path.exists(aws_config_file):
                module.fail_json(msg="Does $HOME/aws/.config even exist?")

            config = ConfigParser.ConfigParser()
            config.read(aws_config_file)

            sections = config.sections()

            if 'profile ' + aws_profile not in sections:
                module.fail_json(msg="AWS profile: %s was not found" %
                                 aws_profile)

            profile_dict = config_section_map(config, 'profile ' + aws_profile)
    else:
        aws_profile = None

    if profile_dict and 'role_arn' in profile_dict:
        role_arn = profile_dict['role_arn']
        source_profile = profile_dict['source_profile']
        role_session_name = 'CustomAnsibleSession'

        # get creds by following source_profile
        aws_credentials_file = os.path.join(os.environ["HOME"],
                                            ".aws/credentials")
        if not os.path.exists(aws_credentials_file):
            module.fail_json(msg="Does $HOME/aws/.credentials even exist?")

        config.read(aws_credentials_file)

        source_profile_dict = config_section_map(config, source_profile)

        aws_access_key = source_profile_dict['aws_access_key_id']
        aws_secret_key = source_profile_dict['aws_secret_access_key']

        sts_connection = STSConnection(aws_access_key_id=aws_access_key,
                                       aws_secret_access_key=aws_secret_key)

        assumedRoleObject = sts_connection.assume_role(
            role_arn=role_arn, role_session_name=role_session_name)
        access_key = assumedRoleObject.credentials.access_key
        secret_key = assumedRoleObject.credentials.secret_key
        security_token = assumedRoleObject.credentials.session_token

    else:
        if not access_key:
            if 'EC2_ACCESS_KEY' in os.environ:
                access_key = os.environ['EC2_ACCESS_KEY']
            elif 'AWS_ACCESS_KEY_ID' in os.environ:
                access_key = os.environ['AWS_ACCESS_KEY_ID']
            elif 'AWS_ACCESS_KEY' in os.environ:
                access_key = os.environ['AWS_ACCESS_KEY']
            else:
                # in case access_key came in as empty string
                access_key = None

        if not secret_key:
            if 'EC2_SECRET_KEY' in os.environ:
                secret_key = os.environ['EC2_SECRET_KEY']
            elif 'AWS_SECRET_ACCESS_KEY' in os.environ:
                secret_key = os.environ['AWS_SECRET_ACCESS_KEY']
            elif 'AWS_SECRET_KEY' in os.environ:
                secret_key = os.environ['AWS_SECRET_KEY']
            else:
                # in case secret_key came in as empty string
                secret_key = None

            if not security_token:
                if 'AWS_SECURITY_TOKEN' in os.environ:
                    security_token = os.environ['AWS_SECURITY_TOKEN']
            else:
                # in case security_token came in as empty string
                security_token = None

    boto_params = dict(aws_access_key_id=access_key,
                       aws_secret_access_key=secret_key,
                       profile_name=aws_profile,
                       security_token=security_token)

    return region, ec2_url, boto_params
Пример #38
0
import urllib, json
import requests  # 'pip install requests'
from boto.sts import STSConnection  # AWS SDK for Python (Boto) 'pip install boto'

# Step 1: Authenticate user in your own identity system.

# Step 2: Using the access keys for an IAM user in your AWS account,
# call "AssumeRole" to get temporary access keys for the federated user

# Note: Calls to AWS STS AssumeRole must be signed using the access key ID
# and secret access key of an IAM user or using existing temporary credentials.
# The credentials can be in EC2 instance metadata, in environment variables,
# or in a configuration file, and will be discovered automatically by the
# STSConnection() function. For more information, see the Python SDK docs:
# http://boto.readthedocs.org/en/latest/boto_config_tut.html
sts_connection = STSConnection()

assumed_role_object = sts_connection.assume_role(
    role_arn="arn:aws:iam::348107122702:role/Test",
    role_session_name="AssumeRoleSession")

# Step 3: Format resulting temporary credentials into JSON
json_string_with_temp_credentials = '{'
json_string_with_temp_credentials += '"sessionId":"' + assumed_role_object.credentials.access_key + '",'
json_string_with_temp_credentials += '"sessionKey":"' + assumed_role_object.credentials.secret_key + '",'
json_string_with_temp_credentials += '"sessionToken":"' + assumed_role_object.credentials.session_token + '"'
json_string_with_temp_credentials += '}'

# Step 4. Make request to AWS federation endpoint to get sign-in token. Pass
# the action and JSON document with temporary credentials as parameters.
request_parameters = "?Action=getSigninToken"
Пример #39
0
# Import the SDK
import boto
import uuid
import boto.ec2
from boto.ec2.connection import EC2Connection
from boto.sts import STSConnection
from sys import argv

script_name, account_id_from_user, role_name_from_user, my_region = argv

theregion = boto.ec2.get_region(my_region)

role_arn = "arn:aws:iam::" + account_id_from_user + ":role/"
role_arn += role_name_from_user

sts_connection = STSConnection()
assumed_role_object = sts_connection.assume_role(
        role_arn=role_arn,
        role_session_name="AssumeRoleSession"
        )
access = assumed_role_object.credentials.access_key
secret = assumed_role_object.credentials.secret_key
token = assumed_role_object.credentials.session_token

myimages = EC2Connection(region=theregion)
listims = myimages.get_all_images(owners='self')
ec2conn = EC2Connection(aws_access_key_id=access,aws_secret_access_key=secret,security_token=token,region=theregion)

for x in listims:
        theimage = str([x])
        theimage = theimage.replace('Image:','')
Пример #40
0
 def decode_message(self, message):
     '''Decodes an any encrypted AWS Error message'''
     from boto.sts import STSConnection
     sts_connection = STSConnection()
     print("---------- Decoded message ----------")
     print((sts_connection.decode_authorization_message(message).decoded_message))
Пример #41
0
def connect_to_sts_region(aws_access_key, aws_secret_key):
    try:
        return STSConnection(aws_access_key, aws_secret_key)
    except:
        raise
Пример #42
0
def get_sts(duration,
            mfa_serial,
            mfa_device_name,
            long_term,
            short_term,
            assume_role_arn=None):
    if boto.config.get(long_term, 'aws_access_key_id') is None:
        logger.error('aws_access_key_id is missing from section %s'
                     'or config file is missing.' % (long_term, ))
        sys.exit(1)
    else:
        long_term_id = boto.config.get(long_term, 'aws_access_key_id')

    if boto.config.get(long_term, 'aws_secret_access_key') is None:
        logger.error('aws_secret_access_key is missing from section '
                     'or config file is missing.' % (long_term, ))
        sys.exit(1)
    else:
        long_term_secret = boto.config.get(long_term, 'aws_secret_access_key')

    if boto.config.has_section(short_term):
        boto.config.remove_option(short_term, 'aws_security_token')

    mfa_TOTP = raw_input('Enter AWS MFA code for user %s '
                         '(renewing for %s seconds):' %
                         (mfa_device_name, duration))
    try:
        sts_connection = STSConnection(aws_access_key_id=long_term_id,
                                       aws_secret_access_key=long_term_secret)
        if assume_role_arn is None:
            tempCredentials = sts_connection.get_session_token(
                duration=duration,
                mfa_serial_number=mfa_serial,
                mfa_token=mfa_TOTP)
            assumed_role = 'False'
        else:
            role_session_name = assume_role_arn.split('/')[-1]
            assumedRole = sts_connection.assume_role(
                assume_role_arn,
                role_session_name,
                duration_seconds=duration,
                mfa_serial_number=mfa_serial,
                mfa_token=mfa_TOTP)
            tempCredentials = assumedRole.credentials
            assumed_role = 'True'

        default_options = [
            ('aws_access_key_id', tempCredentials.access_key),
            ('aws_secret_access_key', tempCredentials.secret_key),
            ('aws_security_token', tempCredentials.session_token),
            ('expiration', tempCredentials.expiration),
            ('assumed_role', assumed_role)
        ]

        for option, value in default_options:
            boto.config.save_user_option(short_term, option, value)

    except boto.exception.BotoServerError as e:
        message = '%s - Please try again.' % (e.message)
        logger.error(message)
        sys.exit(1)
Пример #43
0
    def token(self):
        global region
        global role
        global externalid
        global browser
        global access_key
        global session_key
        global session_token
        global filter_name

        # Welcome
        if self.args.verbose:
            print("")
            print("             __          ___     _  _____ ")
            print("     /\      \ \        / / |   (_)/ ____|")
            print("    /  \   _ _\ \  /\  / /| |__  _| (___  ")
            print("   / /\ \ | '_ \ \/  \/ / | '_ \| |\___ \ ")
            print("  / ____ \| | | \  /\  /  | |_) | |____) |")
            print(" /_/    \_\_| |_|\/  \/   |_.__/|_|_____/ ")
            print("")
            print("       Amazon Account Access "+ version)
            print("")

        else:
            print("")
            print("AnWbiS Amazon Account Access "+ version)
            print("")

        # Set values from parser

        if not self.args.project or not self.args.env:
            if not self.args.iam_master_group or not self.args.iam_policy or not self.args.iam_delegated_role and not self.args.from_ec2_role:
                colormsg("You must provide either -p and -e flags or --iam_master_group, --iam_policy and --iam_delegated_role to use Anwbis", "error")
                exit(1)
            elif self.args.from_ec2_role and not self.args.iam_delegated_role:
                colormsg("When using credentials stored in EC2 roles you must use either -p and -e flags or --iam_delegated_role to use Anwbis", "error")
                exit(1)
        if self.args.role:
            if self.args.role == 'contractor' and not self.args.contractor:
                colormsg ("When using role contractor you must provide --contractor (-c) flag with the contractor policy to asume", "error")
                exit(1)
            elif self.args.role == 'contractor' and self.args.contractor and not self.args.externalid:
                colormsg ("When using role contractor you must provide --externalid (-ext) code with the ExternalID to use", "error")
                exit(1)
            elif self.args.role == 'contractor' and self.args.contractor and self.args.externalid:
                role = self.args.role+'-'+self.args.contractor
                verbose("Asuming contractor role: "+ self.args.role+'-'+self.args.contractor)
            else:
                role = self.args.role
        elif self.args.iam_delegated_role:
            role = self.args.iam_delegated_role
        else:
            role = 'developer'

        if self.args.profile:
            profile_name = self.args.profile

        if self.args.region:
            region = self.args.region
        else:
            region = 'eu-west-1'

        if self.args.project:
            project = self.args.project
            #project = project.lower()
            verbose("Proyect: "+project)

        if self.args.env:
            env = self.args.env
            #env = env.lower()
            verbose("Environment: "+env)

        if self.args.browser:
            browser = self.args.browser
        else:
            browser = 'none'

        # Max token duration = 1h, session token = 8h

        if self.args.duration > 3600:
            token_expiration = 3600
            if self.args.get_session:
                if self.args.duration > 28800:
                    session_token_expiration = 28800
        elif self.args.duration < 900:
            token_expiration = 900
            if self.args.get_session:
                session_token_expiration = token_expiration
        else:
            token_expiration = self.args.duration
            if self.args.get_session and not self.args.duration:
                session_token_expiration = token_expiration
            else:
                session_token_expiration = 28800

        if self.args.externalid:
            externalid = self.args.externalid

        # Get Corp Account ID and set session name

        if self.args.profile:
            iam_connection = IAMConnection(profile_name=self.args.profile)
        else:
            iam_connection = IAMConnection()

        # role_session_name=iam_connection.get_user()['get_user_response']['get_user_result']['user']['user_name']
        try:
            if self.args.from_ec2_role:
                request_url = "http://169.254.169.254/latest/meta-data/iam/info/"
                r = requests.get(request_url)
                profilearn = json.loads(r.text)["InstanceProfileArn"]
                profileid = json.loads(r.text)["InstanceProfileId"]
                profilename = json.loads(r.text)["InstanceProfileArn"].split('/')[1]
                role_session_name = profilename
            else:
                role_session_name=iam_connection.get_user().get_user_response.get_user_result.user.user_name
        except Exception as e:
            colormsg("There was an error retrieving your session_name. Check your credentials", "error")
            verbose(str(e))
            exit(1)

        # account_id=iam_connection.get_user()['get_user_response']['get_user_result']['user']['arn'].split(':')[4]
        try:
            if self.args.from_ec2_role:
                account_id = profilearn = json.loads(r.text)["InstanceProfileArn"].split(':')[4]
                account_id_from_user = account_id
                role_name_from_user = profilename
            else:
                account_id=iam_connection.get_user().get_user_response.get_user_result.user.arn.split(':')[4]
        except Exception as e:
            colormsg ("There was an error retrieving your account id. Check your credentials", "error")
            verbose(str(e))
            exit(1)

        # Regexp for groups and policies. Set the policy name used by your organization
        group_name = None
        if self.args.project and self.args.env:
            if not self.args.from_ec2_role:
                group_name = 'corp-'+project+'-master-'+role
                policy_name = 'Delegated_Roles'
                role_filter = env+'-'+project+'-delegated-'+role
            else:
                group_name = 'IAM EC2 ROLE'
                policy_name = 'Delegated_Roles'
                role_filter = env+'-'+project+'-delegated-'+role

        # Get rid of the standard for using another policies or group names
        elif self.args.from_ec2_role and self.args.iam_delegated_role:
            role_filter = self.args.iam_delegated_role
            # Fix references to project, env and role in .anwbis file for non-standard use
            role = role_filter
            project = group_name
            env = "ec2-role"
        elif self.args.iam_master_group and self.args.iam_policy and self.args.iam_delegated_role:
            group_name = self.args.iam_master_group
            policy_name = self.args.iam_policy
            role_filter = self.args.iam_delegated_role
            # Fix references to project, env and role in .anwbis file for non-standard use
            role = role_filter
            project = group_name
            env = policy_name

        # Step 1: Prompt user for target account ID and name of role to assume

        # IAM groups
        verbose("Getting IAM group info:")
        delegated_policy = []
        group_policy = []
        delegated_arn = []

        try:
            if not self.args.from_ec2_role:
                policy = iam_connection.get_group_policy(group_name, policy_name)
            else:
                # policy = iam_connection.get_instance_profile(profilename)
                policy = iam_connection.get_role_policy(profilename, policy_name)
        except Exception as e:
            colormsg("There was an error retrieving your group policy. Check your credentials, group_name and policy_name",
                     "error")
            verbose(e)
            exit(1)

        if not self.args.from_ec2_role:
            policy = policy.get_group_policy_response.get_group_policy_result.policy_document
            policy = urllib.parse.unquote(policy)
            group_policy.append(config_line_policy("iam:grouppolicy", group_name, policy_name, policy))

        else:
            policy = policy.get_role_policy_response.get_role_policy_result.policy_document
            policy = urllib.parse.unquote(policy)
            group_policy.append(config_line_policy("iam:grouppolicy", group_name, policy_name, policy))

        output_lines(group_policy)

        # Format policy and search by role_filter

        policy = re.split('"', policy)

        for i in policy:
            result_filter = re.search(role_filter, i)
            if result_filter:
                delegated_arn.append(i)

        if len(delegated_arn) == 0:
            if self.args.role and self.args.project:
                colormsg("Sorry, you are not authorized to use the role " + role + " for project "+ project, "error")
                exit(1)
            else:
                colormsg("Sorry, you are not authorized to use the role "+ role_filter, "error")
                exit(1)

        elif len(delegated_arn) == 1:
            account_id_from_user = delegated_arn[0].split(':')[4]
            role_name_from_user = delegated_arn[0].split('/')[1]

        else:
            colormsg("There are two or more policies matching your input", "error")
            exit(1)

        colormsg("You are authenticated as " + role_session_name, "ok")

        # MFA
        if not self.args.nomfa:
            mfa_devices_r = iam_connection.get_all_mfa_devices(role_session_name)
            if mfa_devices_r.list_mfa_devices_response.list_mfa_devices_result.mfa_devices:
                mfa_serial_number =  mfa_devices_r.list_mfa_devices_response.list_mfa_devices_result.mfa_devices[0].serial_number
            else:
                colormsg("You don't have MFA devices associated with our user", "error")
                exit(1)
        else:
            mfa_serial_number = "arn:aws:iam::"+ account_id +":mfa/"+role_session_name

        # Create an ARN out of the information provided by the user.
        role_arn = "arn:aws:iam::" + account_id_from_user + ":role/"
        role_arn += role_name_from_user

        # Connect to AWS STS and then call AssumeRole. This returns temporary security credentials.
        if self.args.profile:
            sts_connection = STSConnection(profile_name=self.args.profile)
        else:
            sts_connection = STSConnection()

        # Assume the role
        if not self.args.nomfa:
            verbose("Assuming role " + role_arn + " using MFA device " + mfa_serial_number + "...")
            if self.args.project:
                colormsg("Assuming role " + role + " from project " + project + " using MFA device from user " + role_session_name + "...", "normal")
            elif self.args.iam_delegated_role:
                colormsg("Assuming role " + role + " using MFA device from user " + role_session_name+ "...", "normal")
        else:
            verbose("Assuming role " + role_arn + "...")
            if self.args.project:
                colormsg("Assuming role " + role + " from project "+ project+ " from user " + role_session_name + "...", "normal")
            elif self.args.iam_delegated_role:
                colormsg("Assuming role " + role + " from user "+ role_session_name + "...", "normal")
        if self.args.get_session:
                sts_token = get_session_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project, env, role, token_expiration, session_token_expiration, self.args)
        else:
            if os.path.isfile(os.path.expanduser('~/.anwbis')):

                with open(os.path.expanduser('~/.anwbis')) as json_file:
                    root_json_data = json.load(json_file)
                    json_file.close()

                    if project in root_json_data and env in root_json_data[project] and role in root_json_data[project][env]:
                        json_data = root_json_data[project][env][role]
                        anwbis_last_timestamp = json_data["anwbis_last_timestamp"]

                        # check if the token has expired
                        # TODO: Check if token is written in credentials
                        if int(time.time()) - int(anwbis_last_timestamp) > token_expiration or self.args.refresh:

                            verbose("token has expired")
                            sts_token = get_sts_token(sts_connection,
                                                      role_arn,
                                                      mfa_serial_number,
                                                      role_session_name,
                                                      project,
                                                      env,
                                                      role,
                                                      token_expiration,
                                                      self.args)

                        else:
                            verbose("token has not expired, trying to login...")
                        login_to_fedaccount(json_data["access_key"],
                                            json_data["session_key"],
                                            json_data["session_token"],
                                            json_data["role_session_name"],
                                            args=self.args)
                        sts_token = {'access_key': json_data["access_key"],
                                     'session_key':json_data["session_key"],
                                     'session_token': json_data["session_token"],
                                     'role_session_name': json_data["role_session_name"]}

                    else:
                        sts_token = get_sts_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project, env, role, token_expiration, self.args)
            else:
                # print ".anwbis configuration file doesn't exists"
                verbose("role is " + role)
                sts_token = get_sts_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project, env, role, token_expiration, self.args)
        return sts_token
Пример #44
0
def get_aws_connection_info(module):
    ec2_url = module.params.get('ec2_url')
    access_key = module.params.get('aws_access_key')
    secret_key = module.params.get('aws_secret_key')
    security_token = module.params.get('security_token')
    region = module.params.get('region')
    aws_profile = module.params.get('aws_profile')
    validate_certs = module.params.get('validate_certs')

    profile_dict = {}

    if not ec2_url:
        if 'EC2_URL' in os.environ:
            ec2_url = os.environ['EC2_URL']
        elif 'AWS_URL' in os.environ:
            ec2_url = os.environ['AWS_URL']

    if not region:
        if 'EC2_REGION' in os.environ:
            region = os.environ['EC2_REGION']
        elif 'AWS_REGION' in os.environ:
            region = os.environ['AWS_REGION']
        else:
            # boto.config.get returns None if config not found
            region = boto.config.get('Boto', 'aws_region')
            if not region:
                region = boto.config.get('Boto', 'ec2_region')

    if aws_profile:
        # sanity checks
        if aws_profile != "default":
            if "HOME" not in os.environ:
                module.fail_json(msg="No $HOME environment variable could be detected. Do you even UNIX bro?")

            aws_config_file = os.path.join(os.environ["HOME"], ".aws/config")
            if not os.path.exists(aws_config_file):
                module.fail_json(msg="Does $HOME/aws/.config even exist?")

            config = ConfigParser.ConfigParser()
            config.read(aws_config_file)

            sections = config.sections()

            if 'profile ' + aws_profile not in sections:
                module.fail_json(msg="AWS profile: %s was not found" % aws_profile)

            profile_dict = config_section_map(config, 'profile ' + aws_profile)
    else:
        aws_profile = None

    if profile_dict and 'role_arn' in profile_dict:
        role_arn = profile_dict['role_arn']
        source_profile = profile_dict['source_profile']
        role_session_name = 'CustomAnsibleSession'

        # get creds by following source_profile
        aws_credentials_file = os.path.join(os.environ["HOME"], ".aws/credentials")
        if not os.path.exists(aws_credentials_file):
            module.fail_json(msg="Does $HOME/aws/.credentials even exist?")

        config.read(aws_credentials_file)

        source_profile_dict = config_section_map(config, source_profile)

        aws_access_key = source_profile_dict['aws_access_key_id']
        aws_secret_key = source_profile_dict['aws_secret_access_key']

        sts_connection = STSConnection(aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key)

        assumedRoleObject = sts_connection.assume_role(
            role_arn=role_arn,
            role_session_name=role_session_name
        )
        access_key = assumedRoleObject.credentials.access_key
        secret_key = assumedRoleObject.credentials.secret_key
        security_token = assumedRoleObject.credentials.session_token

    else:
        if not access_key:
            if 'EC2_ACCESS_KEY' in os.environ:
                access_key = os.environ['EC2_ACCESS_KEY']
            elif 'AWS_ACCESS_KEY_ID' in os.environ:
                access_key = os.environ['AWS_ACCESS_KEY_ID']
            elif 'AWS_ACCESS_KEY' in os.environ:
                access_key = os.environ['AWS_ACCESS_KEY']
            else:
                # in case access_key came in as empty string
                access_key = None

        if not secret_key:
            if 'EC2_SECRET_KEY' in os.environ:
                secret_key = os.environ['EC2_SECRET_KEY']
            elif 'AWS_SECRET_ACCESS_KEY' in os.environ:
                secret_key = os.environ['AWS_SECRET_ACCESS_KEY']
            elif 'AWS_SECRET_KEY' in os.environ:
                secret_key = os.environ['AWS_SECRET_KEY']
            else:
                # in case secret_key came in as empty string
                secret_key = None

            if not security_token:
                if 'AWS_SECURITY_TOKEN' in os.environ:
                    security_token = os.environ['AWS_SECURITY_TOKEN']
            else:
                # in case security_token came in as empty string
                security_token = None

    boto_params = dict(aws_access_key_id=access_key,
                       aws_secret_access_key=secret_key,
                       profile_name=aws_profile,
                       security_token=security_token)

    return region, ec2_url, boto_params
Пример #45
0
    def run(self,
            conn,
            tmp,
            module_name,
            module_args,
            inject,
            complex_args=None,
            **kwargs):

        try:

            args = {}
            if complex_args:
                args.update(complex_args)
            args.update(parse_kv(module_args))

            access_policies = {}

            role_name = args["role_name"]
            print "Role Name: ", role_name

            assume_role_trust_policy = json.dumps(args["trust_policy"])

            access_policies = args["access_policies"]

            envdict = {}
            if self.runner.environment:
                env = template.template(self.runner.basedir,
                                        self.runner.environment,
                                        inject,
                                        convert_bare=True)
                env = utils.safe_eval(env)

                sts_connection = STSConnection(
                    aws_access_key_id=env.get("AWS_ACCESS_KEY_ID"),
                    aws_secret_access_key=env.get("AWS_SECRET_ACCESS_KEY"),
                    security_token=env.get("AWS_SECURITY_TOKEN"))

            c = boto.connect_iam(
                aws_access_key_id=env.get("AWS_ACCESS_KEY_ID"),
                aws_secret_access_key=env.get("AWS_SECRET_ACCESS_KEY"),
                security_token=env.get("AWS_SECURITY_TOKEN"))

            #Look for the role
            try:
                role = c.get_role(role_name)

                #Make sure the trust policy exists
                try:
                    temp_trust_policy = urllib.unquote(
                        role["get_role_response"]["get_role_result"]["role"]
                        ["assume_role_policy_document"])

                    #Reorganize the json dict so it is in the same order of the yaml policy
                    temp_trust_policy = json.dumps(
                        json.loads(temp_trust_policy))

                    #Trust policy does not match, update it
                    if not assume_role_trust_policy == temp_trust_policy:
                        if not assume_role_trust_policy == "\"\"":
                            c.update_assume_role_policy(
                                role_name, assume_role_trust_policy)

                    #Make sure each new policy exists
                    for policies in access_policies:
                        try:

                            temp_policy = urllib.unquote(
                                c.get_role_policy(role_name,
                                                  policies["policy_name"])
                                ["get_role_policy_response"]
                                ["get_role_policy_result"]["policy_document"])

                            #Policy has same name but does not match, update it
                            if not temp_policy == json.dumps(
                                    policies["policy_document"]):
                                if not policies["policy_document"] == "\"\"":
                                    c.delete_role_policy(
                                        role_name, policies["policy_name"])
                                    c.put_role_policy(
                                        role_name, policies["policy_name"],
                                        json.dumps(
                                            policies["policy_document"]))

                        #Can't find policy, add it
                        except Exception, e:
                            try:
                                c.put_role_policy(
                                    role_name, policies["policy_name"],
                                    json.dumps(policies["policy_document"]))
                            except Exception, e:
                                # deal with failure gracefully
                                result = dict(failed=True,
                                              msg=type(e).__name__ + ": " +
                                              str(e))
                                return ReturnData(conn=conn,
                                                  comm_ok=False,
                                                  result=result)

                    #Returns true if the policy name exists
                    def checkIfPolicyExists(access_policies, temp_name):
                        for policy_name in access_policies:
                            if policy_name["policy_name"] == temp_name:
                                return True
                        return False

                    #Delete any policies that are not in the yaml
                    temp_policy_names = c.list_role_policies(role_name)
                    for temp_name in temp_policy_names[
                            "list_role_policies_response"][
                                "list_role_policies_result"]["policy_names"]:
                        exists = checkIfPolicyExists(access_policies,
                                                     temp_name)
                        if not exists:
                            c.delete_role_policy(role_name, temp_name)

                #Can't find trust policy, add it
                except Exception, e:
                    try:
                        c.update_assume_role_policy(role_name,
                                                    assume_role_trust_policy)
                    except Exception, e:
                        # deal with failure gracefully
                        result = dict(failed=True,
                                      msg=type(e).__name__ + ": " + str(e))
                        return ReturnData(conn=conn,
                                          comm_ok=False,
                                          result=result)
Пример #46
0
# snippet-start:[iam.python.get_session_token_with_mfa.complete]

import boto
from boto.s3.connection import S3Connection
from boto.sts import STSConnection

# Prompt for MFA time-based one-time password (TOTP)
mfa_TOTP = raw_input("Enter the MFA code: ")

# The calls to AWS STS GetSessionToken must be signed with the access key ID and secret
# access key of an IAM user. The credentials can be in environment variables or in 
# a configuration file and will be discovered automatically
# by the STSConnection() function. For more information, see the Python SDK 
# documentation: http://boto.readthedocs.org/en/latest/boto_config_tut.html

sts_connection = STSConnection()

# Use the appropriate device ID (serial number for hardware device or ARN for virtual device). 
# Replace ACCOUNT-NUMBER-WITHOUT-HYPHENS and MFA-DEVICE-ID with appropriate values.

tempCredentials = sts_connection.get_session_token(
    duration=3600,
    mfa_serial_number="&region-arn;iam::ACCOUNT-NUMBER-WITHOUT-HYPHENS:mfa/MFA-DEVICE-ID",
    mfa_token=mfa_TOTP
)

# Use the temporary credentials to list the contents of an S3 bucket
s3_connection = S3Connection(
    aws_access_key_id=tempCredentials.access_key,
    aws_secret_access_key=tempCredentials.secret_key,
    security_token=tempCredentials.session_token
Пример #47
0
import urllib, json
import requests  # 'pip install requests'
from boto.sts import STSConnection  # AWS SDK for Python (Boto) 'pip install boto'

# Step 1: Authenticate user in your own identity system.

# Step 2: Using the access keys for an IAM user in your AWS account,
# call "AssumeRole" to get temporary access keys for the federated user

# Note: Calls to AWS STS AssumeRole must be signed using the access key ID
# and secret access key of an IAM user or using existing temporary credentials.
# The credentials can be in EC2 instance metadata, in environment variables,
# or in a configuration file, and will be discovered automatically by the
# STSConnection() function. For more information, see the Python SDK docs:
# http://boto.readthedocs.org/en/latest/boto_config_tut.html
sts_connection = STSConnection()

assumed_role_object = sts_connection.assume_role(
    role_arn="arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:role/ROLE-NAME",
    role_session_name="AssumeRoleSession")

# Step 3: Format resulting temporary credentials into JSON
json_string_with_temp_credentials = '{'
json_string_with_temp_credentials += '"sessionId":"' + assumed_role_object.credentials.access_key + '",'
json_string_with_temp_credentials += '"sessionKey":"' + assumed_role_object.credentials.secret_key + '",'
json_string_with_temp_credentials += '"sessionToken":"' + assumed_role_object.credentials.session_token + '"'
json_string_with_temp_credentials += '}'

# Step 4. Make request to AWS federation endpoint to get sign-in token. Construct the parameter string with
# the sign-in action request, a 12-hour session duration, and the JSON document with temporary credentials
# as parameters.
Пример #48
0
    def token(self):
        global region
        global role
        global access_key
        global session_key
        global session_token

        # Welcome
        if args.verbose:
            print()
            print("Awsauth Amazon Account Access " + version)
            print()

        else:
            print()
            print("Awsauth Amazon Account Access " + version)
            print()

        # Set values from parser
        if args.role:
            role = args.role
        else:
            role = 'developer'

        if args.region:
            region = args.region
        else:
            region = 'eu-west-1'

        if args.project:
            project = args.project
            project = project.lower()
            verbose("Project: " + project)

        if args.env:
            env = args.env
            env = env.lower()
            verbose("Environment: " + env)

        token_expiration = 3600

        iam_connection = IAMConnection()

        # role_session_name=iam_connection.get_user()['get_user_response']['get_user_result']['user']['user_name']
        try:
            role_session_name = iam_connection.get_user().get_user_response.get_user_result.user.user_name
        except Exception as e:
            colormsg("There was an error retrieving your session_name. Check your credentials", "error")
            verbose(e)
            exit(1)

        # account_id=iam_connection.get_user()['get_user_response']['get_user_result']['user']['arn'].split(':')[4]
        try:
            account_id = iam_connection.get_user().get_user_response.get_user_result.user.arn.split(':')[4]
        except Exception as e:
            colormsg("There was an error retrieving your account id. Check your credentials", "error")
            verbose(e)
            exit(1)

        # Regexp for groups and policies. Set the policy name used by your organization

        if args.project and args.env:
            group_name = 'corp-' + project + '-master-' + role
            policy_name = 'Delegated_Roles'
            role_filter = env + '-' + project + '-delegated-' + role

        # Step 1: Prompt user for target account ID and name of role to assume

        # IAM groups
        verbose("Getting IAM group info:")
        delegated_policy = []
        group_policy = []
        delegated_arn = []

        try:
            policy = iam_connection.get_group_policy(group_name, policy_name)
        except Exception as e:
            colormsg(
                "There was an error retrieving your group policy. Check your credentials, group_name and policy_name",
                "error")
            verbose(e)
            exit(1)

        policy = policy.get_group_policy_response.get_group_policy_result.policy_document
        policy = unquote(policy)
        group_policy.append(config_line_policy("iam:grouppolicy", group_name, policy_name, policy))

        output_lines(group_policy)

        # Format policy and search by role_filter

        policy = re.split('"', policy)

        for i in policy:
            result_filter = re.search(role_filter, i)
            if result_filter:
                delegated_arn.append(i)

        if len(delegated_arn) == 0:
            if args.role and args.project:
                colormsg("Sorry, you are not authorized to use the role " + role + " for project " + project, "error")
                exit(1)
            else:
                colormsg("Sorry, you are not authorized to use the role " + role_filter, "error")
                exit(1)

        elif len(delegated_arn) == 1:
            account_id_from_user = delegated_arn[0].split(':')[4]
            role_name_from_user = delegated_arn[0].split('/')[1]

        else:
            colormsg("There are two or more policies matching your input", "error")
            exit(1)

        colormsg("You are authenticated as " + role_session_name, "ok")

        # MFA
        if not args.nomfa:
            mfa_devices_r = iam_connection.get_all_mfa_devices(role_session_name)
            if mfa_devices_r.list_mfa_devices_response.list_mfa_devices_result.mfa_devices:
                mfa_serial_number = mfa_devices_r.list_mfa_devices_response.list_mfa_devices_result.mfa_devices[
                    0].serial_number
            else:
                colormsg("You don't have MFA devices associated with our user", "error")
                exit(1)
        else:
            mfa_serial_number = "arn:aws:iam::" + account_id + ":mfa/" + role_session_name

        # Create an ARN out of the information provided by the user.
        role_arn = "arn:aws:iam::" + account_id_from_user + ":role/"
        role_arn += role_name_from_user

        # Connect to AWS STS and then call AssumeRole. This returns temporary security credentials.
        sts_connection = STSConnection()

        # Assume the role
        if not args.nomfa:
            verbose("Assuming role " + role_arn + " using MFA device " + mfa_serial_number + "...")
            if args.project:
                colormsg(
                    "Assuming role " + role + " from project " + project + " using MFA device from user " + role_session_name + "...",
                    "normal")
            elif args.iam_delegated_role:
                colormsg("Assuming role " + role + " using MFA device from user " + role_session_name + "...", "normal")
        else:
            verbose("Assuming role " + role_arn + "...")
            if args.project:
                colormsg(
                    "Assuming role " + role + " from project " + project + " from user " + role_session_name + "...",
                    "normal")
            elif args.iam_delegated_role:
                colormsg("Assuming role " + role + " from user " + role_session_name + "...", "normal")

        if os.path.isfile(os.path.expanduser('~/.awsauth')):

            with open(os.path.expanduser('~/.awsauth')) as json_file:
                root_json_data = json.load(json_file)
                json_file.close()

                if project in root_json_data and env in root_json_data[project] and role in root_json_data[project][
                    env]:
                    json_data = root_json_data[project][env][role]
                    awsauth_last_timestamp = json_data["awsauth_last_timestamp"]

                    # check if the token has expired
                    if int(time.time()) - int(awsauth_last_timestamp) > token_expiration or args.refresh:

                        verbose("token has expired")
                        sts_token = get_sts_token(sts_connection, role_arn, mfa_serial_number, role_session_name,
                                                  project, env, role, token_expiration)

                    else:
                        verbose("token has not expired, trying to login...")
                    login_to_fedaccount(json_data["access_key"], json_data["session_key"], json_data["session_token"],
                                        json_data["role_session_name"])
                    sts_token = {'access_key': json_data["access_key"], 'session_key': json_data["session_key"],
                                 'session_token': json_data["session_token"],
                                 'role_session_name': json_data["role_session_name"]}

                else:
                    sts_token = get_sts_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project,
                                              env, role, token_expiration)
        else:
            verbose("role is " + role)
            sts_token = get_sts_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project, env,
                                      role, token_expiration)
        return sts_token
Пример #49
0
if len(sys.argv) == 3:
    account_id_from_user = sys.argv[1]
    role_name_from_user = sys.argv[2]
else:
    print "\n\tUsage: ",
    print os.path.basename(sys.argv[0]),  # script name
    print " <account_id> <role_name>"
    exit(0)

# Create an ARN out of the information provided by the user.
role_arn = "arn:aws:iam::" + account_id_from_user + ":role/"
role_arn += role_name_from_user

# Step 2: Connect to AWS STS and then call AssumeRole. This returns
# temporary security credentials.
sts_connection = STSConnection()
assumed_role_object = sts_connection.assume_role(
    role_arn=role_arn, role_session_name="AssumeRoleSession")

# Step 3: Format resulting temporary credentials into a JSON block using
# known field names.
access_key = assumed_role_object.credentials.access_key
session_key = assumed_role_object.credentials.secret_key
session_token = assumed_role_object.credentials.session_token
json_temp_credentials = '{'
json_temp_credentials += '"sessionId":"' + access_key + '",'
json_temp_credentials += '"sessionKey":"' + session_key + '",'
json_temp_credentials += '"sessionToken":"' + session_token + '"'
json_temp_credentials += '}'

# Step 4. Make a request to the AWS federation endpoint to get a sign-in
Пример #50
0
import boto
from boto.s3.connection import S3Connection
from boto.sts import STSConnection

# Prompt for MFA time-based one-time password (TOTP)
mfa_TOTP = raw_input("Enter the MFA code: ")

# The calls to AWS STS AssumeRole must be signed with the access key ID and secret
# access key of an IAM user. (The AssumeRole API operation can also be called using temporary
# credentials, but this example does not show that scenario.) 
# The IAM user credentials can be in environment variables or in 
# a configuration file and will be discovered automatically
# by the STSConnection() function. For more information, see the Python SDK 
# documentation: http://boto.readthedocs.org/en/latest/boto_config_tut.html

sts_connection = STSConnection()

# Use appropriate device ID (serial number for hardware device or ARN for virtual device)
# Replace ACCOUNT-NUMBER-WITHOUT-HYPHENS, ROLE-NAME, and MFA-DEVICE-ID with appropriate values
tempCredentials = sts_connection.assume_role(
    role_arn="arn:aws:iam::ACCOUNT-NUMBER-WITHOUT-HYPHENS:role/ROLE-NAME",
    role_session_name="AssumeRoleSession1",
    mfa_serial_number="arn:aws:iam::ACCOUNT-NUMBER-WITHOUT-HYPHENS:mfa/MFA-DEVICE-ID",
    mfa_token=mfa_TOTP
)

# Use the temporary credentials to list the contents of an S3 bucket
s3_connection = S3Connection(
    aws_access_key_id=tempCredentials.credentials.access_key,
    aws_secret_access_key=tempCredentials.credentials.secret_key,
    security_token=tempCredentials.credentials.session_token