Exemple #1
0
def _validate_user_credentials(registry_name, path, resultIndex, username=None, password=None):
    registry, _ = get_registry_by_name(registry_name)
    login_server = registry.login_server  # pylint: disable=no-member

    if username:
        if not password:
            try:
                password = prompt_pass(msg='Password: '******'Please specify both username and password in non-interactive mode.')
        return _obtain_data_from_registry(login_server, path, resultIndex, username, password)

    try:
        cred = acr_credential_show(registry_name)
        username = cred.username
        password = cred.passwords[0].value
        return _obtain_data_from_registry(login_server, path, resultIndex, username, password)
    except:  # pylint: disable=bare-except
        pass

    try:
        username = prompt('Username: '******'Password: '******'Unable to authenticate using admin login credentials or admin is not enabled. ' +
            'Please specify both username and password in non-interactive mode.')
    return _obtain_data_from_registry(login_server, path, resultIndex, username, password)
Exemple #2
0
def _validate_user_credentials(registry_name, path, resultIndex, username=None, password=None):
    registry, _ = get_registry_by_name(registry_name)
    login_server = registry.login_server #pylint: disable=no-member

    if username:
        if not password:
            try:
                password = prompt_pass(msg='Password: '******'Please specify both username and password in non-interactive mode.')
        return _obtain_data_from_registry(login_server, path, resultIndex, username, password)

    try:
        cred = acr_credential_show(registry_name)
        username = cred.username
        password = cred.password
        return _obtain_data_from_registry(login_server, path, resultIndex, username, password)
    except: #pylint: disable=bare-except
        pass

    try:
        username = prompt('Username: '******'Password: '******'Unable to authenticate using admin login credentials or admin is not enabled. ' +
            'Please specify both username and password in non-interactive mode.')
    return _obtain_data_from_registry(login_server, path, resultIndex, username, password)
Exemple #3
0
def _prompt_for_parameters(missing_parameters):
    result = {}
    for param_name in missing_parameters:
        prompt_str = 'Please provide a value for \'{}\' (? for help): '.format(param_name)
        param = missing_parameters[param_name]
        param_type = param.get('type', 'string')
        description = 'Missing description'
        metadata = param.get('metadata', None)
        if metadata is not None:
            description = metadata.get('description', description)
        allowed_values = param.get('allowedValues', None)

        while True:
            if allowed_values is not None:
                ix = prompt_choice_list(prompt_str, allowed_values, help_string=description)
                result[param_name] = allowed_values[ix]
                break
            elif param_type == 'securestring':
                value = prompt_pass(prompt_str, help_string=description)
                result[param_name] = value
            elif param_type == 'int':
                int_value = prompt_int(prompt_str, help_string=description)
                result[param_name] = int_value
                break
            elif param_type == 'bool':
                value = prompt_t_f(prompt_str, help_string=description)
                result[param_name] = value
                break
            else:
                value = prompt(prompt_str, help_string=description)
                result[param_name] = value
            if value:
                break
    return result
Exemple #4
0
def _prompt_for_parameters(missing_parameters):
    result = {}
    for param_name in missing_parameters:
        prompt_str = 'Please provide a value for \'{}\' (? for help): '.format(param_name)
        param = missing_parameters[param_name]
        param_type = param.get('type', 'string')
        description = 'Missing description'
        metadata = param.get('metadata', None)
        if metadata is not None:
            description = metadata.get('description', description)
        allowed_values = param.get('allowedValues', None)

        while True:
            if allowed_values is not None:
                ix = prompt_choice_list(prompt_str, allowed_values, help_string=description)
                result[param_name] = allowed_values[ix]
                break
            elif param_type == 'securestring':
                value = prompt_pass(prompt_str, help_string=description)
            elif param_type == 'int':
                int_value = prompt_int(prompt_str, help_string=description)
                result[param_name] = int_value
                break
            elif param_type == 'bool':
                value = prompt_t_f(prompt_str, help_string=description)
                result[param_name] = value
                break
            else:
                value = prompt(prompt_str, help_string=description)
            if len(value) > 0:
                break
    return {}
Exemple #5
0
def _validate_vm_create_auth(namespace):
    if namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk:
        return

    if len(namespace.admin_username) < 6 or namespace.admin_username.lower(
    ) == 'root':
        # prompt for admin username if inadequate
        from azure.cli.core.prompting import prompt, NoTTYException
        try:
            logger.warning(
                "Cannot use admin username: %s. Admin username should be at "
                "least 6 characters and cannot be 'root'",
                namespace.admin_username)
            namespace.admin_username = prompt('Admin Username: '******'Please specify a valid admin username in non-interactive mode.'
            )

    if not namespace.os_type:
        raise CLIError(
            "Unable to resolve OS type. Specify '--os-type' argument.")

    if not namespace.authentication_type:
        # apply default auth type (password for Windows, ssh for Linux) by examining the OS type
        namespace.authentication_type = 'password' if namespace.os_type == 'windows' else 'ssh'

    if namespace.os_type == 'windows' and namespace.authentication_type == 'ssh':
        raise CLIError('SSH not supported for Windows VMs.')

    # validate proper arguments supplied based on the authentication type
    if namespace.authentication_type == 'password':
        if namespace.ssh_key_value or namespace.ssh_dest_key_path:
            raise ValueError(
                "incorrect usage for authentication-type 'password': "******"[--admin-username USERNAME] --admin-password PASSWORD")

        if not namespace.admin_password:
            # prompt for admin password if not supplied
            from azure.cli.core.prompting import prompt_pass, NoTTYException
            try:
                namespace.admin_password = prompt_pass('Admin Password: '******'Please specify both username and password in non-interactive mode.'
                )

    elif namespace.authentication_type == 'ssh':

        if namespace.admin_password:
            raise ValueError(
                'Admin password cannot be used with SSH authentication type')

        validate_ssh_key(namespace)

        if not namespace.ssh_dest_key_path:
            namespace.ssh_dest_key_path = \
                '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username)
Exemple #6
0
def handle_feedback():
    try:
        print(MESSAGES['intro'])
        score = _prompt_net_promoter_score()
        response_do_well = None
        response_what_changes = None
        if score == 10:
            response_do_well = prompt(MESSAGES['prompt_do_well'])
        else:
            response_what_changes = prompt(MESSAGES['prompt_what_changes'])
        email_address = prompt(MESSAGES['prompt_email_addr'])
        _send_feedback(score, response_what_changes, response_do_well, email_address)
        print(MESSAGES['thanks'])
    except NoTTYException:
        raise CLIError('This command is interactive and no tty available.')
    except (EOFError, KeyboardInterrupt):
        print()
def _get_credentials(registry_name,
                     resource_group_name,
                     username,
                     password,
                     only_refresh_token,
                     repository=None,
                     permission='*'):
    """Try to get AAD authorization tokens or admin user credentials.
    :param str registry_name: The name of container registry
    :param str resource_group_name: The name of resource group
    :param str username: The username used to log into the container registry
    :param str password: The password used to log into the container registry
    :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens
    :param str repository: Repository for which the access token is requested
    :param str permission: The requested permission on the repository, '*' or 'pull'
    """
    registry, _ = get_registry_by_name(registry_name, resource_group_name)
    login_server = registry.login_server

    # 1. if username was specified, verify that password was also specified
    if username:
        if not password:
            try:
                password = prompt_pass(msg='Password: '******'Please specify both username and password in non-interactive mode.')

        return login_server, username, password

    # 2. if we don't yet have credentials, attempt to get a refresh token
    if not password and registry.sku.name in MANAGED_REGISTRY_SKU:
        try:
            username = "******" if only_refresh_token else None
            password = _get_aad_token(login_server, only_refresh_token, repository, permission)
            return login_server, username, password
        except CLIError as e:
            logger.warning("Unable to get AAD authorization tokens with message: %s", str(e))

    # 3. if we still don't have credentials, attempt to get the admin credentials (if enabled)
    if not password:
        try:
            cred = acr_credential_show(registry_name)
            username = cred.username
            password = cred.passwords[0].value
            return login_server, username, password
        except CLIError as e:
            logger.warning("Unable to get admin user credentials with message: %s", str(e))

    # 4. if we still don't have credentials, prompt the user
    if not password:
        try:
            username = prompt('Username: '******'Password: '******'Unable to authenticate using AAD or admin login credentials. ' +
                'Please specify both username and password in non-interactive mode.')
Exemple #8
0
def _config_env_public_azure(_):
    from adal.adal_error import AdalError
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    from azure.mgmt.resource import ResourceManagementClient
    from azure.cli.core._profile import Profile
    # Determine if user logged in
    try:
        list(get_mgmt_service_client(ResourceManagementClient).resources.list())
    except CLIError:
        # Not logged in
        login_successful = False
        while not login_successful:
            method_index = prompt_choice_list(MSG_PROMPT_LOGIN, LOGIN_METHOD_LIST)
            answers['login_index'] = method_index
            answers['login_options'] = str(LOGIN_METHOD_LIST)
            profile = Profile()
            interactive = False
            username = None
            password = None
            service_principal = None
            tenant = None
            if method_index == 0:  # device auth
                interactive = True
            elif method_index == 1:  # username and password
                username = prompt('Username: '******'Password: '******'Service principal: ')
                tenant = prompt('Tenant: ')
                password = prompt_pass(msg='Client secret: ')
            elif method_index == 3:  # skip
                return
            try:
                profile.find_subscriptions_on_login(
                    interactive,
                    username,
                    password,
                    service_principal,
                    tenant)
                login_successful = True
                logger.warning('Login successful!')
            except AdalError as err:
                logger.error('Login error!')
                logger.error(err)
Exemple #9
0
def handle_feedback():
    try:
        print(MESSAGES['intro'])
        score = _prompt_net_promoter_score()
        response_do_well = None
        response_what_changes = None
        if score == 10:
            response_do_well = prompt(MESSAGES['prompt_do_well'])
        else:
            response_what_changes = prompt(MESSAGES['prompt_what_changes'])
        email_address = prompt(MESSAGES['prompt_email_addr'])
        _send_feedback(score, response_what_changes, response_do_well,
                       email_address)
        print(MESSAGES['thanks'])
    except NoTTYException:
        raise CLIError('This command is interactive and no tty available.')
    except (EOFError, KeyboardInterrupt):
        print()
Exemple #10
0
def _prompt_net_promoter_score():
    while True:
        try:
            score = int(prompt(MESSAGES['prompt_how_likely']))
            if 0 <= score <= 10:
                return score
            raise ValueError
        except ValueError:
            logger.warning('Valid values are %s', list(range(11)))
Exemple #11
0
def _prompt_net_promoter_score():
    while True:
        try:
            score = int(prompt(MESSAGES['prompt_how_likely']))
            if 0 <= score <= 10:
                return score
            raise ValueError
        except ValueError:
            logger.warning('Valid values are %s', list(range(11)))
Exemple #12
0
def _config_env_public_azure(_):
    from adal.adal_error import AdalError
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    from azure.mgmt.resource import ResourceManagementClient
    from azure.cli.core._profile import Profile
    # Determine if user logged in
    try:
        list(
            get_mgmt_service_client(ResourceManagementClient).resources.list())
    except CLIError:
        # Not logged in
        login_successful = False
        while not login_successful:
            method_index = prompt_choice_list(MSG_PROMPT_LOGIN,
                                              LOGIN_METHOD_LIST)
            answers['login_index'] = method_index
            answers['login_options'] = str(LOGIN_METHOD_LIST)
            profile = Profile()
            interactive = False
            username = None
            password = None
            service_principal = None
            tenant = None
            if method_index == 0:  # device auth
                interactive = True
            elif method_index == 1:  # username and password
                username = prompt('Username: '******'Password: '******'Service principal: ')
                tenant = prompt('Tenant: ')
                password = prompt_pass(msg='Client secret: ')
            elif method_index == 3:  # skip
                return
            try:
                profile.find_subscriptions_on_login(interactive, username,
                                                    password,
                                                    service_principal, tenant)
                login_successful = True
                logger.warning('Login successful!')
            except AdalError as err:
                logger.error('Login error!')
                logger.error(err)
Exemple #13
0
def _validate_user_credentials(registry_name,
                               resource_group_name,
                               path,
                               username=None,
                               password=None,
                               repository=None,
                               result_index=None,
                               request_method=None):
    registry, _ = get_registry_by_name(registry_name, resource_group_name)
    sku_tier = registry.sku.tier
    login_server = registry.login_server

    # 1. if username was specified, verify that password was also specified
    if username:
        if not password:
            try:
                password = prompt_pass(msg='Password: '******'Please specify both username and password in non-interactive mode.')
        return request_method(login_server, path, username, password, result_index)

    if sku_tier == SkuTier.managed.value:
        # 2. if we don't yet have credentials, attempt to get an access token
        try:
            managed_registry_validation(registry_name, resource_group_name)
            access_token = get_login_access_token(login_server, repository)
            return request_method(login_server, path, None, access_token, result_index)
        except NotFound as e:
            raise CLIError(str(e))
        except Unauthorized as e:
            logger.warning("Unable to authenticate using AAD tokens: %s", str(e))
        except Exception as e:  # pylint: disable=broad-except
            logger.warning("AAD authentication failed with message: %s", str(e))

    # 3. if we still don't have credentials, attempt to get the admin credentials (if enabled)
    try:
        cred = acr_credential_show(registry_name)
        username = cred.username
        password = cred.passwords[0].value
        return request_method(login_server, path, username, password, result_index)
    except NotFound as e:
        raise CLIError(str(e))
    except Unauthorized as e:
        logger.warning("Unable to authenticate using admin login credentials: %s", str(e))
    except Exception as e:  # pylint: disable=broad-except
        logger.warning("Admin user authentication failed with message: %s", str(e))

    # 4. if we still don't have credentials, prompt the user
    try:
        username = prompt('Username: '******'Password: '******'Unable to authenticate using AAD tokens or admin login credentials. ' +
            'Please specify both username and password in non-interactive mode.')
    return request_method(login_server, path, username, password, result_index)
def acr_login(registry_name, resource_group_name=None, username=None, password=None):
    """Login to a container registry through Docker.
    :param str registry_name: The name of container registry
    :param str resource_group_name: The name of resource group
    :param str username: The username used to log into the container registry
    :param str password: The password used to log into the container registry
    """
    try:
        call(["docker", "ps"], stdout=PIPE, stderr=PIPE)
    except:
        raise CLIError("Please verify whether docker is installed and running properly")

    registry, _ = get_registry_by_name(registry_name, resource_group_name)
    sku_tier = registry.sku.tier
    login_server = registry.login_server

    # 1. if username was specified, verify that password was also specified
    if username and not password:
        try:
            password = prompt_pass(msg='Password: '******'Please specify both username and password in non-interactive mode.')

    if sku_tier == SkuTier.managed.value:
        # 2. if we don't yet have credentials, attempt to get a refresh token
        if not password:
            try:
                username = "******"
                password = get_login_refresh_token(login_server)
            except Exception as e:  # pylint: disable=broad-except
                logger.warning("AAD authentication failed with message: %s", str(e))

    # 3. if we still don't have credentials, attempt to get the admin credentials (if enabled)
    if not password:
        try:
            cred = acr_credential_show(registry_name)
            username = cred.username
            password = cred.passwords[0].value
        except Exception as e:  # pylint: disable=broad-except
            logger.warning("Admin user authentication failed with message: %s", str(e))

    # 4. if we still don't have credentials, prompt the user
    if not password:
        try:
            username = prompt('Username: '******'Password: '******'Unable to authenticate using AAD or admin login credentials. ' +
                'Please specify both username and password in non-interactive mode.')

    call(["docker", "login",
          "--username", username,
          "--password", password,
          login_server])
Exemple #15
0
def add_reference(service_name, target_group, target_name, reference_name,
                  env_variables, namespace_name, reference_type):
    """
    Adds a references to an Azure resource
    """
    instance_type = None
    created_variables = []

    # If target_group and target_name are not set
    # it means we are dealing with a generic reference
    if reference_type == 'custom' and not target_group and not target_name:
        instance_type = 'Generic'
        if not env_variables:
            raise CLIError('Environment variables were not provided')
        dict_vars = _get_dictionary(env_variables)
        created_variables = _create_custom_reference(service_name,
                                                     reference_name, dict_vars,
                                                     namespace_name)
    else:
        instance, client = get_reference_type(target_group, target_name,
                                              reference_type)
        instance_type = instance.type
        if instance_type == 'Microsoft.DocumentDB/databaseAccounts':
            results = client.list_connection_strings(target_group, target_name)
            if len(results.connection_strings) <= 0:
                raise CLIError('No connection strings found')
            connection_string = results.connection_strings[0].connection_string
            created_variables = create_connection_string_reference(
                service_name, reference_name, connection_string,
                namespace_name)
        elif instance_type == 'Microsoft.Sql/servers':
            sql_admin_login = instance.administrator_login
            if not sql_admin_login:
                sql_admin_login = prompt('Administrator login:'******'Password:'******'Microsoft.ServiceBus':
            connection_string = instance.list_keys(
                target_group, target_name,
                'RootManageSharedAccessKey').primary_connection_string
            created_variables = create_connection_string_reference(
                service_name, reference_name, connection_string)
        else:
            raise CLIError('Could not determine the reference type')

    project_settings = settings.Project()
    project_settings.add_reference(service_name, reference_name, instance_type)
    return created_variables, instance_type
Exemple #16
0
def _validate_vm_create_auth(namespace):
    if namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk:
        return

    if len(namespace.admin_username) < 6 or namespace.admin_username.lower() == 'root':
        # prompt for admin username if inadequate
        from azure.cli.core.prompting import prompt, NoTTYException
        try:
            logger.warning("Cannot use admin username: %s. Admin username should be at "
                           "least 6 characters and cannot be 'root'", namespace.admin_username)
            namespace.admin_username = prompt('Admin Username: '******'Please specify a valid admin username in non-interactive mode.')

    if not namespace.os_type:
        raise CLIError("Unable to resolve OS type. Specify '--os-type' argument.")

    if not namespace.authentication_type:
        # apply default auth type (password for Windows, ssh for Linux) by examining the OS type
        namespace.authentication_type = 'password' if namespace.os_type == 'windows' else 'ssh'

    if namespace.os_type == 'windows' and namespace.authentication_type == 'ssh':
        raise CLIError('SSH not supported for Windows VMs.')

    # validate proper arguments supplied based on the authentication type
    if namespace.authentication_type == 'password':
        if namespace.ssh_key_value or namespace.ssh_dest_key_path:
            raise ValueError(
                "incorrect usage for authentication-type 'password': "******"[--admin-username USERNAME] --admin-password PASSWORD")

        if not namespace.admin_password:
            # prompt for admin password if not supplied
            from azure.cli.core.prompting import prompt_pass, NoTTYException
            try:
                namespace.admin_password = prompt_pass('Admin Password: '******'Please specify both username and password in non-interactive mode.')

    elif namespace.authentication_type == 'ssh':

        if namespace.admin_password:
            raise ValueError('Admin password cannot be used with SSH authentication type')

        validate_ssh_key(namespace)

        if not namespace.ssh_dest_key_path:
            namespace.ssh_dest_key_path = \
                '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username)
Exemple #17
0
def _get_credentials(registry_name,
                     resource_group_name,
                     username,
                     password,
                     only_refresh_token,
                     repository=None,
                     permission='*'):
    """Try to get AAD authorization tokens or admin user credentials.
    :param str registry_name: The name of container registry
    :param str resource_group_name: The name of resource group
    :param str username: The username used to log into the container registry
    :param str password: The password used to log into the container registry
    :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens
    :param str repository: Repository for which the access token is requested
    :param str permission: The requested permission on the repository, '*' or 'pull'
    """
    registry, _ = get_registry_by_name(registry_name, resource_group_name)
    login_server = registry.login_server

    # 1. if username was specified, verify that password was also specified
    if username:
        if not password:
            try:
                password = prompt_pass(msg='Password: '******'Please specify both username and password in non-interactive mode.'
                )

        return login_server, username, password

    # 2. if we don't yet have credentials, attempt to get a refresh token
    if not password and registry.sku.name in MANAGED_REGISTRY_SKU:
        try:
            username = "******" if only_refresh_token else None
            password = _get_aad_token(login_server, only_refresh_token,
                                      repository, permission)
            return login_server, username, password
        except CLIError as e:
            logger.warning(
                "Unable to get AAD authorization tokens with message: %s",
                str(e))

    # 3. if we still don't have credentials, attempt to get the admin credentials (if enabled)
    if not password:
        try:
            cred = acr_credential_show(registry_name)
            username = cred.username
            password = cred.passwords[0].value
            return login_server, username, password
        except CLIError as e:
            logger.warning(
                "Unable to get admin user credentials with message: %s",
                str(e))

    # 4. if we still don't have credentials, prompt the user
    if not password:
        try:
            username = prompt('Username: '******'Password: '******'Unable to authenticate using AAD or admin login credentials. '
                +
                'Please specify both username and password in non-interactive mode.'
            )