Share via


How to Remove ACLs from CSP Key Containers

Using Cryptographic Service providers is the way to implement PKI on PCs and we are using it for our project. Lately I needed to remove some ACLs for an upgrade scenario. I searched the msdn for related info but couldn’t find a direct API to change ACLs on key containers. Then Shawn a security expert at Microsoft helped me to use RSACryptoServiceProvider object to alter keycontainer ACLs. If a modified CspParameters.CryptoKeySecurity RSACryptoServiceProvider constructor, it will change the ACLs on key container. Actually you can use same method to add a new ACL, just add the desired rule using CryptoKeySecurity.AddAccessRule(rule). Here is a sample function to remove a user from key container access.

public void RemoveKeyContainerAccess(string userName, string CSPName, string keyContainerName)

        {

            NTAccount account = GetAccount(userName);

            CspParameters cspParams = new CspParameters(1, CSPName, keyContainerName);

            cspParams.Flags = CspProviderFlags.UseMachineKeyStore;

            CspKeyContainerInfo container = new CspKeyContainerInfo(cspParams);

            //get the original acls first

            cspParams.CryptoKeySecurity = container.CryptoKeySecurity;

            //Search for the account given to us and remove it from accessrules

            foreach (CryptoKeyAccessRule rule in cspParams.CryptoKeySecurity.GetAccessRules(true, false, typeof(NTAccount)))

            {

                if (rule.IdentityReference.Equals(account))

                    cspParams.CryptoKeySecurity.RemoveAccessRule(rule);

            }

            //persist accessrules on key container.

            RSACryptoServiceProvider cryptoServiceProvider = new RSACryptoServiceProvider(cspParams);

        }

Comments