Monday, July 18, 2011

Granting Network Service permissions to a Certificates Private key

There are many many reasons why you want your applications to run under the more restricted Network Service instead of the higher Local System.

The problem that you run in to is when certificates are involved.

A Local Machine Certificate is generally available to processes running as Local System by default.

In my case I have Azure injecting the certificate into the role for me and I have a legacy application component that needs to be able to use that certificate.  For security reasons this service runs as the pretty restricted Network Service. 

If I simply add the application and point to the certificate it cannot use the certificate to perform encryption because the application does not have access not the private key.  Once again, script it!

My script assumes one thing, that you have gotten the actual SSL Certificate that you want to use.  There are lots of ways to get the certificate; here is what I used:

$sslCert = Get-ChildItem Cert:\LocalMachine\My | where {$_.Subject -match ""}

Here is the script that does the rest:

$sslCertPrivKey = $sslCert.PrivateKey
$privKeyCertFile = Get-Item -path "$ENV:ProgramData\Microsoft\Crypto\RSA\MachineKeys\*"  | where {$_.Name -eq $sslCertPrivKey.CspKeyContainerInfo.UniqueKeyContainerName}
$privKeyAcl = (Get-Item -Path $privKeyCertFile.FullName).GetAccessControl("Access")
$permission = "NT AUTHORITY\NETWORK SERVICE","Read","Allow"
$accessRule = new-object System.Security.AccessControl.FileSystemAccessRule $permission
Set-Acl $privKeyCertFile.FullName $privKeyAcl

From the certificate we can discover its private key.  Using this I can then turn to the file system and discover that physical private key.

The gotcha resides in one line when setting $privKeyAcl  Notice the GetAccessControl(“Access”) – that only fetches the Access properties, if you don’t use that you get all properties and will end up with an error when you try to Set or Add the new permissions.  (thank you to Bilal Aslam for posting the workaround here.)

The rest simply covers modifying the ACL of the file system object.

I hope you found this one useful.


Anonymous said...

Thank god for that extra little fix! :). Saved my day!

Anonymous said...

Thank you for this excellent example script !!!. Exactly what i needed to do. MR

Jeff said...

Well done sir, saved me some time!