如何创建适用于 Windows 的 Guest Configuration 策略How to create Guest Configuration policies for Windows

在创建自定义策略之前,最好是先阅读 Azure Policy Guest Configuration 页中的概念概述信息。Before creating custom policies, it's a good idea to read the conceptual overview information at the page Azure Policy Guest Configuration.

若要了解如何创建适用于 Linux 的 Guest Configuration 策略,请参阅如何创建适用于 Linux 的 Guest Configuration 策略To learn about creating Guest Configuration policies for Linux, see the page How to create Guest Configuration policies for Linux

审核 Windows 时,Guest Configuration 使用 Desired State Configuration (DSC) 资源模块创建配置文件。When auditing Windows, Guest Configuration uses a Desired State Configuration (DSC) resource module to create the configuration file. DSC 配置定义计算机的应有状态。The DSC configuration defines the condition that the machine should be in. 如果配置评估失败,则会触发策略效应 auditIfNotExists,并将计算机视为不合规。 If the evaluation of the configuration fails, the policy effect auditIfNotExists is triggered and the machine is considered non-compliant.

Azure Policy Guest Configuration 只可用于审核计算机内部的设置。Azure Policy Guest Configuration can only be used to audit settings inside machines. 目前尚未提供修正计算机内部设置的功能。Remediation of settings inside machines isn't yet available.

使用以下操作创建自己的配置用于验证 Azure 或非 Azure 计算机的状态。Use the following actions to create your own configuration for validating the state of an Azure or non-Azure machine.

Important

使用 Guest Configuration 的自定义策略是一项预览版功能。Custom policies with Guest Configuration is a Preview feature.

在 Azure 虚拟机中执行审核需要 Guest Configuration 扩展。The Guest Configuration extension is required to perform audits in Azure virtual machines. 若要在所有 Windows 计算机上大规模部署该扩展,请分配以下策略定义:To deploy the extension at scale across all Windows machines, assign the following policy definitions:

安装 PowerShell 模块Install the PowerShell module

在 PowerShell 中使用 Guest Configuration 模块创建 Guest Configuration 项目、自动测试项目、创建策略定义和发布策略的过程完全可自动化。Creating a Guest Configuration artifact, automated testing of the artifact, creating a policy definition, and publishing the policy, is entirely automatable using the Guest Configuration module in PowerShell. 该模块可以安装在运行 Windows、macOS 或 Linux 并装有 PowerShell 6.2 或更高版本的计算机本地,或者与 Azure PowerShell Core Docker 映像一起安装。The module can be installed on a machine running Windows, macOS, or Linux with PowerShell 6.2 or later running locally, or with the Azure PowerShell Core Docker image.

Note

Linux 尚不支持配置编译。Compilation of configurations is not yet supported on Linux.

基本要求Base requirements

可安装该模块的操作系统:Operating Systems where the module can be installed:

  • LinuxLinux
  • macOSmacOS
  • WindowsWindows

Guest Configuration 资源模块需要以下软件:The Guest Configuration resource module requires the following software:

  • PowerShell 6.2 或更高版本。PowerShell 6.2 or later. 若尚未安装,请遵循这些说明If it isn't yet installed, follow these instructions.
  • Azure PowerShell 1.5.0 或更高版本。Azure PowerShell 1.5.0 or higher. 若尚未安装,请遵循这些说明If it isn't yet installed, follow these instructions.
    • 只有 AZ 模块“Az.Accounts”和“Az.Resources”是必需的。Only the AZ modules 'Az.Accounts' and 'Az.Resources' are required.

安装模块Install the module

若要在 PowerShell 中安装 GuestConfiguration 模块:To install the GuestConfiguration module in PowerShell:

  1. 在 PowerShell 提示符下,运行以下命令:From a PowerShell prompt, run the following command:

    # Install the Guest Configuration DSC resource module from PowerShell Gallery
    Install-Module -Name GuestConfiguration
    
  2. 验证是否已导入该模块:Validate that the module has been imported:

    # Get a list of commands for the imported GuestConfiguration module
    Get-Command -Module 'GuestConfiguration'
    

适用于 Windows 的 Guest Configuration 项目和策略Guest Configuration artifacts and policy for Windows

Guest Configuration 使用 PowerShell Desired State Configuration 作为语言抽象来编写要在 Windows 中审核的内容。Guest Configuration uses PowerShell Desired State Configuration as a language abstraction for writing what to audit in Windows. 代理将加载 PowerShell 6.2 的独立实例,因此,在 Windows PowerShell 5.1 中使用 PowerShell DSC 不会产生冲突,并且不要求预先安装 PowerShell 6.2 或更高版本。The agent loads a standalone instance of PowerShell 6.2, so there isn't conflict with usage of PowerShell DSC in Windows PowerShell 5.1, and there's no requirement to pre-install PowerShell 6.2 or later.

有关 DSC 的概念和术语概述,请参阅 PowerShell DSC 概述For an overview of DSC concepts and terminology, see PowerShell DSC Overview.

Guest Configuration 模块与 Windows PowerShell DSC 模块的差别How Guest Configuration modules differ from Windows PowerShell DSC modules

当 Guest Configuration 审核计算机时:When Guest Configuration audits a machine:

  1. 代理首先运行 Test-TargetResource 以确定配置是否处于正确的状态。The agent first runs Test-TargetResource to determine if the configuration is in the correct state.
  2. 该函数返回的布尔值确定来宾分配的 Azure 资源管理器状态是合规还是不合规。The boolean value returned by the function determines if the Azure Resource Manager status for the Guest Assignment should be Compliant/Not-Compliant.
  3. 提供程序会运行 Get-TargetResource 以返回每项设置的当前状态。因此,会获得有关计算机为何不合规的详细信息,以及用于确认当前状态是否合规的详细信息。The provider runs Get-TargetResource to return the current state of each setting so details are available both about why a machine isn't compliant and to confirm that the current state is compliant.

Get-TargetResource 要求Get-TargetResource requirements

函数 Get-TargetResource 对 Guest Configuration 提出了特殊的要求,而 Windows Desired State Configuration 并不需要满足这些要求。The function Get-TargetResource has special requirements for Guest Configuration that haven't been needed for Windows Desired State Configuration.

  • 返回的哈希表必须包含名为 Reasons 的属性。The hashtable that is returned must include a property named Reasons.
  • Reasons 属性必须是数组。The Reasons property must be an array.
  • 该数组中的每个项应是包含名为 CodePhrase 的键的哈希表。Each item in the array should be a hashtable with keys named Code and Phrase.

当计算机不合规时,服务使用 Reasons 属性来标准化信息的呈现方式。The Reasons property is used by the service to standardize how information is presented when a machine is out of compliance. 可将 Reasons 中的每个项视为资源不合规的一个“原因”。You can think of each item in Reasons as a "reason" that the resource isn't compliant. 该属性之所以是数组,是因为资源可能出于多种原因而不合规。The property is an array because a resource could be out of compliance for more than one reason.

服务需要 CodePhrase 属性。The properties Code and Phrase are expected by the service. 创作自定义资源时,请将要作为资源不合规原因显示的文本(通常是 stdout)设置为 Phrase 的值。When authoring a custom resource, set the text (typically stdout) you would like to show as the reason the resource isn't compliant as the value for Phrase. Code 具有特定的格式要求,因此报告可以清楚地显示有关用于执行审核的资源的信息。Code has specific formatting requirements so reporting can clearly display information about the resource used to do the audit. 此解决方案使得 Guest Configuration 可扩展。This solution makes Guest Configuration extensible. 只要能够为 Phrase 属性返回字符串值形式的输出,就可以运行任何命令。Any command could be run as long as the output can be returned as a string value for the Phrase property.

  • Code(字符串):资源的名称,重复该名称,后接一个不包含空格的短名称(作为原因标识符)。Code (string): The name of the resource, repeated, and then a short name with no spaces as an identifier for the reason. 这三个值应以冒号分隔,且不包含空格。These three values should be colon-delimited with no spaces.
    • 例如 registry:registry:keynotpresentAn example would be registry:registry:keynotpresent
  • Phrase(字符串):用户可读的文本,用于解释设置不合规的原因。Phrase (string): Human-readable text to explain why the setting isn't compliant.
    • 例如 The registry key $key is not present on the machine.An example would be The registry key $key is not present on the machine.
$reasons = @()
$reasons += @{
  Code = 'Name:Name:ReasonIdentifer'
  Phrase = 'Explain why the setting is not compliant'
}
return @{
    reasons = $reasons
}

还必须将 Reasons 属性添加到嵌入类形式的资源的架构 MOF。The Reasons property must also be added to the schema MOF for the resource as an embedded class.

[ClassVersion("1.0.0.0")] 
class Reason
{
    [Read] String Phrase;
    [Read] String Code;
};

[ClassVersion("1.0.0.0"), FriendlyName("ResourceName")]
class ResourceName : OMI_BaseResource
{
    [Key, Description("Example description")] String Example;
    [Read, EmbeddedInstance("Reason")] String Reasons[];
};

配置要求Configuration requirements

自定义配置的名称必须在每个位置保持一致。The name of the custom configuration must be consistent everywhere. 内容包的 .zip 文件名称、MOF 文件中的配置名称,以及资源管理器模板中的来宾分配名称必须相同。The name of the .zip file for the content package, the configuration name in the MOF file, and the guest assignment name in the Resource Manager template, must be the same.

搭建 Guest Configuration 项目Scaffolding a Guest Configuration project

想要更快入门并参考示例代码的开发人员可以安装一个名为“Guest Configuration 项目”的社区项目。Developers who would like to accelerate the process of getting started and work from sample code can install a community project named Guest Configuration Project. 该项目将安装 Plaster PowerShell 模块的模板。The project installs a template for the Plaster PowerShell module. 此工具可用于搭建项目(包括工作配置和示例资源)以及一组 Pester 测试用于验证项目。This tool can be used to scaffold a project including a working configuration and sample resource, and a set of Pester tests to validate the project. 该模板还包含适用于 Visual Studio Code 的任务运行程序,可自动生成和验证 Guest Configuration 包。The template also includes task runners for Visual Studio Code to automate building and validating the Guest Configuration package. 有关详细信息,请参阅 GitHub 项目 Guest Configuration 项目For more information, see the GitHub project Guest Configuration Project.

有关处理配置的一般详细信息,请参阅编写、编译和应用配置For more information about working with configurations in general, see Write, Compile, and Apply a Configuration.

Guest Configuration 项目的预期内容Expected contents of a Guest Configuration artifact

Guest Configuration 使用已完成的包来创建 Azure Policy 定义。The completed package is used by Guest Configuration to create the Azure Policy definitions. 该包中包括:The package consists of:

  • 用作 MOF 的已编译 DSC 配置The compiled DSC configuration as a MOF
  • 模块文件夹Modules folder
    • GuestConfiguration 模块GuestConfiguration module
    • DscNativeResources 模块DscNativeResources module
    • (Windows) MOF 所需的 DSC 资源模块(Windows) DSC resource modules required by the MOF

PowerShell cmdlet 可帮助创建包。PowerShell cmdlets assist in creating the package. 不需要根级别文件夹或版本文件夹。No root level folder or version folder is required. 包格式必须是 .zip 文件。The package format must be a .zip file.

存储 Guest Configuration 项目Storing Guest Configuration artifacts

.zip 包必须存储在可由托管虚拟机访问的位置。The .zip package must be stored in a location that is accessible by the managed virtual machines. 例如,存储在 GitHub 存储库、Azure 存储库或 Azure 存储中。Examples include GitHub repositories, an Azure Repo, or Azure storage. 如果你不希望公开该包,可以在 URL 中包含 SAS 令牌If you prefer to not make the package public, you can include a SAS token in the URL. 还可以针对专用网络中的计算机实施服务终结点,不过,这种配置仅适用于访问包,而不适用于与服务之间的通信。You could also implement service endpoint for machines in a private network, although this configuration applies only to accessing the package and not communicating with the service.

逐步创建适用于 Windows 的自定义 Guest Configuration 审核策略Step by step, creating a custom Guest Configuration audit policy for Windows

创建 DSC 配置以审核设置。Create a DSC configuration to audit settings. 以下 PowerShell 脚本示例创建名为 AuditBitLocker 的配置,导入 PsDscResources 资源模块,然后使用 Service 资源来审核正在运行的服务。 The following PowerShell script example creates a configuration named AuditBitLocker, imports the PsDscResources resource module, and uses the Service resource to audit for a running service. 可以从 Windows 或 macOS 计算机执行配置脚本。The configuration script can be executed from a Windows or macOS machine.

# Define the DSC configuration and import GuestConfiguration
Configuration AuditBitLocker
{
    Import-DscResource -ModuleName 'PSDscResources'

    Node AuditBitlocker {
      Service 'Ensure BitLocker service is present and running'
      {
          Name = 'BDESVC'
          Ensure = 'Present'
          State = 'Running'
      }
    }
}

# Compile the configuration to create the MOF files
AuditBitLocker ./Config

使用 config.ps1 名称将此文件保存在项目文件夹中。Save this file with name config.ps1 in the project folder. 通过在终端中执行 ./config.ps1,在 PowerShell 中运行它。Run it in PowerShell by executing ./config.ps1 in the terminal. 随即将创建新的 mof 文件。A new mof file will be created.

从技术上讲,Node AuditBitlocker 命令不是必需的,但它会生成名为 AuditBitlocker.mof 的文件,而不是默认文件 localhost.mofThe Node AuditBitlocker command isn't technically required but it produces a file named AuditBitlocker.mof rather than the default, localhost.mof. 使 .mof 文件名遵循配置可以在大规模操作时轻松组织许多文件。Having the .mof file name follow the configuration makes it easy to organize many files when operating at scale.

编译 MOF 后,必须将支持文件打包在一起。Once the MOF is compiled, the supporting files must be packaged together. Guest Configuration 使用已完成的包来创建 Azure Policy 定义。The completed package is used by Guest Configuration to create the Azure Policy definitions.

可以使用 New-GuestConfigurationPackage cmdlet 创建该包。The New-GuestConfigurationPackage cmdlet creates the package. 配置所需的模块必须在 $Env:PSModulePath 中提供。Modules that are needed by the configuration must be in available in $Env:PSModulePath. 创建 Windows 内容时 New-GuestConfigurationPackage cmdlet 的参数:Parameters of the New-GuestConfigurationPackage cmdlet when creating Windows content:

  • 名称:Guest Configuration 包名称。Name: Guest Configuration package name.
  • 配置:编译的 DSC 配置文档的完整路径。Configuration: Compiled DSC configuration document full path.
  • 路径:输出文件夹路径。Path: Output folder path. 此参数是可选的。This parameter is optional. 如果未指定,将在当前目录中创建包。If not specified, the package is created in current directory.

运行以下命令,使用上一步骤中提供的配置创建一个包:Run the following command to create a package using the configuration given in the previous step:

New-GuestConfigurationPackage `
  -Name 'AuditBitlocker' `
  -Configuration './Config/AuditBitlocker.mof'

创建配置包之后、将其发布到 Azure 之前,可以从工作站或 CI/CD 环境测试该包。After creating the Configuration package but before publishing it to Azure, you can test the package from your workstation or CI/CD environment. GuestConfiguration cmdlet Test-GuestConfigurationPackage 在开发环境中包含 Azure 计算机中所用的同一代理。The GuestConfiguration cmdlet Test-GuestConfigurationPackage includes the same agent in your development environment as is used inside Azure machines. 使用此解决方案可以在发布到计费的云环境之前,在本地执行集成测试。Using this solution, you can do integration testing locally before releasing to billed cloud environments.

由于该代理实际上评估的是本地环境,因此,在大多数情况下,需要在你计划审核的同一个 OS 平台上运行 Test- cmdlet。Since the agent is actually evaluating the local environment, in most cases you need to run the Test- cmdlet on the same OS platform as you plan to audit. 该测试将仅使用内容包中包含的模块。The test will only use modules that are included in the content package.

Test-GuestConfigurationPackage cmdlet 的参数:Parameters of the Test-GuestConfigurationPackage cmdlet:

  • 名称:Guest Configuration 策略名称。Name: Guest Configuration policy name.
  • 参数:以哈希表格式提供的策略参数。Parameter: Policy parameters provided in hashtable format.
  • 路径:Guest Configuration 包的完整路径。Path: Full path of the Guest Configuration package.

运行以下命令来测试上一步骤创建的包:Run the following command to test the package created by the previous step:

Test-GuestConfigurationPackage `
  -Path ./AuditBitlocker.zip

该 cmdlet 还支持来自 PowerShell 管道的输入。The cmdlet also supports input from the PowerShell pipeline. 通过管道将 New-GuestConfigurationPackage cmdlet 的输出传送到 Test-GuestConfigurationPackage cmdlet。Pipe the output of New-GuestConfigurationPackage cmdlet to the Test-GuestConfigurationPackage cmdlet.

New-GuestConfigurationPackage -Name AuditBitlocker -Configuration ./Config/AuditBitlocker.mof | Test-GuestConfigurationPackage

下一步是将文件发布到 Blob 存储。The next step is to publish the file to blob storage. 以下脚本包含一个可用于自动完成此任务的函数。The script below contains a function you can use to automate this task. publish 函数中使用的命令需要 Az.Storage 模块。The commands used in the publish function require the Az.Storage module.

function publish {
    param(
    [Parameter(Mandatory=$true)]
    $resourceGroup,
    [Parameter(Mandatory=$true)]
    $storageAccountName,
    [Parameter(Mandatory=$true)]
    $storageContainerName,
    [Parameter(Mandatory=$true)]
    $filePath,
    [Parameter(Mandatory=$true)]
    $blobName
    )

    # Get Storage Context
    $Context = Get-AzStorageAccount -ResourceGroupName $resourceGroup `
        -Name $storageAccountName | `
        ForEach-Object { $_.Context }

    # Upload file
    $Blob = Set-AzStorageBlobContent -Context $Context `
        -Container $storageContainerName `
        -File $filePath `
        -Blob $blobName `
        -Force

    # Get url with SAS token
    $StartTime = (Get-Date)
    $ExpiryTime = $StartTime.AddYears('3')  # THREE YEAR EXPIRATION
    $SAS = New-AzStorageBlobSASToken -Context $Context `
        -Container $storageContainerName `
        -Blob $blobName `
        -StartTime $StartTime `
        -ExpiryTime $ExpiryTime `
        -Permission rl `
        -FullUri

    # Output
    return $SAS
}

# replace the $storageAccountName value below, it must be globally unique
$resourceGroup        = 'policyfiles'
$storageAccountName   = 'youraccountname'
$storageContainerName = 'artifacts'

$uri = publish `
  -resourceGroup $resourceGroup `
  -storageAccountName $storageAccountName `
  -storageContainerName $storageContainerName `
  -filePath ./AuditBitlocker.zip `
  -blobName 'AuditBitlocker'

创建并上传 Guest Configuration 自定义策略包后,创建 Guest Configuration 策略定义。Once a Guest Configuration custom policy package has been created and uploaded, create the Guest Configuration policy definition. New-GuestConfigurationPolicy cmdlet 采用自定义策略包并创建策略定义。The New-GuestConfigurationPolicy cmdlet takes a custom policy package and creates a policy definition.

New-GuestConfigurationPolicy cmdlet 的参数:Parameters of the New-GuestConfigurationPolicy cmdlet:

  • ContentUri:Guest Configuration 内容包的公共 http(s) URI。ContentUri: Public http(s) uri of Guest Configuration content package.
  • DisplayName:策略显示名称。DisplayName: Policy display name.
  • 说明:策略说明。Description: Policy description.
  • 参数:以哈希表格式提供的策略参数。Parameter: Policy parameters provided in hashtable format.
  • 版本:策略版本。Version: Policy version.
  • 路径:要在其中创建策略定义的目标路径。Path: Destination path where policy definitions are created.
  • Platform:Guest Configuration 策略和内容包的目标平台 (Windows/Linux)。Platform: Target platform (Windows/Linux) for Guest Configuration policy and content package.

以下示例在自定义策略包的指定路径中创建策略定义:The following example creates the policy definitions in a specified path from a custom policy package:

New-GuestConfigurationPolicy `
    -ContentUri 'https://storageaccountname.blob.core.chinacloudapi.cn/packages/AuditBitLocker.zip?st=2019-07-01T00%3A00%3A00Z&se=2024-07-01T00%3A00%3A00Z&sp=rl&sv=2018-03-28&sr=b&sig=JdUf4nOCo8fvuflOoX%2FnGo4sXqVfP5BYXHzTl3%2BovJo%3D' `
    -DisplayName 'Audit BitLocker Service.' `
    -Description 'Audit if BitLocker is not enabled on Windows machine.' `
    -Path './policies' `
    -Platform 'Windows' `
    -Version 1.0.0 `
    -Verbose

New-GuestConfigurationPolicy 创建以下文件:The following files are created by New-GuestConfigurationPolicy:

  • auditIfNotExists.jsonauditIfNotExists.json
  • deployIfNotExists.jsondeployIfNotExists.json
  • Initiative.jsonInitiative.json

cmdlet 输出中会返回一个对象,其中包含策略文件的计划显示名称和路径。The cmdlet output returns an object containing the initiative display name and path of the policy files.

最后,使用 Publish-GuestConfigurationPolicy cmdlet 发布策略定义。Finally, publish the policy definitions using the Publish-GuestConfigurationPolicy cmdlet. 该 cmdlet 仅包含指向 New-GuestConfigurationPolicy 所创建的 JSON 文件的位置的 Path 参数。The cmdlet only has the Path parameter that points to the location of the JSON files created by New-GuestConfigurationPolicy.

若要运行 Publish 命令,需要拥有在 Azure 中创建策略的访问权限。To run the Publish command, you need access to create policies in Azure. Azure Policy 概述页中阐述了具体的授权要求。The specific authorization requirements are documented in the Azure Policy Overview page. 最佳内置角色是“资源策略参与者”。The best built-in role is Resource Policy Contributor.

Publish-GuestConfigurationPolicy -Path '.\policyDefinitions'

Publish-GuestConfigurationPolicy cmdlet 接受源自 PowerShell 管道的路径。The Publish-GuestConfigurationPolicy cmdlet accepts the path from the PowerShell pipeline. 此功能意味着,可以在一组管道命令中创建并发布策略文件。This feature means you can create the policy files and publish them in a single set of piped commands.

New-GuestConfigurationPolicy `
 -ContentUri 'https://storageaccountname.blob.core.chinacloudapi.cn/packages/AuditBitLocker.zip?st=2019-07-01T00%3A00%3A00Z&se=2024-07-01T00%3A00%3A00Z&sp=rl&sv=2018-03-28&sr=b&sig=JdUf4nOCo8fvuflOoX%2FnGo4sXqVfP5BYXHzTl3%2BovJo%3D' `
  -DisplayName 'Audit BitLocker service.' `
  -Description 'Audit if the BitLocker service is not enabled on Windows machine.' `
  -Path './policies' `
 | Publish-GuestConfigurationPolicy

在 Azure 中创建策略后,最后一步是分配计划。With the policy created in Azure, the last step is to assign the initiative. 请参阅如何使用门户Azure CLIAzure PowerShell 分配计划。See how to assign the initiative with Portal, Azure CLI, and Azure PowerShell.

Important

始终必须使用结合了 AuditIfNotExistsDeployIfNotExists 策略的计划来分配 Guest Configuration 策略。Guest Configuration policies must always be assigned using the initiative that combines the AuditIfNotExists and DeployIfNotExists policies. 如果仅分配 AuditIfNotExists 策略,则不会部署必备组件,并且该策略始终显示“0”个服务器合规。If only the AuditIfNotExists policy is assigned, the prerequisites aren't deployed and the policy always shows that '0' servers are compliant.

分配包含 DeployIfNotExists 效应的策略定义需要额外的访问权限级别。Assigning an policy definition with DeployIfNotExists effect requires an additional level of access. 若要授予最低特权,可以创建一个用于扩展“资源策略参与者”的自定义角色定义。To grant the least privilege, you can create a custom role definition that extends Resource Policy Contributor. 以下示例创建名为“资源策略参与者 DINE”的、拥有“Microsoft.Authorization/roleAssignments/write”权限的角色。The example below creates a role named Resource Policy Contributor DINE with the additional permission Microsoft.Authorization/roleAssignments/write.

$subscriptionid = '00000000-0000-0000-0000-000000000000'
$role = Get-AzRoleDefinition "Resource Policy Contributor"
$role.Id = $null
$role.Name = "Resource Policy Contributor DINE"
$role.Description = "Can assign Policies that require remediation."
$role.Actions.Clear()
$role.Actions.Add("Microsoft.Authorization/roleAssignments/write")
$role.AssignableScopes.Clear()
$role.AssignableScopes.Add("/subscriptions/$subscriptionid")
New-AzRoleDefinition -Role $role

使用自定义 Guest Configuration 策略中的参数Using parameters in custom Guest Configuration policies

Guest Configuration 支持在运行时重写配置的属性。Guest Configuration supports overriding properties of a Configuration at run time. 此功能意味着,不一定要将包中 MOF 文件中的值视为静态值。This feature means that the values in the MOF file in the package don't have to be considered static. 重写值是通过 Azure Policy 提供的,不会影响配置的创作或编译方式。The override values are provided through Azure Policy and don't impact how the Configurations are authored or compiled.

cmdlet New-GuestConfigurationPolicyTest-GuestConfigurationPolicyPackage 包含名为 Parameters 的参数。The cmdlets New-GuestConfigurationPolicy and Test-GuestConfigurationPolicyPackage include a parameter named Parameters. 此参数采用一个包含有关每个参数的所有详细信息的哈希表定义,并创建每个文件的所需节用于定义 Azure Policy。This parameter takes a hashtable definition including all details about each parameter and creates the required sections of each file used for the Azure Policy definition.

以下示例创建一个策略定义用于审核服务,其中,用户在分配策略时可从列表中进行选择。The following example creates a policy definition to audit a service, where the user selects from a list at the time of policy assignment.

$PolicyParameterInfo = @(
    @{
        Name = 'ServiceName'                                            # Policy parameter name (mandatory)
        DisplayName = 'windows service name.'                           # Policy parameter display name (mandatory)
        Description = "Name of the windows service to be audited."      # Policy parameter description (optional)
        ResourceType = "Service"                                        # DSC configuration resource type (mandatory)
        ResourceId = 'windowsService'                                   # DSC configuration resource property name (mandatory)
        ResourcePropertyName = "Name"                                   # DSC configuration resource property name (mandatory)
        DefaultValue = 'winrm'                                          # Policy parameter default value (optional)
        AllowedValues = @('BDESVC','TermService','wuauserv','winrm')    # Policy parameter allowed values (optional)
    }
)

New-GuestConfigurationPolicy
    -ContentUri 'https://storageaccountname.blob.core.chinacloudapi.cn/packages/AuditBitLocker.zip?st=2019-07-01T00%3A00%3A00Z&se=2024-07-01T00%3A00%3A00Z&sp=rl&sv=2018-03-28&sr=b&sig=JdUf4nOCo8fvuflOoX%2FnGo4sXqVfP5BYXHzTl3%2BovJo%3D' `
    -DisplayName 'Audit Windows Service.' `
    -Description 'Audit if a Windows Service is not enabled on Windows machine.' `
    -Path '.\policyDefinitions' `
    -Parameters $PolicyParameterInfo `
    -Version 1.0.0

策略生命周期Policy lifecycle

若要发布对策略的更新,需要注意两个字段。If you would like to release an update to the policy, there are two fields that require attention.

  • 版本:运行 New-GuestConfigurationPolicy cmdlet 时,必须指定大于当前发布版本的版本号。Version: When you run the New-GuestConfigurationPolicy cmdlet, you must specify a version number greater than what is currently published. 该属性更新 Guest Configuration 分配版本,使代理能够识别更新的包。The property updates the version of the Guest Configuration assignment so the agent recognizes the updated package.
  • contentHash:此属性由 New-GuestConfigurationPolicy cmdlet 自动更新。contentHash: This property is updated automatically by the New-GuestConfigurationPolicy cmdlet. 它是 New-GuestConfigurationPackage 创建的包的哈希值。It's a hash value of the package created by New-GuestConfigurationPackage. 对于发布的 .zip 文件,该属性必须正确。The property must be correct for the .zip file you publish. 如果仅更新了 contentUri 属性,扩展不会接受内容包。If only the contentUri property is updated, the Extension won't accept the content package.

发布已更新的包的最简单方法是重复本文所述的过程,并提供更新的版本号。The easiest way to release an updated package is to repeat the process described in this article and provide an updated version number. 该过程可保证正确更新所有属性。That process guarantees all properties have been correctly updated.

将 Windows 组策略内容转换为 Azure Policy Guest ConfigurationConverting Windows Group Policy content to Azure Policy Guest Configuration

审核 Windows 计算机时,Guest Configuration 是 PowerShell Desired State Configuration 语法的实现。Guest Configuration, when auditing Windows machines, is an implementation of the PowerShell Desired State Configuration syntax. DSC 社区已发布相应的工具用于将导出的组策略模板转换为 DSC 格式。The DSC community has published tooling to convert exported Group Policy templates to DSC format. 结合上述 Guest Configuration cmdlet 使用此工具,可以转换 Windows 组策略内容和包,并将其发布以供 Azure Policy 审核。By using this tool together with the Guest Configuration cmdlets described above, you can convert Windows Group Policy content and package/publish it for Azure Policy to audit. 有关使用该工具的详细信息,请参阅文章快速入门:将组策略转换为 DSCFor details about using the tool, see the article Quickstart: Convert Group Policy into DSC. 转换内容后,创建包并将其发布为 Azure Policy的步骤与处理任何 DSC 内容的相应步骤相同。Once the content has been converted, the steps above to create a package and publish it as Azure Policy are the same as for any DSC content.

可选:为 Guest Configuration 包签名Optional: Signing Guest Configuration packages

Guest Configuration 自定义策略使用 SHA256 哈希来验证策略包是否未更改。Guest Configuration custom policies use SHA256 hash to validate the policy package hasn't changed. 客户还可以选择性地使用证书来为该包签名,并强制 Guest Configuration 扩展仅允许已签名的内容。Optionally, customers may also use a certificate to sign packages and force the Guest Configuration extension to only allow signed content.

若要实现此方案,需要完成两个步骤。To enable this scenario, there are two steps you need to complete. 运行 cmdlet 以便为内容包签名,并将一个标记追加到要求为代码签名的计算机。Run the cmdlet to sign the content package, and append a tag to the machines that should require code to be signed.

若要使用签名验证功能,请在发布该包之前,运行 Protect-GuestConfigurationPackage cmdlet 为其签名。To use the Signature Validation feature, run the Protect-GuestConfigurationPackage cmdlet to sign the package before it's published. 此 cmdlet 需要“代码签名”证书。This cmdlet requires a 'Code Signing' certificate.

$Cert = Get-ChildItem -Path cert:\LocalMachine\My | Where-Object {($_.Subject-eq "CN=mycert") }
Protect-GuestConfigurationPackage -Path .\package\AuditWindowsService\AuditWindowsService.zip -Certificate $Cert -Verbose

Protect-GuestConfigurationPackage cmdlet 的参数:Parameters of the Protect-GuestConfigurationPackage cmdlet:

  • 路径:Guest Configuration 包的完整路径。Path: Full path of the Guest Configuration package.
  • Certificate:用来为包签名的代码签名证书。Certificate: Code signing certificate to sign the package. 仅当为适用于 Windows 的内容签名时才支持此参数。This parameter is only supported when signing content for Windows.

GuestConfiguration 代理要求证书公钥在 Windows 计算机上的“受信任的根证书颁发机构”和 Linux 计算机上的 /usr/local/share/ca-certificates/extra 路径中存在。GuestConfiguration agent expects the certificate public key to be present in "Trusted Root Certificate Authorities" on Windows machines and in the path /usr/local/share/ca-certificates/extra on Linux machines. 要使节点能够验证已签名的内容,请在应用自定义策略之前在计算机上安装证书公钥。For the node to verify signed content, install the certificate public key on the machine before applying the custom policy. 可以使用 VM 中的任何技术或使用 Azure Policy 来完成此过程。This process can be done using any technique inside the VM or by using Azure Policy. 此处提供了一个示例模板。An example template is provided here. Key Vault 访问策略必须允许计算资源提供程序在部署期间访问证书。The Key Vault access policy must allow the Compute resource provider to access certificates during deployments. 有关详细步骤,请参阅在 Azure 资源管理器中为虚拟机设置 Key VaultFor detailed steps, see Set up Key Vault for virtual machines in Azure Resource Manager.

下面是从签名证书导出公钥并将其导入计算机的示例。Following is an example to export the public key from a signing certificate, to import to the machine.

$Cert = Get-ChildItem -Path cert:\LocalMachine\My | Where-Object {($_.Subject-eq "CN=mycert3") } | Select-Object -First 1
$Cert | Export-Certificate -FilePath "$env:temp\DscPublicKey.cer" -Force

发布内容后,将名为 GuestConfigPolicyCertificateValidation、值为 enabled 的标记追加到需要代码签名的所有虚拟机。After your content is published, append a tag with name GuestConfigPolicyCertificateValidation and value enabled to all virtual machines where code signing should be required. 请参阅标记示例,了解如何使用 Azure Policy 大规模传递标记。See the Tag samples for how tags can be delivered at scale using Azure Policy. 追加此标记后,使用 New-GuestConfigurationPolicy cmdlet 生成的策略定义可通过 Guest Configuration 扩展来满足要求。Once this tag is in place, the policy definition generated using the New-GuestConfigurationPolicy cmdlet enables the requirement through the Guest Configuration extension.

排查 Guest Configuration 策略分配问题(预览版)Troubleshooting Guest Configuration policy assignments (Preview)

我们已提供一个预览版工具用于帮助排查 Azure Policy Guest Configuration 分配问题。A tool is available in preview to assist in troubleshooting Azure Policy Guest Configuration assignments. 该工具目前为预览版,已发布到 PowerShell 库,其名称为 Guest Configuration 故障排除工具The tool is in preview and has been published to the PowerShell Gallery as module name Guest Configuration Troubleshooter.

有关此工具中的 cmdlet 的详细信息,请在 PowerShell 中使用 Get-Help 命令显示内置的指导。For more information about the cmdlets in this tool, use the Get-Help command in PowerShell to show the built-in guidance. 在该工具的频繁更新过程中,此命令是获取最新信息的最佳方式。As the tool is getting frequent updates, that is the best way to get most recent information.

后续步骤Next steps