1

I am trying to modify access rules for particular $cert with the following code:

$csp = New-Object System.Security.Cryptography.CspParameters (
    $cert.PrivateKey.CspKeyContainerInfo.ProviderType, 
    $cert.PrivateKey.CspKeyContainerInfo.ProviderName, 
    $cert.PrivateKey.CspKeyContainerInfo.KeyContainerName)

$csp.Flags = [System.Security.Cryptography.CspProviderFlags]::UseExistingKey -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
$csp.CryptoKeySecurity = $cert.PrivateKey.CspKeyContainerInfo.CryptoKeySecurity
$csp.KeyNumber = $cert.PrivateKey.CspKeyContainerInfo.KeyNumber

$access = New-Object System.Security.AccessControl.CryptoKeyAccessRule (
    $identity, 
    [System.Security.AccessControl.CryptoKeyRights]::GenericRead, 
    [System.Security.AccessControl.AccessControlType]::Allow)

$csp.CryptoKeySecurity.AddAccessRule($access)

But it throws an exception on last line because $csp.CryptoKeySecurity is null. While debugging it turned out $cert.PrivateKey.CspKeyContainerInfo.CryptoKeySecurity is null as well. However, the hard part is this only happens on 1 out of 5 machines, is not dependent on OS version, nor PS version, happens in our prod environment only, why... ? FYI $cert.PrivateKey is not null, neither $cert.PrivateKey.CspKeyContainerInfo.

Michal Hosala
  • 5,570
  • 1
  • 22
  • 49
  • 1
    .NET Framework reference code seems to show a non-null case always, https://referencesource.microsoft.com/#mscorlib/system/security/cryptography/icspasymmetricalgorithm.cs,184 – Lex Li Sep 07 '18 at 15:56
  • @LexLi after looking at the code you posted and rewriting the code into C# it turbned out it blows up on `kp.Demand();` because I do not posses necessary privilege - "Manage auditing and security log", hence `null` in PS and exception in c#. – Michal Hosala Sep 17 '18 at 10:39

1 Answers1

1

In the end the problem was in different configuration of security settings on our production environment. On my machine, setting Manage auditing and security log was set to Administrators, while on server it was different, just our OPS people. Found out about this after rewriting the code into C#, which throws an exception, unlike PS, which just silently returns null.

The process does not possess the ‘SeSecurityPrivilege’ privilege which is required for this operation.

For how to work around this issue see this SO question.

Michal Hosala
  • 5,570
  • 1
  • 22
  • 49