I have a Powershell script that imports a PFX certificate into the Machine store. This script is intended to be invoked by chef. When I run it manually, it works great. However, when chef runs it, it seems to only complete half its operation.
echo "Importing as PFX" >> $log
$rule = new-object security.accesscontrol.filesystemaccessrule ".\IIS_IUSRS", "Read", allow
$pfx = Get-PfxCertificate -FilePath $file
$certThumbprint = $pfx.Thumbprint
echo "Thumbprint is $certThumbprint" >> $log
"$password" | certutil -ImportPFX "$certStoreLocation" "$file" >> $log
$keyPath = "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\" + (((Get-ChildItem -Path cert:\LocalMachine\My | Where-Object { $_.thumbprint -eq $certThumbprint }).PrivateKey).CspKeyContainerInfo).UniqueKeyContainerName
echo "Updating private key permissions: $keyPath" >> $log
$acl = get-acl -path $keyPath
$acl.AddAccessRule($rule)
# Allow IIS to read this private key
set-acl $keyPath $acl
In my log, I see successful output:
Examining certificate for import: c:\www\certificates\xyz.pfx
Importing as PFX
Thumbprint is 206E30F2694C8627C18EAE97729C643A3CC1317E
Enter PFX password:
Certificate "xyz" added to store.
CertUtil: -importPFX command completed successfully.
Updating private key permissions: C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\aee87c90ef6606b733130f970131e498_051677f6-7959-49c2-afb8-d2fad091409a
And, in MMC, I can see my certificate. However, the path listed in the log is missing, and when I try and examine the private key, it says it's missing. Again, when I run this as myself, it imports fine.
Thinking that I'm going insane, I used Process Monitor to see what's going on:
I don't know why, but it seems that Powershell marks the private key for deletion when it closes the file. What?? Why???
Notes:
- I cannot use Import-PFXCertificate, because it imports it as a CNG certificate, not a CSP certificate, which I lost 10-12 hours on.
- If I remove all the parts relating to setting the ACL, the issue doesn't happen. However, then my application can't read the private key.
