Пример #1
0
def test_refresh_userpassword_common_session(user_password):
    user, password = user_password

    creds = UserPassCredentials(user, password)
    root_session = Session()

    # Basic scenarion, I recreate the session each time
    session = creds.signed_session(root_session)

    response = session.get(
        "https://management.azure.com/subscriptions?api-version=2016-06-01")
    response.raise_for_status()  # Should never raise

    try:
        session = creds.signed_session(root_session)
        # Hacking the token time
        session.auth._client.token[
            'expires_in'] = session.auth._client.expires_in = -10
        session.auth._client.token[
            'expires_on'] = session.auth._client.expires_on = time.time() - 10
        session.auth._client.token[
            'expires_at'] = session.auth._client.expires_at = session.auth._client._expires_at = session.auth._client.expires_on

        response = session.get(
            "https://management.azure.com/subscriptions?api-version=2016-06-01"
        )
        pytest.fail("Requests should have failed")
    except oauthlib.oauth2.rfc6749.errors.TokenExpiredError:
        session = creds.refresh_session(root_session)
        response = session.get(
            "https://management.azure.com/subscriptions?api-version=2016-06-01"
        )
        response.raise_for_status()  # Should never raise
Пример #2
0
    def getCredentialsForResource(credentials, tenantId, resource):

        authType = credentials['type']
        if authType == CREDENTIALS_TYPE_USER_PASS:
            userName = credentials[KEY_USERNAME]
            password = credentials[KEY_PASSWORD]
            if tenantId:
                return UserPassCredentials(userName,
                                           password,
                                           resource=resource,
                                           tenant=tenantId)
            else:
                return UserPassCredentials(userName,
                                           password,
                                           resource=resource)
        if authType in [CREDENTIALS_TYPE_CLI, CREDENTIALS_TYPE_PORTAL]:
            if tenantId:
                return AzureEnvironmentSessionCredentials(resource=resource,
                                                          tenant=tenantId)
            else:
                return AzureEnvironmentSessionCredentials(resource=resource)
        if authType == CREDENTIALS_TYPE_APP:
            appId = credentials[KEY_APP_ID]
            secret = credentials[KEY_CLIENT_SECRET]
            return AppCredentialsProvider.getAADTokenCredentials(
                AZURE_PUBLIC_CLOUD, resource, appId, tenantId, secret)
        raise Exception("Invalid Auth Type: " + authType)
Пример #3
0
    def __init__(self, config):
        super(UserPasswordCredentialsProvider, self).__init__(config)
        cloud = config.getCloudType()
        credentials = config.getCredentials()
        userName = credentials[KEY_USERNAME]
        password = credentials[KEY_PASSWORD]

        self.__userName = userName
        graphResource = cloud.endpoints.active_directory_graph_resource_id
        managementResource = cloud.endpoints.management
        self.__graphCredentials = UserPassCredentials(
            userName,
            password,
            resource=graphResource,
            tenant=config.getTenantId())
        self.__grantCredentials = UserPassCredentials(
            userName,
            password,
            resource="74658136-14ec-4630-ad9b-26e160ff0fc6",
            tenant=config.getTenantId())
        self.__managementCredentials = UserPassCredentials(
            userName,
            password,
            resource=managementResource,
            tenant=config.getTenantId())
        self.__keyVaultCredentials = UserPassCredentials(
            userName,
            password,
            resource="https://vault.azure.net",
            tenant=config.getTenantId())
Пример #4
0
    def test_user_pass_credentials(self):

        creds = mock.create_autospec(UserPassCredentials)
        session = mock.create_autospec(OAuth2Session)
        creds._setup_session.return_value = session

        session.fetch_token.return_value = {
            'expires_at':'1',
            'expires_in':'2'}

        creds.token_uri = "token_uri"
        creds.verify = True
        creds.username = "******"
        creds.password = '******'
        creds.secret = 'secret'
        creds.resource = 'resource'
        creds.id = "id"

        UserPassCredentials.set_token(creds)
        self.assertEqual(creds.token, session.fetch_token.return_value)
        session.fetch_token.assert_called_with(
            "token_uri", client_id="id", username='******',
            client_secret="secret", password='******', resource='resource', verify=True)

        session.fetch_token.side_effect = oauthlib.oauth2.OAuth2Error

        with self.assertRaises(AuthenticationError):
            UserPassCredentials.set_token(creds)

        session = mock.create_autospec(OAuth2Session)
        with mock.patch.object(
            UserPassCredentials, '_setup_session', return_value=session):
            
            creds = UserPassCredentials("my_username", "my_password", 
                                        verify=False, tenant="private", resource='resource')

            session.fetch_token.assert_called_with(
                "https://login.microsoftonline.com/private/oauth2/token",
                client_id='04b07795-8ddb-461a-bbee-02f9e1bf7b46', username='******',
                password='******', resource='resource', verify=False)

        with mock.patch.object(
            UserPassCredentials, '_setup_session', return_value=session):
            
            creds = UserPassCredentials("my_username", "my_password", client_id="client_id",
                                        verify=False, tenant="private", china=True)

            session.fetch_token.assert_called_with(
                "https://login.chinacloudapi.cn/private/oauth2/token",
                client_id="client_id", username='******',
                password='******', resource='https://management.core.chinacloudapi.cn/', verify=False)
def removeUser(email, configMap, allPermissions, plugin_tag):
    log = plugin_tag + ': ' + email[:-13] + removalMessage(
        configMap, plugin_tag) + '\n'
    instruction = email[:-13] + removalMessage(configMap, plugin_tag)

    for plugin in configMap['plugins']:
        if plugin['plugin'] + ':' + plugin['tag'] == plugin_tag:
            azureConfig = plugin

    credentialsToken = UserPassCredentials(
        azureConfig['email'],
        azureConfig["password"],
        resource="https://graph.windows.net")

    graphrbac_client = GraphRbacManagementClient(credentialsToken,
                                                 azureConfig["directory"])

    users = graphrbac_client.users.list()
    for user in users:
        if user.user_principal_name[:-29] == email[:-13]:
            userID = user.object_id
            break
    try:
        graphrbac_client.users.delete(userID)
    except:
        log = plugin_tag + ': ' + email[:-13] + ' does not exist in Azure AD\n'
        instruction = email[:-13] + ' does not exist in Azure AD'
    return getJsonResponse("Azure Active Directory", email, log, instruction)
Пример #6
0
    def _get_credentials(self):
        if self.context.auth_type == MapRAzure.SERVICE_PRINCIPAL:
            secret = urllib.quote(self.context.secret)
            credentials = ServicePrincipalCredentials(self.context.client_id, secret, tenant=self.context.tenant)
        else:
            credentials = UserPassCredentials(self.context.username, self.context.password, client_id=self.context.client_id)

        return credentials
Пример #7
0
def get_credentials_from_username_password(tenant, username, password):
    """ Get credentials from tenant, username and password.

    The tenant is the uuid in your OAuth 2 endpoint:
    https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/
    """
    return UserPassCredentials(
        client_id=_XPLAT_CLIENT_ID,
        username=username,
        password=password,
        tenant=tenant,
    )
def inviteUser(email, configMap, allPermissions, plugin_tag, name):

    groups = getCLIgroups(configMap, plugin_tag, allPermissions)

    for plugin in configMap['plugins']:
        if plugin['plugin'] + ':' + plugin['tag'] == plugin_tag:
            azureConfig = plugin

    log = 'Azure: ' + email[:-13] + ' added to ' + azureConfig[
        "directory"] + '.\n'
    instruction = inviteMessage(configMap, plugin_tag).replace(
        "<username>", email[:-13] + "@{}".format(azureConfig["directory"]))
    pw = 'Ab1' + ''.join(
        random.choices(
            string.ascii_uppercase + string.ascii_lowercase + string.digits,
            k=13))

    credentialsToken = UserPassCredentials(
        azureConfig['email'],  #  new user
        azureConfig["password"],
        resource="https://graph.windows.net")

    graphrbac_client = GraphRbacManagementClient(credentialsToken,
                                                 azureConfig["directory"])
    try:
        user = graphrbac_client.users.create(
            UserCreateParameters(user_principal_name=email[:-13] +
                                 "@{}".format(azureConfig["directory"]),
                                 account_enabled=True,
                                 display_name=name,
                                 mail_nickname=email[:-13],
                                 password_profile=PasswordProfile(
                                     password=pw,
                                     force_change_password_next_login=True)))

        url = azureConfig['url'] + user.object_id

        groupIDs = []
        azureGroups = graphrbac_client.groups.list()
        for group in groups:
            for azureGroup in azureGroups:
                if group == azureGroup.display_name:
                    groupIDs.append(azureGroup.object_id)

        for groupId in groupIDs:
            addGroup = graphrbac_client.groups.add_member(groupId, url)
    except:
        log = 'Azure: failed to add, ' + email + ', user already exists  .\n'
        instruction = email + ' already exists.'

    return getJsonResponse("Azure Active Directory", email, log, instruction)
Пример #9
0
    def __init__(self, config):
        super(AzureBaseADUserPassAction, self).__init__(config=config)
        user_config = self.config['user']
        resource_config = self.config['resource_manager']
        self.credentials = UserPassCredentials(
            user_config['username'],
            user_config['password'],
            resource='https://graph.windows.net'
        )

        self.graphrbac_client = GraphRbacManagementClient(
            self.credentials,
            resource_config['tenant']
        )
Пример #10
0
    def test_user_pass_credentials(self):

        creds = mock.create_autospec(UserPassCredentials)
        session = mock.create_autospec(OAuth2Session)
        creds._setup_session.return_value = session

        session.fetch_token.return_value = {
            'expires_at':'1',
            'expires_in':'2'}

        creds.token_uri = "token_uri"
        creds.verify = True
        creds.username = "******"
        creds.password = '******'
        creds.secret = 'secret'
        creds.resource = 'resource'
        creds.id = "id"

        UserPassCredentials.set_token(creds)
        self.assertEqual(creds.token, session.fetch_token.return_value)
        session.fetch_token.assert_called_with(
            "token_uri", client_id="id", username='******',
            client_secret="secret", password='******', resource='resource')

        session.fetch_token.side_effect = oauthlib.oauth2.OAuth2Error

        with self.assertRaises(AuthenticationError):
            UserPassCredentials.set_token(creds)

        session = mock.create_autospec(OAuth2Session)
        with mock.patch.object(
            UserPassCredentials, '_setup_session', return_value=session):
            
            creds = UserPassCredentials("my_username", "my_password", 
                                        verify=False, tenant="private", resource='resource')

            session.fetch_token.assert_called_with(
                "https://login.microsoftonline.com/private/oauth2/token",
                client_id='04b07795-8ddb-461a-bbee-02f9e1bf7b46', username='******',
                password='******', resource='resource')

        with mock.patch.object(
            UserPassCredentials, '_setup_session', return_value=session):
            
            creds = UserPassCredentials("my_username", "my_password", client_id="client_id",
                                        verify=False, tenant="private", china=True)

            session.fetch_token.assert_called_with(
                "https://login.chinacloudapi.cn/private/oauth2/token",
                client_id="client_id", username='******',
                password='******', resource='https://management.core.chinacloudapi.cn/')
Пример #11
0
from azure.keyvault import KeyVaultClient, KeyVaultAuthentication

#region Key Vault Parameters
#--------------------------------------------------------
# Setup Azure Key Vault Authentication Parameters
#--------------------------------------------------------
VAULT_URI = 'https://<KeyVaultName>.vault.azure.net/'  #Replace with Azure Key Vault URI, Should be input argument
userName = '******'  #Replace with Azure AD User Name, Prompt or input argument
#--------------------------------------------------------
#endregion

#region Key Vault Connection
#--------------------------------------------------------
# Connection to Azure Key Vault
#--------------------------------------------------------
userCredential = UserPassCredentials(
    userName, getpass.getpass(prompt='Azure AD Password: '******'<Key_Name>', '')
).value  #Replace with correct Key Vault Secret Key Name, Should be input argument
#---------------------------------------------------------
#endregion
Пример #12
0
    def test_user_pass_credentials(self, adal_context):

        adal_context.acquire_token_with_username_password = mock.Mock()

        # Basic with parameters

        mock_proxies = {
            'http': 'http://myproxy:8080',
            'https': 'https://myproxy:8080',
        }

        creds = UserPassCredentials('user',
                                    'pass',
                                    'id',
                                    resource="resource",
                                    timeout=12,
                                    verify=True,
                                    validate_authority=True,
                                    cache=None,
                                    proxies=mock_proxies)

        adal_context.assert_called_with(
            "https://login.microsoftonline.com/common",
            timeout=12,
            verify_ssl=True,
            proxies=mock_proxies,
            validate_authority=True,
            cache=None,
            api_version=None)

        creds.set_token()

        creds._context.acquire_token_with_username_password.assert_called_with(
            "resource", "user", "pass", "id")

        # Using default

        creds = UserPassCredentials(
            'user',
            'pass',
        )

        adal_context.assert_called_with(
            "https://login.microsoftonline.com/common",
            timeout=None,
            verify_ssl=None,
            proxies=None,
            validate_authority=True,
            cache=None,
            api_version=None)

        creds.set_token()

        creds._context.acquire_token_with_username_password.assert_called_with(
            "https://management.core.windows.net/", "user", "pass",
            "04b07795-8ddb-461a-bbee-02f9e1bf7b46")

        # Testing cloud_environment

        creds = UserPassCredentials('user',
                                    'pass',
                                    cloud_environment=AZURE_CHINA_CLOUD)

        adal_context.assert_called_with(
            "https://login.chinacloudapi.cn/common",
            timeout=None,
            verify_ssl=None,
            proxies=None,
            validate_authority=True,
            cache=None,
            api_version=None)
        creds.set_token()
        creds._context.acquire_token_with_username_password.assert_called_with(
            "https://management.core.chinacloudapi.cn/", "user", "pass",
            "04b07795-8ddb-461a-bbee-02f9e1bf7b46")

        # Testing china=True

        creds = UserPassCredentials('user', 'pass', china=True)

        adal_context.assert_called_with(
            "https://login.chinacloudapi.cn/common",
            timeout=None,
            verify_ssl=None,
            proxies=None,
            validate_authority=True,
            cache=None,
            api_version=None)
        creds.set_token()
        creds._context.acquire_token_with_username_password.assert_called_with(
            "https://management.core.chinacloudapi.cn/", "user", "pass",
            "04b07795-8ddb-461a-bbee-02f9e1bf7b46")

        # ADAL boom

        creds._context.acquire_token_with_username_password.side_effect = adal.AdalError(
            "Boom")

        with self.assertRaises(AuthenticationError):
            creds.set_token()
Пример #13
0
 def credentials(self, config: dict) -> UserPassCredentials:
     credential_kwargs = super()._transform_key_to_credential_kwargs(
         config["azure"]["keyvault_keys"][current_filename(__file__)]
     )
     return UserPassCredentials(**credential_kwargs)