Exemple #1
0
		static CertificateProvider()
		{
			CertificateProvider.tracer = PSTraceSource.GetTracer("CertificateProvider", "The core command provider for certificates");
			CertificateProvider.staticLock = new object();
			CertificateProvider.storeLocations = null;
			CertificateProvider.pathCache = null;
			CertificateProvider.fIsWin8AndAbove = DownLevelHelper.IsWin8AndAbove();
			char[] chrArray = new char[2];
			chrArray[0] = '/';
			chrArray[1] = '\\';
			CertificateProvider.pathSeparators = chrArray;
			CertificateProvider.storeCache = null;
			CertificateProvider.certPathRegex = null;
		}
        public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, string certPath, bool addProperty)
        {
            if (DownLevelHelper.TrustedIssuerSupported())
            {
                IntPtr propertyPtr = IntPtr.Zero;
                Security.NativeMethods.CRYPT_DATA_BLOB dataBlob = new Security.NativeMethods.CRYPT_DATA_BLOB();
                dataBlob.cbData = 0;
                dataBlob.pbData = IntPtr.Zero;
                X509Certificate certFromStore = null;

                try
                {
                    if (certPath != null)
                    {
                        //try to open the store and get the cert out
                        //in case the store handle is already released
                        string[] pathElements = GetPathElements(certPath);

                        //certpath is in the format: Microsoft.Powershell.Security\
                        //Certificate::CurrentUser(LocalMachine)\my\HashID
                        //obtained pathElements[0] is Microsoft.Powershell.Security
                        //obtained pathElements[1] is Certificate::CurrentUser
                        //obtained pathElements[2] is MY
                        //obtained pathElements[3] is HashID

                        bool fUserContext = String.Equals(pathElements[1], "Certificate::CurrentUser", StringComparison.OrdinalIgnoreCase);

                        X509StoreLocation storeLocation =
                            new X509StoreLocation(fUserContext ? StoreLocation.CurrentUser : StoreLocation.LocalMachine);

                        //get certificate from the store pathElements[2]
                        X509NativeStore store = null;

                        store = new X509NativeStore(storeLocation, pathElements[2]);
                        store.Open(true); //including archival flag

                        IntPtr certContext = store.GetCertByName(pathElements[3]);

                        if (certContext != IntPtr.Zero)
                        {
                            certFromStore = new X509Certificate2(certContext);
                            store.FreeCert(certContext);
                        }
                    }

                    if (addProperty) //should add the property
                    {
                        propertyPtr = Marshal.AllocHGlobal(Marshal.SizeOf(dataBlob));
                        Marshal.StructureToPtr(dataBlob, propertyPtr, false);
                    }

                    //set property
                    if (!Security.NativeMethods.CertSetCertificateContextProperty(
                                certFromStore != null ? certFromStore.Handle : cert.Handle,
                                Security.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID,
                                0,
                                propertyPtr))
                    {
                        throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                finally
                {
                    if (propertyPtr != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(propertyPtr);
                    }
                }
            }
            else
            {
                throw Marshal.GetExceptionForHR(Security.NativeMethods.NTE_NOT_SUPPORTED);
            }
        }
        /// <summary>
        /// gets the X509NativeStore at the specified path.
        /// Adds to cache if not already there.
        /// </summary>
        ///
        /// <param name="storePath"> path to the store </param>
        ///
        /// <param name="storeName"> name of store (path leaf element) </param>
        ///
        /// <param name="storeLocation"> location of store (CurrentUser or LocalMachine) </param>
        ///
        /// <returns> X509NativeStore object </returns>
        ///
        private X509NativeStore GetStore(string storePath,
                                   string storeName,
                                   X509StoreLocation storeLocation)
        {
            if (!storeLocation.StoreNames.ContainsKey(storeName))
            {
                ThrowItemNotFound(storePath, CertificateProviderItem.Store);
            }
            if (s_storeCache != null)
            {
                if (s_storeCache.Location != storeLocation ||
                    !String.Equals(
                                s_storeCache.StoreName,
                                storeName,
                                StringComparison.OrdinalIgnoreCase))
                {
                    s_storeCache = null;
                }
            }

            if (s_storeCache == null)
            {
                s_storeCache = new X509NativeStore(storeLocation, storeName);
            }

            return s_storeCache;
        }
        private void DoMove(string destination, X509Certificate2 cert, X509NativeStore store, string sourcePath)
        {
            IntPtr dupCert = IntPtr.Zero;  //should not free this
            IntPtr outCert = IntPtr.Zero;

            //duplicate cert first
            dupCert = Security.NativeMethods.CertDuplicateCertificateContext(cert.Handle);

            if (dupCert == IntPtr.Zero)
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }
            else
            {
                if (!Security.NativeMethods.CertAddCertificateContextToStore(
                                             store.StoreHandle,
                                             cert.Handle,
                                             (uint)Security.NativeMethods.AddCertificateContext.CERT_STORE_ADD_ALWAYS,
                                             ref outCert))
                {
                    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                }

                if (!Security.NativeMethods.CertDeleteCertificateFromStore(dupCert))
                {
                    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                }

                if (DownLevelHelper.LogCertChangeSupported())
                {
                    bool fMachine = store.Location.Location == StoreLocation.LocalMachine;

                    if (cert.HasPrivateKey &&
                        String.Equals(store.StoreName, "MY", StringComparison.OrdinalIgnoreCase))
                    {
                        Security.NativeMethods.LogCertCopy(fMachine, cert.Handle);
                    }

                    Security.NativeMethods.LogCertDelete(fMachine, cert.Handle);
                }
            }

            //commit the change to physical store
            if (destination.Contains("UserDS"))
            {
                CommitUserDS(store.StoreHandle);
            }

            if (sourcePath.Contains("UserDS"))
            {
                Security.NativeMethods.CERT_CONTEXT context = ClrFacade.PtrToStructure<Security.NativeMethods.CERT_CONTEXT>(cert.Handle);

                CommitUserDS(context.hCertStore);
            }

            //get the output object
            X509Certificate2 outObj = new X509Certificate2(outCert);
            string certName = GetCertName(outObj);
            string certPath = MakePath(destination, certName);
            WriteItemObject((object)outObj, certPath, false);
        }
Exemple #5
0
		private void DoMove(string destination, X509Certificate2 cert, X509NativeStore store, string sourcePath)
		{
			IntPtr zero = IntPtr.Zero;
			IntPtr intPtr = NativeMethods.CertDuplicateCertificateContext(cert.Handle);
			if (intPtr != IntPtr.Zero)
			{
				if (NativeMethods.CertAddCertificateContextToStore(store.StoreHandle, cert.Handle, 4, ref zero))
				{
					if (NativeMethods.CertDeleteCertificateFromStore(intPtr))
					{
						if (DownLevelHelper.IsWin8AndAbove())
						{
							bool location = store.Location.Location == StoreLocation.LocalMachine;
							if (cert.HasPrivateKey && string.Equals(store.StoreName, "MY", StringComparison.OrdinalIgnoreCase))
							{
								NativeMethods.LogCertCopy(location, cert.Handle);
							}
							NativeMethods.LogCertDelete(location, cert.Handle);
						}
						if (destination.Contains("UserDS"))
						{
							this.CommitUserDS(store.StoreHandle);
						}
						if (sourcePath.Contains("UserDS"))
						{
							NativeMethods.CERT_CONTEXT structure = (NativeMethods.CERT_CONTEXT)Marshal.PtrToStructure(cert.Handle, typeof(NativeMethods.CERT_CONTEXT));
							this.CommitUserDS(structure.hCertStore);
						}
						X509Certificate2 x509Certificate2 = new X509Certificate2(zero);
						string certName = CertificateProvider.GetCertName(x509Certificate2);
						string str = this.MakePath(destination, certName);
						base.WriteItemObject(x509Certificate2, str, false);
						return;
					}
					else
					{
						throw new Win32Exception(Marshal.GetLastWin32Error());
					}
				}
				else
				{
					throw new Win32Exception(Marshal.GetLastWin32Error());
				}
			}
			else
			{
				throw new Win32Exception(Marshal.GetLastWin32Error());
			}
		}
Exemple #6
0
        public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, string certPath, bool addProperty)
        {
            IntPtr        handle;
            StoreLocation storeLocation;

            if (!DownLevelHelper.IsWin8AndAbove())
            {
                throw Marshal.GetExceptionForHR(-2146893783);
            }
            else
            {
                IntPtr zero = IntPtr.Zero;
                NativeMethods.CRYPT_DATA_BLOB cRYPTDATABLOB = new NativeMethods.CRYPT_DATA_BLOB();
                cRYPTDATABLOB.cbData = 0;
                cRYPTDATABLOB.pbData = IntPtr.Zero;
                X509Certificate x509Certificate2 = null;
                try
                {
                    if (certPath != null)
                    {
                        string[] pathElements = SendAsTrustedIssuerProperty.GetPathElements(certPath);
                        bool     flag         = string.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase);
                        if (flag)
                        {
                            storeLocation = StoreLocation.CurrentUser;
                        }
                        else
                        {
                            storeLocation = StoreLocation.LocalMachine;
                        }
                        X509StoreLocation x509StoreLocation = new X509StoreLocation(storeLocation);
                        X509NativeStore   x509NativeStore   = new X509NativeStore(x509StoreLocation, pathElements[1]);
                        x509NativeStore.Open(true);
                        IntPtr certByName = x509NativeStore.GetCertByName(pathElements[2]);
                        if (certByName != IntPtr.Zero)
                        {
                            x509Certificate2 = new X509Certificate2(certByName);
                            x509NativeStore.FreeCert(certByName);
                        }
                    }
                    if (addProperty)
                    {
                        zero = Marshal.AllocHGlobal(Marshal.SizeOf(cRYPTDATABLOB));
                        Marshal.StructureToPtr(cRYPTDATABLOB, zero, false);
                    }
                    if (x509Certificate2 != null)
                    {
                        handle = x509Certificate2.Handle;
                    }
                    else
                    {
                        handle = cert.Handle;
                    }
                    if (!NativeMethods.CertSetCertificateContextProperty(handle, NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID, 0, zero))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                finally
                {
                    if (zero != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(zero);
                    }
                }
                return;
            }
        }
		public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, string certPath, bool addProperty)
		{
			IntPtr handle;
			StoreLocation storeLocation;
			if (!DownLevelHelper.IsWin8AndAbove())
			{
				throw Marshal.GetExceptionForHR(-2146893783);
			}
			else
			{
				IntPtr zero = IntPtr.Zero;
				NativeMethods.CRYPT_DATA_BLOB cRYPTDATABLOB = new NativeMethods.CRYPT_DATA_BLOB();
				cRYPTDATABLOB.cbData = 0;
				cRYPTDATABLOB.pbData = IntPtr.Zero;
				X509Certificate x509Certificate2 = null;
				try
				{
					if (certPath != null)
					{
						string[] pathElements = SendAsTrustedIssuerProperty.GetPathElements(certPath);
						bool flag = string.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase);
						if (flag)
						{
							storeLocation = StoreLocation.CurrentUser;
						}
						else
						{
							storeLocation = StoreLocation.LocalMachine;
						}
						X509StoreLocation x509StoreLocation = new X509StoreLocation(storeLocation);
						X509NativeStore x509NativeStore = new X509NativeStore(x509StoreLocation, pathElements[1]);
						x509NativeStore.Open(true);
						IntPtr certByName = x509NativeStore.GetCertByName(pathElements[2]);
						if (certByName != IntPtr.Zero)
						{
							x509Certificate2 = new X509Certificate2(certByName);
							x509NativeStore.FreeCert(certByName);
						}
					}
					if (addProperty)
					{
						zero = Marshal.AllocHGlobal(Marshal.SizeOf(cRYPTDATABLOB));
						Marshal.StructureToPtr(cRYPTDATABLOB, zero, false);
					}
					if (x509Certificate2 != null)
					{
						handle = x509Certificate2.Handle;
					}
					else
					{
						handle = cert.Handle;
					}
					if (!NativeMethods.CertSetCertificateContextProperty(handle, NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID, 0, zero))
					{
						throw new Win32Exception(Marshal.GetLastWin32Error());
					}
				}
				finally
				{
					if (zero != IntPtr.Zero)
					{
						Marshal.FreeHGlobal(zero);
					}
				}
				return;
			}
		}