public override IPermission Intersect(IPermission target)
        {
            StorePermission dp = Cast(target);

            if (dp == null)
            {
                return(null);
            }

            if (this.IsUnrestricted() && dp.IsUnrestricted())
            {
                return(new StorePermission(PermissionState.Unrestricted));
            }
            if (this.IsUnrestricted())
            {
                return(dp.Copy());
            }
            if (dp.IsUnrestricted())
            {
                return(this.Copy());
            }

            StorePermissionFlags spf = _flags & dp._flags;

            if (spf == StorePermissionFlags.NoFlags)
            {
                return(null);
            }

            return(new StorePermission(spf));
        }
Beispiel #2
0
		public void PermissionState_None_Copy ()
		{
			// both will return null under 2.0 final
			// StorePermission sp1 = new StorePermission (PermissionState.None).Copy();
			// StorePermission sp2 = new StorePermission (StorePermissionFlags.NoFlags).Copy ();
			StorePermission sp = new StorePermission (PermissionState.None);

			StorePermission copy = (StorePermission) sp.Copy ();
			Assert.IsFalse (Object.ReferenceEquals (sp, copy), "ReferenceEquals");
			Assert.AreEqual (sp.Flags, copy.Flags, "Copy Flags");
			Assert.AreEqual (sp.IsUnrestricted (), copy.IsUnrestricted (), "IsUnrestricted ()");
		}
Beispiel #3
0
		public void ConstructorLevel_Deny_Unrestricted ()
		{
			StorePermission p = new StorePermission (StorePermissionFlags.AllFlags);
			Assert.AreEqual (StorePermissionFlags.AllFlags, p.Flags, "Flags");
			Assert.IsTrue (p.IsUnrestricted (), "IsUnrestricted");
			Assert.IsNotNull (p.Copy (), "Copy");
			SecurityElement se = p.ToXml ();
			Assert.IsNotNull (se, "ToXml");
			p.FromXml (se);
			Assert.IsNotNull (p.Intersect (p), "Intersect");
			Assert.IsTrue (p.IsSubsetOf (p), "IsSubsetOf");
			Assert.IsNotNull (p.Union (p), "Union");
		}
Beispiel #4
0
		public void ConstructorState_Deny_Unrestricted ()
		{
			StorePermission p = new StorePermission (PermissionState.None);
			Assert.AreEqual (StorePermissionFlags.NoFlags, p.Flags, "Flags");
			Assert.IsFalse (p.IsUnrestricted (), "IsUnrestricted");
			SecurityElement se = p.ToXml ();
			Assert.IsNotNull (se, "ToXml");
			p.FromXml (se);
			Assert.IsTrue (p.IsSubsetOf (p), "IsSubsetOf");
			// strange behaviour of Copy under MS fx 2.0 (returns null for NoFlags)
			p.Copy ();
			p.Intersect (p);
			p.Union (p);
		}
Beispiel #5
0
        public override IPermission CreatePermission()
        {
            StorePermission perm = null;

            if (this.Unrestricted)
            {
                perm = new StorePermission(PermissionState.Unrestricted);
            }
            else
            {
                perm = new StorePermission(_flags);
            }
            return(perm);
        }
Beispiel #6
0
		public void PermissionState_None ()
		{
			PermissionState ps = PermissionState.None;
			StorePermission sp = new StorePermission (ps);
			Assert.AreEqual (StorePermissionFlags.NoFlags, sp.Flags, "Flags");
			Assert.IsFalse (sp.IsUnrestricted (), "IsUnrestricted");

			SecurityElement se = sp.ToXml ();
			// only class and version are present
			Assert.AreEqual ("NoFlags", se.Attribute ("Flags"), "Xml-Flags");
			Assert.IsNull (se.Children, "Xml-Children");

			StorePermission copy = (StorePermission) sp.Copy ();
			Assert.IsNull (copy, "Copy");
		}
        // helpers

        private StorePermission Cast(IPermission target)
        {
            if (target == null)
            {
                return(null);
            }

            StorePermission dp = (target as StorePermission);

            if (dp == null)
            {
                PermissionHelper.ThrowInvalidPermission(target, typeof(StorePermission));
            }

            return(dp);
        }
        public override bool IsSubsetOf(IPermission target)
        {
            if (target == null)
            {
                return(m_flags == StorePermissionFlags.NoFlags);
            }

            try {
                StorePermission      operand    = (StorePermission)target;
                StorePermissionFlags sourceFlag = this.m_flags;
                StorePermissionFlags targetFlag = operand.m_flags;
                return((sourceFlag & targetFlag) == sourceFlag);
            }
            catch (InvalidCastException) {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Argument_WrongType), this.GetType().FullName));
            }
        }
Beispiel #9
0
		public void PermissionState_Unrestricted ()
		{
			PermissionState ps = PermissionState.Unrestricted;
			StorePermission sp = new StorePermission (ps);
			Assert.AreEqual (StorePermissionFlags.AllFlags, sp.Flags, "Flags");
			Assert.IsTrue (sp.IsUnrestricted (), "IsUnrestricted");

			SecurityElement se = sp.ToXml ();
			Assert.IsNotNull (se.Attribute ("Unrestricted"), "Xml-Unrestricted");
			Assert.IsNull (se.Attribute ("Level"), "Xml-Flags");
			Assert.IsNull (se.Children, "Xml-Children");

			StorePermission copy = (StorePermission) sp.Copy ();
			Assert.IsFalse (Object.ReferenceEquals (sp, copy), "ReferenceEquals");
			Assert.AreEqual (sp.Flags, copy.Flags, "Copy Flags");
			Assert.AreEqual (sp.IsUnrestricted (), copy.IsUnrestricted (), "IsUnrestricted ()");
		}
        public override bool IsSubsetOf(IPermission target)
        {
            StorePermission dp = Cast(target);

            if (dp == null)
            {
                return(_flags == StorePermissionFlags.NoFlags);
            }

            if (dp.IsUnrestricted())
            {
                return(true);
            }
            if (this.IsUnrestricted())
            {
                return(false);
            }

            return((_flags & ~dp._flags) == 0);
        }
Beispiel #11
0
        public override bool IsSubsetOf(IPermission target)
        {
            bool flag;

            if (target == null)
            {
                return(this.m_flags == StorePermissionFlags.NoFlags);
            }
            try
            {
                StorePermission      permission = (StorePermission)target;
                StorePermissionFlags flags      = this.m_flags;
                StorePermissionFlags flags2     = permission.m_flags;
                flag = (flags & flags2) == flags;
            }
            catch (InvalidCastException)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Argument_WrongType"), new object[] { base.GetType().FullName }));
            }
            return(flag);
        }
        public override IPermission Union(IPermission target)
        {
            StorePermission dp = Cast(target);

            if (dp == null)
            {
                return(this.Copy()); // will return null for NoFlags
            }
            if (this.IsUnrestricted() || dp.IsUnrestricted())
            {
                return(new StorePermission(PermissionState.Unrestricted));
            }

            StorePermissionFlags spf = _flags | dp._flags;

            if (spf == StorePermissionFlags.NoFlags)
            {
                return(null);
            }

            return(new StorePermission(spf));
        }
        //
        // IPermission implementation
        //

        public override IPermission Union(IPermission target)
        {
            if (target == null)
            {
                return(this.Copy());
            }

            try {
                StorePermission      operand    = (StorePermission)target;
                StorePermissionFlags flag_union = m_flags | operand.m_flags;
                if (flag_union == StorePermissionFlags.NoFlags)
                {
                    return(null);
                }
                else
                {
                    return(new StorePermission(flag_union));
                }
            }
            catch (InvalidCastException) {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Argument_WrongType), this.GetType().FullName));
            }
        }
 public override IPermission Intersect(IPermission target)
 {
     IPermission permission2;
     if (target == null)
     {
         return null;
     }
     try
     {
         StorePermission permission = (StorePermission) target;
         StorePermissionFlags flag = permission.m_flags & this.m_flags;
         if (flag == StorePermissionFlags.NoFlags)
         {
             return null;
         }
         permission2 = new StorePermission(flag);
     }
     catch (InvalidCastException)
     {
         throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Argument_WrongType"), new object[] { base.GetType().FullName }));
     }
     return permission2;
 }
        /// <summary>  
        /// 安装资源文件中的证书  
        /// </summary>  
        public static string InstallCertificateFromResource(StoreName sn, byte[] certificatefile)
        {
            try
            {
                StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);
                sp.Demand();
                X509Certificate2 certificate = new X509Certificate2(certificatefile);

                if (TryGetCertificate(sn, certificatefile) == null)
                {
                    X509Store AuthRoot = new X509Store(sn, StoreLocation.LocalMachine);
                    AuthRoot.Open(OpenFlags.ReadWrite);
                    //AuthRoot.Remove(certificate);
                    AuthRoot.Add(certificate);
                    AuthRoot.Close();
                }
                return string.Empty;
            }
            catch(Exception ex)
            {
                return ex.Message;
            }
        }
Beispiel #16
0
        public override IPermission Intersect(IPermission target)
        {
            IPermission permission2;

            if (target == null)
            {
                return(null);
            }
            try
            {
                StorePermission      permission = (StorePermission)target;
                StorePermissionFlags flag       = permission.m_flags & this.m_flags;
                if (flag == StorePermissionFlags.NoFlags)
                {
                    return(null);
                }
                permission2 = new StorePermission(flag);
            }
            catch (InvalidCastException)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Argument_WrongType"), new object[] { base.GetType().FullName }));
            }
            return(permission2);
        }
Beispiel #17
0
        SafeCertStoreHandle CertOpenStore(
            [In]    IntPtr  lpszStoreProvider,
            [In]    uint    dwMsgAndCertEncodingType,
            [In]    IntPtr  hCryptProv,
            [In]    uint    dwFlags,
            [In]    string  pvPara) {

            if (lpszStoreProvider != new IntPtr(CERT_STORE_PROV_MEMORY) && lpszStoreProvider != new IntPtr(CERT_STORE_PROV_SYSTEM))
                throw new ArgumentException(SR.GetString(SR.Security_InvalidValue), "lpszStoreProvider");

#if !FEATURE_CORESYSTEM
            if ((dwFlags & CERT_SYSTEM_STORE_LOCAL_MACHINE) == CERT_SYSTEM_STORE_LOCAL_MACHINE ||
                (dwFlags & CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY) == CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY ||
                (dwFlags & CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE) == CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE) {
                // We do not allow opening remote local machine stores if in semi-trusted environment.
                if (pvPara != null && pvPara.StartsWith(@"\\", StringComparison.Ordinal))
                    new PermissionSet(PermissionState.Unrestricted).Demand();
            }

            if ((dwFlags & CERT_STORE_DELETE_FLAG) == CERT_STORE_DELETE_FLAG) {
                StorePermission sp = new StorePermission(StorePermissionFlags.DeleteStore);
                sp.Demand();
            } else {
                StorePermission sp = new StorePermission(StorePermissionFlags.OpenStore);
                sp.Demand();
            }

            if ((dwFlags & CERT_STORE_CREATE_NEW_FLAG) == CERT_STORE_CREATE_NEW_FLAG) {
                StorePermission sp = new StorePermission(StorePermissionFlags.CreateStore);
                sp.Demand();
            }

            if ((dwFlags & CERT_STORE_OPEN_EXISTING_FLAG) == 0) {
                StorePermission sp = new StorePermission(StorePermissionFlags.CreateStore);
                sp.Demand();
            }
#endif

            return CAPIMethods.CertOpenStore(lpszStoreProvider, 
                                             dwMsgAndCertEncodingType, 
                                             hCryptProv, 
                                             dwFlags | CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, 
                                             pvPara);
        }
Beispiel #18
0
        bool CertSaveStore(
            [In]     SafeCertStoreHandle    hCertStore,
            [In]     uint                   dwMsgAndCertEncodingType,
            [In]     uint                   dwSaveAs,
            [In]     uint                   dwSaveTo,
            [In,Out] IntPtr                 pvSaveToPara,
            [In]     uint                   dwFlags) {

            if (hCertStore == null)
                throw new ArgumentNullException("hCertStore");
            if (hCertStore.IsInvalid)
                throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "hCertStore");

#if !FEATURE_CORESYSTEM
            StorePermission sp = new StorePermission(StorePermissionFlags.EnumerateCertificates);
            sp.Demand();
#endif

            if (dwSaveTo == CERT_STORE_SAVE_TO_FILENAME_A || dwSaveTo == CERT_STORE_SAVE_TO_FILENAME_W)
                throw new ArgumentException(SR.GetString(SR.Security_InvalidValue), "pvSaveToPara");

            return CAPIMethods.CertSaveStore(hCertStore,
                                             dwMsgAndCertEncodingType,
                                             dwSaveAs,
                                             dwSaveTo,
                                             pvSaveToPara,
                                             dwFlags);
        }
Beispiel #19
0
        bool CertAddCertificateLinkToStore (
            [In]     SafeCertStoreHandle        hCertStore,
            [In]     SafeCertContextHandle      pCertContext,
            [In]     uint                       dwAddDisposition,
            [In,Out] SafeCertContextHandle      ppStoreContext) {

            if (hCertStore == null)
                throw new ArgumentNullException("hCertStore");
            if (hCertStore.IsInvalid)
                throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "hCertStore");

            if (pCertContext == null)
                throw new ArgumentNullException("pCertContext");
            if (pCertContext.IsInvalid)
                throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "pCertContext");

#if !FEATURE_CORESYSTEM
            StorePermission sp = new StorePermission(StorePermissionFlags.AddToStore);
            sp.Demand();
#endif

            return CAPIMethods.CertAddCertificateLinkToStore(hCertStore, 
                                                             pCertContext, 
                                                             dwAddDisposition, 
                                                             ppStoreContext);
        }
Beispiel #20
0
        bool CertDeleteCertificateFromStore (
            [In]     SafeCertContextHandle  pCertContext) {

            if (pCertContext == null)
                throw new ArgumentNullException("pCertContext");
            if (pCertContext.IsInvalid) 
                throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "pCertContext");

#if !FEATURE_CORESYSTEM
            StorePermission sp = new StorePermission(StorePermissionFlags.RemoveFromStore);
            sp.Demand();
#endif

            return CAPIMethods.CertDeleteCertificateFromStore(pCertContext); 
        }
        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;
        }
Beispiel #22
0
        SafeCertContextHandle CertEnumCertificatesInStore (
            [In]     SafeCertStoreHandle     hCertStore, 
            [In]     SafeCertContextHandle   pPrevCertContext) {

            if (hCertStore == null)
                throw new ArgumentNullException("hCertStore");
            if (hCertStore.IsInvalid)
                throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "hCertStore");

#if !FEATURE_CORESYSTEM
            if (pPrevCertContext.IsInvalid) {
                StorePermission sp = new StorePermission(StorePermissionFlags.EnumerateCertificates);
                sp.Demand();
            }
#endif

            SafeCertContextHandle safeCertContextHandle = CAPIMethods.CertEnumCertificatesInStore(hCertStore, pPrevCertContext);
            if (safeCertContextHandle == null || safeCertContextHandle.IsInvalid) {
                int dwErrorCode = Marshal.GetLastWin32Error();
                if (dwErrorCode != CRYPT_E_NOT_FOUND)
                    throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            return safeCertContextHandle;
        }
Beispiel #23
0
		public void FromXml_WrongTagCase ()
		{
			StorePermission sp = new StorePermission (PermissionState.None);
			SecurityElement se = sp.ToXml ();
			se.Tag = "IPERMISSION"; // instead of IPermission
			sp.FromXml (se);
			// note: normally IPermission classes (in corlib) DO care about the
			// IPermission tag
		}
Beispiel #24
0
		public void FromXml_NoVersion ()
		{
			StorePermission sp = new StorePermission (PermissionState.None);
			SecurityElement se = sp.ToXml ();

			SecurityElement w = new SecurityElement (se.Tag);
			w.AddAttribute ("class", se.Attribute ("class"));
			sp.FromXml (w);
			// version is optional (in this case)
		}
Beispiel #25
0
		public void FromXml_WrongClass ()
		{
			StorePermission sp = new StorePermission (PermissionState.None);
			SecurityElement se = sp.ToXml ();

			SecurityElement w = new SecurityElement (se.Tag);
			w.AddAttribute ("class", "Wrong" + se.Attribute ("class"));
			w.AddAttribute ("version", se.Attribute ("version"));
			sp.FromXml (w);
			// doesn't care of the class name at that stage
			// anyway the class has already be created so...
		}
        public bool Build (X509Certificate2 certificate) {
            lock (m_syncRoot) {
                if (certificate == null || certificate.CertContext.IsInvalid)
                    throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidContextHandle), "certificate");

                // Chain building opens and enumerates the root store to see if the root of the chain is trusted.
                StorePermission sp = new StorePermission(StorePermissionFlags.OpenStore | StorePermissionFlags.EnumerateCertificates);
                sp.Demand();

                X509ChainPolicy chainPolicy = this.ChainPolicy;
                if (chainPolicy.RevocationMode == X509RevocationMode.Online) {
                    if (certificate.Extensions[CAPI.szOID_CRL_DIST_POINTS] != null ||
                        certificate.Extensions[CAPI.szOID_AUTHORITY_INFO_ACCESS] != null) {
                        // If there is a CDP or AIA extension, we demand unrestricted network access and store add permission
                        // since CAPI can download certificates into the CA store from the network.
                        PermissionSet ps = new PermissionSet(PermissionState.None);
                        ps.AddPermission(new WebPermission(PermissionState.Unrestricted));
                        ps.AddPermission(new StorePermission(StorePermissionFlags.AddToStore));
                        ps.Demand();
                    }
                }

                Reset();
                int hr = BuildChain(m_useMachineContext ? new IntPtr(CAPI.HCCE_LOCAL_MACHINE) : new IntPtr(CAPI.HCCE_CURRENT_USER),
                                    certificate.CertContext,
                                    chainPolicy.ExtraStore,
                                    chainPolicy.ApplicationPolicy,
                                    chainPolicy.CertificatePolicy,
                                    chainPolicy.RevocationMode,
                                    chainPolicy.RevocationFlag,
                                    chainPolicy.VerificationTime,
                                    chainPolicy.UrlRetrievalTimeout,
                                    ref m_safeCertChainHandle);

                if (hr != CAPI.S_OK)
                    return false;

                // Init.
                Init();

                // Verify the chain using the specified policy.
                CAPI.CERT_CHAIN_POLICY_PARA PolicyPara = new CAPI.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_PARA)));
                CAPI.CERT_CHAIN_POLICY_STATUS PolicyStatus = new CAPI.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_STATUS)));

                PolicyPara.dwFlags = (uint) chainPolicy.VerificationFlags;

                if (!CAPI.CertVerifyCertificateChainPolicy(new IntPtr(CAPI.CERT_CHAIN_POLICY_BASE),
                                                           m_safeCertChainHandle,
                                                           ref PolicyPara,
                                                           ref PolicyStatus))
                    // The API failed.
                    throw new CryptographicException(Marshal.GetLastWin32Error());

                CAPI.SetLastError(PolicyStatus.dwError);
                return (PolicyStatus.dwError == 0);
            }
        }
Beispiel #27
0
		public void FromXml_NoClass ()
		{
			StorePermission sp = new StorePermission (PermissionState.None);
			SecurityElement se = sp.ToXml ();

			SecurityElement w = new SecurityElement (se.Tag);
			w.AddAttribute ("version", se.Attribute ("version"));
			sp.FromXml (w);
			// note: normally IPermission classes (in corlib) DO NOT care about
			// attribute "class" name presence in the XML
		}
Beispiel #28
0
		public void FromXml_WrongVersion ()
		{
			StorePermission sp = new StorePermission (PermissionState.None);
			SecurityElement se = sp.ToXml ();
			se.Attributes.Remove ("version");
			se.Attributes.Add ("version", "2");
			sp.FromXml (se);
		}
        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);
        }
        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;
        }
Beispiel #31
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 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 #33
0
		public void PermissionState_Bad ()
		{
			PermissionState ps = (PermissionState) Int32.MinValue;
			StorePermission sp = new StorePermission (ps);
		}
		public override IPermission CreatePermission ()
		{
			StorePermission perm = null;
			if (this.Unrestricted)
				perm = new StorePermission (PermissionState.Unrestricted);
			else
				perm = new StorePermission (_flags);
			return perm;
		}
Beispiel #35
0
		public void FromXml_Null ()
		{
			StorePermission sp = new StorePermission (PermissionState.None);
			sp.FromXml (null);
		}
        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;
        }
        IntPtr CertEnumCertificatesInStore (
            [In]     SafeCertStoreHandle     hCertStore, 
            [In]     IntPtr                  pPrevCertContext) {

            if (hCertStore == null)
                throw new ArgumentNullException("hCertStore");
            if (hCertStore.IsInvalid)
                throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidHandle), "hCertStore");

            if (pPrevCertContext == IntPtr.Zero) {
                StorePermission sp = new StorePermission(StorePermissionFlags.EnumerateCertificates);
                sp.Demand();
            }

            IntPtr handle = CAPIMethods.CertEnumCertificatesInStore(hCertStore, pPrevCertContext);
            if (handle == IntPtr.Zero) {
                int dwErrorCode = Marshal.GetLastWin32Error();
                if (dwErrorCode != CRYPT_E_NOT_FOUND) {
                    CAPIMethods.CertFreeCertificateContext(handle);
                    throw new CryptographicException(dwErrorCode);
                }
            }
            return handle;
        }
        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;
        }
Beispiel #39
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);
            }
        }