Backing up ADCS Certificate Authorities (Part 2 of 2)

In my last blog post (Backing up ADCS Certificate Authorities Part 1) I covered the inner workings of how ADCS and the Jet database works to maintain the CA data. In this post I am going to go over a comprehensive PowerShell script that I wrote to perform a full backup of all necessary ADCS components. In addition, this backup will ensure the CA performs the necessary log maintenance and truncation that I indicated was vital in Part 1.

A customer recently tasked me with improving my old batch backup script. The batch file lacked any command arguments, diagnostic reporting, event monitoring and script statuses. To properly implement this in an enterprise, customers needed a stronger backup script.

The full script is available for download at: https://pkisolutions.com/downloads/CABackup.ps1

This script is capable of backing up the following data:

  • ADCS Certificate Authority database
  • CA certificates, including previously renewed CA certificates
  • CA Configuration data stored in the registry
  • Thales nCipher HSM configuration and key files
  • List of published templates available on the CA

 

Details about the script

  • The script is not signed at this point, you can either sign it or temporarily change the execution level to allow it to run
  • The first time you use the script, you need to register the script so that it creates the event log source CABackup in the Application Log. The syntax is “.\cabackup.ps1 -Register $True”. You will need to be a local admin
  • There are a few switches to use as arguments. The most important might be the “EventLogging” so information goes into the Application Event Log, source CABackup.
    • Event IDs to watch:
      • Event 1, Backup Started
      • Event 2, Backup Completed Successfully,
      • Events 3,4 (Error) are problems with aspects in backing up the CA and should be alerted on
  • Argument BackupFolder allows you to specify where backups go, by default it is c:\cabackups

 

CABackup.ps1

[CmdletBinding()]
 Param(
 [Parameter(Mandatory=$False,Position=1)]
 [string]$BackupFolder="c:\CABackups",
 #Specifies the destiniation backup folder

[Parameter(Mandatory=$False,Position=2)]
 [bool]$ThalesHSM,
 #Determines if Thales HSM Files should be backedup

[Parameter(Mandatory=$False,Position=3)]
 [bool]$Diagnostic,
 #Enables diagnostic logging

[Parameter(Mandatory=$False,Position=4)]
 [bool]$EventLogging=$true,
 #Enables Event Log Entries

[Parameter(Mandatory=$False,Position=5)]
 [bool]$Register
 #Used during install to register the eventlog source
 )

#************************************************************************************
 # Scripted by: Mark B. Cooper
 # PKI Solutions Inc.
 # www.pkisolutions.com
 #
 # Version: 1.0
 # Date: October 6, 2017
 #************************************************************************************

function WriteDebugLog ([string]$msg)
 {
 $(Get-Date -format 'MM-dd-yy hh:mm:ss') +": " + $msg | Out-File -FilePath $logfile -Append
 if ($Diagnostic)
 {
 Write-Host $msg
 }
 }

function WriteEventLog ([string]$msg, [int]$EventID,[bool]$Error)
 {
 if ($EventLogging)
 {
 if ($Error)
 {
 Write-EventLog -LogName Application -Source "CABackup" -EventId $EventID -EntryType Error -Message $msg -Category 0
 }
 else
 {
 Write-EventLog -LogName Application -Source "CABackup" -EventId $EventID -EntryType Information -Message $msg -Category 0
 }
 }
 }

cls
 Set-PSDebug -Trace 0

#Revision and Log detail tracking purposes only
 $ScriptVersion="1.0"

#Log and temp files
 $logfile = "$BackupFolder\Backup-Log-$(Get-Date -format 'yyyy-MM-dd').log"

if ($Register)
 {
 New-EventLog -LogName "Application" -Source "CABackup"
 Exit
 }

if (Test-Path $BackupFolder)
 {}
 else
 {
 New-Item $BackupFolder -ItemType Directory | Out-Null
 }

WriteDebugLog "Script Starting -Version $ScriptVersion"

Write-Host "Starting Certification Authority Backup..."
 WriteEventLog "Starting Certification Authority Backup" 1

WriteDebugLog "Removing Backup Folder Contents"

Remove-Item $BackupFolder\* -Recurse

if(!$?)
 {
 WriteDebugLog "Error removing old backup folder contents. Error: " + $error[0]
 Write-Host "Unable to empty the target backup folder. Script is ending"
 WriteEventLog "Unable to empty the target backup folder. Script is ending" 3 $true
 Exit
 }

WriteDebugLog "Backup Folder Prepared"

WriteDebugLog "Backing Up CA Database"

Backup-CARoleService -path $BackupFolder -DatabaseOnly
 if(!$?)
 {
 WriteDebugLog "Error Performing CA Database Backup. Error: " + $error[0]
 Write-Host "Unable to perform CA Database Backup. Script is ending"
 WriteEventLog "Unable to perform CA Database Backup. Script is ending" 4 $true
 Exit
 }
 WriteDebugLog "CA Database backup completed"

WriteDebugLog "Copying CA Certificates"

Copy-Item $env:windir\System32\Certsrv\CertEnroll\*.crt $BackupFolder
 if(!$?)
 {
 WriteDebugLog "Error Copying CA Certificate Files. Error: " + $error[0]
 #Not considered a critical error, so backup will continue
 }
 else
 {
 WriteDebugLog "CA certificates backup completed."
 }

WriteDebugLog "Exporting CA Registry Configuration"

&'reg.exe' "export" "HKLM\system\currentcontrolset\services\certsvc\configuration" $BackupFolder\caregistry.reg

if ($ThalesHSM)
 {
 WriteDebugLog "Backing up Thales HSM Files"
 Copy-Item $env:nfast_kmdata $BackupFolder\HSM
 if(!$?)
 {
 WriteDebugLog "Error Copying Thales HSM Files. Error: " + $error[0]
 #Not considered a critical error, so backup will continue
 }
 }

WriteDebugLog "Checking CA Type to determine if an Issuing CA"
 $activeConfig = get-itemproperty -path "HKLM:\System\CurrentControlSet\Services\CertSvc\configuration" -Name active
 $activeConfig = $activeConfig.Active
 $CAType = get-itemproperty -path HKLM:\System\CurrentControlSet\Services\CertSvc\configuration\$activeConfig -Name CAType
 if ($CAType.CAType -eq "1")
 {
 WriteDebugLog "CA is an Issuing CA - Dumping list of templates"
 certutil –catemplates > $BackupFolder\CATemplates.txt
 }

WriteDebugLog "Backup Completed."
 Write-Host "Certification Authority Backup COMPLETED"
 WriteEventLog "Certification Authority Backup COMPLETED" 2

About Mark B. Cooper aka "The PKI Guy"

President & Founder at PKI Solutions, Leading PKI Cybersecurity Subject Matter Expert, Author, Speaker, Trainer, Microsoft Certified Master.

Leave a Comment





This site uses Akismet to reduce spam. Learn how your comment data is processed.