def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=False, port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, host=None, debug=0, https_connection_factory=None, path='/', security_token=None, validate_certs=True): """ Euca-specific extension to boto's IAM connection. """ IAMConnection.__init__(self, aws_access_key_id, aws_secret_access_key, is_secure, port, proxy, proxy_port, proxy_user, proxy_pass, host, debug, https_connection_factory, path, security_token, validate_certs=validate_certs)
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)
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)
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
def get_iam_users(): """Requires: none """ config = get_config() conn = IAMConnection(config['access_key'],config['secret_key']) users = conn.get_all_users() for user in users['list_users_response']['list_users_result']['users']: print user['user_name']+","+user['create_date']
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 ""
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
def get_user_name(accessKey,secretKey): """ Connects to the IAM Gets the username for given access key and secret key """ try: acc = IAMConnection(accessKey,secretKey) result = acc.get_user() uname = result['get_user_response']['get_user_result']['user']['user_name'] return uname except Exception as e: print "Exception occurred while fetching IAM info: ", e.message
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 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)
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
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
def main(): arguments = docopt(__doc__) aws_access_key = arguments["--aws_access_key"] aws_secret_key = arguments["--aws_secret_key"] with open(arguments["--certificate"], "r") as f: certificate = f.read() with open(arguments["--chain"], "r") as f: chain = f.read() with open(arguments["--private_key"], "r") as f: private_key = f.read() connection = IAMConnection(aws_access_key, aws_secret_key) connection.upload_server_cert( "PythonAnywhere-main-wildcard-cert-{:%Y-%m-%d}".format(datetime.now()), certificate, private_key, chain, path="/cloudfront/", )
def create_iam_user(): """Create a new IAM user. :rtype: json :returns: The resource uri of the new user, the ARN of the user, the user's access key, and their secret key. Usage:: $ curl -H "Content-Type: application/json" -X POST --data '{"user_name": "rdegges"}' /iam { "resource_uri": "http://dummy", "arn": "arn:aws:iam::xxxxxxxxxxxx:user/user_name", "aws_access_key_id": "blah" "aws_secret_access_key": "blah" } """ user_name = request.json.get("user_name") if request.json else None # If no user name is specified in the request, fail immediately: if not user_name: return (None, 400) # Create the new IAM user: conn = IAMConnection(app.config["AWS_ACCESS_KEY_ID"], app.config["AWS_SECRET_ACCESS_KEY"]) create_user_resp = conn.create_user(user_name) # Generate an AWS access key ID and secret access key for the new IAM user: create_key_resp = conn.create_access_key(user_name=user_name) # Store the new IAM user information: user_data = {} user_data["arn"] = create_user_resp["create_user_response"]["create_user_result"]["user"]["arn"] user_data["aws_access_key_id"] = create_key_resp["create_access_key_response"]["create_access_key_result"][ "access_key" ]["access_key_id"] user_data["aws_secret_access_key"] = create_key_resp["create_access_key_response"]["create_access_key_result"][ "access_key" ]["secret_access_key"] user_data["resource_uri"] = "http://dummy" return jsonify(user_data)
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'], )
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
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
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)
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
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
#!/usr/bin/env python from keyring import get_password from boto.iam.connection import IAMConnection import lib.LoadBotoConfig as BotoConfig from sys import exit envs = ['dev', 'qa', 'staging', 'demo', 'prod'] for env in envs: id = BotoConfig.config.get(env, 'aws_access_key_id') key = get_password(BotoConfig.config.get(env, 'keyring'), id) conn = IAMConnection(aws_access_key_id=id, aws_secret_access_key=key) print(conn.get_signin_url())
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']
# 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
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'] = (
def __init__(self): self._users = set() self._groups = set() self._policies = set() self._conn = IAMConnection()
class IamCloud(object): """Representation of the IAM database in AWS""" def __init__(self): self._users = set() self._groups = set() self._policies = set() self._conn = IAMConnection() def _load_users(self): raw_users = self._conn.get_all_users() u_list = (raw_users[u'list_users_response'] [u'list_users_result'] [u'users']) for u_dict in u_list: name = u_dict[u'user_name'] # User's groups groups = set() raw_groups = self._conn.get_groups_for_user(name) g_list = (raw_groups[u'list_groups_for_user_response'] [u'list_groups_for_user_result'] [u'groups']) for g_dict in g_list: groups.add(g_dict[u'group_name']) # User's policies policies = set() raw_policies = self._conn.get_all_user_policies(name) p_list = (raw_policies[u'list_user_policies_response'] [u'list_user_policies_result'] [u'policy_names']) for policy_name in p_list: raw_policy = self._conn.get_user_policy(name, policy_name) encoded_policy = (raw_policy[u'get_user_policy_response'] [u'get_user_policy_result'] [u'policy_document']) str_policy = urllib.unquote_plus(encoded_policy) dict_policy = json.loads(str_policy) policy = IamPolicy(policy_name, dict_policy) policies.add(policy) user = IamUser(name, groups, policies) self._users.add(user) @property def users(self): if not self._users: self._load_users() return self._users def _load_groups(self): raw_groups = self._conn.get_all_groups() g_list = (raw_groups[u'list_groups_response'] [u'list_groups_result'] [u'groups']) for g_dict in g_list: name = g_dict[u'group_name'] # Group's policies policies = set() raw_policies = self._conn.get_all_group_policies(name) p_list = (raw_policies[u'list_group_policies_response'] [u'list_group_policies_result'] [u'policy_names']) for policy_name in p_list: raw_policy = self._conn.get_group_policy(name, policy_name) encoded_policy = (raw_policy[u'get_group_policy_response'] [u'get_group_policy_result'] [u'policy_document']) str_policy = urllib.unquote_plus(encoded_policy) dict_policy = json.loads(str_policy) policy = IamPolicy(policy_name, dict_policy) policies.add(policy) group = IamGroup(name, policies) self._groups.add(group) @property def groups(self): if not self._groups: self._load_groups() return self._groups @property def policies(self): if not self._policies: self._load_policies() return self._policies def dump_users(self): """Dump users into files""" config = SafeConfigParser() for user in sorted(self.users): config.add_section(user.name) if user.groups: config.set(user.name, u'groups', ',\n'.join(sorted(user.groups))) if user.policies: policy_names = set() for policy in user.policies: policy_names.add(policy.name) config.set(user.name, u'policies', ',\n'.join(sorted(policy_names))) with open(USERS_FILE, 'w') as configfile: config.write(configfile) def dump_groups(self): """Dump groups into files""" config = SafeConfigParser() for group in sorted(self.groups): config.add_section(group.name) if group.policies: policy_names = set() for policy in group.policies: policy_names.add(policy.name) config.set(group.name, u'policies', ',\n'.join(sorted(policy_names))) with open(GROUPS_FILE, 'w') as configfile: config.write(configfile) def dump_policies(self): """Dump user and group policies into files""" policies_to_dump = set() # Check that there is no dupe policy policy_used = {} for user in self.users: for policy in user.policies: if policy.name not in policy_used: policy_used[policy.name] = set(["user:"******"user:"******"group:" + group.name]) else: policy_used[policy.name].add("group:" + group.name) for policy_name in policy_used: if len(policy_used[policy_name]) > 1: print("Multiple policies named {} have been found:" .format(policy_name)) for policy_user in policy_used[policy_name]: print " - {}".format(policy_user) print print ("You must rename any duplicate policy for the dump to " "be consistent.") print "Rename those and dump again." for user in self.users: for policy in user.policies: policies_to_dump.add(policy) for group in self.groups: for policy in group.policies: policies_to_dump.add(policy) # If the policies folder is not there, create it if policies_to_dump and not os.path.isdir(POLICIES_DIR): os.mkdir(POLICIES_DIR, 0755) for policy in policies_to_dump: filename = policy.name + u'.json' filepath = os.path.join(POLICIES_DIR, filename) with open(filepath, 'w') as policy_file: json.dump(policy.document, policy_file, sort_keys=True, indent=2, separators=(',', ': ')) def dump(self): """Dump everything into files""" print "Dumping users into {filename}...".format(filename=USERS_FILE) self.dump_users() print "Dumping groups into {filename}...".format(filename=GROUPS_FILE) self.dump_groups() print ("Dumping policies into {foldername}/*.json..." .format(foldername=POLICIES_DIR)) self.dump_policies()
#!/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 user create = iamconn.create_user(username) #print create data = iamconn.get_user(user_name=username) print "useername is:%s" % data.get_user_result.user.user_name #print type(data) #create access_key
#!/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
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)
# 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
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'