question

PrinsAndre-6100 avatar image
0 Votes"
PrinsAndre-6100 asked IanXue-MSFT commented

Create Certificates using Powershell - 2 certificates created

I have a script which generates certificates, that works, but for some reason it also generates a certificate for the OU

 cls
 $url = "https://certenroll.Domain.com/certsrv/certrqma.asp"
 $servers = get-content "C:\Certificates\servers.txt"
    
 $CAName = "certenroll.Domain.com"
 $TemplateName = "operationsManagerCert"
 $E = "andre.prins@Domain.com"
 $OU = "CES"
 $O = "Company"
 $L = "Dallas"
 $S = "Texas"
 $C = "US"
    
    
 ##############################################################################
    
    
 function Remove-ReqTempfiles() {
     param(
         [String[]]$tempfiles
     )
     Write-Verbose "Cleanup temp files..."
     Remove-Item -Path $tempfiles -Force -ErrorAction SilentlyContinue
 }
    
 Function TestReq
 {
     $Done=$False
     Start-Sleep -Seconds 5
     do
     {
         $proc = Get-Process -Name certreq -ErrorAction SilentlyContinue
         if ($proc.count -ge 1)
         {start-sleep -Seconds 1}
         else
         {$Done = $true}
     } until ($Done)
 }
    
    
 ##############################################################################
    
 $rootDSE = [System.DirectoryServices.DirectoryEntry]'LDAP://RootDSE'
 $searchBase = [System.DirectoryServices.DirectoryEntry]"LDAP://$($rootDSE.configurationNamingContext)"
 $CAs = [System.DirectoryServices.DirectorySearcher]::new($searchBase,'objectClass=pKIEnrollmentService').FindAll()
    
 if($CAs.Count -eq 4)
 {$CAName = "$($CAs[1].Properties.dnshostname)\$($CAs[1].Properties.cn)"}
 else 
 {$CAName = ""}
    
 if (!$CAName -eq "") 
 {$CAName = " -config `"$CAName`""}
    
 foreach ($CN in ($servers -split ("`n")))
 {
     if ($CN.IndexOf(".") -gt 1)
     {$FriendlyName = $CN.Substring(0,$CN.IndexOf("."))}
     else
     {$FriendlyName = $CN}
    
 $file = @"
 [NewRequest]
 Subject = "E=$E,CN=$CN,C=$c, S=$s, L=$l, O=$o, OU=$OU"
 MachineKeySet = TRUE
 UseExistingKeySet = False
 KeyLength = 2048
 KeySpec=1
 Exportable = TRUE
 RequestType = PKCS10
 ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0" 
 FriendlyName = "$FriendlyName"
 [RequestAttributes]
 CertificateTemplate = "$TemplateName"
 "@
     
     try
     {
    
         $inf = [System.IO.Path]::GetTempFileName()
         $req = [System.IO.Path]::GetTempFileName()
         $cer = Join-Path -Path $env:TEMP -ChildPath "$CN.cer"
    
         Set-Content -Path $inf -Value $file
    
         Write-host "generate .req file with certreq.exe"
         $error.Clear()
         Start-Process "certreq" -ArgumentList "-new $inf $req" -Verb "RunAs"
         TestReq
    
         Write-host "certreq -submit $CAName `"$req`" `"$cer`""
         Start-Process "certreq" -ArgumentList "-submit $CAName $req $cer" -Verb "RunAs"
         TestReq
    
         Write-host "request was successful. Result was saved to $cer"
    
         write-host "retrieve and install the certificate"
         Start-Process "certreq" -ArgumentList "-accept $cer -machine" -Verb "RunAs"
         TestReq
    
         write-host "Done, cleaning up temp files"
         Remove-ReqTempfiles -tempfiles $inf, $req, $cer
    
     }
     catch
     {
         write-host "Error during request"
         $error
     }
 }

Result:
77735-untitled.png



as you can see at the start of the program, OU="CES" and later in my local machine certificates, I see the CES certificate...
I can see that the Subject of the CES certificate is the same and it is created also with the OperationsManagerCert template...

I just cannot figure out how/why a CES certificate is created and not only the $CN
in servers.txt I have 4 server FQDN names, one per line. and if I just let the script run, it also creates 4x a CES certificate.??!!!??

this is the $inf file:
[NewRequest]
Subject = "E=andre.prins@domain.com,CN=ui1pawb921,C=US, S=Texas, L=Dallas, O=Company, OU=CES"
MachineKeySet = TRUE
UseExistingKeySet = False
KeyLength = 2048
KeySpec=1
Exportable = TRUE
RequestType = PKCS10
ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"
FriendlyName = "ui1pawb921"
[RequestAttributes]
CertificateTemplate = "operationsManagerCert"

(I checked - when I create the certificates manually, OU is also "only" showing CES)

the $req file looks good to me (I deleted most lines to save space )
get-content $req

-----BEGIN NEW CERTIFICATE REQUEST-----
MIIFTDCCBDQCAQAwgacxDDAKBgNVBAsMA0NFUzEVMBMGA1UECgwMQmFrZXIgSHVn
cOG8CqpIzZ42EPgMVZPksQ==
-----END NEW CERTIFICATE REQUEST-----

And I checked the $cer file too
get-content $cer

-----BEGIN CERTIFICATE-----
MIIHQzCCBSugAwIBAgIKG1gOKQAAAAAMATANBgkqhkiG9w0BAQsFADBhMRMwEQYK
RhER3xBDiVTQ/Hq16Rw5LcTpjrqfkIqriEkoDrHeKy3dT2EKNuBk
-----END CERTIFICATE-----

windows-server-powershellmsc-operations-manager
untitled.png (4.1 KiB)
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

What's going on at line #55?

You populate the $servers variable with Get-Content (which will either create a string or an array of strings) on line #3. But then you split $servers on a "`n" character. How did you manage to get the "`n" in there? Did you originally use the "-Raw" switch on the Get-Content and then remove it without modifying line #55 to remove that splitting?

0 Votes 0 ·

Hi,
Have you checked the value of '$servers -split ("`n")' or $CN in the foreach loop?

0 Votes 0 ·

thanks - you're right... CN was empty and that resulted in the CES certificate

0 Votes 0 ·
PrinsAndre-6100 avatar image
0 Votes"
PrinsAndre-6100 answered RichMatheisen-8856 commented

ahhh sometimes the most obvious is overlooked.....

sorry my bad - it turns out the result of the split is adding empty lines, and that is causing the unwanted certificate
I put in a simple check if ($CN -eq "") {continue} and that skips the blank lines.


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

If you're not using the "-Raw" switch on the Get-Content on line #3 than there should be no "`n" characters in the $servers variable.

If you ARE using the -Raw switch then there will be empty elements in the $server array . . . AND each of the elements will also contain a trailing "`r" character! That's because each line of a text file is terminated by a CrLf pair ("`r`n"). Splitting on "`r`n" will fix that, but it won't fix the empty array elements.

The solution? Don't use the -Raw switch and remove the split on line #55. This will be sufficient "foreach ($CN in $servers)"


0 Votes 0 ·
PrinsAndre-6100 avatar image
0 Votes"
PrinsAndre-6100 answered IanXue-MSFT commented

thanks for your response,
but I added the split because it was not behaving as I expected.
but you are right, without the split works fine too - that's how I started, but I was stepping thru manually in debug and noticed the 2nd loop was blank, so I assumed it was the last line, and assumed it was treating the lines with text as one string... jumping to conclusions too quick....

I later looked at it via Notepad++ and then it revealed the extra linefeeds
see below the result in notepad++ and the "normal" notepad - which why I did not notice the extra lines initially.
78731-image.png



after removing the extra empty lines in notepad++ it worked fine without the split.


image.png (4.3 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

You may open the file with a hex editor to see what is added at the end of each line.

0 Votes 0 ·