I have a small application as a 'certificate manager' to a larger program, so that users won't have to manually install and configure certificates.
It's fairly simple - it has some certificates as Embedded Resources, which it loads into the appropriate stores, then sets appropriately configured permissions.
This appears to work correctly while the program is running. Using MMC, I can see that the certificate is installed. If I Manage Private Keys, it has a new permission added correctly. However, as soon as I close the certificate manager, the permissions break. The certificate is still installed, but hitting Manage Private Keys pops up an error similar to "Key does not exist."
Additionally, if the program is run a second time, the permissions will 'stick' correctly after the program exits.
Here's code which the program uses to verify that the permissions were added. This method returns 'true' every time, even when the permissions break afterwards.
private bool GetSecurityStatus(X509Certificate2 cert, X509Store store)
{
store.Open(OpenFlags.ReadOnly);
//add Authenticated Users to private cert
RSACryptoServiceProvider privKeyRSA = cert.PrivateKey as RSACryptoServiceProvider;
string keyFilePath = FindKeyLocation(privKeyRSA.CspKeyContainerInfo.UniqueKeyContainerName);
FileInfo privateKeyFileInfo = new FileInfo(keyFilePath + "\\" + privKeyRSA.CspKeyContainerInfo.UniqueKeyContainerName);
FileSecurity privateKeyFileSecurity = privateKeyFileInfo.GetAccessControl();
AuthorizationRuleCollection rules = privateKeyFileSecurity.GetAccessRules(true, true, typeof(NTAccount));
foreach (FileSystemAccessRule fsar in rules)
{
if(fsar.IdentityReference.Value.Contains("Authenticated Users") && fsar.AccessControlType == AccessControlType.Allow && fsar.FileSystemRights == FileSystemRights.FullControl){
store.Close();return true;
}
}
//Close Private Cert store
store.Close();
return false;
}
The FindKeyLocation returns the appdata\Microsoft\Crypto\RSA\ path of the private key.
I'm thinking it has to do somehow with the exiting of the program altering the private key file itself, but I'm unsure why it would then work the second time.