Remotely renewing a certificate using CertEnroll

5.4k views Asked by At

I am trying to renew a certificate using CertEnroll and CertLib COM libraries in PowerShell. Here is my code:

[CmdletBinding()]
param(
[parameter (mandatory=$true)]
[string]$ServerName
)

$credential = Get-Credential

Invoke-Command -ComputerName $ServerName -Credential $credential -ScriptBlock{

$location=[System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser
$store =New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList $location
$store.Open(1)
$cert = $store.Certificates.Find([System.Security.Cryptography.X509Certificates.X509FindType]::FindByIssuerName,"<CA-Name>",$false)[0]
#Write-Output $cert.IssuerName
$store.Close()
$request = New-Object -ComObject X509Enrollment.CX509CertificateRequestPkcs7 
try{
$request.InitializeFromCertificate(0x2,$true,[System.Convert]::ToBase64String($cert.RawData),0x1,3 -band 1024)

$enroll = New-Object -ComObject X509Enrollment.CX509Enrollment
$enroll.InitializeFromRequest($request)

$message = $enroll.CreateRequest(1)

$certReq = New-Object -ComObject CertificateAuthority.Request
$val=$certReq.Submit(0x1 -bor 0,$message,[string]::Empty,"<CA-Server>\"+ $cert.Issuer.Split('=')[1])

if($val -eq 3)
{
    Write-Host "Certificate request accepted"
} 
$reqid=$certReq.GetRequestId()
#$reqid=[System.Convert]::ToInt32($id)
$objcertRequest = New-Object -ComObject CertificateAuthority.Request
$pending = $objcertRequest.RetrievePending($reqid,"<CA-Server>"+$cert.Issuer.Split('=')[1])
if($pending -eq 3)
{
        $certificate = $objcertRequest.GetCertificate(0x1 -bor 0x100);
        $objEnroll = New-Object -ComObject  X509Enrollment.CX509Enrollment
        $objEnroll.Initialize(1);
        $objEnroll.InstallResponse(4,$certificate,1,$null);
       Write-Host "Installed Successfully"
}
else
{
   Write-Error 'error'
}
}
catch
{
Write-Output $_.Exception.Message
Write-Output $_.Exception.ItemName
}
}

I've given correct values for the CA server and the CA Name. I am able to renew the certificates on my local machine but I'm getting error when I try to do it for a certificate on another computer. This is the error I'm getting:

 Exception calling "InitializeFromCertificate" with "5" argument  (s): "CertEnroll::CX509CertificateRequestPkcs7::InitializeFromCertificate: The operation being requested was not performed because the user has not been authenticated. 0x800704dc (WIN32: 1244)"

Can anyone tell me why I'm getting an authentication error. I'm providing the correct credentials.

1

There are 1 answers

1
Crypt32 On BEST ANSWER

You provided credentials to authenticate on a remote host, however these credentials are not used to authenticate on CA server. You have either to:

  1. make remote computer as trusted for delegation (not recommended)
  2. use CredSSP to allow these credentials to use to authenticate on CA server. More details: Enable PowerShell "Second-Hop" Functionality with CredSSP