コード例 #1
0
        internal X509Certificate2 InstallCertificate(string certFile)
        {
            SecurityIdentifier sid;

            try
            {
                sid = (SecurityIdentifier) new NTAccount("IME_SYSTEM").Translate(typeof(SecurityIdentifier));
            }
            catch
            {
                logger.Fatal("Could not get SID for IME_SYSTEM user.");

                return(null);
            }

            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadWrite);

            foreach (var c in store.Certificates)
            {
                if (c.GetNameInfo(X509NameType.DnsName, false) == Properties.Settings.Default.MainDomain)
                {
                    logger.Debug("Removing old certificate from store");
                    store.Remove(c);
                }
            }

            store.Close();
            store.Open(OpenFlags.ReadWrite);

            X509Certificate2 cert = new X509Certificate2(certFile, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet)
            {
                FriendlyName = mainDomain
            };

            logger.Debug("Adding new certificate to store");
            store.Add(cert);

            RSACryptoServiceProvider certRsa = cert.PrivateKey as RSACryptoServiceProvider;

            var cspParams = new CspParameters(certRsa.CspKeyContainerInfo.ProviderType, certRsa.CspKeyContainerInfo.ProviderName, certRsa.CspKeyContainerInfo.KeyContainerName)
            {
                Flags             = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore,
                CryptoKeySecurity = certRsa.CspKeyContainerInfo.CryptoKeySecurity
            };

            var rule = new CryptoKeyAccessRule(sid, CryptoKeyRights.GenericRead, AccessControlType.Allow);

            cspParams.CryptoKeySecurity.AddAccessRule(rule);

            logger.Debug("Granting IME_SYSTEM access to certificate.");

            new RSACryptoServiceProvider(cspParams).Dispose();

            store.Close();

            return(cert);
        }
コード例 #2
0
        private static void AclCert(CertId certId, string accountName)
        {
            X509Store store = null;

            try
            {
                store = new X509Store(certId.StoreName, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly);

                X509Certificate2Collection certs = store.Certificates.Find(ConvertToX509FindType(certId.FindType), certId.FindValue, validOnly: false);
                if (certs == null || certs.Count == 0)
                {
                    DeployerTrace.WriteInfo("AclCert is skipped for {0} because it's not installed", certId);
                    return;
                }

                foreach (X509Certificate2 cert in certs)
                {
                    if (cert.PrivateKey == null)
                    {
                        DeployerTrace.WriteWarning("AclCert is skipped for {0} because its private key is null", certId);
                        continue;
                    }

                    RSACryptoServiceProvider privateKey = cert.PrivateKey as RSACryptoServiceProvider;
                    if (privateKey == null)
                    {
                        DeployerTrace.WriteWarning("AclCert is skipped for {0} because its private key type {1} is not supported ", certId, cert.PrivateKey.GetType());
                        continue;
                    }

                    CspParameters csp = new CspParameters(privateKey.CspKeyContainerInfo.ProviderType, privateKey.CspKeyContainerInfo.ProviderName, privateKey.CspKeyContainerInfo.KeyContainerName);
                    csp.Flags     = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore;
                    csp.KeyNumber = (int)privateKey.CspKeyContainerInfo.KeyNumber;
#if !DotNetCoreClr
                    csp.CryptoKeySecurity = privateKey.CspKeyContainerInfo.CryptoKeySecurity;

                    CryptoKeyAccessRule accessRule = new CryptoKeyAccessRule(accountName, CryptoKeyRights.FullControl, AccessControlType.Allow);
                    csp.CryptoKeySecurity.AddAccessRule(accessRule);
#endif

                    using (RSACryptoServiceProvider newCsp = new RSACryptoServiceProvider(csp))
                    {
                        DeployerTrace.WriteInfo("AclCert success: {0}", certId);
                    }
                }
            }
            catch (Exception ex)
            {
                DeployerTrace.WriteError("AclCert error with {0}: {1}", certId, ex);
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }
        }
コード例 #3
0
        public void StringOverloadIsNotSID()
        {
            CryptoKeyAccessRule rule;

            rule = new CryptoKeyAccessRule(@"S-1-5-32-545", CryptoKeyRights.FullControl, AccessControlType.Allow);
            Assert.AreNotEqual(new SecurityIdentifier("S-1-5-32-545"), rule.IdentityReference);
            Assert.AreEqual(new NTAccount(@"S-1-5-32-545"), rule.IdentityReference);
        }
コード例 #4
0
        void RemoveCertificatePrivateKeyAccess(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);
                        AuthorizationRuleCollection rules = keySec.GetAccessRules(true, false, typeof(SecurityIdentifier));
                        foreach (AuthorizationRule rule in rules)
                        {
                            CryptoKeyAccessRule keyAccessRule = (CryptoKeyAccessRule)rule;

                            if (keyAccessRule.AccessControlType == AccessControlType.Allow &&
                                (int)(keyAccessRule.CryptoKeyRights & CryptoKeyRights.GenericRead) != 0)
                            {
                                SecurityIdentifier sid = keyAccessRule.IdentityReference as SecurityIdentifier;
                                if (ns.Equals(sid))
                                {
                                    CryptoKeyAccessRule nsReadRule = new CryptoKeyAccessRule(ns,
                                                                                             CryptoKeyRights.GenericRead,
                                                                                             AccessControlType.Allow);
                                    keySec.RemoveAccessRule(nsReadRule);

                                    CommitCryptoKeySecurity(info, keySec);
                                    break;
                                }
                            }
                        }
                    }
                }
#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);
                }
            }
        }
コード例 #5
0
        public AsymmetricAlgorithm getPrivateKeyForXML()
        {
            if (!this.hasPrivateKey)
            {
                this.error.setError("PK0021", "No private key loaded");
                return(null);
            }
            string algorithm = getPrivateKeyAlgorithm();

            if (SecurityUtils.compareStrings("RSA", algorithm))
            {
                byte[] serializedPrivateBytes         = this.privateKeyInfo.ToAsn1Object().GetDerEncoded();
                string serializedPrivate              = Convert.ToBase64String(serializedPrivateBytes);
                RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(serializedPrivate));
#if NETCORE
                return(DotNetUtilities.ToRSA(privateKey));
#else
                /****System.Security.Cryptography.CryptographicException: The system cannot find the file specified.****/
                /****HACK****/
                //https://social.msdn.microsoft.com/Forums/vstudio/en-US/7ea48fd0-8d6b-43ed-b272-1a0249ae490f/systemsecuritycryptographycryptographicexception-the-system-cannot-find-the-file-specified?forum=clr#37d4d83d-0eb3-497a-af31-030f5278781a
                CspParameters cspParameters = new CspParameters();
                cspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
                if (SecurityUtils.compareStrings(Config.Global.GLOBAL_KEY_COONTAINER_NAME, ""))
                {
                    string uid = Guid.NewGuid().ToString();
                    cspParameters.KeyContainerName           = uid;
                    Config.Global.GLOBAL_KEY_COONTAINER_NAME = uid;
                    System.Security.Principal.SecurityIdentifier userId = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WindowsIdentity.GetCurrent().User.ToString());
                    CryptoKeyAccessRule rule = new CryptoKeyAccessRule(userId, CryptoKeyRights.FullControl, AccessControlType.Allow);
                    cspParameters.CryptoKeySecurity = new CryptoKeySecurity();
                    cspParameters.CryptoKeySecurity.SetAccessRule(rule);
                }
                else
                {
                    cspParameters.KeyContainerName = Config.Global.GLOBAL_KEY_COONTAINER_NAME;
                }
                /****System.Security.Cryptography.CryptographicException: The system cannot find the file specified.****/
                /****HACK****/
                return(DotNetUtilities.ToRSA(privateKey, cspParameters));
#endif
            }
            else
            {
                this.error.setError("PK002", "XML signature with ECDSA keys is not implemented on Net Framework");
                return(null);
                //https://stackoverflow.com/questions/27420789/sign-xml-with-ecdsa-and-sha256-in-net?rq=1
                // https://www.powershellgallery.com/packages/Posh-ACME/2.6.0/Content/Private%5CConvertFrom-BCKey.ps1
            }
        }
コード例 #6
0
        private static void setServiceUserPermissions(CspParameters cspParams)
        {
            //Copied to do not delete any permission
            cspParams.CryptoKeySecurity =
                new RSACryptoServiceProvider(cspParams)
                .CspKeyContainerInfo.CryptoKeySecurity;

            var serviceUser = new CryptoKeyAccessRule(
                ServiceUser.Get(),
                CryptoKeyRights.FullControl,
                AccessControlType.Allow
                );

            cspParams.CryptoKeySecurity.AddAccessRule(serviceUser);
        }
コード例 #7
0
        /// <summary>
        /// Returns a new CspParameters object configured for the specified keystore and key container name.
        /// </summary>
        /// <param name="keystore">Specify which keystore should be used.</param>
        /// <param name="keyContainerName">A string which uniquely identifies this encryption key among all other keys in the keystore.</param>
        /// <returns></returns>
        private static CspParameters CreateCspParameters(Keystore keystore, string keyContainerName)
        {
            CspParameters cspParams = new CspParameters(1);             // 1 for RSA.  This is also the default if omitted.

            cspParams.KeyContainerName = keyContainerName;
            cspParams.Flags            = CspProviderFlags.NoFlags;
            if (keystore == Keystore.Machine)
            {
                cspParams.Flags |= CspProviderFlags.UseMachineKeyStore;
                CryptoKeyAccessRule rule = new CryptoKeyAccessRule("everyone", CryptoKeyRights.FullControl, AccessControlType.Allow);
                cspParams.CryptoKeySecurity = new CryptoKeySecurity();
                cspParams.CryptoKeySecurity.SetAccessRule(rule);
            }
            return(cspParams);
        }
コード例 #8
0
 internal static bool IsCertEnabledForNetworkService(ExchangeCertificate cert)
 {
     if (cert.AccessRules != null)
     {
         foreach (AccessRule accessRule in cert.AccessRules)
         {
             CryptoKeyAccessRule cryptoKeyAccessRule = (CryptoKeyAccessRule)accessRule;
             if (cryptoKeyAccessRule.IdentityReference == ManageExchangeCertificate.NetworkServiceIdentityReference && cryptoKeyAccessRule.AccessControlType == AccessControlType.Allow && (cryptoKeyAccessRule.CryptoKeyRights & CryptoKeyRights.GenericRead) != (CryptoKeyRights)0)
             {
                 return(true);
             }
         }
         return(false);
     }
     return(false);
 }
コード例 #9
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);
                }
            }
        }
コード例 #10
0
	public void RemoveAccessRuleSpecific(CryptoKeyAccessRule rule) {}
コード例 #11
0
	public void RemoveAccessRuleAll(CryptoKeyAccessRule rule) {}
コード例 #12
0
	public bool RemoveAccessRule(CryptoKeyAccessRule rule) {}
コード例 #13
0
	public void ResetAccessRule(CryptoKeyAccessRule rule) {}
コード例 #14
0
	public void AddAccessRule(CryptoKeyAccessRule rule) {}
コード例 #15
0
 public void SetAccessRule(CryptoKeyAccessRule rule)
 {
     SetAccessRule((AccessRule)rule);
 }
コード例 #16
0
 public void AddAccessRule(CryptoKeyAccessRule rule)
 {
     AddAccessRule((AccessRule)rule);
 }
コード例 #17
0
        public AsymmetricAlgorithm getPrivateKeyForJWT()
        {
            if (!this.hasPrivateKey)
            {
                this.error.setError("PK0020", "No private key loaded");
                return(null);
            }
            AsymmetricAlgorithm alg;
            string algorithm = getPrivateKeyAlgorithm();

            if (SecurityUtils.compareStrings("RSA", algorithm))
            {
                byte[] serializedPrivateBytes         = this.privateKeyInfo.ToAsn1Object().GetDerEncoded();
                string serializedPrivate              = Convert.ToBase64String(serializedPrivateBytes);
                RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(serializedPrivate));
#if NETCORE
                alg = DotNetUtilities.ToRSA(privateKey);
#else
                /****System.Security.Cryptography.CryptographicException: The system cannot find the file specified.****/
                /****HACK****/
                //https://social.msdn.microsoft.com/Forums/vstudio/en-US/7ea48fd0-8d6b-43ed-b272-1a0249ae490f/systemsecuritycryptographycryptographicexception-the-system-cannot-find-the-file-specified?forum=clr#37d4d83d-0eb3-497a-af31-030f5278781a
                CspParameters cspParameters = new CspParameters();
                cspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
                if (SecurityUtils.compareStrings(Config.Global.GLOBAL_KEY_COONTAINER_NAME, ""))
                {
                    string uid = Guid.NewGuid().ToString();
                    cspParameters.KeyContainerName           = uid;
                    Config.Global.GLOBAL_KEY_COONTAINER_NAME = uid;
                    System.Security.Principal.SecurityIdentifier userId = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WindowsIdentity.GetCurrent().User.ToString());
                    CryptoKeyAccessRule rule = new CryptoKeyAccessRule(userId, CryptoKeyRights.FullControl, AccessControlType.Allow);
                    cspParameters.CryptoKeySecurity = new CryptoKeySecurity();
                    cspParameters.CryptoKeySecurity.SetAccessRule(rule);
                }
                else
                {
                    cspParameters.KeyContainerName = Config.Global.GLOBAL_KEY_COONTAINER_NAME;
                }
                /****System.Security.Cryptography.CryptographicException: The system cannot find the file specified.****/
                /****HACK****/
                alg = DotNetUtilities.ToRSA(privateKey, cspParameters);
#endif
            }
            else if (SecurityUtils.compareStrings("ECDSA", algorithm))
            {
                string b64Encoded    = this.ToBase64();
                byte[] privKeyBytes8 = Convert.FromBase64String(b64Encoded);    //Encoding.UTF8.GetBytes(privKeyEcc);
                try
                {
                    ECDsaCng pubCNG = new ECDsaCng(CngKey.Import(privKeyBytes8, CngKeyBlobFormat.Pkcs8PrivateBlob));
                    alg = pubCNG;
                }catch (Exception e)
                {
                    this.error.setError("PK022", e.Message);
                    return(null);
                }
            }
            else
            {
                this.error.setError("PK019", "Unrecognized key type");
                return(null);
            }
            if (alg != null)
            {
                this.error.cleanError();
            }
            return(alg);
        }
コード例 #18
0
 public bool RemoveAccessRule(CryptoKeyAccessRule rule)
 {
     return(RemoveAccessRule((AccessRule)rule));
 }
コード例 #19
0
 public void AddAccessRule(CryptoKeyAccessRule rule)
 {
 }
コード例 #20
0
        internal static Dictionary <AllowedServices, LocalizedString> EnableForServices(X509Certificate2 cert, AllowedServices services, string websiteName, bool requireSsl, ITopologyConfigurationSession dataSession, Server server, List <LocalizedString> warningList, bool allowConfirmation, bool forceNetworkService)
        {
            Dictionary <AllowedServices, LocalizedString> dictionary = new Dictionary <AllowedServices, LocalizedString>(3);

            if (dataSession == null)
            {
                throw new ArgumentNullException("dataSession");
            }
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if ((services & AllowedServices.IIS) != AllowedServices.None)
            {
                if (allowConfirmation && !IisUtility.SslRequiredOnTheRoot(null) && requireSsl)
                {
                    dictionary[AllowedServices.IIS] = Strings.ConfirmEnforceRequireSslOnRoot;
                }
                else
                {
                    IisUtility.SetSslCertificateByName(websiteName, cert, requireSsl);
                }
            }
            if ((services & AllowedServices.POP) != AllowedServices.None || (services & AllowedServices.IMAP) != AllowedServices.None || (services & AllowedServices.SMTP) != AllowedServices.None || forceNetworkService)
            {
                AccessRule rule = new CryptoKeyAccessRule(new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null), CryptoKeyRights.GenericRead, AccessControlType.Allow);
                try
                {
                    TlsCertificateInfo.AddAccessRule(cert, rule);
                }
                catch (CryptographicException innerException)
                {
                    throw new AddAccessRuleCryptographicException(cert.Thumbprint, innerException);
                }
                catch (ArgumentException innerException2)
                {
                    throw new AddAccessRuleArgumentException(cert.Thumbprint, innerException2);
                }
                catch (UnauthorizedAccessException innerException3)
                {
                    throw new AddAccessRuleUnauthorizedAccessException(cert.Thumbprint, innerException3);
                }
                catch (COMException innerException4)
                {
                    throw new AddAccessRuleCOMException(cert.Thumbprint, innerException4);
                }
            }
            if ((services & AllowedServices.SMTP) != AllowedServices.None)
            {
                ManageExchangeCertificate.WarnIfNotBestMatch(new ExchangeCertificate(cert), dataSession, server, warningList);
                LocalizedString localizedString = ManageExchangeCertificate.UpdateActiveDirectory(cert, dataSession, server, warningList, allowConfirmation);
                if (localizedString != LocalizedString.Empty)
                {
                    dictionary[AllowedServices.SMTP] = localizedString;
                }
            }
            if ((services & AllowedServices.POP) != AllowedServices.None)
            {
                ManageExchangeCertificate.SetPop3Certificate(cert, dataSession, warningList);
            }
            if ((services & AllowedServices.IMAP) != AllowedServices.None)
            {
                ManageExchangeCertificate.SetImap4Certificate(cert, dataSession, warningList);
            }
            if ((services & AllowedServices.UM) != AllowedServices.None)
            {
                ManageExchangeCertificate.SetUMCertificate(cert, server, dataSession, allowConfirmation, dictionary, warningList);
            }
            if ((services & AllowedServices.UMCallRouter) != AllowedServices.None)
            {
                ManageExchangeCertificate.SetUMCallRouterCertificate(cert, server, dataSession, allowConfirmation, dictionary, warningList);
            }
            if (dictionary.Count <= 0)
            {
                return(null);
            }
            return(dictionary);
        }
コード例 #21
0
 public void ResetAccessRule(CryptoKeyAccessRule rule)
 {
 }
コード例 #22
0
 public bool RemoveAccessRule(CryptoKeyAccessRule rule)
 {
 }
コード例 #23
0
 public void RemoveAccessRuleSpecific(CryptoKeyAccessRule rule)
 {
 }
コード例 #24
0
 public void RemoveAccessRuleAll(CryptoKeyAccessRule rule)
 {
 }