Sunday, May 10, 2020

Backup VM Encryption & VM Signing certificate for Shielded VMs with Powershell

One of the new technologies that was introduced in Hyper-V 2016 is Shielded Virtual Machines.

In this post, I will show you how to back up Shielded VM Local Certificates with powershell.

These certificates are critical. If you loose them, there is no way to start Shielded VMs and they are permanently lost.

More info on this great article here https://www.altaro.com/hyper-v/hyper-v-2016-shielded-virtual-machines-stand-alone-hosts/

This is the powershell script that I use to back up those certificates. Once, those certificates are exported/zipped, you need to move them to a secure location.
Currently, I'm using RMM tool to backup and move those certificate to a safe place automatically.

$ExportDestination = "c:\data\certs"
$certs = certutil -store "Shielded VM Local Certificates" 
$password = "YourCertPassword"

$shieldedVMEncryption = '*Issuer: CN=Shielded Vm Encryption Certificate*'
for ($i = 0; $i -lt $certs.Length; $i++) {

    if ($certs[$i] -like $shieldedVMEncryption) {
        $issuer = ((($certs[$i]).split(' ')))[-1]
        $issuer = $issuer.Replace('(''')
        $issuer = $issuer.Replace(')''')
        Write-host "Shielded cert is stored in line $($i-1)"
        $ShieldedCert = $certs[$i - 1]
        $FinalShieldedCert = $ShieldedCert.Split(" ")[-1]
        Write-host  $FinalShieldedCert -ForegroundColor Yellow
        certutil -exportPFX -p $password "Shielded VM Local Certificates" `
        $FinalShieldedCert  "$($ExportDestination)\\$($issuer)-ShieldedVMEncryption-$($i)-$($FinalShieldedCert).pfx"
    }

}

#For Signing Certificate
$shieldedVMSigning = '*Issuer: CN=Shielded Vm Signing Certificate*'
for ($i = 0; $i -lt $certs.Length; $i++) {

    if ($certs[$i] -like $shieldedVMSigning) {
        $issuer = ((($certs[$i]).split(' ')))[-1]
        $issuer = $issuer.Replace('(''')
        $issuer = $issuer.Replace(')''')
        Write-host "Shielded cert is stored in line $($i-1)"
        $ShieldedCert = $certs[$i - 1]
        $FinalShieldedCert = $ShieldedCert.Split(" ")[-1]
        Write-host  $FinalShieldedCert -ForegroundColor Yellow
        certutil -exportPFX -p $password "Shielded VM Local Certificates" `
        $FinalShieldedCert  "$($ExportDestination)\$($issuer)-ShieldedVMSigning-$($i)-$($FinalShieldedCert).pfx"
    }

}


$compress = @{

    path            = "$ExportDestination\*.pfx"
    DestinationPath = "$ExportDestination\ShieldedCerts"
}

Compress-Archive @compress -Force