Exemplo n.º 1
0
        private CryptoKeySecurity createAccessRules()
        {
            var defaultRules = true;
            var result       = new CryptoKeySecurity();

            foreach (var identity in getIdentityList(_writeAccess))
            {
                result.AddAccessRule(new CryptoKeyAccessRule(new NTAccount(identity), CryptoKeyRights.FullControl, AccessControlType.Allow));
                defaultRules = false;
            }

            foreach (var identity in getIdentityList(_readAccess))
            {
                result.AddAccessRule(new CryptoKeyAccessRule(new NTAccount(identity), CryptoKeyRights.GenericRead, AccessControlType.Allow));
                defaultRules = false;
            }

            return(defaultRules ? null : result);
        }
Exemplo n.º 2
0
        internal static void SetAccessRuleOnKSPKey(CngKey key, string accountName, CryptoKeyRights keyAccessMask)
        {
            const string             NCRYPT_SECURITY_DESCR_PROPERTY = "Security Descr";
            const CngPropertyOptions DACL_SECURITY_INFORMATION      = (CngPropertyOptions)4;

            // retrieve existing permissions
            var existingACL = key.GetProperty(NCRYPT_SECURITY_DESCR_PROPERTY, DACL_SECURITY_INFORMATION);

            // add new rule
            CryptoKeySecurity keySec = new CryptoKeySecurity();

            keySec.SetSecurityDescriptorBinaryForm(existingACL.GetValue());
            keySec.AddAccessRule(new CryptoKeyAccessRule(accountName, keyAccessMask, AccessControlType.Allow));

            // put back
            CngProperty updatedACL = new CngProperty(existingACL.Name, keySec.GetSecurityDescriptorBinaryForm(), CngPropertyOptions.Persist | DACL_SECURITY_INFORMATION);

            key.SetProperty(updatedACL);
        }
Exemplo n.º 3
0
        void AddCertificatePrivateKeyAccess(X509Certificate2 cert)
        {
            if (cert != null && cert.HasPrivateKey)
            {
                try
                {
                    AsymmetricAlgorithm key = cert.PrivateKey;

                    // Only RSA provider is supported here
                    if (key is RSACryptoServiceProvider)
                    {
                        RSACryptoServiceProvider prov   = key as RSACryptoServiceProvider;
                        CspKeyContainerInfo      info   = prov.CspKeyContainerInfo;
                        CryptoKeySecurity        keySec = info.CryptoKeySecurity;

                        SecurityIdentifier ns = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null);
                        // Just add a rule, exisitng settings will be merged
                        CryptoKeyAccessRule rule = new CryptoKeyAccessRule(ns,
                                                                           CryptoKeyRights.GenericRead,
                                                                           AccessControlType.Allow);
                        keySec.AddAccessRule(rule);

                        CommitCryptoKeySecurity(info, keySec);
                    }
                }
#pragma warning suppress 56500
                catch (Exception e)
                {
                    // CommitCryptoKeySecurity can actually throw any exception,
                    // so the safest way here is to catch a generic exception while throw on critical ones
                    if (Utilities.IsCriticalException(e))
                    {
                        throw;
                    }
                    throw new WsatAdminException(WsatAdminErrorCode.CANNOT_UPDATE_PRIVATE_KEY_PERM,
                                                 SR.GetString(SR.ErrorUpdateCertPrivateKeyPerm), e);
                }
            }
        }
Exemplo n.º 4
0
        public static RSA CreateRSAAlgorithm(String containerName)
        {
            RSACryptoServiceProvider rsaKey = null;

            try
            {
                // Create a new CspParameters object to specify a key container.
                CspParameters cspParams = new CspParameters();
                cspParams.KeyContainerName = containerName;
                cspParams.Flags            = CspProviderFlags.UseMachineKeyStore;
                // Add the key's access privilege
                CryptoKeySecurity  keySecurity = new CryptoKeySecurity();
                SecurityIdentifier si          = new SecurityIdentifier(WellKnownSidType.LocalSid /*WorldSid*/, null);
                keySecurity.AddAccessRule(new CryptoKeyAccessRule(si, CryptoKeyRights.FullControl, AccessControlType.Allow));
                cspParams.CryptoKeySecurity = keySecurity;
                // Create a new RSA key and save it in the container. This key will encrypt
                // a symmetric key, which will then be encrypted in the XML document.
                rsaKey = new RSACryptoServiceProvider(cspParams);
            }
            catch (System.Exception ex)
            {
            }
            return(rsaKey);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Import a key from a file for use on the machine.
        /// </summary>
        /// <param name="providerName"></param>
        /// <param name="filePath"></param>
        public bool ImportKeyToKSP(string providerName, string keyName, string filePath, bool makeExportable = false)
        {
            CngProvider provider = new CngProvider(providerName);

            bool keyExists = doesKeyExists(provider, keyName);

            if (keyExists)
            {
                //Key already exists. Can't create it.
                return(false);
            }

            CryptoKeySecurity        sec       = new CryptoKeySecurity();
            CngKeyCreationParameters keyParams = null;

            byte[] keyBlob = File.ReadAllBytes(filePath);

            CngProperty keyBlobProp = new CngProperty(new CngKeyBlobFormat("RSAFULLPRIVATEBLOB").Format, keyBlob, CngPropertyOptions.None);

            if (IsMicrosoftSoftwareKSP(provider))
            {
                sec.AddAccessRule(
                    new CryptoKeyAccessRule(
                        new SecurityIdentifier(sidType: WellKnownSidType.BuiltinAdministratorsSid, domainSid: null),
                        cryptoKeyRights: CryptoKeyRights.FullControl,
                        type: AccessControlType.Allow));

                sec.AddAccessRule(
                    new CryptoKeyAccessRule(
                        new SecurityIdentifier(sidType: WellKnownSidType.BuiltinSystemOperatorsSid, domainSid: null),
                        cryptoKeyRights: CryptoKeyRights.GenericRead,
                        type: AccessControlType.Allow));

                const string             NCRYPT_SECURITY_DESCR_PROPERTY = "Security Descr";
                const CngPropertyOptions DACL_SECURITY_INFORMATION      = (CngPropertyOptions)4;

                CngProperty permissions = new CngProperty(
                    NCRYPT_SECURITY_DESCR_PROPERTY,
                    sec.GetSecurityDescriptorBinaryForm(),
                    CngPropertyOptions.Persist | DACL_SECURITY_INFORMATION);
                keyParams = new CngKeyCreationParameters()
                {
                    ExportPolicy       = makeExportable ? CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport : CngExportPolicies.None,
                    Provider           = provider,
                    Parameters         = { permissions, keyBlobProp },
                    KeyCreationOptions = CngKeyCreationOptions.MachineKey
                };
                using (CngKey key = CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams))
                {
                    if (key == null)
                    {
                        return(false);
                    }
                    return(true);
                }
            }
            else
            {
                keyParams = new CngKeyCreationParameters()
                {
                    ExportPolicy       = makeExportable ? CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport : CngExportPolicies.None,
                    Provider           = provider,
                    Parameters         = { keyBlobProp },
                    KeyCreationOptions = CngKeyCreationOptions.MachineKey
                };
                using (CngKey key = CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams))
                {
                    if (key == null)
                    {
                        return(false);
                    }
                    // nothing to do inside here, except to return without throwing an exception
                    return(true);
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Tries to generate and RSA Key in the given provider with this keyName.
        /// </summary>
        /// <param name="providerName">Name of the provider</param>
        /// <param name="keyName">Name of the key</param>
        /// <param name="keyLength">Length of the key to generate</param>
        /// <returns>true if successful, false if that key already exists.</returns>
        public bool TryGenerateLocalRSAKey(string providerName, string keyName, int keyLength = 2048)
        {
            CngProvider provider = new CngProvider(providerName);

            bool keyExists = doesKeyExists(provider, keyName);

            if (keyExists)
            {
                //Key already exists. Can't create it.
                return(false);
            }

            CryptoKeySecurity        sec       = new CryptoKeySecurity();
            CngKeyCreationParameters keyParams = null;

            if (IsMicrosoftSoftwareKSP(provider))
            {
                sec.AddAccessRule(
                    new CryptoKeyAccessRule(
                        new SecurityIdentifier(sidType: WellKnownSidType.BuiltinAdministratorsSid, domainSid: null),
                        cryptoKeyRights: CryptoKeyRights.FullControl,
                        type: AccessControlType.Allow));

                sec.AddAccessRule(
                    new CryptoKeyAccessRule(
                        new SecurityIdentifier(sidType: WellKnownSidType.BuiltinSystemOperatorsSid, domainSid: null),
                        cryptoKeyRights: CryptoKeyRights.GenericRead,
                        type: AccessControlType.Allow));

                const string             NCRYPT_SECURITY_DESCR_PROPERTY = "Security Descr";
                const CngPropertyOptions DACL_SECURITY_INFORMATION      = (CngPropertyOptions)4;

                CngProperty permissions = new CngProperty(
                    NCRYPT_SECURITY_DESCR_PROPERTY,
                    sec.GetSecurityDescriptorBinaryForm(),
                    CngPropertyOptions.Persist | DACL_SECURITY_INFORMATION);
                keyParams = new CngKeyCreationParameters()
                {
                    ExportPolicy = CngExportPolicies.None,
                    Provider     = provider,
                    Parameters   = { new CngProperty("Length", BitConverter.GetBytes(keyLength), CngPropertyOptions.None),
                                     permissions },
                    KeyCreationOptions = CngKeyCreationOptions.MachineKey
                };
                using (CngKey key = CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams))
                {
                    if (key == null)
                    {
                        return(false);
                    }
                    return(true);
                }
            }
            else
            {
                keyParams = new CngKeyCreationParameters()
                {
                    ExportPolicy = CngExportPolicies.None,
                    Provider     = provider,
                    Parameters   = { new CngProperty("Length", BitConverter.GetBytes(keyLength), CngPropertyOptions.None) }
                };
                using (CngKey key = CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams))
                {
                    if (key == null)
                    {
                        return(false);
                    }
                    // nothing to do inside here, except to return without throwing an exception
                    return(true);
                }
            }
        }