Azure PowerShell - 使用客户管理的密钥进行服务器端加密 - 托管磁盘Azure PowerShell - Enable customer-managed keys with server-side encryption - managed disks

Azure 磁盘存储使你能在对托管磁盘使用服务器端加密 (SSE) 时管理自己的密钥(如果你选择)。Azure Disk Storage allows you to manage your own keys when using server-side encryption (SSE) for managed disks, if you choose. 有关使用客户管理的密钥的 SSE 以及其他托管磁盘加密类型的概念信息,请参阅磁盘加密文章的客户管理的密钥部分。For conceptual information on SSE with customer-managed keys, and other managed disk encryption types, see the Customer-managed keys section of our disk encryption article.

限制Restrictions

目前,客户托管密钥具有以下限制:For now, customer-managed keys have the following restrictions:

  • 如果为磁盘启用了此功能,则无法禁用它。If this feature is enabled for your disk, you cannot disable it.

    如果需要解决此问题,则必须复制所有数据到完全不同的托管磁盘(未使用客户托管密钥)。If you need to work around this, you must copy all the data to an entirely different managed disk that isn't using customer-managed keys.

  • 仅支持大小为 2048 位、3,072 位和 4,096 位的软件密钥,不支持其他密钥或其他大小。Only software keys of sizes 2,048-bit, 3,072-bit and 4,096-bit are supported, no other keys or sizes.

  • 从使用服务器端加密和客户托管密钥加密的自定义映像创建的磁盘必须使用相同的客户托管密钥进行加密,且必须位于同一订阅中。Disks created from custom images that are encrypted using server-side encryption and customer-managed keys must be encrypted using the same customer-managed keys and must be in the same subscription.

  • 从使用服务器端加密和客户托管密钥加密的磁盘创建的快照必须使用相同的客户托管密钥进行加密。Snapshots created from disks that are encrypted with server-side encryption and customer-managed keys must be encrypted with the same customer-managed keys.

  • 与客户托管密钥相关的所有资源(Azure Key Vault、磁盘加密集、VM、磁盘和快照)都必须位于同一订阅和区域中。All resources related to your customer-managed keys (Azure Key Vaults, disk encryption sets, VMs, disks, and snapshots) must be in the same subscription and region.

  • 使用客户托管密钥加密的磁盘、快照和映像不能移至其他资源组和订阅。Disks, snapshots, and images encrypted with customer-managed keys cannot move to another resource group and subscription.

  • 当前或以前使用 Azure 磁盘加密加密的托管磁盘不能使用客户管理的密钥进行加密。Managed disks currently or previously encrypted using Azure Disk Encryption cannot be encrypted using customer-managed keys.

  • 每个区域、每个订阅最多只能创建 1000 个磁盘加密集。Can only create up to 1000 disk encryption sets per region per subscription.

在没有自动密钥轮换的情况下设置 Azure Key Vault DiskEncryptionSetSet up an Azure Key Vault and DiskEncryptionSet without automatic key rotation

若要使用客户管理的密钥进行 SSE,必须设置 Azure Key Vault 和 DiskEncryptionSet 资源。To use customer-managed keys with SSE, you must set up an Azure Key Vault and a DiskEncryptionSet resource.

  1. 请确保已安装最新的 Azure PowerShell 版本,并已使用 Connect-AzAccount -Environment AzureChinaCloud 登录到 Azure 帐户Make sure that you have installed latest Azure PowerShell version, and you are signed in to an Azure account in with Connect-AzAccount -Environment AzureChinaCloud

  2. 创建 Azure Key Vault 和加密密钥的实例。Create an instance of Azure Key Vault and encryption key.

    创建 Key Vault 实例时,必须启用软删除和清除保护。When creating the Key Vault instance, you must enable soft delete and purge protection. 软删除可确保 Key Vault 在给定的保留期(默认为 90 天)内保留已删除的密钥。Soft delete ensures that the Key Vault holds a deleted key for a given retention period (90 day default). 清除保护可确保在保留期结束之前,无法永久删除已删除的密钥。Purge protection ensures that a deleted key cannot be permanently deleted until the retention period lapses. 这些设置可防止由于意外删除而丢失数据。These settings protect you from losing data due to accidental deletion. 使用 Key Vault 加密托管磁盘时,这些设置是必需的。These settings are mandatory when using a Key Vault for encrypting managed disks.

    $ResourceGroupName="yourResourceGroupName"
    $LocationName="chinaeast"
    $keyVaultName="yourKeyVaultName"
    $keyName="yourKeyName"
    $keyDestination="Software"
    $diskEncryptionSetName="yourDiskEncryptionSetName"
    
    $keyVault = New-AzKeyVault -Name $keyVaultName -ResourceGroupName $ResourceGroupName -Location $LocationName -EnableSoftDelete -EnablePurgeProtection
    
    $key = Add-AzKeyVaultKey -VaultName $keyVaultName -Name $keyName -Destination $keyDestination  
    
  3. 创建一个 DiskEncryptionSet 实例。Create an instance of a DiskEncryptionSet.

    $desConfig=New-AzDiskEncryptionSetConfig -Location $LocationName -SourceVaultId $keyVault.ResourceId -KeyUrl $key.Key.Kid -IdentityType SystemAssigned
    
    $des=New-AzDiskEncryptionSet -Name $diskEncryptionSetName -ResourceGroupName $ResourceGroupName -InputObject $desConfig 
    
  4. 授予对密钥保管库的 DiskEncryptionSet 资源访问权限。Grant the DiskEncryptionSet resource access to the key vault.

    备注

    Azure 可能需要几分钟时间才能在 Azure Active Directory 中创建 DiskEncryptionSet 的标识。It may take few minutes for Azure to create the identity of your DiskEncryptionSet in your Azure Active Directory. 如果在运行以下命令时收到类似于“找不到 Active Directory 对象”的错误,请等待几分钟,然后重试。If you get an error like "Cannot find the Active Directory object" when running the following command, wait a few minutes and try again.

    Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ObjectId $des.Identity.PrincipalId -PermissionsToKeys wrapkey,unwrapkey,get
    

在有自动密钥轮换的情况下设置 Azure Key Vault DiskEncryptionSet(预览)Set up an Azure Key Vault and DiskEncryptionSet with automatic key rotation (preview)

  1. 请确保已安装最新的 Azure PowerShell 版本,并已使用 Connect-AzAccount -Environment AzureChinaCloud 登录到 Azure 帐户。Make sure that you have installed latest Azure PowerShell version, and you are signed in to an Azure account in with Connect-AzAccount -Environment AzureChinaCloud.

  2. 创建 Azure Key Vault 和加密密钥的实例。Create an instance of Azure Key Vault and encryption key.

    创建 Key Vault 实例时,必须启用清除保护。When creating the Key Vault instance, you must enable purge protection. 清除保护可确保在保留期结束之前,无法永久删除已删除的密钥。Purge protection ensures that a deleted key cannot be permanently deleted until the retention period lapses. 此设置可保护你免于因意外删除而丢失数据,并且对于加密托管磁盘是必需的。This setting protects you from losing data due to accidental deletion and is mandatory for encrypting managed disks.

    $ResourceGroupName="yourResourceGroupName"
    $LocationName="chinaeast"
    $keyVaultName="yourKeyVaultName"
    $keyName="yourKeyName"
    $keyDestination="Software"
    $diskEncryptionSetName="yourDiskEncryptionSetName"
    
    $keyVault = New-AzKeyVault -Name $keyVaultName -ResourceGroupName $ResourceGroupName -Location $LocationName -EnablePurgeProtection
    
    $key = Add-AzKeyVaultKey -VaultName $keyVaultName -Name $keyName -Destination $keyDestination  
    
  3. 使用 API 版本 2020-12-01 和通过 Azure 资源管理器模板 CreateDiskEncryptionSetWithAutoKeyRotation.json 将属性 rotationToLatestKeyVersionEnabled 设置为 true,来创建 DiskEncryptionSetCreate a DiskEncryptionSet by using the API version 2020-12-01 and setting the property rotationToLatestKeyVersionEnabled to true via the Azure Resource Manager template CreateDiskEncryptionSetWithAutoKeyRotation.json

    New-AzResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
    -TemplateUri "https://raw.githubusercontent.com/Azure-Samples/managed-disks-powershell-getting-started/master/AutoKeyRotation/CreateDiskEncryptionSetWithAutoKeyRotation.json" `
    -diskEncryptionSetName $diskEncryptionSetName `
    -keyVaultId $($keyVault.ResourceId) `
    -keyVaultKeyUrl $($key.Key.Kid) `
    -encryptionType "EncryptionAtRestWithCustomerKey" `
    -region $LocationName
    
  4. 授予对密钥保管库的 DiskEncryptionSet 资源访问权限。Grant the DiskEncryptionSet resource access to the key vault.

    备注

    Azure 可能需要几分钟时间才能在 Azure Active Directory 中创建 DiskEncryptionSet 的标识。It may take few minutes for Azure to create the identity of your DiskEncryptionSet in your Azure Active Directory. 如果在运行以下命令时收到类似于“找不到 Active Directory 对象”的错误,请等待几分钟,然后重试。If you get an error like "Cannot find the Active Directory object" when running the following command, wait a few minutes and try again.

    $des=Get-AzDiskEncryptionSet -Name $diskEncryptionSetName -ResourceGroupName $ResourceGroupName
    Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ObjectId $des.Identity.PrincipalId -PermissionsToKeys wrapkey,unwrapkey,get
    

示例Examples

创建并配置这些资源之后,可以使用它们来保护托管磁盘。Now that you've created and configured these resources, you can use them to secure your managed disks. 以下是示例脚本,每个脚本都有各自的方案,可用于保护托管磁盘。The following are example scripts, each with a respective scenario, that you can use to secure your managed disks.

使用市场映像创建 VM,并使用客户托管密钥加密 OS 和数据磁盘Create a VM using a Marketplace image, encrypting the OS and data disks with customer-managed keys

复制该脚本,将所有示例值替换为你自己的参数,然后运行该脚本。Copy the script, replace all of the example values with your own parameters, and then run it.

$VMLocalAdminUser = "yourVMLocalAdminUserName"
$VMLocalAdminSecurePassword = ConvertTo-SecureString <password> -AsPlainText -Force
$LocationName = "yourRegion"
$ResourceGroupName = "yourResourceGroupName"
$ComputerName = "yourComputerName"
$VMName = "yourVMName"
$VMSize = "yourVMSize"
$diskEncryptionSetName="yourdiskEncryptionSetName"

$NetworkName = "yourNetworkName"
$NICName = "yourNICName"
$SubnetName = "yourSubnetName"
$SubnetAddressPrefix = "10.0.0.0/24"
$VnetAddressPrefix = "10.0.0.0/16"

$SingleSubnet = New-AzVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetAddressPrefix
$Vnet = New-AzVirtualNetwork -Name $NetworkName -ResourceGroupName $ResourceGroupName -Location $LocationName -AddressPrefix $VnetAddressPrefix -Subnet $SingleSubnet
$NIC = New-AzNetworkInterface -Name $NICName -ResourceGroupName $ResourceGroupName -Location $LocationName -SubnetId $Vnet.Subnets[0].Id

$Credential = New-Object System.Management.Automation.PSCredential ($VMLocalAdminUser, $VMLocalAdminSecurePassword);

$VirtualMachine = New-AzVMConfig -VMName $VMName -VMSize $VMSize
$VirtualMachine = Set-AzVMOperatingSystem -VM $VirtualMachine -Windows -ComputerName $ComputerName -Credential $Credential -ProvisionVMAgent -EnableAutoUpdate
$VirtualMachine = Add-AzVMNetworkInterface -VM $VirtualMachine -Id $NIC.Id
$VirtualMachine = Set-AzVMSourceImage -VM $VirtualMachine -PublisherName 'MicrosoftWindowsServer' -Offer 'WindowsServer' -Skus '2012-R2-Datacenter' -Version latest

$diskEncryptionSet=Get-AzDiskEncryptionSet -ResourceGroupName $ResourceGroupName -Name $diskEncryptionSetName

$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -Name $($VMName +"_OSDisk") -DiskEncryptionSetId $diskEncryptionSet.Id -CreateOption FromImage

$VirtualMachine = Add-AzVMDataDisk -VM $VirtualMachine -Name $($VMName +"DataDisk1") -DiskSizeInGB 128 -StorageAccountType Premium_LRS -CreateOption Empty -Lun 0 -DiskEncryptionSetId $diskEncryptionSet.Id 

New-AzVM -ResourceGroupName $ResourceGroupName -Location $LocationName -VM $VirtualMachine -Verbose

创建一个使用客户托管密钥的服务器端加密进行了加密的空磁盘,并将其附加到 VMCreate an empty disk encrypted using server-side encryption with customer-managed keys and attach it to a VM

复制该脚本,将所有示例值替换为你自己的参数,然后运行该脚本。Copy the script, replace all of the example values with your own parameters, and then run it.

$vmName = "yourVMName"
$LocationName = "chinaeast"
$ResourceGroupName = "yourResourceGroupName"
$diskName = "yourDiskName"
$diskSKU = "Premium_LRS"
$diskSizeinGiB = 30
$diskLUN = 1
$diskEncryptionSetName="yourDiskEncryptionSetName"

$vm = Get-AzVM -Name $vmName -ResourceGroupName $ResourceGroupName 

$diskEncryptionSet=Get-AzDiskEncryptionSet -ResourceGroupName $ResourceGroupName -Name $diskEncryptionSetName

$vm = Add-AzVMDataDisk -VM $vm -Name $diskName -CreateOption Empty -DiskSizeInGB $diskSizeinGiB -StorageAccountType $diskSKU -Lun $diskLUN -DiskEncryptionSetId $diskEncryptionSet.Id 

Update-AzVM -ResourceGroupName $ResourceGroupName -VM $vm

加密现有托管磁盘Encrypt existing managed disks

不得将现有磁盘附加到正在运行的 VM,以便可以使用以下脚本加密这些磁盘:Your existing disks must not be attached to a running VM in order for you to encrypt them using the following script:

$rgName = "yourResourceGroupName"
$diskName = "yourDiskName"
$diskEncryptionSetName = "yourDiskEncryptionSetName"

$diskEncryptionSet = Get-AzDiskEncryptionSet -ResourceGroupName $rgName -Name $diskEncryptionSetName

New-AzDiskUpdateConfig -EncryptionType "EncryptionAtRestWithCustomerKey" -DiskEncryptionSetId $diskEncryptionSet.Id | Update-AzDisk -ResourceGroupName $rgName -DiskName $diskName

使用 SSE 和客户管理的密钥加密现有虚拟机规模集Encrypt an existing virtual machine scale set with SSE and customer-managed keys

复制该脚本,将所有示例值替换为自己的参数,然后运行该脚本:Copy the script, replace all the example values with your own parameters, and then run it:

#set variables 
$vmssname = "name of the vmss that is already created"
$diskencryptionsetname = "name of the diskencryptionset already created"
$vmssrgname = "vmss resourcegroup name"
$diskencryptionsetrgname = "diskencryptionset resourcegroup name"

#get vmss object and create diskencryptionset object attach to vmss os disk
$ssevmss = get-azvmss -ResourceGroupName $vmssrgname -VMScaleSetName $vmssname
$ssevmss.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet = New-Object -TypeName Microsoft.Azure.Management.Compute.Models.DiskEncryptionSetParameters

#get diskencryption object and retrieve the resource id
$des = Get-AzDiskEncryptionSet -ResourceGroupName $diskencryptionsetrgname -Name $diskencryptionsetname
write-host "the diskencryptionset resource id is:" $des.Id

#associate DES resource id to os disk and update vmss 
$ssevmss.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.id = $des.Id
$ssevmss | update-azvmss

使用市场映像创建虚拟机规模集,并使用客户托管密钥加密 OS 和数据磁盘Create a virtual machine scale set using a Marketplace image, encrypting the OS and data disks with customer-managed keys

复制该脚本,将所有示例值替换为你自己的参数,然后运行该脚本。Copy the script, replace all of the example values with your own parameters, and then run it.

$VMLocalAdminUser = "yourLocalAdminUser"
$VMLocalAdminSecurePassword = ConvertTo-SecureString Password@123 -AsPlainText -Force
$LocationName = "chinaeast"
$ResourceGroupName = "yourResourceGroupName"
$ComputerNamePrefix = "yourComputerNamePrefix"
$VMScaleSetName = "yourVMSSName"
$VMSize = "Standard_DS3_v2"
$diskEncryptionSetName="yourDiskEncryptionSetName"

$NetworkName = "yourVNETName"
$SubnetName = "yourSubnetName"
$SubnetAddressPrefix = "10.0.0.0/24"
$VnetAddressPrefix = "10.0.0.0/16"

$SingleSubnet = New-AzVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetAddressPrefix

$Vnet = New-AzVirtualNetwork -Name $NetworkName -ResourceGroupName $ResourceGroupName -Location $LocationName -AddressPrefix $VnetAddressPrefix -Subnet $SingleSubnet

$ipConfig = New-AzVmssIpConfig -Name "myIPConfig" -SubnetId $Vnet.Subnets[0].Id 

$VMSS = New-AzVmssConfig -Location $LocationName -SkuCapacity 2 -SkuName $VMSize -UpgradePolicyMode 'Automatic'

$VMSS = Add-AzVmssNetworkInterfaceConfiguration -Name "myVMSSNetworkConfig" -VirtualMachineScaleSet $VMSS -Primary $true -IpConfiguration $ipConfig

$diskEncryptionSet=Get-AzDiskEncryptionSet -ResourceGroupName $ResourceGroupName -Name $diskEncryptionSetName

# Enable encryption at rest with customer managed keys for OS disk by setting DiskEncryptionSetId property 

$VMSS = Set-AzVmssStorageProfile $VMSS -OsDiskCreateOption "FromImage" -DiskEncryptionSetId $diskEncryptionSet.Id -ImageReferenceOffer 'WindowsServer' -ImageReferenceSku '2012-R2-Datacenter' -ImageReferenceVersion latest -ImageReferencePublisher 'MicrosoftWindowsServer'

$VMSS = Set-AzVmssOsProfile $VMSS -ComputerNamePrefix $ComputerNamePrefix -AdminUsername $VMLocalAdminUser -AdminPassword $VMLocalAdminSecurePassword

# Add a data disk encrypted at rest with customer managed keys by setting DiskEncryptionSetId property 

$VMSS = Add-AzVmssDataDisk -VirtualMachineScaleSet $VMSS -CreateOption Empty -Lun 1 -DiskSizeGB 128 -StorageAccountType Premium_LRS -DiskEncryptionSetId $diskEncryptionSet.Id

$Credential = New-Object System.Management.Automation.PSCredential ($VMLocalAdminUser, $VMLocalAdminSecurePassword);

New-AzVmss -VirtualMachineScaleSet $VMSS -ResourceGroupName $ResourceGroupName -VMScaleSetName $VMScaleSetName

更改 DiskEncryptionSet 的密钥,以轮替所有引用 DiskEncryptionSet 的资源的密钥Change the key of a DiskEncryptionSet to rotate the key for all the resources referencing the DiskEncryptionSet

复制该脚本,将所有示例值替换为你自己的参数,然后运行该脚本。Copy the script, replace all of the example values with your own parameters, and then run it.

$ResourceGroupName="yourResourceGroupName"
$keyVaultName="yourKeyVaultName"
$keyName="yourKeyName"
$diskEncryptionSetName="yourDiskEncryptionSetName"

$keyVault = Get-AzKeyVault -VaultName $keyVaultName -ResourceGroupName $ResourceGroupName

$keyVaultKey = Get-AzKeyVaultKey -VaultName $keyVaultName -Name $keyName

Update-AzDiskEncryptionSet -Name $diskEncryptionSetName -ResourceGroupName $ResourceGroupName -SourceVaultId $keyVault.ResourceId -KeyUrl $keyVaultKey.Id

查找磁盘的服务器端加密状态Find the status of server-side encryption of a disk

$ResourceGroupName="yourResourceGroupName"
$DiskName="yourDiskName"

$disk=Get-AzDisk -ResourceGroupName $ResourceGroupName -DiskName $DiskName
$disk.Encryption.Type

重要

客户托管密钥依赖于 Azure 资源的托管标识(Azure Active Directory (Azure AD) 的一项功能)。Customer-managed keys rely on managed identities for Azure resources, a feature of Azure Active Directory (Azure AD). 配置客户托管密钥时,实际上会自动将托管标识分配给你的资源。When you configure customer-managed keys, a managed identity is automatically assigned to your resources under the covers. 如果随后将订阅、资源组或托管磁盘从一个 Azure AD 目录移动到另一个目录,则与托管磁盘关联的托管标识不会转移到新租户,因此,客户托管密钥可能不再有效。If you subsequently move the subscription, resource group, or managed disk from one Azure AD directory to another, the managed identity associated with the managed disks is not transferred to the new tenant, so customer-managed keys may no longer work. 有关详细信息,请参阅在 Azure AD 目录之间转移订阅For more information, see Transferring a subscription between Azure AD directories.

后续步骤Next steps