Exemple #1
0
def delete_iam_role(
    role_name: str, region: Optional[str] = None, quiet: bool = True
) -> None:
    from boto.iam.connection import IAMConnection
    # TODO: the Boto3 type hints are a bit oversealous here; they want hundreds
    # of overloads of the client-getting methods to exist based on the literal
    # string passed in, to return exactly the right kind of client or resource.
    # So we end up having to wrap all the calls in casts, which kind of defeats
    # the point of a nice fluent method you can call with the name of the thing
    # you want; we should have been calling iam_client() and so on all along if
    # we wanted MyPy to be able to understand us. So at some point we should
    # consider revising our API here to be less annoying to explain to the type
    # checker.
    iam_client = cast(IAMClient, session.client('iam', region_name=region))
    iam_resource = cast(IAMServiceResource, session.resource('iam', region_name=region))
    boto_iam_connection = IAMConnection()
    role = iam_resource.Role(role_name)
    # normal policies
    for attached_policy in role.attached_policies.all():
        printq(f'Now dissociating policy: {attached_policy.policy_name} from role {role.name}', quiet)
        role.detach_policy(PolicyArn=attached_policy.arn)
    # inline policies
    for inline_policy in role.policies.all():
        printq(f'Deleting inline policy: {inline_policy.policy_name} from role {role.name}', quiet)
        # couldn't find an easy way to remove inline policies with boto3; use boto
        boto_iam_connection.delete_role_policy(role.name, inline_policy.policy_name)
    iam_client.delete_role(RoleName=role_name)
    printq(f'Role {role_name} successfully deleted.', quiet)
Exemple #2
0
    def attach_policy(self, S3_User, bucket_name):
        policy = '''{
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": [
                        "s3:ListAllMyBuckets"
                    ],
                    "Effect": "Allow",
                    "Resource": "arn:aws:s3:::*"
                },
                {
                    "Action": "s3:*",
                    "Effect": "Allow",
                    "Resource": [
                        "arn:aws:s3:::%s*",
                        "arn:aws:s3:::%s*/*"
                    ]
                }
            ]
         }''' % (bucket_name, bucket_name)

        print policy
        # # Attach Policy to acces s3 bucket
        connect = IAMConnection(self.admin_access_key, self.admin_secret_key)
        connect.put_user_policy(S3_User, bucket_name, policy)
Exemple #3
0
def list_users(conn):
    conn = IAMConnection()
    users = conn.get_all_users()

    print "\nCurrent AWS user accounts:\n"
    for user in users.list_users_result.users:
        print "- {0}".format(user.user_name)
    print ""
Exemple #4
0
 def from_environment(kls, create_epoch=None, half_life=None):
     """Get an IAMPair from our environment variables"""
     pair = kls(os.environ["AWS_ACCESS_KEY_ID"],
                os.environ["AWS_SECRET_ACCESS_KEY"],
                os.environ.get("AWS_SECURITY_TOKEN"), create_epoch,
                half_life)
     pair._connection = IAMConnection()
     return pair
Exemple #5
0
 def connection(self):
     """Get a connection for these keys"""
     if not getattr(self, "_connection", None):
         self._connection = IAMConnection(
             self.aws_access_key_id,
             self.aws_secret_access_key,
             security_token=self.aws_security_token)
     return self._connection
Exemple #6
0
def setup_iam():
    """
    Sets up IAM policy, roles and instance profile
    """
    IAM = IAMConnection()
    profile = IAM.create_instance_profile(IAM_PROFILE)
    role = IAM.create_role(IAM_ROLE)
    IAM.add_role_to_instance_profile(IAM_PROFILE, IAM_ROLE)
    IAM.put_role_policy(IAM_ROLE, IAM_POLICY_NAME, IAM_POLICY)
Exemple #7
0
    def access_key(self, s3_user):
        connect = IAMConnection(self.admin_access_key, self.admin_secret_key)
        key = connect.create_access_key(s3_user)
        access_key = key['create_access_key_response'][
            u'create_access_key_result'][u'access_key'][u'access_key_id']
        secret_key = key['create_access_key_response'][
            u'create_access_key_result'][u'access_key'][u'secret_access_key']

        return s3_user, access_key, secret_key
Exemple #8
0
def main():
    if len(sys.argv) > 2:
        printUsage()
        raise SystemExit(1)

    try:
        section = sys.argv[1]
    except IndexError:
        section = 'default'

    credentials = CredentialsFile(section)

    iam = IAMConnection(
        aws_access_key_id=credentials.keyId,
        aws_secret_access_key=credentials.secretKey,
    )

    userName = getUserName(iam)
    deleteOldKeys(iam, credentials.keyId, userName)
    newKey = makeNewKey(iam, userName)

    iam = IAMConnection(
        aws_access_key_id=newKey['access_key_id'],
        aws_secret_access_key=newKey['secret_access_key'],
    )

    oldKey = credentials.keyId
    try:
        deactivateKey(iam, oldKey, userName)
    except BotoServerError as e:
        print(e)
        raise SystemExit(
            dedent('''
        Failed to deactivate the old key (%s) after one minute of
        retrying. Manual remediation will be required.
        %s
        ''' % (oldKey, ACCESS_KEY_DOCS)).strip())

    credentials.updateCredentials(
        newKey['access_key_id'],
        newKey['secret_access_key'],
    )
Exemple #9
0
    def create_user(self, s3_user):
        connect = IAMConnection(self.admin_access_key, self.admin_secret_key)
        user = connect.get_all_users()

        users = user['list_users_response']['list_users_result']['users']

        for user in users:
            if s3_user in user['user_name']:
                return False

        connect.create_user(s3_user)
        return True
    def __connections_setup(self, is_secure, boto_debug):
        """
        Creates FCU, OSU and EIM connections if endpoints are configured
        :param is_secure: allow connection without SSL
        :type is_secure: bool
        :param boto_debug: debug level for boto
        :type boto_debug: int
        :raises OCBError: When connections can not be created because AK and SK are not set up in environment variable
        """

        access_key_id, secret_access_key, endpoints, icu_conn = self.__load_config()

        if endpoints['fcu']:
            fcu_endpoint = EC2RegionInfo(endpoint=endpoints['fcu'])
            self.fcu = FCUConnection(access_key_id, secret_access_key, region=fcu_endpoint, is_secure=is_secure, debug=boto_debug)
        else:
            self.__logger.info('No FCU connection configured')
            self.fcu = None

        if endpoints['lbu']:
            lbu_endpoint = EC2RegionInfo(endpoint=endpoints['lbu'])
            self.lbu = ELBConnection(access_key_id, secret_access_key, region=lbu_endpoint, debug=boto_debug)
        else:
            self.__logger.info('No LBU connection configured')
            self.lbu = None

        if endpoints['eim']:
            self.eim = IAMConnection(access_key_id, secret_access_key, host=endpoints['eim'], debug=boto_debug)
        else:
            self.__logger.info('No EIM connection configured')
            self.eim = None

        if endpoints['osu']:
            self.osu = boto.connect_s3(access_key_id, secret_access_key, host=endpoints['osu'],
                                       calling_format=boto.s3.connection.ProtocolIndependentOrdinaryCallingFormat())
        else:
            self.__logger.info('No OSU connection configured')
            self.osu = None

        if icu_conn['endpoint']:
            self.icu = self.__connect_icu(icu_conn['endpoint'], access_key_id, secret_access_key, icu_conn['login'], icu_conn['password'])
        else:
            self.__logger.info('No ICU connection configured')
            self.icu = None
Exemple #11
0
def iam_connect(region=None, *args, **kwargs):
    """Helper to connect to Amazon Web Services IAM, using identify provided
    by environment, as also optional region in arguments.

    .. note:: The region parameter is allowed, but do nothing, still here
        for future API compatibility and orthogonality between libraries.
    """

    if not os_environ.get("AWS_ACCESS_KEY_ID", None):
        raise IAMLibraryError(
            "Environment variable AWS_ACCESS_KEY_ID is not set.")
    if not os_environ.get("AWS_SECRET_ACCESS_KEY", None):
        raise IAMLibraryError(
            "Environment variable AWS_SECRET_ACCESS_KEY is not set.")

    connection = IAMConnection(os_environ.get("AWS_ACCESS_KEY_ID"),
                               os_environ.get("AWS_SECRET_ACCESS_KEY"), *args,
                               **kwargs)

    return connection
def s3_bucket_maker(answers):
    access_key = os.environ['ACCESS_KEY_ID']
    secret_key = os.environ['SECRET_ACCESS_KEY']
    s3conn = S3Connection(access_key, secret_key)
    iamconn = IAMConnection(access_key, secret_key)

    bucket = s3conn.create_bucket(answers['bucket_name'])

    print("BUCKET: %s created" % answers['bucket_name'])

    user = None
    try:
        user = iamconn.get_user(answers['username'])
    except boto.exception.BotoServerError, e:
        if e.status == 404:
            print('User not found... creating one')
            user = iamconn.create_user(answers['username'])
            keys = iamconn.create_access_key(answers['username'])
            print(keys)
        else:
            raise e
Exemple #13
0
    def setup(self):
        """Make sure our current credentials are for this account and set self.connection"""
        try:
            connection = IAMConnection()
        except boto.exception.NoAuthHandlerFound:
            raise SyncrError("Export AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY before running this script (your aws credentials)")

        # Need roles to make sure we have the correct account
        log.info("Finding roles in your account")
        try:
            result = connection.list_roles()
        except boto.exception.BotoServerError as error:
            if error.status == 403:
                raise SyncrError("Your credentials aren't allowed to look at iam roles :(")
            else:
                raise

        roles = self.all_roles = result["list_roles_response"]["list_roles_result"]["roles"]
        if not roles:
            raise SyncrError("There are no roles in your account, I can't figure out the account id")

        # Need users for kms to be able to grant to users
        log.info("Finding users in your account")
        try:
            result = connection.get_all_users()
        except boto.exception.BotoServerError as error:
            if error.status == 403:
                raise SyncrError("Your credentials aren't allowed to look at iam users :(")
            else:
                raise
        self.all_users = result["list_users_response"]["list_users_result"]["users"]

        amazon_account_id = roles[0]['arn'].split(":")[4]
        if str(self.account_id) != str(amazon_account_id):
            raise SyncrError("Please use credentials for the right account", expect=self.account_id, got=amazon_account_id)

        # If reached this far, the credentials belong to the correct account :)
        self.connection = connection
        return connection
Exemple #14
0
def delete_iam_role(role_name: str,
                    region: Optional[str] = None,
                    quiet: bool = True):
    from boto.iam.connection import IAMConnection
    iam_client = aws.client('iam', region_name=region)
    iam_resource = aws.resource('iam', region_name=region)
    boto_iam_connection = IAMConnection()
    role = iam_resource.Role(role_name)
    # normal policies
    for attached_policy in role.attached_policies.all():
        printq(
            f'Now dissociating policy: {attached_policy.name} from role {role.name}',
            quiet)
        role.detach_policy(PolicyName=attached_policy.name)
    # inline policies
    for attached_policy in role.policies.all():
        printq(
            f'Deleting inline policy: {attached_policy.name} from role {role.name}',
            quiet)
        # couldn't find an easy way to remove inline policies with boto3; use boto
        boto_iam_connection.delete_role_policy(role.name, attached_policy.name)
    iam_client.delete_role(RoleName=role_name)
    printq(f'Role {role_name} successfully deleted.', quiet)
Exemple #15
0
import boto
from boto import iam
from boto.iam.connection import IAMConnection
from boto.iam.connection import MFADevices

conn= IAMConnection()
summary= conn.get_all_users();

for user in summary.users:
   name=user['user_name']
   print get_all_mfa_devices(name)

Exemple #16
0
# Prints a list of all access keys with the associated user.

import boto
from boto.iam.connection import IAMConnection

cfn = IAMConnection()
data = cfn.get_all_users()
for user in data.list_users_result.users:
    for ak in cfn.get_all_access_keys(
            user.user_name).list_access_keys_result.access_key_metadata:
        print user.user_name + ': ' + ak.access_key_id
Exemple #17
0
#!/usr/bin/env python

import os
import sys
import json
import time
import boto
from boto.iam.connection import IAMConnection

AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''

iamconn = IAMConnection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)

#data = iamconn.get_all_users()

username = raw_input('please input a name for iam create: ')

#create the  user on aws/iam

create = iamconn.create_user(username)

#diplay the user you  created

data = iamconn.get_user(user_name=username)

print "useername is:%s" % data.get_user_result.user.user_name
#print type(data)

#create access_key
from boto.iam.connection import IAMConnection
from boto.s3.key import Key
import boto3

import json

import base64

credentials = {}
with open(os.getcwd() + '/.credentials.example') as credentials_json:
    credentials = json.load(credentials_json)
    # print credentials_json.read()

app = Flask(__name__)

iam = IAMConnection(aws_access_key_id=credentials['AWS_ACCESS_KEY'],
                    aws_secret_access_key=credentials['AWS_ACCESS_SECRET_KEY'])
arn = iam.get_user().user.arn

account_id = arn[arn.find('::') + 2:arn.rfind(':')]

app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024

CORS(app)


@app.route('/', methods=['POST'])
def load_file():

    image_data_json = json.loads(request.data)

    image_data_json['encoded_data'] = (
Exemple #19
0
                    good_grant = True
                    break
            if not good_grant:
                return "BadRange"

        return None

    conn = boto.ec2.connect_to_region(region, aws_access_key_id=access_key,
                                      aws_secret_access_key=secret_key)
    sdb = boto.sdb.connect_to_region(region, aws_access_key_id=access_key,
                                     aws_secret_access_key=secret_key)

    for sg_name in get_sg_names():
        if action == 'initialize' or action == 'initialize-destructive':
            destructive = action == 'initialize-destructive'
            iam = IAMConnection(aws_access_key_id=access_key,
                                aws_secret_access_key=secret_key)

            owner_id = None

            sg_exists = False

            for sg in conn.get_all_security_groups():
                if sg.owner_id:
                    ownerid = sg.owner_id
                if sg.name == sg_name:
                    sg_exists = True

            assert ownerid is not None
            group_name = 'can-opener-grp'
            user_name = 'can-opener-user'
            policy_name = 'can-opener-policy'
synapseAccessKeyProjectId=environ["SYNAPSE_ACCESS_KEY_PROJECT_ID"]

s3Connections = []
iamConnections = []
i=0
while True:
    aws_access_key_id = environ.get("AWS_ACCESS_KEY_ID_"+str(i+1))
    aws_secret_access_key = environ.get("AWS_SECRET_ACCESS_KEY_"+str(i+1))
    if (i==0):
        snsConnection = SNSConnection(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)

    if ((aws_access_key_id is None) or (aws_secret_access_key is None)):
        break
    else:
        s3Connections.append(S3Connection(aws_access_key_id, aws_secret_access_key))
        iamConnections.append(IAMConnection(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key))
        i=i+1
        
if (len(s3Connections)==0):
    raise("No AWS crdentials provided")

MAXIMUM_USER_NAME_LENGTH = 63

## connect to Synapse
syn = Synapse()
syn.login(synapseUserId, synapseUserPw)
ownUserProfile = syn.getUserProfile()
ownPrincipalId = ownUserProfile['ownerId']

## get all Participants for Evaluation
participants = syn.restGET("/evaluation/"+evaluationId+'/participant?limit=99999')['results']