Azure Disk Encryption – How to recover KEK from Azure Key Vault


If you have encrypted the VHD using Azure Disk Encryption with KEK, use the below steps to Unwrap the BEK Key.

Pre-requisites:

  1. The user who is running the commands must have the ‘unwrap‘ permission on the Keys within Key Vault use the Set-AzureRmKeyVaultAccessPolicy

Example:

Replace below parameters with your KeyVault and UPN Name

$keyVaultName = “KeyVaultName”

$rgName = “RGName of KeyVaultServer”

-UserPrincipalName = ‘UPN name of user’

 

Open PowerShell and Login to you Azure Account link to your subscription

Login-AzureRmAccount

Set-AzureRmKeyVaultAccessPolicy -VaultName $keyVaultName -ResourceGroupName $rgName -UserPrincipalName ‘manojse@microsoft.com’ -PermissionsToKeys all -PermissionsToSecrets all -PermissionsToCertificates all 

 

# Get the Secret from Azure Key Vault if VM was encrypted with KEK

#For All Drives including the OS and Data disks

Get-AzureKeyVaultSecret -VaultName $vaultName | where {($_.Tags.MachineName -eq $vmName) -and ($_.ContentType -eq ‘Wrapped BEK’)}

OR

#For OS drive

Get-AzureKeyVaultSecret -VaultName $vaultName | where {($_.Tags.MachineName -eq $vmName) -and ($_.Tags.VolumeLetter -eq “C:\”) -and ($_.ContentType -eq ‘Wrapped BEK‘)}

 

Example:

PS C:\> $rgName = ‘VMRG’;

$VMName = ‘manojse-kek’;

$vaultName = ‘keyvault’;

 

PS C:\> Get-AzureKeyVaultSecret -VaultName $vaultName | where {($_.Tags.MachineName -eq $vmName) -and ($_.Tags.VolumeLetter -eq “C:\”) -and ($_.ContentType -eq ‘Wrapped BEK‘)}

Vault Name   : keyvaultwestus

Name         : 3561E876-5E5F-4C24-9112-947A4B928EA9

Id           : https://keyvaultwestus.vault.azure.net:443/secrets/3561E876-5E5F-4C24-9112-947A4B928EA9

Enabled      : True

Created      : 2/15/2017 20:12:05

Updated      : 2/15/2017 20:12:05

Content Type : Wrapped BEK

Tags         : Name                                  Value

VolumeLetter                          C:\

DiskEncryptionKeyEncryptionAlgorithm  RSA-OAEP

DiskEncryptionKeyFileName             3561E876-5E5F-4C24-9112-947A4B928EA9.BEK

DiskEncryptionKeyEncryptionKeyURL     https://keyvault.vault.azure.net/keys/KEK/1848053030b64216a476ab53f7c5fc5f

MachineName                           MANOJSE-KEK

 

Note the Name from the output which will be used as $secretName below.

  1. The Active Directory Authentication Library (ADAL) paths may need to be modified if the Azure PowerShell modules are download from the PowerShell. In the following example the path is set to the Azure SDK Directory.

Microsoft Azure SDK for .NET – 2.9 – https://www.microsoft.com/en-us/download/details.aspx?id=51657

  1. To Run below Script you require the below variables.

 

$keyVaultName = ‘keyvaultname’;

$secretName = ‘3561E876-5E5F-4C24-9112-947A4B928EA9’;

$kekName = ‘KEKName’;

$bekFilePath = ‘C:\bek\3561E876-5E5F-4C24-9112-947A4B928EA9.BEK’;

 

The $adTenant variable needs to be set to the Azure AD Tenant that is linked to the subscription. e.g. example.onmicrosoft.com

$adTenant = “example.onmicrosoft.com”

 

Solution:

Step 1: Open PowerShell ISE on your machine and Login to your Azure Account using

Login-AzureRmAccount

 

Step 2: Run below command

Set-ExecutionPolicy Unrestricted

Copy the below text in notepad and rename the file extension to .ps1, so you can execute as a PowerShell script.

Save the below script to your machine and then execute from PowerShell

Once the script is executed successfully, you will see that you have the BEK file located at ‘C:\bek\3561E876-5E5F-4C24-9112-947A4B928EA9.BEK’

 

#####################################################################################

# Initialize names of keyvault, secret, kek, bekFilePath to place the retrieved BEK file

#####################################################################################

$keyVaultName = ‘keyvaultname’;

$secretName = ‘3561E876-5E5F-4C24-9112-947A4B928EA9’;

$kekName = ‘KEKName’;

$bekFilePath = ‘C:\bek\3561E876-5E5F-4C24-9112-947A4B928EA9.BEK’;

 

#####################################################################################

# This requires Azure SDK to be installed on the machine

# Initialize ADAL libraries to make REST API called against KeyVault REST APIs.

#####################################################################################

# Load ADAL Assemblies

$adal = “${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.dll”

$adalforms = “${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll”

[System.Reflection.Assembly]::LoadFrom($adal)

[System.Reflection.Assembly]::LoadFrom($adalforms)

# Set Azure AD Tenant name

$adTenant = “microsoft.onmicrosoft.com”

# Set well-known client ID for AzurePowerShell

$clientId = “1950a258-227b-4e31-a9cf-717495945fc2”

# Set redirect URI for Azure PowerShell

$redirectUri = “urn:ietf:wg:oauth:2.0:oob”

# Set Resource URI to Azure Service Management API

$resourceAppIdURI = “https://vault.azure.net”

# Set Authority to Azure AD Tenant

$authority = “https://login.windows.net/$adtenant”

# Create Authentication Context tied to Azure AD Tenant

$authContext = New-Object “Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext” -ArgumentList $authority

# Acquire token

$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, “Auto”)

# Generate auth header

$authHeader = $authResult.CreateAuthorizationHeader()

# Set HTTP request headers to include Authorization header

$headers = @{‘x-ms-version’=’2014-08-01’;”Authorization” = $authHeader}

###################################################################################### 1. Retrieve wrapped BEK

# 2. Make KeyVault REST API call to unwrap the BEK

# 3. Convert the Base64Url string returned by KeyVault unwrap to Base64 string

# 4. Convert Base64 string to bytes and write to the BEK file

#####################################################################################

#Get wrapped BEK and place it in JSON object to send to KeyVault REST API

$keyVaultSecret = Get-AzureKeyVaultSecret -VaultName $keyVaultName -Name $secretName

$wrappedBekSecretBase64 = $keyVaultSecret.SecretValueText

$jsonObject = @”

{

“alg”: “RSA-OAEP”,

“value” : “$wrappedBekSecretBase64”

}

“@

#Get KEK Url

$kekUrl = (Get-AzureKeyVaultKey -VaultName $keyVaultName -Name $kekName).Key.Kid;

$unwrapKeyRequestUrl = $kekUrl+ “/unwrapkey?api-version=2015-06-01”;

 

#Call KeyVault REST API to Unwrap

$result = Invoke-RestMethod -Method POST -Uri $unwrapKeyRequestUrl -Headers $headers -Body $jsonObject -ContentType “application/json” -Debug

 

#Convert Base64Url string returned by KeyVault unwrap to Base64 string

$base64UrlBek = $result.value;

$base64Bek = $base64UrlBek.Replace(‘-‘, ‘+’);

$base64Bek = $base64Bek.Replace(‘_’, ‘/’);

if($base64Bek.Length %4 -eq 2)

{

$base64Bek+= ‘==’;

}

elseif($base64Bek.Length %4 -eq 3)

{

$base64Bek+= ‘=’;

}

 

#Convert base64 string to bytes and write to BEK file

$bekFileBytes = [System.Convert]::FromBase64String($base64Bek);

[System.IO.File]::WriteAllBytes($bekFilePath,$bekFileBytes)

###############################################################################

 

Unlock the volume by running below command

C:\>manage-bde -unlock F: -rk C:\bek\3561E876-5E5F-4C24-9112-947A4B928EA9.BEK’

BitLocker Drive Encryption: Configuration Tool version 10.0.14393

Copyright (C) 2013 Microsoft Corporation. All rights reserved.

The file “C:\BEK\3561E876-5E5F-4C24-9112-947A4B928EA9.BEK” successfully unlocked volume F:.

 

If the above command fails to unlock the drive, it means either the BEK file which you got from KeyVault is incorrect.

OR

The drive which is locked does not have the External Key Protector and someone has removed the protector manually using manage-bde command.

To check the External Key protector, use the below command from elevated command prompt:

manage-bde -protectors -get F:

where F is the drive letter of the volume.

 

 

References:

Azure Disk Encryption: https://azure.microsoft.com/en-us/documentation/articles/azure-security-disk-encryption/

Whitepaper with detail steps: https://gallery.technet.microsoft.com/Azure-Disk-Encryption-for-a0018eb0

 

Comments (0)

Skip to main content