Ejemplo n.º 1
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 = _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
     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,
                                   profile_name=self.profile)
     return connection
Ejemplo n.º 2
0
 def get_sts_connection(self):
     token_url = urlparse(self.vars['TOKEN_URL'])
     STSConnection.DefaultRegionEndpoint = token_url.hostname
     port = token_url.port if token_url.port else 80
     return STSConnection(is_secure=False, port=port, path=token_url.path,
                          aws_access_key_id=self.get_env_var('AWS_ACCESS_KEY_ID'),
                          aws_secret_access_key=self.get_env_var('AWS_SECRET_ACCESS_KEY'))
def conn_aws_arnrole_s3(aws_access_key, aws_access_secret, aws_arn_role, aws_arn_session_name, aws_arn_session_duration, aws_bucket):
    """

    Makes connection to AWS S3 bucket with arn details. The connection details comes from extract_postgres.getawsarn(id)
    :return: Returns the bucket.

    If using boto3:
        sts_client = boto3.client('sts')
        assumedroleobject = sts_client.assume_role(RoleArn=aws_arn_role,
                                                   RoleSessionName=aws_arn_session_name,
                                                   DurationSeconds=aws_arn_session_duration)
        credentials = assumedroleobject['Credentials']
        s3_resource = boto3.resource(
            's3', aws_access_key_id=credentials['AccessKeyId'],
            aws_secret_access_key=credentials['SecretAccessKey'],
            aws_session_token=credentials['SessionToken'])
        return s3_resource.Bucket(aws_bucket)

    """
    try:
        sts_connection = STSConnection(aws_access_key, aws_access_secret)
        tempCredentials = sts_connection.assume_role(role_arn=aws_arn_role,
                                                     role_session_name=aws_arn_session_name,
                                                     duration_seconds=aws_arn_session_duration)

        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)
        return s3_connection.get_bucket(aws_bucket)

    except Exception as exn:
        print "The error is {} : {}".format(exn.__class__.__name__, exn)
Ejemplo n.º 4
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.º 5
0
 def check_credentials(self):
     result = False
     if not self._role_arn:
         result = True
     else:
         try:
             if self._parameters.get('assumed_region_name', None):
                 sts_connection = boto.sts.connect_to_region(
                     self._parameters['assumed_region_name'])
             else:
                 sts_connection = STSConnection()
             assumed_role_object = sts_connection.assume_role(
                 role_arn=self._role_arn,
                 role_session_name=self._role_session)
             self._parameters[
                 'access_key'] = assumed_role_object.credentials.access_key
             self._parameters[
                 'secret_key'] = assumed_role_object.credentials.secret_key
             self._parameters[
                 'session_token'] = assumed_role_object.credentials.session_token
             result = True
         except:
             if self._log_file:
                 log(
                     "An error occured when creating connection, check the exception error message for more details",
                     self._log_file)
             result = False
             raise
     return (result)
Ejemplo n.º 6
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))
Ejemplo n.º 7
0
def main(options):
    sts_connection = STSConnection()

    # conn = dynamodb.connect_to_region(options.region)
    assumedRoleObject = sts_connection.assume_role()

    conn = dynamodb.layer2.Layer2(region=options.region,
                                  aws_access_key_id=assumedRoleObject.credentials.access_key,
                                  aws_secret_access_key=assumedRoleObject.credentials.secret_key,
                                  security_token=assumedRoleObject.credentials.session_token)

    def create_table(name):
        table_schema = conn.create_schema(
            hash_key_name='Key',
            hash_key_proto_value=str
        )
        table = conn.create_table(
            name=name,
            schema=table_schema,
            read_units=2,
            write_units=1
        )
        return table

    try:
        create_table(CONFIGURATION_TABLE_NAME)
        time.sleep(5)
    except:
        pass

    table = conn.get_table(CONFIGURATION_TABLE_NAME)

    availability_zones = ",".join([zone.name for zone in ec2.connect_to_region(options.region).get_all_zones()])

    account_id = iam.connect_to_region(options.region).get_user().arn.split(':')[4]

    items = {
        'account_name': options.account_name,
        'account_environment': options.account_environment,
        'availability_zones': availability_zones,
        'account_id': account_id,
        'output_path': options.output_path,
        'output_path': options.output_path
    }

    if options.accounts:
        items['accounts'] = options.accounts

    if options.okta_credential:
        okta_config = json.load(open(options.okta_credential))
        items['okta_credential'] = json.dumps(okta_config)

    for key, value in items.iteritems():
        print key
        attrs = {'Key': key, 'Value': value}
        time.sleep(1)

        my_item = table.new_item(attrs=attrs)
        print my_item.put()
Ejemplo n.º 8
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.º 9
0
 def _create_s3_connection_assuming_role(self):
     """Creates S3 connection by assuming the role necessary to read from
     the S3 bucket that contains the logs.
     """
     JsonLogger.log_event('assuming_role', assumed_role_arn=self.role_arn)
     sts_connection = STSConnection()
     assumed_role = sts_connection.assume_role(
         role_arn=self.role_arn, role_session_name="AssumeRoleS3BucketRead")
     self.s3_connection = S3Connection(
         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)
Ejemplo n.º 10
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
Ejemplo n.º 11
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)
Ejemplo n.º 12
0
def openConsole():
    """ Get STS token and open AWS console.
    """
    # Create an ARN out of the information provided by the user.
    role_arn = "arn:aws:iam::" + accountId() + ":role/" + getArgs().role_name

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

    # Format resulting credentials into a JSON block.
    tmp_creds = {
        "sessionId": assumed_role_object.credentials.access_key,
        "sessionKey": assumed_role_object.credentials.secret_key,
        "sessionToken": assumed_role_object.credentials.session_token,
    }
    json_temp_credentials = json.dumps(tmp_creds)

    # Make a request to the AWS federation endpoint to get a sign-in
    # token, passing parameters in the query string.
    params = {
        "Action": "getSigninToken",
        "Session": json_temp_credentials,
    }
    request_url = "https://signin.aws.amazon.com/federation"
    r = requests.get(request_url, params=params)

    # The return value from the federation endpoint, the token.
    sign_in_token = json.loads(r.text)["SigninToken"]
    # Token is good for 15 minutes.

    # Create the URL to the console with token.
    params = {
        "Action": "login",
        "Issuer": "",
        "Destination": "https://console.aws.amazon.com/",
        "SigninToken": sign_in_token,
    }
    request_url = "https://signin.aws.amazon.com/federation?"
    request_url += urlencode(params)

    # Use the default browser to sign in to the console using the
    # generated URL.
    browser = webbrowser.get()
    if getArgs().incognito:
        webbrowser.Chromium.raise_opts = ["", "--incognito"]
        webbrowser.Chrome.raise_opts = ["", "--incognito"]
        webbrowser.Mozilla.remote_args = ['--private-window', '%s']
    browser.open(request_url, new=1)
Ejemplo n.º 13
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 = 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)

            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(e)
        exit(1)

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

    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)

    credential_profile = 'default'

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

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

    return {'access_key': access_key, 'session_key': session_key, 'session_token': session_token,
            'role_session_name': role_session_name}
Ejemplo n.º 14
0
    def __init__(self):
        """ Virtually private constructor. """
        if AssumeRole.__instance:
            raise Exception("This is a singleton class!")

        sts = STSConnection(settings.AWS_ACCESS_KEY_ID,
                            settings.AWS_SECRET_ACCESS_KEY)
        self.credentials = sts.assume_role(
            role_arn=settings.ROLE_ARN,
            role_session_name='vem',
            duration_seconds=3600,
            mfa_serial_number=settings.MFA_SERIAL_NUMBER,
            mfa_token=settings.MFA_TOKEN).credentials.to_dict()

        AssumeRole.__instance = self
Ejemplo n.º 15
0
    def get_conn(self):
        """
        Returns the boto S3Connection object.
        """
        if self._default_to_boto:
            return S3Connection(profile_name=self.profile, host=self.s3_host)
        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
Ejemplo n.º 16
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.º 17
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)
Ejemplo n.º 18
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')
Ejemplo n.º 19
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.º 20
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)
Ejemplo n.º 21
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
Ejemplo n.º 22
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
Ejemplo n.º 23
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 " +
Ejemplo n.º 24
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.º 25
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
Ejemplo n.º 26
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)
Ejemplo n.º 27
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
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.º 29
0
def connect_to_sts_region(aws_access_key, aws_secret_key):
    try:
        return STSConnection(aws_access_key, aws_secret_key)
    except:
        raise
Ejemplo n.º 30
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: