Ejemplo n.º 1
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)
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
def create_user(user, mfa):
    from boto.s3.connection import S3Connection
    from boto.sts import STSConnection
    import yaml
    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)

    try:
        f = open('users.yaml')
    except IOError as err:
        click.echo("Error: %s" % err)
    else:
        with f:
            config = yaml.load(f)
            if config[user]:
                policy = config[user]['policies']
                access = config[user]['programmatic']
                console = config[user]['console']
                mfa = config[user]['mfa']
                try:
                    response = iam.create_user(UserName=user)
                except botocore.exceptions.ClientError as e:
                    logging.error(e.response['Error']['Code'])
                    click.echo("Exception Caught: %s" % e)
                else:
                    print(json.dumps(response, indent=4, default=str))
                    attach_policy(user, policy)
                    # dispatch dictionary
                    dispatch_dict = {
                        'programmatic': programmatic_access,
                        'console': console_access,
                        'mfa': configure_mfa
                    }

                    for k, v in config[user].items():
                        if k in ('programmatic', 'console',
                                 'mfa') and v is True:
                            handler = dispatch_dict[k]
                            handler(user)

            else:
                click.echo("User configuraton does not exist in %s" % f)
                sys.exit(1)
Ejemplo n.º 4
0
def get_sts_creds(profile, duration, device_id, mfa_code):
    """
    Get STS creds from AWS.

    :param profile: AWS creds profile name
    :param duration: Token lifetime
    :param device_id: MFA device ARN
    :param mfa_code: MFA TOTP code
    :return:
    """
    sts_connection = STSConnection(profile_name=profile)

    sts_creds = sts_connection.get_session_token(
        duration=duration,
        mfa_serial_number="{device_id}".format(device_id=device_id),
        mfa_token=mfa_code)

    return sts_creds
Ejemplo n.º 5
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))
Ejemplo n.º 6
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
Ejemplo n.º 7
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)
Ejemplo n.º 8
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
Ejemplo n.º 9
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)
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'])
Ejemplo n.º 11
0
        with open(config_file_path, 'w') as config_file:
            config.write(config_file)


    # Open the connection, specifying the profile to use
    sts_connection = STSConnection(profile_name=profile)

    # Prompt for MFA device and time-based one-time password (TOTP)
    mfa_device = config.get(profile, AWS_MFA_DEVICE)
    serial_number = "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
    )
    config.set(ConfigParser.DEFAULTSECT, AWS_ACCESS_KEY_ID, tempCredentials.access_key)
    config.set(ConfigParser.DEFAULTSECT, AWS_SECRET_ACCESS_KEY, tempCredentials.secret_key)
    config.set(ConfigParser.DEFAULTSECT, AWS_SESSION_TOKEN, tempCredentials.session_token)

# Write out the config
with open(config_file_path, 'w') as configfile:
    config.write(configfile)

print("\nAll set! You can now use AWS CLI commands.")
Ejemplo n.º 12
0
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
)

# Replace BUCKET-NAME with an appropriate value.
bucket = s3_connection.get_bucket(bucket_name="BUCKET-NAME")
objectlist = bucket.list()
for obj in objectlist:
    print(obj.name)
# 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(
    aws_access_key_id=tempCredentials.access_key,
    aws_secret_access_key=tempCredentials.secret_key,
    security_token=tempCredentials.session_token)

# Call the assume_role method of the STSConnection object and pass the role
# ARN and a role session name.
assumedRoleObject = sts_connection1.assume_role(
    role_arn=