Skip to main content

PowerShell Crypto Guy's weblog

Go Search
Blog-EN
Blog-RU
PS PKI Module
  

 About



E-mail - Send mail to the author(s)
Live Messenger -
My main blog -
Links
Archive

 Postrank

 ‭(Hidden)‬ Admin Links

Locations of visitors to this page
с блек-джеком и шлюхами
Test, whether CA server is online and which interfaces are available

Few days ago someone asked me how to programmatically test whether CA server is online, and which interfaces (both administration — ICertAdmin and/or enrollment — ICertRequest) are available.

At first, I want to mention that you can use the following CMD commands:

  • certutil –ping

Pings certificate management (ICertAdmin) and enrollment (ICertRequest) interfaces. Optionally you can ping remote CA interfaces: certutil –config CAHostName\CAName –ping

What if you want to do this programmatically? Nice question! Looking to CryptoAPI reference you can find the following methods: ICertAdminD::Ping and ICertRequestD::Ping methods. However, local COM interfaces does not support these methods. Workarounds? PowerShell has workaround! Here is a simple code example, that tests CA and interface availability:

function Test-CAOnline {
[CmdletBinding()]
    param(
        [Parameter(Position = 0)]
        [string]$Config,
        [switch]$ShowUI
    )
$signature = @"
[DllImport("Certadm.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool CertSrvIsServerOnline(
    string pwszServerName,
    ref bool pfServerOnline
);
"@
    Add-Type -MemberDefinition $signature -Namespace CryptoAPI -Name CertAdm
    $CertConfig = New-Object -ComObject CertificateAuthority.Config
    if ($Config -ne "" -and !$Config.Contains("\")) {
        Write-Error -Category InvalidArgument -ErrorId InvalidArgumentException `
        -Message "Config string must be passed in 'CAHostName\CAName' form."
        break
    } elseif ($Config -eq "" -and !$ShowUI) {
        try {$Config = $CertConfig.GetConfig(0x3)}
        catch {
            Write-Error -Category ObjectNotFound -ErrorId ObjectNotFoundElement `
            -Message "Certificate Services are not installed on local computer."
            break
        }
    } elseif ($Config -eq "" -and $ShowUI) {
        $Config = $CertConfig.GetConfig(0x1)
    }
    if ($Config) {
        [void]($Config -match "(.+)\\(.+)")
        $Server = $matches[1]
        $CAName = $matches[2]
        $ServerStatus = $false
        $hresult = [CryptoAPI.CertAdm]::CertSrvIsServerOnline($Server,[ref]$ServerStatus)
        if ($ServerStatus) {
            $CertAdmin = New-Object -ComObject CertificateAuthority.Admin
            $CertRequest = New-Object -ComObject CertificateAuthority.Request
            $CA = New-Object psobject -Property @{
                Name = $CAName;
                ICertAdmin = $true;
                ICertRequest = $true
            }
            try {$retn = $CertAdmin.GetCAProperty($Config,0x6,0,4,0)}
            catch {$CA.ICertAdmin = $false}
            try {$retn = $CertRequest.GetCAProperty($Config,0x6,0,4,0)}
            catch {$CA.ICertRequest = $false}
            $CA
        } else {
            Write-Error -Category ObjectNotFound -ErrorId ObjectNotFoundException `
            -Message "Unable to find a Certification Authority server on '$Server'."
        }
    } else {return}
}

This is more complicated, but more helpful example. If you want to test local CA (when CA server is installed on the same computer), or remote CA server. Remote server can be specified explicitly by using –Config parameter. Remote CA server must be passed in a 'CAHostName\CAName' form. Alternatively you can use –ShowUI parameter to select from Enterprise CA list. In that case you must omit –Config parameter. Here are some useful examples:

[Administrator] Test-CAOnline Name ICertRequest ICertAdmin ---- ------------ ---------- Contoso CA True True [Administrator] Test-CAOnline -Config "dc2\contoso-dc2-ca" Name ICertRequest ICertAdmin ---- ------------ ---------- contoso-dc2-ca True True [Administrator] Test-CAOnline -ShowUI Name ICertRequest ICertAdmin ---- ------------ ---------- contoso-DC2-CA True True [Administrator]

If CA server is unavailable — an error will be thrown.

HTH.

PS PKI v1.0 is released!

Hello мир! Yesterdays I've published another version of my PowerShell PKI module — v1.0. Here are release notes:

Installation experience

I've spent much time on reviewing existing installation experience. My main goals were:

  • Provide a single package for different platforms — x86 and x64.
  • Support direct updates (without requiring to manually remove previous installation).
  • Provide custom installation scenarios — for current user or for all users.

As you may be noticed, previously I've used Advanced Installer (thanks to PowerShell MVP Shay Levy who advised me this product) to wrap my package in MSI. Advanced Installer has intuitive, well-designed (attractive) and rich UI and this product is (possible) the best for beginners like me. However, free license is not enough for custom installation scenarios (like 32/64-bit mixed packages, direct upgrades, patching and so on). In order to accomplish these goals, I've contacted Caphyon Advanced Installer team for some support here. Advanced Installer support was very quick and kind, so I'm ready to provide new installation experience.

Now you need only single package to install the module on either x86 or x64 platform and all future updates will automatically upgrade existing installation.

Besides these technical questions, I was thinking about installation paths. Generally speaking, Windows PowerShell team do not recommend to install custom modules to the default location: %windir%\System32\WindowsPowerShell\v1.0\Modules due to the fact that the folder may be replaced by certain updates or upgrades. I'm still looking for the best solution here. Therefore I've changed module installation default path from System32 folder to My Documents folder. By default it is installed to My Documents\WindowsPowerShell\Modules folder (for current user only). Optionally you can switch to System32 folder by checking corresponding check-box in installation UI.

Even though the default path is My Documents folder and do not require administrator permissions, I don't think that this is a good idea, when any user can install the module by using MSI/EXE. This means that local administrator permissions are required for all cases!

What is changed in the code?

  • CRL Distribution Points and Authority Information Access extension management

During module usage I've faced some bad things. For example, it was not possible to replace all CDP/AIA URLs. You was able to remove particular URLs, but not replace them all. To address this issue I've revisited and changed AuthorityInformationAccess and CRLDistributionPoint objects, so now you receive one object per CA. All URLs are placed in the URI property:

PS C:\> Get-CA int* | get-cdp DisplayName URI ----------- --- Sysadmins LV Internal Class 1 SubCA-1 {65:C:\Windows\system32\CertSrv\CertEnroll\%3%8%9.crl, 65:\\sysadmins.lv\Sh...

You can expand the URI property by piping the object to 'Select -Expand URI' command and you'll get detailed information about each URI:

PS C:\> Get-CA int* | get-cdp | select -ExpandProperty uri RegURI : 65:C:\Windows\system32\CertSrv\CertEnroll\%3%8%9.crl ConfigURI : C:\Windows\system32\CertSrv\CertEnroll\.crl Flags : {1, 64} CRLPublish : True DeltaCRLPublish : True AddToCertCDP : False AddToFreshestCRL : False AddToCRLCDP : False IDP : False <...>

Now you can create oneliners that will replace all links like this:

Get-CA | Get-CDP | Remove-CDP –URI * | Add-CDP –URI "link1","link2","link3" | Set-CDP

Another good improvement is in Get-CertificationAuthority command. At first I've added short Get-CA alias, because even PowerShell has tab-completion, I had to press Tab button many times to get the right command. Now the things are easier. In addition, I've encountered an issue with annoying delays during CA information retrieval in the case when one or more CAs are offline. Even if I explicitly specify the right CA name (which is online). I've changed the behavior to filter out unnecessary CA objects and they are returned immediately after object construction (say, you've specified particular CA or CAs server which is online and there are other stopped CAs).

  • Service start/stop operations

Many commands (especially Set-* and Restore-*) has –RestartCA switch parameter to restart CA service to immediately apply changes. Previously there was a fixed 2sec timeout between StopService and StartService function calls. This fixed timeout causes service start issues when the CA database is relatively large. Now, the behavior is changed to wait until CA service is completely stopped and then call for service start. There are 2 notes:

Note: After service is started, CA server may not be immediately available. This is because, CA server continues database checking and will not respond to client calls.

Warning: do not use –RestartCA switch parameter and Start/Stop/Restart-CertificationAuthority commands against clustered CAs. This is because, when you try to stop CertSvc service, cluster will treat this as a node failure and will move CA resource to second node and CA cluster may fail. Instead, all service stop/start operations MUST be performed by using cluster tools (cluadmin.msc or Cluster PowerShell module), so the cluster service is aware about your actions. In other words, you must take appropriate resource offline or bring it back online.

New stuff

Mainly I've spent attention to existing commands and only 2 new commands are added:

If you are subscribed to my blog or read it on a regular basis, you may notice that this is the same stuff as posted here: Install Certification Authority with PowerShell. Enjoy CA installation from PowerShell console! :)

Other stuff

I've performed some additional tests and can say about:

  • PowerShell 3.0 support — not supported!

The module isn't working in Windows PowerShell 3.0 CTP1 and partially works in CTP2. The problem (still exist) with CTP2 is that it won't load format (PKI.Format.ps1xml) file. Other functionality seems ok, but without formatting. Will wait for next bits.

  • Clustered CA support

The module supports clustered CAs with the only limitation mentioned above (about CA server start and stop operations). Everything else works just fine and is supported.

Other notes and downloads are available here: Downloads

p.s. do not hesitate to share your opinions and suggestions regarding the module. It is designed for you and you have some good ideas to implement — you are welcome.

p.p.s. after new version publishing I've noticed that the module was downloaded 1k times (since project launch):

image

:)

Do I need to implement Online Responder for Root/Policy CAs?

Hi S-1-1-0, PS Crypto Guy is again on the board! Today I want to discuss about implementing Online Responder for Root and Policy CAs.

Abstract

Online Responder implements Online Certificate Status Protocol (OCSP) as a part of alternate certificate validation mechanism (or revocation provider). Classic PKI uses Certificate Revocation Lists (CRL) to provide an information about revoked and untrusted certificates issued by the particular Certification Authority (CA). Most applications perform certificate checking for revocation by downloading and examining the particular issuer's CRL (or CRLs). If the presented certificate's serial number is listed in the corresponding issuer's CRL, an application rejects that certificate. During the CA lifecycle, you sometimes revoke some unnecessary and untrusted certificates. For example, if a certificate holder lost his/her certificate and associated private key, or a user left the company. Each revoked certificate's serial number is added to the CRL.

When you setup a new fresh CA server, an initial CRL is about 500 bytes in size. Each revoked certificate increases this size by about 30-80 bytes. If you revoke 1,000 certificates, a CRL size will increase by 30-80kb. In large environments this number of revoked certificates can be reached quite quickly. This cause network overload and certificate validation delays due to regular CRL transmission over the network and additional client resources (CPU) is used to decode large binary CRL.

To address this issue, a OCSP was introduced. OCSP assumes client-server communications consuming fixed size — about 2kb regardless of CRL size. The CRL can be 1mb large (or even more), but OCSP communications still takes about 2kb for each certificate being validated. OCSP greatly reduce network load and certificate revocation delays.

Source of the problem

Since Windows Server 2008 implements Online Responder role, many administrators started Online Responder deployment within their private PKIs. In most cases, Online Responder is implemented for all CAs in the particular PKI, including Issuing, Policy (if any) and Root CAs. There is nothing wrong with such configuration, but it is really useless to implement Online Responder for offline CAs — Policy and Root. This is because, these CA roles issue certificates only to the subordinate CAs and not to other entities. While user and computer certificates are revoked quite frequently, it is unlikely to have many revoked CA certificates. Therefore Root and Policy CAs maintain an empty (or with only few revoked subordinate CA certificates) CRL.

As said, a OCSP is intended to reduce large CRL retrieval and decode delays. Since empty CRL is about 500 bytes, there are no performance or any other benefits. Moreover, OCSP communication consumes more traffic, than empty CRL retrieval. Also, this causes additional administrative overhead in additional Online Responder configuration management.

And remember, that OCSP is not a classic CRL replacement, just additional revocation provider and there are no strict requirements to implement OCSP for all CAs in the PKI. Ok, you can say, that some guys from VeriSign have implemented Online Responder for Root CAs too (while their CRLs are empty) — http://evsecure-crl.verisign.com/pca3-g5.crl. I doubt that you are a large CA provider as VeriSign with active certificate support in worldwide.

Conclusion

By summarizing this post, we can conclude that Online Responder should be implemented for those CAs which have quite large CRLs or there is a tendency for CRL growing — most likely Issuing CAs, that issue certificates to end entities (users and computers). There are no benefits (at all) in implementing Online Responder for less active CAs that issue certificates only to other CAs. Therefore, you should not implement Online Responder for these CA roles unless there is a special requirement in the external certificate/security policy.

Database log files are not truncated when you perform a full Certification Authority database backup.
SYMPTOMS

Consider the following scenario. You have Windows Server 2008 R2 with installed Active Directory Certification Authority role. When you perform a full database backup by using either certutil.exe utility, or Certification Authority, the database log files are not truncated, as expected and backup set may contain up to 60 database log files. When using certutil.exe tool, it reports that log files are successfully truncated:

Backing up Database files: 100%
Backing up Log files: 100%
Truncating Logs: 100%
Backed up database to C:\Backup.
Database logs successfully truncated.
CertUtil: -backupDB command completed successfully.

In the Application eventlog you can find a record with EventID = 225 and the following message:

certsrv.exe (2420) No log files can be truncated.

If you restart Certificate Services before database backup, all logs, except the newest (created after Certificate Services start), are successfully truncated.

In previous operating systems (Windows Server 2003 and Windows Server 2008), log files are truncated to the most recent log file after each successive backup.


CAUSE

This behavior occurs due to internal changes in Certificate Services JET database to provide better stability in the case of unexpected Certificate Services exit.

Note: the following detailed description is provided for informative purposes only. The information below don't provide any steps to change the behavior.

After securing a backup of the database and log files, the log files can optionally be truncated. Log file volume increases with database activity, and truncating the log files will reduce the redundant records in the log files (thereby decreasing the disk space used to store the log files).
 
The log files are provided for database integrity and efficiency. If a less-than-graceful exit occurs with the Certificate Services application, the next time Certificate Services is started, the database replays the log files to prevent data corruption from being introduced into the database.

Certificate Services database supports a number that is known as "checkpoint". All log files behind this checkpoint number are protected from truncation. To determine the current checkpoint you can use esentutl.exe tool. The esentutl.exe tool is shipped with each Windows Server 2008 R2 installation and is stored in %windir%\System32 folder. Here is an example syntax to use:

esentutl /mk <PathToADatabaseFolder>\edb.chk

and the following example output is returned:

Extensible Storage Engine Utilities for Microsoft(R) Windows(R)
Version 6.1
Copyright (C) Microsoft Corporation. All Rights Reserved.

Initiating FILE DUMP mode...
      Checkpoint file: .\CertLog\edb.chk

      LastFullBackupCheckpoint: (0x0,0,0)
      Checkpoint: (0x3B,2E,70)
      FullBackup: (0x3B,8,16)
      FullBackup time: 11/26/2011 15:40:03

The number identifies the start log file number to protect. In a given example, the file is — edb0003B.log. Any log files behind this number (edb0003C.log, edb0003E.log, etc.) are protected from truncation. Certificate Services database maintains 60 latest log files created from the last Certificate Services start. When 61st (and subsequent) log file is created, a checkpoint is increased by one to keep only 60 latest log files.

As mentioned in this section, when Certificate Services is successfully started, the database replays the log files to prevent data corruption from being introduced into the database. In this case checkpoint number is feed to the current log file ID, thereby allowing to truncate all log files, created before Certificate Services start.


STATUS

This behavior is by design.


WORKAROUND

No workaround available.


APPLIES TO
  • Windows Server 2008 R2 RTM Standard, Enterprise and Datacenter editions
  • Windows Server 2008 R2 SP1 Standard, Enterprise and Datacenter editions
  • Active Directory Certificate Services
Install Certification Authority with PowerShell

Hi there! PowerShell Crypto Guy is again here!

Today I've finished SetupCA.ps1 script testing and I'm ready to share it with you. Of course this is not the first attempt to install CA role from cmdline, there is already SetupCA.vbs script written by Windows PKI team. To be honest, this is not the first PowerShell script for CA installation from cmdline. The first attempt was made by Hasain Alshakarti — http://secadmins.com/?dl_id=3. However this script just illustrates basic API functionality with ability to specify CA name, CA certificate validity and CA type. There is no error handling at all, even whether the CA can be installed on the computer.

My script is primarily intended for automated CA installation and as the only way to install CA service on Server Core installations, because there is no server manager UI. I will not post the script here, but attach as a file (there are 346 lines of PowerShell code).

Abstract

At first I want to compare my script — SetupCA.ps1 and Microsoft's SetupCA.vbs. The advantages of my script:

  • Much less code (but who cares?);
  • The code uses the most efficient APIs (unlike SetupCA.vbs that actively uses some hand-routines, instead of using available APIs);
  • Unlike original CASetup.vbs, PowerShell implementation can setup root CA with custom validity (by default 5 years);
  • User-friendly and unified syntax. Most parameters are self-explanatory;
  • The script has improved error handling with detailed (as possible) error messages;
  • It works really faster than VBS;

The disadvantages:

  • Requires PowerShell 2.0 (not installed by default on Windows Server 2008/2008 R2 Server Core installations);
  • Is published after SetupCA.vbs and has no chances to become so popular as existing VBS script.

But in any way, for PS guys this might be preferred, because PS really rocks!

Script parameters

The script shares 3 parametersets for CA installation:

  1. NewKeySet — to generate new public/private key pair. All parameters within this parameter set are optional;
  2. PFXKeySet — this parameterset is commonly used for CA failover cluster installations. During setup you specify only path to a PFX file and password.
  3. ExistingKeySet — is similar to previous. During installation you specify CA certificate thumbprint. CA certificate must be already installed in system certificate store.

Install CA with new keys

The following parameters can be used:

  • CAName (optional)

This parameter specifies custom CA certificate name/subject (what you see in the certificate display UI). If not passed, a '<ComputerName>-CA' form is used for workgroup CAs and '<DomainName>-<ComputerName-CA>' form is used for domain CAs. The parameter supports Unicode names.

  • CADNSuffix (optional)

This parameter specifies DN suffix to specify some additional information. For example, company name, country, city, etc. DN suffix is empty for workgroup CAs and includes current domain distinguished name (for example, DC=domain,DC=com). The parameter accepts suffixes in a X500 form, for example: OU=Information Systems, O=Sysadmins LV, C=LV.

  • CAType (optional)

Specifies CA type — Standalone Root, Standalone Subordinate, Enterprise Root, Enterprise Subordinate. If not passed, for non-domain environments or if you don't have Enterprise Admins rights, Standalone Root is used. If you have Enterprise Admins rights and your forest already has installed CAs, Enterprise Subordinate is used. If no Enterprise CAs installed in the forest, Enterprise Root is used.

  • ParentCA (optional)

This parameter allows you to specify parent CA location only if you install Enterprise Subordinate CA. For other CA types, the parameter is ignored. Parent CA information must be passed in the following form: CAComputerName\CASanitizedName. Sanitized name is a sanitized form of CA name (subject). Mostly sanitized name is the same as CA name (unless you use Unicode and/or special characters, that are disallowed in X500). If the parameter is not specified, a certificate request will be generated on the root of system drive. I've decided to not implement this parameter for Standalone Subordinate CAs, because mostly they are installed in a workgroup environments and direct request submission to other CAs is likely unavailable (due of computer authentication complexity in non-domain environments). However, if you need it — contact me.

  • CSP (optional)

Specifies custom cryptographic service provider. By default 'RSA#Microsoft Software Key Storage Provider' is used (in most cases you will use default CSP). You need to explicitly specify custom CSP only when you setup completely CNG authority (CSPs with ECDSA prefix) or you use HSM. Each HSM uses it's own custom CSP. You must install HSM middleware before CA installation.

The full list of supportable and available "by default" CSP for Windows Server 2008+ is:

Microsoft Base Cryptographic Provider v1.0
Microsoft Base DSS Cryptographic Provider
Microsoft Base Smart Card Crypto Provider
Microsoft Enhanced Cryptographic Provider v1.0
Microsoft Strong Cryptographic Provider
RSA#Microsoft Software Key Storage Provider
DSA#Microsoft Software Key Storage Provider
ECDSA_P256#Microsoft Software Key Storage Provider
ECDSA_P384#Microsoft Software Key Storage Provider
ECDSA_P521#Microsoft Software Key Storage Provider
RSA#Microsoft Smart Card Key Storage Provider
ECDSA_P256#Microsoft Smart Card Key Storage Provider
ECDSA_P384#Microsoft Smart Card Key Storage Provider
ECDSA_P521#Microsoft Smart Card Key Storage Provider
  • KeyLength (optional)

This parameter specifies key length. If not specified, a 2048-bit key will be generated. There is a little trick: if you look to a CSP list (above), you will see that key length is specified for each ECDSA* provider. I've developed a script logic in that way, so the script ignores this parameter if one of ECDSA* CSP is explicitly chosen and uses key length that is supported by the CSP. Therefore you will not receive an error if you select 'ECDSA_P256#Microsoft Smart Card Key Storage Provider' CSP with 2048 key length. 256-bit key will be selected automatically.

  • HashAlgorithm (optional)

This parameter specifies hash algorithm that will be used for CA certificate/request hashing. Note that this is important for root CA installations. Subordinate CA certificates are hashed and signed by the parent CA with it's own settings. By default 'SHA1' is used (though this parameter is applicable for all CA installation types).

  • ValidForYears (optional)

Specifies the validity for root CA installations. By default root CA certificates are valid for 5 years. You can increase this value to 10, 20, 50, whatever you need. For any subordinate CA types this parameter is silently ignored. This is because subordinate CA validity is determined by the parent CA. This parameter accepts integer values, assuming that the value is specified in years.

  • RequestFileName (optional)

If you setup any sort of subordinate (not root) CAs you can specify custom path to a request file. By default request file is generated on the root of system drive.

Install CA and specify PFX for input information

As said, this setup type commonly is used when you setup additional failover cluster nodes or you restore CA from backup. If you specify PFX file, it is used as input information to properly setup Certification Authority. Therefore there are only 2 mandatory parameters:

  • CACertFile (mandatory)

Specifies the path to a PFX file with CA certificate. Relative paths are allowed. Setup API performs additional checks for the certificate. Therefore you must ensure if: this is CA certificate (but not EFS encryption ;)), CA certificate is trusted (for non-root certificates) and chains to trusted CA and CA certificate revocation checking can be performed. Otherwise you will unable to setup CA with that CA certificate.

  • Password (mandatory)

Specifies the password to open PFX file. The parameter supports only securestrings! You can't type a password as a simple text. This is made for security reasons. There are few ways to pass a password in a securestring form:

$Password = Read-Host –a

or

ConvertTo-SecureString <plaintext> –a –f

You can enclose last command in parentheses and pass directly as a parameter value.

Install CA and specify already installed certificate

This method differs with previous only by the place where the CA certificate is stored — in an external PFX file or already installed to the system store. Since it is already installed, the only parameter you need to specify is:

  • Thumbprint (mandatory)

this parameter specifies a thumbprint of the certificate to use. The certificate must be installed in Local Machine\Personal store and must be trusted (for non-root certificates) and must not be revoked (the issuer revocation information must be available).

Common parameters

The script uses some additional parameters that can be specified for any CA installation scenario:

  • DBDirectory (optional)

Specifies the path to a folder to store CA database. If not specified, the default path: %windir%\System32\CertLog folder is used. If you need to specify custom path (for example, shared storage for CA clusters), you need to specify the next parameter too. The path must be valid.

  • LogDirectory (optional)

Specifies the path to a folderto store CA database log files. By default %windir%\System32\CertLog folder is used. If you use custom path for either database or log folders, you must explicitly specify both paths. Probably I'll change this behavior in next versions.

  • OverwriteExisting (optional)

Specifies, whether to overwrite any existing database files in the specified directories.

  • AllowCSPInteraction (optional)

Specifies, whether the cryptographic service provider (CSP) is allowed to interact with the desktop. This parameter should be used only if you use custom hardware-based CSP (HSM or smart card CSP). In other cases you don't need to allow CSP interactions.

  • Force (optional)

By default, the script explicitly prompts you whether you want to install Certification Authority with selected values. If you want to implement silent (quiet) installations — specify this parameter to suppress any prompts during role installation.

Script installation

To install the script (expose included commands) you do either:

  • copy file contents to a console. Not very good choice :)
  • dot-source the script.

To dot-source the script you must type dot, space and path to a script file:

. c:\temp\setupca.ps1

and all commands from the file will be exposed to the PowerShell session and can be used like other native commands.

Examples

To simplify script usage, I'll provide some common examples.

To install offline Root CA you can do something like this:

  • Example 1
Install-CertificationAuthority -CAName "My Root CA" -CADNSuffix "OU=Information Systems, O=Sysadmins LV, C=LV" `
-CAType "Standalone Root" -ValidForYears 10

In this scenario you setup new Standalone Root CA with "CN=My Root CA, OU=Information Systems, O=Sysadmins LV, C=LV" subject, that will be valid for 10 years. The CA will use default paths to CA database and log files and certificate will use 'RSA#Microsoft Software Key Storage Provider' CSP with 2048-bit key and SHA1 hashing algorithm.

  • Example 2
Install-CertificationAuthority -CAName "My Root CA" -CADNSuffix "OU=Information Systems, O=Sysadmins LV, C=LV" `
-CAType "Standalone Root" -ValidForYears 20 -CSP "ECDSA_P256#Microsoft Smart Card Key Storage Provider" `
-HashAlgorithm SHA512

This example is similar to previous, with the exception that this CA will be completely CNG/SHA2 root. CA certificate will use CNG (not RSA) keys and hashing algorithm will be SHA512.

  • Example 3
Install-CertificationAuthority -CAName "Clustered CA" -CADNSuffix "OU=Information Systems, O=Sysadmins LV, C=LV" `
-CAType "Enterprise Subordinate" -KeyLength 4096 -DBDirectory "S:\CertDB" -LogDirectory "S:\CertLog" `
-RequestFileName "S:\Clustered CA.req"

This example assumes that you setup CA cluster first node (but not necessary). CA database will be stored on a shared storage (attached with S: drive letter). CA certificate will use default 'RSA#Microsoft Software Key Storage Provider' with 4096-bit key and default SHA1 hashing algorithm. CA certificate validity will be determined by the parent CA. In addition, CA certificate request will be stored on the shared storage.

  • Example 4
$Password = Read-Host -AsSecureString
Install-CertificationAuthority -CACertFile .\ClusteredCA.pfx -Password $Password `
-DBDirectory "S:\CertDB" -LogDirectory "S:\CertLog" -OverwriteExisting

This is two-line example. Say, you have successfully installed CA cluster first node and have exported CA certificate to a PFX, and moved it to the second node (to the current directory). At first you will be prompted for a password. Since you type password to a securestring prompt, no characters will be displayed. After that you will specify relative path to a PFX file and specify shared storage to store CA database and log files. You overwrite database files that was created during first node installation. Actually this command installs CA cluster second node.

  • Example 5
Install-CertificationAuthority -CAName "Company Enterprise CA-2" -CADNSuffix "O=Company, E=companypky@company.com" `
-CAType "Enterprise Subordinate" -ParentCA "ca01.company.com\Company Enterprise CA-1"

From best-practices perspective this is not a very good example, because it assumes at least 2 tiers of Enterprise CAs. However, it is still common. In a given example, Enterprise Subordinate CA will be installed and certificate request will be sent directly to existing Enterprise CA — 'Company Enterprise CA-1' that is hosted on 'ca01.company.com'. Note that existing CA must be online and must issue 'Subordinate Certification Authority' template.

Uninstall Certification Authority

The script provides an ability to uninstall CA role from the server. CA removal command consist of two optional parameters (switches):

  • AutoRestart (optional)

Automatically restarts computer to complete CA role removal. Otherwise you will have to restart the server manually.

  • Force (optional)

By default, the commands prompts you whether you want to remove CA role. Use –Force switch to suppress all prompts.

The syntax is very simple:

Uninstall-CertificationAuthority -AutoRestart -Force

The command will uninstall CA role, suppresses all prompts and automatically restarts the server upon completion.

And the last use this button to download the script:

1 - 5 Next