public void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) {
            uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags);
            Cryptography.SafeCertStoreHandle safeCertStoreHandle = Cryptography.SafeCertStoreHandle.InvalidHandle;

#if !FEATURE_CORESYSTEM
            //
            // We need to Assert all StorePermission flags since this is a memory store and we want 
            // semi-trusted code to be able to import certificates to a memory store.
            //

            StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);
            sp.Assert();
#endif

            safeCertStoreHandle = LoadStoreFromFile(fileName, password, dwFlags, (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) != 0);

            X509Certificate2Collection collection = X509Utils.GetCertificates(safeCertStoreHandle);

            safeCertStoreHandle.Dispose();
            X509Certificate2[] x509Certs = new X509Certificate2[collection.Count];
            collection.CopyTo(x509Certs, 0);
            this.AddRange(x509Certs);
        }
        public byte[] Export(X509ContentType contentType, string password) {
#if !FEATURE_CORESYSTEM
            //
            // We need to Assert all StorePermission flags since this is a memory store and we want 
            // semi-trusted code to be able to export certificates to a memory store.
            //

            StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);
            sp.Assert();
#endif

            Cryptography.SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportToMemoryStore(this);

            byte[] result = ExportCertificatesToBlob(safeCertStoreHandle, contentType, password);
            safeCertStoreHandle.Dispose();
            return result;
        }
        internal static Cryptography.SafeCertStoreHandle ExportToMemoryStore (X509Certificate2Collection collection) {
            //
            // We need to Assert all StorePermission flags since this is a memory store and we want 
            // semi-trusted code to be able to export certificates to a memory store.
            //

#if !FEATURE_CORESYSTEM
            StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);
            sp.Assert();
#endif

            Cryptography.SafeCertStoreHandle safeCertStoreHandle = Cryptography.SafeCertStoreHandle.InvalidHandle;

            // we always want to use CERT_STORE_ENUM_ARCHIVED_FLAG since we want to preserve the collection in this operation.
            // By default, Archived certificates will not be included.

            safeCertStoreHandle = CAPI.CertOpenStore(new IntPtr(CAPI.CERT_STORE_PROV_MEMORY), 
                                                     CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
                                                     IntPtr.Zero,
                                                     CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG | CAPI.CERT_STORE_CREATE_NEW_FLAG, 
                                                     null);

            if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid)
                throw new CryptographicException(Marshal.GetLastWin32Error());

            //
            // We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get
            // applied to the original store. This has a limit of 99 links per cert context however.
            //

            foreach (X509Certificate2 x509 in collection) {
                if (!CAPI.CertAddCertificateLinkToStore(safeCertStoreHandle,
                                                        x509.CertContext,
                                                        CAPI.CERT_STORE_ADD_ALWAYS,
                                                        Cryptography.SafeCertContextHandle.InvalidHandle))
                    throw new CryptographicException(Marshal.GetLastWin32Error());
            }

            return safeCertStoreHandle;
        }
        public X509Certificate2Collection Find(X509FindType findType, Object findValue, bool validOnly) {
#if !FEATURE_CORESYSTEM
            //
            // We need to Assert all StorePermission flags since this is a memory store and we want 
            // semi-trusted code to be able to find certificates in a memory store.
            //

            StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);
            sp.Assert();
#endif

            Cryptography.SafeCertStoreHandle safeSourceStoreHandle = X509Utils.ExportToMemoryStore(this);

            Cryptography.SafeCertStoreHandle safeTargetStoreHandle = FindCertInStore(safeSourceStoreHandle, findType, findValue, validOnly);
            X509Certificate2Collection collection = X509Utils.GetCertificates(safeTargetStoreHandle);

            safeTargetStoreHandle.Dispose();
            safeSourceStoreHandle.Dispose();

            return collection;
        }
Beispiel #5
0
        internal static X509Certificate2Collection BuildBagOfCerts (KeyInfoX509Data keyInfoX509Data, CertUsageType certUsageType) {
            X509Certificate2Collection collection = new X509Certificate2Collection();
            ArrayList decryptionIssuerSerials = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null);
            if (keyInfoX509Data.Certificates != null) {
                foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates) {
                    switch (certUsageType) {
                    case CertUsageType.Verification:
                        collection.Add(certificate);
                        break;
                    case CertUsageType.Decryption:
                        decryptionIssuerSerials.Add(new X509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber));
                        break;
                    }
                }
            }

            if (keyInfoX509Data.SubjectNames == null && keyInfoX509Data.IssuerSerials == null &&
                keyInfoX509Data.SubjectKeyIds == null && decryptionIssuerSerials == null)
                return collection;

            // Open LocalMachine and CurrentUser "Other People"/"My" stores.

            // Assert OpenStore since we are not giving back any certificates to the user.
            StorePermission sp = new StorePermission(StorePermissionFlags.OpenStore);
            sp.Assert();

            X509Store[] stores = new X509Store[2];
            string storeName = (certUsageType == CertUsageType.Verification ? "AddressBook" : "My");
            stores[0] = new X509Store(storeName, StoreLocation.CurrentUser);
            stores[1] = new X509Store(storeName, StoreLocation.LocalMachine);

            for (int index=0; index < stores.Length; index++) {
                if (stores[index] != null) {
                    X509Certificate2Collection filters = null;
                    // We don't care if we can't open the store.
                    try {
                        stores[index].Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                        filters = stores[index].Certificates;
                        stores[index].Close();
                        if (keyInfoX509Data.SubjectNames != null) {
                            foreach (string subjectName in keyInfoX509Data.SubjectNames) {
                                filters = filters.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false);
                            }
                        }
                        if (keyInfoX509Data.IssuerSerials != null) {
                            foreach (X509IssuerSerial issuerSerial in keyInfoX509Data.IssuerSerials) {
                                filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false);
                                filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
                            }
                        }
                        if (keyInfoX509Data.SubjectKeyIds != null) {
                            foreach (byte[] ski in keyInfoX509Data.SubjectKeyIds) {
                                string hex = X509Utils.EncodeHexString(ski);
                                filters = filters.Find(X509FindType.FindBySubjectKeyIdentifier, hex, false);
                            }
                        }
                        if (decryptionIssuerSerials != null) {
                            foreach (X509IssuerSerial issuerSerial in decryptionIssuerSerials) {
                                filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false);
                                filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
                            }
                        }
                    }
                    catch (CryptographicException) {}

                    if (filters != null) 
                        collection.AddRange(filters);
                }
            }

            return collection;
        }
        public AjaxResponse UploadCertificate(string fileName, string password)
        {
            var response = new AjaxResponse();

            try
            {
                var filePath = Path.Combine(Path.GetTempPath(), fileName);
                var store2 = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                var sp = new StorePermission(PermissionState.Unrestricted) {Flags = StorePermissionFlags.AllFlags};
                sp.Assert();
                store2.Open(OpenFlags.MaxAllowed);

                var cert = fileName.EndsWith(".pfx")
                                            ? new X509Certificate2(filePath, password) {FriendlyName = fileName}
                                            : new X509Certificate2(new X509Certificate(filePath));

                store2.Add(cert);
                store2.Close();

                if (CoreContext.Configuration.Standalone)
                    UploadStandAloneCertificate(store2, cert);
                else
                    UploadSaaSCertificate(store2, cert);

                response.status = "success";
                response.message = Resource.UploadHttpsSettingsSuccess;
            }
            catch (Exception e)
            {
                response.status = "error";
                response.message = e.Message;
            }

            return response;
        }
        public void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) {
            uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags);
            SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle;

            //
            // We need to Assert all StorePermission flags since this is a memory store and we want 
            // semi-trusted code to be able to import certificates to a memory store.
            //

            StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);
            sp.Assert();

            safeCertStoreHandle = LoadStoreFromBlob(rawData, password, dwFlags, (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) != 0);

            X509Certificate2Collection collection = X509Utils.GetCertificates(safeCertStoreHandle);

            safeCertStoreHandle.Dispose();
            X509Certificate2[] x509Certs = new X509Certificate2[collection.Count];
            collection.CopyTo(x509Certs, 0);
            this.AddRange(x509Certs);
        }
Beispiel #8
0
        private static X509Certificate2Collection SelectFromCollectionHelper (X509Certificate2Collection certificates, string title, string message, X509SelectionFlag selectionFlag, IntPtr hwndParent) {
            if (certificates == null)
                throw new ArgumentNullException("certificates");
            if (selectionFlag < X509SelectionFlag.SingleSelection || selectionFlag > X509SelectionFlag.MultiSelection)
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Arg_EnumIllegalVal"), "selectionFlag"));

            //
            // We need to Assert all StorePermission flags since this is a memory store and we want 
            // semi-trusted code to be able to select certificates from a memory store.
            //

            StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);
            sp.Assert();

            using (SafeCertStoreHandle safeSourceStoreHandle = X509Utils.ExportToMemoryStore(certificates))
            using (SafeCertStoreHandle safeTargetStoreHandle = SelectFromStore(safeSourceStoreHandle, title, message, selectionFlag, hwndParent))
            {
                return X509Utils.GetCertificates(safeTargetStoreHandle);
            }
        }
 private void uninstallCert()
 {
     X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
     StorePermission sp = new StorePermission(PermissionState.Unrestricted);
     sp.Flags = StorePermissionFlags.OpenStore;
     sp.Assert();
     store.Open(OpenFlags.ReadWrite);
     consoleLine("Removing Touchmote Test Certificate.");
     foreach (X509Certificate2 c in store.Certificates)
     {
         if (c.IssuerName.Name.Contains("Touchmote"))
         {
             store.Remove(c);
         }
     }
     store.Close();
 }
 private void installCert()
 {
     X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
     StorePermission sp = new StorePermission(PermissionState.Unrestricted);
     sp.Flags = StorePermissionFlags.OpenStore;
     sp.Assert();
     store.Open(OpenFlags.ReadWrite);
     X509Certificate2Collection collection = new X509Certificate2Collection();
     string path = System.AppDomain.CurrentDomain.BaseDirectory + "CodeSign.cer";
     X509Certificate2 cert = new X509Certificate2(path);
     byte[] encodedCert = cert.GetRawCertData();
     consoleLine("Adding Touchmote Test Certificate to trusted root.");
     store.Add(cert);
     store.Close();
 }
        public AjaxResponse UploadCertificate(string fileName, string password)
        {
            var response = new AjaxResponse();

            try
            {
                const string newbindinginformation = "*:443:";

                var store2 = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                var sp = new StorePermission(PermissionState.Unrestricted) {Flags = StorePermissionFlags.AllFlags};
                sp.Assert();
                store2.Open(OpenFlags.MaxAllowed);

                var cert = new X509Certificate2(fileName, password) {FriendlyName = fileName.Split('\\').Last()};
                store2.Add(cert);
                store2.Close();

                using (var serverManager = new ServerManager())
                {
                    foreach (var s in serverManager.Sites)
                    {
                        var bindingIndex = -1;
                        foreach (var b in s.Bindings.Where(r => r.BindingInformation.Contains(newbindinginformation)))
                        {
                            bindingIndex = s.Bindings.IndexOf(b);
                        }

                        if (bindingIndex != -1)
                        {
                            s.Bindings.RemoveAt(bindingIndex);
                        }
                    }

                    var site = serverManager.Sites[HostingEnvironment.ApplicationHost.GetSiteName()];
                    var binding = site.Bindings.Add(newbindinginformation, cert.GetCertHash(), store2.Name);
                    binding.Protocol = "https";

                    AddRewriteRules(serverManager);

                    serverManager.CommitChanges();
                }

                response.status = "success";
                response.message = Resource.UploadHttpsSettingsSuccess;
            }
            catch (Exception e)
            {
                response.status = "error";
                response.message = e.Message;
            }

            return response;
        }