4

I've been wrapping my head around automating a way to perform this task:

We deploy Windows Server 2008 R2 images for our customers. We use PowerShell (version 2) to deploy our proprietary software and make various other changes to the system before shipping. This PowerShell process is run under the local Administrator account until it finishes and disables the local Administrator account.

Now, to the issue - I'm trying to install a .PFX client certificate to a SEPARATE user's CurrentUser\My certificate store. Let's call that user "SQL".

Right now the certificate is getting installed under the LocalMachine\My certificate store but one of our development teams have concerns on that position and would like to replicate the original setup.

Now, I know how to get this done dirty by adding in a reboot-step to our deployment script and having this performed under the "SQL" user but I would like to avoid that as it seems like there has to be a way to get this done while under another account. Here's the basic code we're using now to install the certificate to the LocalMachine\My store. Assume $certPath is the path to the .pfx and $pfxPass is the .pfx's password.

function Import-PfxCertificate {
param([string] $certPath, [string]$pfxPass)

$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import([string]$certPath, [string]$pfxPass, "Exportable,PersistKeySet")

$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My", "LocalMachine")
$store.open("MaxAllowed")
$store.add($pfx)
$store.close()
}    
  • You'll need to impersonate the "SQL" user and instantiate the X509Store targeting the "CurrentUser" Store Location – Mathias R. Jessen Feb 2 '15 at 18:13
  • Thanks Mathias - Do you have any recommendations on the impersonate aspect? I understand changing "LocalMachine" to "CurrentUser", that's easy. Would you recommend using Invoke-Commands with PowerShell credentials? Start-Process? – The_Gribbler Feb 2 '15 at 18:23
5

I do a similar thing for my servers, but I'm not using pure PowerShell:

psexec.exe -accepteula -u sql -p sqlspassword certutil.exe -p certpassword -importPFX cert.pfx

This just runs the certutil command under the specified account, you need to download psexec.exe,

0

I ended up using Start-Process with -Credentials and the free importpfx.exe tool. Basically the same idea as @Mathias stated and @Peter gave an example of.

Thank you both for your help. This was a lot easier than the past two days of research has led me to believe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.