def enable_encryption()

in VMEncryption/main/handle.py [0:0]


def enable_encryption():
    hutil.do_parse_context('EnableEncryption')
    # we need to start another subprocess to do it, because the initial process
    # would be killed by the wala in 5 minutes.
    logger.log('Enabling encryption')

    """
    trying to mount the crypted items.
    """
    disk_util = DiskUtil(hutil=hutil, patching=DistroPatcher, logger=logger, encryption_environment=encryption_environment)
    bek_util = BekUtil(disk_util, logger)

    existing_passphrase_file = None
    encryption_config = EncryptionConfig(encryption_environment=encryption_environment, logger=logger)
    config_path_result = disk_util.make_sure_path_exists(encryption_environment.encryption_config_path)

    if config_path_result != CommonVariables.process_success:
        logger.log(msg="azure encryption path creation failed.",
                   level=CommonVariables.ErrorLevel)

    if encryption_config.config_file_exists():
        existing_passphrase_file = bek_util.get_bek_passphrase_file(encryption_config)
        if existing_passphrase_file is not None:
            mount_encrypted_disks(disk_util=disk_util,
                                  bek_util=bek_util,
                                  encryption_config=encryption_config,
                                  passphrase_file=existing_passphrase_file)
        else:
            logger.log(msg="EncryptionConfig is present, but could not get the BEK file.",
                       level=CommonVariables.WarningLevel)
            hutil.redo_last_status()
            exit_without_status_report()

    ps = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    ps_stdout, ps_stderr = ps.communicate()
    if re.search(r"dd.*of=/dev/mapper/osencrypt", ps_stdout):
        logger.log(msg="OS disk encryption already in progress, exiting",
                   level=CommonVariables.WarningLevel)
        exit_without_status_report()

    # handle the re-call scenario.  the re-call would resume?
    # if there's one tag for the next reboot.
    encryption_marker = EncryptionMarkConfig(logger, encryption_environment)

    try:
        protected_settings_str = hutil._context._config['runtimeSettings'][0]['handlerSettings'].get('protectedSettings')
        public_settings_str = hutil._context._config['runtimeSettings'][0]['handlerSettings'].get('publicSettings')

        if isinstance(public_settings_str, basestring):
            public_settings = json.loads(public_settings_str)
        else:
            public_settings = public_settings_str

        if isinstance(protected_settings_str, basestring):
            protected_settings = json.loads(protected_settings_str)
        else:
            protected_settings = protected_settings_str

        extension_parameter = ExtensionParameter(hutil, logger, DistroPatcher, encryption_environment, protected_settings, public_settings)

        kek_secret_id_created = None

        encryption_marker = EncryptionMarkConfig(logger, encryption_environment)
        if encryption_marker.config_file_exists():
            # verify the encryption mark
            logger.log(msg="encryption mark is there, starting daemon.", level=CommonVariables.InfoLevel)
            start_daemon('EnableEncryption')
        else:
            encryption_config = EncryptionConfig(encryption_environment, logger)

            exit_status = None
            if encryption_config.config_file_exists():
                exit_status = {
                    'operation': 'EnableEncryption',
                    'status': CommonVariables.extension_success_status,
                    'status_code': str(CommonVariables.success),
                    'message': encryption_config.get_secret_id()
                }

            hutil.exit_if_same_seq(exit_status)
            hutil.save_seq()

            encryption_config.volume_type = extension_parameter.VolumeType
            encryption_config.commit()

            if encryption_config.config_file_exists() and existing_passphrase_file is not None:
                logger.log(msg="config file exists and passphrase file exists.", level=CommonVariables.WarningLevel)
                encryption_marker = mark_encryption(command=extension_parameter.command,
                                                    volume_type=extension_parameter.VolumeType,
                                                    disk_format_query=extension_parameter.DiskFormatQuery)
                start_daemon('EnableEncryption')
            else:
                """
                creating the secret, the secret would be transferred to a bek volume after the updatevm called in powershell.
                """
                # store the luks passphrase in the secret.
                keyVaultUtil = KeyVaultUtil(logger)

                """
                validate the parameters
                """
                if(extension_parameter.VolumeType is None or
                   not any([extension_parameter.VolumeType.lower() == vt.lower() for vt in CommonVariables.SupportedVolumeTypes])):
                    if encryption_config.config_file_exists():
                        existing_passphrase_file = bek_util.get_bek_passphrase_file(encryption_config)

                        if existing_passphrase_file is None:
                            logger.log("Unsupported volume type specified and BEK volume does not exist, clearing encryption config")
                            encryption_config.clear_config()

                    hutil.do_exit(exit_code=CommonVariables.configuration_error,
                                  operation='EnableEncryption',
                                  status=CommonVariables.extension_error_status,
                                  code=str(CommonVariables.configuration_error),
                                  message='VolumeType "{0}" is not supported'.format(extension_parameter.VolumeType))

                if extension_parameter.command not in [CommonVariables.EnableEncryption, CommonVariables.EnableEncryptionFormat, CommonVariables.EnableEncryptionFormatAll]:
                    hutil.do_exit(exit_code=CommonVariables.configuration_error,
                                  operation='EnableEncryption',
                                  status=CommonVariables.extension_error_status,
                                  code=str(CommonVariables.configuration_error),
                                  message='Command "{0}" is not supported'.format(extension_parameter.command))

                """
                this is the fresh call case
                """
                # handle the passphrase related
                if existing_passphrase_file is None:
                    if extension_parameter.passphrase is None or extension_parameter.passphrase == "":
                        extension_parameter.passphrase = bek_util.generate_passphrase(extension_parameter.KeyEncryptionAlgorithm)
                    else:
                        logger.log(msg="the extension_parameter.passphrase is already defined")

                    # install Python ADAL support if using client certificate authentication
                    if extension_parameter.AADClientCertThumbprint:
                        DistroPatcher.install_adal()

                    kek_secret_id_created = keyVaultUtil.create_kek_secret(Passphrase=extension_parameter.passphrase,
                                                                           KeyVaultURL=extension_parameter.KeyVaultURL,
                                                                           KeyEncryptionKeyURL=extension_parameter.KeyEncryptionKeyURL,
                                                                           AADClientID=extension_parameter.AADClientID,
                                                                           AADClientCertThumbprint=extension_parameter.AADClientCertThumbprint,
                                                                           KeyEncryptionAlgorithm=extension_parameter.KeyEncryptionAlgorithm,
                                                                           AADClientSecret=extension_parameter.AADClientSecret,
                                                                           DiskEncryptionKeyFileName=extension_parameter.DiskEncryptionKeyFileName)

                    if kek_secret_id_created is None:
                        encryption_config.clear_config()
                        hutil.do_exit(exit_code=CommonVariables.create_encryption_secret_failed,
                                      operation='EnableEncryption',
                                      status=CommonVariables.extension_error_status,
                                      code=str(CommonVariables.create_encryption_secret_failed),
                                      message='Enable failed.')
                    else:
                        encryption_config.passphrase_file_name = extension_parameter.DiskEncryptionKeyFileName
                        encryption_config.volume_type = extension_parameter.VolumeType
                        encryption_config.secret_id = kek_secret_id_created
                        encryption_config.secret_seq_num = hutil.get_current_seq()
                        encryption_config.commit()

                        extension_parameter.commit()

                encryption_marker = mark_encryption(command=extension_parameter.command,
                                                    volume_type=extension_parameter.VolumeType,
                                                    disk_format_query=extension_parameter.DiskFormatQuery)

                if kek_secret_id_created:
                    hutil.do_exit(exit_code=0,
                                  operation='EnableEncryption',
                                  status=CommonVariables.extension_success_status,
                                  code=str(CommonVariables.success),
                                  message=str(kek_secret_id_created))
                else:
                    """
                    the enabling called again. the passphrase would be re-used.
                    """
                    hutil.do_exit(exit_code=0,
                                  operation='EnableEncryption',
                                  status=CommonVariables.extension_success_status,
                                  code=str(CommonVariables.encrypttion_already_enabled),
                                  message=str(kek_secret_id_created))
    except Exception as e:
        message = "Failed to enable the extension with error: {0}, stack trace: {1}".format(e, traceback.format_exc())
        logger.log(msg=message, level=CommonVariables.ErrorLevel)
        hutil.do_exit(exit_code=CommonVariables.unknown_error,
                      operation='EnableEncryption',
                      status=CommonVariables.extension_error_status,
                      code=str(CommonVariables.unknown_error),
                      message=message)