Esempio n. 1
0
        private unsafe void GetCredentials()
        {
            CredentialUse   direction;
            CredentialFlags flags;

            if (_isServer)
            {
                direction = CredentialUse.Inbound;
                flags     = CredentialFlags.UseStrongCrypto | CredentialFlags.SendAuxRecord;
            }
            else
            {
                direction = CredentialUse.Outbound;
                flags     = CredentialFlags.ValidateManual | CredentialFlags.NoDefaultCred | CredentialFlags.SendAuxRecord | CredentialFlags.UseStrongCrypto;
            }

            var creds = new SecureCredential()
            {
                rootStore               = IntPtr.Zero,
                phMappers               = IntPtr.Zero,
                palgSupportedAlgs       = IntPtr.Zero,
                cMappers                = 0,
                cSupportedAlgs          = 0,
                dwSessionLifespan       = 0,
                reserved                = 0,
                dwMinimumCipherStrength = 0, //this is required to force encryption
                dwMaximumCipherStrength = 0,
                version          = SecureCredential.CurrentVersion,
                dwFlags          = flags,
                certContextArray = IntPtr.Zero,
                cCreds           = 0
            };
            IntPtr certPointer;

            if (_isServer)
            {
                creds.grbitEnabledProtocols = InteropSspi.ServerProtocolMask;
                certPointer = _serverCertificate.Handle;
                //pointer to the pointer
                IntPtr certPointerPointer = new IntPtr(&certPointer);
                creds.certContextArray = certPointerPointer;
                creds.cCreds           = 1;
            }
            else
            {
                creds.grbitEnabledProtocols = InteropSspi.ClientProtocolMask;
            }

            long           timestamp = 0;
            SecurityStatus code      = (SecurityStatus)InteropSspi.AcquireCredentialsHandleW(null, SecurityPackage, (int)direction, null, ref creds, null, null, ref _credsHandle, out timestamp);

            if (code != 0)
            {
                throw new InvalidOperationException("Could not acquire the credentials");
            }
        }
Esempio n. 2
0
        private void AcquireClientCredentials()
        {
            SecureCredential secureCredential = new SecureCredential(SecureCredential.CurrentVersion, this.ClientCertificate, SecureCredential.Flags.ValidateManual | SecureCredential.Flags.NoDefaultCred, this.protocolFlags);

            this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle(
                SecurityPackage,
                CredentialUse.Outbound,
                secureCredential
                );
        }
Esempio n. 3
0
        private void AcquireServerCredentials()
        {
            SecureCredential secureCredential = new SecureCredential(SecureCredential.CurrentVersion, this.serverCertificate, SecureCredential.Flags.Zero, this.protocolFlags);

            this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle(
                SecurityPackage,
                CredentialUse.Inbound,
                secureCredential
                );
        }
Esempio n. 4
0
 internal unsafe static extern int AcquireCredentialsHandleW(
     [In] string principal,
     [In] string moduleName,
     [In] int usage,
     [In] void *logonID,
     [In] ref SecureCredential authData,
     [In] void *keyCallback,
     [In] void *keyArgument,
     ref SSPIHandle handlePtr,
     [Out] out long timeStamp
     );
Esempio n. 5
0
        public SecureCredential(int version, X509Certificate certificate, SecureCredential.Flags flags, SchProtocols protocols, EncryptionPolicy policy) {
            // default values required for a struct
            rootStore = phMappers = palgSupportedAlgs = certContextArray = IntPtr.Zero;
            cCreds = cMappers = cSupportedAlgs = 0;

            if (policy == EncryptionPolicy.RequireEncryption) {
                // Prohibit null encryption cipher
                dwMinimumCipherStrength = 0;
                dwMaximumCipherStrength = 0;
            }
            else if (policy == EncryptionPolicy.AllowNoEncryption) {
                // Allow null encryption cipher in addition to other ciphers
                dwMinimumCipherStrength = -1;
                dwMaximumCipherStrength =  0;
            }
            else if (policy == EncryptionPolicy.NoEncryption) {
                // Suppress all encryption and require null encryption cipher only
                dwMinimumCipherStrength = -1;
                dwMaximumCipherStrength = -1;
            }
            else {
                throw new ArgumentException(SR.GetString(SR.net_invalid_enum, "EncryptionPolicy"), "policy");
            }
            
            dwSessionLifespan = reserved = 0;
            this.version = version;
            dwFlags = flags;
            grbitEnabledProtocols = protocols;
            if (certificate != null) {
                certContextArray = certificate.Handle;
                cCreds = 1;
            }
        }
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="T:System.ComponentModel.Component"></see> and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (this.credentials != null)
            {
                this.credentials.Dispose();
                this.credentials = null;
            }
        }
 /// <summary>
 /// Set all properties to it's default values.
 /// </summary>
 public override void Reset()
 {
     this.target = Application.ProductName ?? AppDomain.CurrentDomain.FriendlyName;
     this.credentials = null;
     this.caption = null;// target as caption;
     this.message = null;
     this.banner = null;
     this.saveChecked = false;
     this.flags = CredentialsDialogFlags.Default;
 }
Esempio n. 8
0
        SafeFreeCredentials AcquireCredentialsHandle(CredentialUse credUsage, ref SecureCredential secureCredential)
        {
            // First try without impersonation, if it fails, then try the process account.
            // I.E. We don't know which account the certificate context was created under.
            try {
                //
                // For v 1.1 compat We want to ensure the credential are accessed under >>process<< acount.
                //
#if FEATURE_MONO_CAS
                using (WindowsIdentity.Impersonate(IntPtr.Zero))
#endif
                {
                    return SSPIWrapper.AcquireCredentialsHandle(m_SecModule, SecurityPackage, credUsage, secureCredential);
                }
            } catch {
                return SSPIWrapper.AcquireCredentialsHandle(m_SecModule, SecurityPackage, credUsage, secureCredential);
            }
        }
Esempio n. 9
0
        private bool AcquireServerCredentials(ref byte[] thumbPrint)
        {
            GlobalLog.Enter("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireServerCredentials");

            X509Certificate localCertificate = null;
            bool cachedCred = false;

            if (m_CertSelectionDelegate != null)
            {
                X509CertificateCollection tempCollection = new X509CertificateCollection();
                tempCollection.Add(m_ServerCertificate);
                localCertificate = m_CertSelectionDelegate(string.Empty, tempCollection, null, new string[0]);
                GlobalLog.Print("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireServerCredentials() Use delegate selected Cert");
            }
            else
            {
                localCertificate = m_ServerCertificate;
            }

            if (localCertificate == null)
                throw new NotSupportedException(SR.GetString(SR.net_ssl_io_no_server_cert));

            // SECURITY: Accessing X509 cert Credential is disabled for semitrust
            // We no longer need to demand for unmanaged code permissions.
            // EnsurePrivateKey should do the right demand for us.
            X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate);

            if (selectedCert == null)
                throw new NotSupportedException(SR.GetString(SR.net_ssl_io_no_server_cert));

            GlobalLog.Assert(localCertificate.Equals(selectedCert), "AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'.");

            //
            // Note selectedCert is a safe ref possibly cloned from the user passed Cert object
            //
            byte [] guessedThumbPrint = selectedCert.GetCertHash();
            try {
                SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, m_ProtocolFlags, m_EncryptionPolicy);

                if (cachedCredentialHandle != null)
                {
                    m_CredentialsHandle = cachedCredentialHandle;
                    m_ServerCertificate = localCertificate;
                    cachedCred = true;
                }
                else
                {
                    SecureCredential.Flags flags = SecureCredential.Flags.Zero;

                    if (!ServicePointManager.DisableSendAuxRecord)
                    {
                        flags |= SecureCredential.Flags.SendAuxRecord;
                    }

                    SecureCredential secureCredential = new SecureCredential(SecureCredential.CurrentVersion, selectedCert, flags, m_ProtocolFlags, m_EncryptionPolicy);
                    m_CredentialsHandle = AcquireCredentialsHandle(CredentialUse.Inbound, ref secureCredential);
                    thumbPrint = guessedThumbPrint;
                    m_ServerCertificate = localCertificate;
                }

            }
            finally {
                // an extra cert could have been created, dispose it now
                if ((object)localCertificate != (object)selectedCert)
                    selectedCert.Reset();
            }

            GlobalLog.Leave("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireServerCredentials, cachedCreds = " + cachedCred.ToString(), ValidationHelper.ToString(m_CredentialsHandle));
            return cachedCred;
        }
Esempio n. 10
0
        private bool AcquireClientCredentials(ref byte[] thumbPrint)
        {
            GlobalLog.Enter("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireClientCredentials");

            //
            // Acquire possible Client Certificate information and set it on the handle
            //

            X509Certificate clientCertificate = null;   // This is a candidate that can come from the user callback or be guessed when targeting a session restart
            ArrayList filteredCerts = new ArrayList();  // This is an intermediate client certs collection that try to use if no selectedCert is available yet.
            string[] issuers = null;                    // This is a list of issuers sent by the server, only valid is we do know what the server cert is.

            bool sessionRestartAttempt = false; // if true and no cached creds we will use anonymous creds.

            if (m_CertSelectionDelegate!=null)
            {
                if (issuers == null)
                    issuers = GetIssuers();

                GlobalLog.Print("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireClientCredentials() calling CertificateSelectionCallback");
                
                X509Certificate2 remoteCert = null;
                try {
                    X509Certificate2Collection dummyCollection;
                    remoteCert = GetRemoteCertificate(out dummyCollection);
                    clientCertificate = m_CertSelectionDelegate(m_HostName, ClientCertificates, remoteCert, issuers);
                }
                finally {
                    if (remoteCert != null)
                        remoteCert.Reset();
                }


                if (clientCertificate != null)
                {
                    if (m_CredentialsHandle == null)
                        sessionRestartAttempt = true;
                    filteredCerts.Add(clientCertificate);
                    if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_got_certificate_from_delegate));
                }
                else 
                {
                    // If ClientCertificates.Count != 0, how come we don't try to go through them and add them to the filtered certs, just like when there is no delegate????
                    if (ClientCertificates.Count == 0)
                    {
                        if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_no_delegate_and_have_no_client_cert));
                        sessionRestartAttempt = true;
                    }
                    else
                    {
                        if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_no_delegate_but_have_client_cert));
                    }
                }

            }
            else if (m_CredentialsHandle == null && m_ClientCertificates != null && m_ClientCertificates.Count > 0)
            {
                // This is where we attempt to restart a session by picking the FIRST cert from the collection.
                // Otheriwse (next elses) it is either server sending a client cert request or the session is renegotiated.
                clientCertificate = ClientCertificates[0];
                sessionRestartAttempt = true;
                if (clientCertificate!=null)
                    filteredCerts.Add(clientCertificate);
                if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_attempting_restart_using_cert, (clientCertificate == null ? "null" : clientCertificate.ToString(true))));
            }
            else if (m_ClientCertificates!=null && m_ClientCertificates.Count > 0)
            {
                //
                // This should be a server request for the client cert sent over currently anonyumous sessions.
                //
                if (issuers == null)
                    issuers = GetIssuers();


                if (Logging.On) 
                {
                    if (issuers == null || issuers.Length == 0)
                        Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_no_issuers_try_all_certs));
                    else
                        Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_server_issuers_look_for_matching_certs, issuers.Length));
                }

                for (int i = 0; i < m_ClientCertificates.Count; ++i)
                {
                    //
                    // make sure we add only if the cert matches one of the issuers
                    // If no issuers were sent and then try all client certs starting with the first one.
                    //
                    if (issuers != null && issuers.Length != 0)
                    {
                        X509Certificate2 certificateEx = null;
                        X509Chain chain = null;
                        try {
                            certificateEx = MakeEx(m_ClientCertificates[i]);
                            if (certificateEx == null)
                                continue;

                            GlobalLog.Print("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireClientCredentials() root cert:" + certificateEx.Issuer);
                            chain = new X509Chain();

                            chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                            chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName;
                            chain.Build(certificateEx);
                            bool found = false;

                            //
                            // We ignore any errors happened with chain.
                            // Consider: try to locate the "best" client cert that has no errors and the lognest validity internal
                            //
                            if (chain.ChainElements.Count > 0)
                            {
                                for (int ii=0; ii< chain.ChainElements.Count; ++ii)
                                {
                                    string issuer = chain.ChainElements[ii].Certificate.Issuer;
                                    found = Array.IndexOf(issuers, issuer)!=-1;
                                    if (found) {
                                        GlobalLog.Print("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireClientCredentials() matched:" + issuer);
                                        break;
                                    }
                                    GlobalLog.Print("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireClientCredentials() no match:" + issuer);
                                }
                            }
                            if (!found) {
                                continue;
                            }
                        }
                        finally {
                            if (chain != null)
                                chain.Reset();

                            if (certificateEx != null && (object)certificateEx != (object)m_ClientCertificates[i])
                                certificateEx.Reset();
                        }
                    }
                    if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_selected_cert, m_ClientCertificates[i].ToString(true)));
                    filteredCerts.Add(m_ClientCertificates[i]);
                }
            }

            bool cachedCred = false;                    // This is a return result from this method
            X509Certificate2 selectedCert = null;      // This is a final selected cert (ensured that it does have private key with it)

            clientCertificate = null;

            if (Logging.On) {
                Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_n_certs_after_filtering, filteredCerts.Count));
                if (filteredCerts.Count != 0) 
                    Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_finding_matching_certs));
            }

            //
            // ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key.
            //       THEN anonymous (no client cert) credential will be used
            //
            // SECURITY: Accessing X509 cert Credential is disabled for semitrust
            // We no longer need to demand for unmanaged code permissions.
            // EnsurePrivateKey should do the right demand for us.
            for (int i=0; i < filteredCerts.Count; ++i)
            {
                clientCertificate = filteredCerts[i] as X509Certificate;
                if ((selectedCert = EnsurePrivateKey(clientCertificate)) != null)
                    break;
                clientCertificate = null;
                selectedCert = null;
            }

            GlobalLog.Assert(((object) clientCertificate == (object) selectedCert) || clientCertificate.Equals(selectedCert), "AcquireClientCredentials()|'selectedCert' does not match 'clientCertificate'.");

            GlobalLog.Print("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireClientCredentials() Selected Cert = " + (selectedCert == null? "null": selectedCert.Subject));
            try {
                // Try to locate cached creds first.
                //
                // SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type.
                //
                byte[] guessedThumbPrint = selectedCert == null? null: selectedCert.GetCertHash();
                SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, m_ProtocolFlags, m_EncryptionPolicy);

                // We can probably do some optimization here. If the selectedCert is returned by the delegate
                // we can always go ahead and use the certificate to create our credential
                // (Instead of going anonymous as we do here)
                if (sessionRestartAttempt && cachedCredentialHandle == null && selectedCert != null)
                {
                    GlobalLog.Print("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireClientCredentials() Reset to anonymous session.");

                    // (see VsWhidbey#363953) For some (probably good) reason IIS does not renegotiate a restarted session if client cert is needed.
                    // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate.
                    // The following block happens if client did specify a certificate but no cached creds were found in the cache
                    // Since we don't restart a session the server side can still challenge for a client cert.
                    if ((object)clientCertificate != (object)selectedCert)
                        selectedCert.Reset();
                    guessedThumbPrint = null;
                    selectedCert = null;
                    clientCertificate = null;
                }

                if (cachedCredentialHandle != null)
                {
                    if (Logging.On) Logging.PrintInfo(Logging.Web, SR.GetString(SR.net_log_using_cached_credential));
                    m_CredentialsHandle = cachedCredentialHandle;
                    m_SelectedClientCertificate = clientCertificate;
                    cachedCred = true;
                }
                else
                {
                    SecureCredential.Flags flags = SecureCredential.Flags.ValidateManual | SecureCredential.Flags.NoDefaultCred;

                    if (!ServicePointManager.DisableSendAuxRecord)
                    {
                        flags |= SecureCredential.Flags.SendAuxRecord;
                    }

                    if (!ServicePointManager.DisableStrongCrypto 
                        && ((m_ProtocolFlags & (SchProtocols.Tls10 | SchProtocols.Tls11 | SchProtocols.Tls12)) != 0)
                        && (m_EncryptionPolicy != EncryptionPolicy.AllowNoEncryption) && (m_EncryptionPolicy != EncryptionPolicy.NoEncryption))
                    {
                        flags |= SecureCredential.Flags.UseStrongCrypto;
                    }

                    SecureCredential secureCredential = new SecureCredential(SecureCredential.CurrentVersion, selectedCert, flags, m_ProtocolFlags, m_EncryptionPolicy);
                    m_CredentialsHandle = AcquireCredentialsHandle(CredentialUse.Outbound, ref secureCredential);
                    thumbPrint = guessedThumbPrint; //delay it until here in case something above threw
                    m_SelectedClientCertificate = clientCertificate;
                }

            }
            finally {
                // an extra cert could have been created, dispose it now
                if (selectedCert != null && (object)clientCertificate != (object)selectedCert)
                    selectedCert.Reset();
            }

            GlobalLog.Leave("SecureChannel#" + ValidationHelper.HashString(this) + "::AcquireClientCredentials, cachedCreds = " + cachedCred.ToString(), ValidationHelper.ToString(m_CredentialsHandle));
            return cachedCred;
        }
Esempio n. 11
0
        public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface SecModule, string package, CredentialUse intent, SecureCredential scc) {
            GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): using " + package);

            if (Logging.On) Logging.PrintInfo(Logging.Web, 
                "AcquireCredentialsHandle(" +
                "package = " + package + ", " +
                "intent  = " + intent + ", " +
                "scc     = " + scc + ")");

            SafeFreeCredentials outCredential = null;
            int errorCode = SecModule.AcquireCredentialsHandle(
                                            package,
                                            intent,
                                            ref scc,
                                            out outCredential
                                            );
             if (errorCode != 0) {
#if TRAVE
                 GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): error " + SecureChannel.MapSecurityStatus((uint)errorCode));
#endif
                if (Logging.On) Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
                 throw new Win32Exception(errorCode);
             }

#if TRAVE
            GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): cred handle = " + outCredential.ToString());
#endif
            return outCredential;
        }
        private void AcquireServerCredentials()
        {
            SecureCredential scc = new SecureCredential(4, this.serverCertificate, SecureCredential.Flags.Zero, this.protocolFlags);

            this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle("Microsoft Unified Security Protocol Provider", CredentialUse.Inbound, scc);
        }
        private void AcquireClientCredentials()
        {
            SecureCredential scc = new SecureCredential(4, this.ClientCertificate, SecureCredential.Flags.NoDefaultCred | SecureCredential.Flags.ValidateManual, this.protocolFlags);

            this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle("Microsoft Unified Security Protocol Provider", CredentialUse.Outbound, scc);
        }
Esempio n. 14
0
 public static SafeFreeCredentials AcquireCredentialsHandle(
     string package,
     CredentialUse intent,
     SecureCredential scc)
 {
     SafeFreeCredentials outCredential = null;
     int errorCode = SafeFreeCredentials.AcquireCredentialsHandle(
         package,
         intent,
         ref scc,
         out outCredential
         );
     if (errorCode != 0)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(errorCode));
     }
     return outCredential;
 }
 private bool AcquireClientCredentials(ref byte[] thumbPrint)
 {
     X509Certificate certificate = null;
     ArrayList list = new ArrayList();
     string[] acceptableIssuers = null;
     bool flag = false;
     if (this.m_CertSelectionDelegate != null)
     {
         if (acceptableIssuers == null)
         {
             acceptableIssuers = this.GetIssuers();
         }
         X509Certificate2 remoteCertificate = null;
         try
         {
             X509Certificate2Collection certificates;
             remoteCertificate = this.GetRemoteCertificate(out certificates);
             certificate = this.m_CertSelectionDelegate(this.m_HostName, this.ClientCertificates, remoteCertificate, acceptableIssuers);
         }
         finally
         {
             if (remoteCertificate != null)
             {
                 remoteCertificate.Reset();
             }
         }
         if (certificate != null)
         {
             if (this.m_CredentialsHandle == null)
             {
                 flag = true;
             }
             list.Add(certificate);
             if (Logging.On)
             {
                 Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_got_certificate_from_delegate"));
             }
         }
         else if (this.ClientCertificates.Count == 0)
         {
             if (Logging.On)
             {
                 Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_no_delegate_and_have_no_client_cert"));
             }
             flag = true;
         }
         else if (Logging.On)
         {
             Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_no_delegate_but_have_client_cert"));
         }
     }
     else if (((this.m_CredentialsHandle == null) && (this.m_ClientCertificates != null)) && (this.m_ClientCertificates.Count > 0))
     {
         certificate = this.ClientCertificates[0];
         flag = true;
         if (certificate != null)
         {
             list.Add(certificate);
         }
         if (Logging.On)
         {
             Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_attempting_restart_using_cert", new object[] { (certificate == null) ? "null" : certificate.ToString(true) }));
         }
     }
     else if ((this.m_ClientCertificates != null) && (this.m_ClientCertificates.Count > 0))
     {
         if (acceptableIssuers == null)
         {
             acceptableIssuers = this.GetIssuers();
         }
         if (Logging.On)
         {
             if ((acceptableIssuers == null) || (acceptableIssuers.Length == 0))
             {
                 Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_no_issuers_try_all_certs"));
             }
             else
             {
                 Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_server_issuers_look_for_matching_certs", new object[] { acceptableIssuers.Length }));
             }
         }
         for (int j = 0; j < this.m_ClientCertificates.Count; j++)
         {
             if ((acceptableIssuers != null) && (acceptableIssuers.Length != 0))
             {
                 X509Certificate2 certificate3 = null;
                 X509Chain chain = null;
                 try
                 {
                     certificate3 = MakeEx(this.m_ClientCertificates[j]);
                     if (certificate3 == null)
                     {
                         continue;
                     }
                     chain = new X509Chain {
                         ChainPolicy = { RevocationMode = X509RevocationMode.NoCheck, VerificationFlags = X509VerificationFlags.IgnoreInvalidName }
                     };
                     chain.Build(certificate3);
                     bool flag2 = false;
                     if (chain.ChainElements.Count > 0)
                     {
                         for (int k = 0; k < chain.ChainElements.Count; k++)
                         {
                             string issuer = chain.ChainElements[k].Certificate.Issuer;
                             flag2 = Array.IndexOf<string>(acceptableIssuers, issuer) != -1;
                             if (flag2)
                             {
                                 break;
                             }
                         }
                     }
                     if (!flag2)
                     {
                         continue;
                     }
                 }
                 finally
                 {
                     if (chain != null)
                     {
                         chain.Reset();
                     }
                     if ((certificate3 != null) && (certificate3 != this.m_ClientCertificates[j]))
                     {
                         certificate3.Reset();
                     }
                 }
             }
             if (Logging.On)
             {
                 Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_selected_cert", new object[] { this.m_ClientCertificates[j].ToString(true) }));
             }
             list.Add(this.m_ClientCertificates[j]);
         }
     }
     X509Certificate2 certificate4 = null;
     certificate = null;
     if (Logging.On)
     {
         Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_n_certs_after_filtering", new object[] { list.Count }));
         if (list.Count != 0)
         {
             Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_finding_matching_certs"));
         }
     }
     for (int i = 0; i < list.Count; i++)
     {
         certificate = list[i] as X509Certificate;
         certificate4 = this.EnsurePrivateKey(certificate);
         if (certificate4 != null)
         {
             break;
         }
         certificate = null;
         certificate4 = null;
     }
     try
     {
         byte[] buffer = (certificate4 == null) ? null : certificate4.GetCertHash();
         SafeFreeCredentials credentials = SslSessionsCache.TryCachedCredential(buffer, this.m_ProtocolFlags, this.m_EncryptionPolicy);
         if ((flag && (credentials == null)) && (certificate4 != null))
         {
             if (certificate != certificate4)
             {
                 certificate4.Reset();
             }
             buffer = null;
             certificate4 = null;
             certificate = null;
         }
         if (credentials != null)
         {
             if (Logging.On)
             {
                 Logging.PrintInfo(Logging.Web, SR.GetString("net_log_using_cached_credential"));
             }
             this.m_CredentialsHandle = credentials;
             this.m_SelectedClientCertificate = certificate;
             return true;
         }
         SecureCredential secureCredential = new SecureCredential(4, certificate4, SecureCredential.Flags.NoDefaultCred | SecureCredential.Flags.ValidateManual, this.m_ProtocolFlags, this.m_EncryptionPolicy);
         this.m_CredentialsHandle = this.AcquireCredentialsHandle(CredentialUse.Outbound, ref secureCredential);
         thumbPrint = buffer;
         this.m_SelectedClientCertificate = certificate;
     }
     finally
     {
         if ((certificate4 != null) && (certificate != certificate4))
         {
             certificate4.Reset();
         }
     }
     return false;
 }
 private bool AcquireServerCredentials(ref byte[] thumbPrint)
 {
     X509Certificate serverCertificate = null;
     if (this.m_CertSelectionDelegate != null)
     {
         X509CertificateCollection localCertificates = new X509CertificateCollection();
         localCertificates.Add(this.m_ServerCertificate);
         serverCertificate = this.m_CertSelectionDelegate(string.Empty, localCertificates, null, new string[0]);
     }
     else
     {
         serverCertificate = this.m_ServerCertificate;
     }
     if (serverCertificate == null)
     {
         throw new NotSupportedException(SR.GetString("net_ssl_io_no_server_cert"));
     }
     X509Certificate2 certificate2 = this.EnsurePrivateKey(serverCertificate);
     if (certificate2 == null)
     {
         throw new NotSupportedException(SR.GetString("net_ssl_io_no_server_cert"));
     }
     byte[] certHash = certificate2.GetCertHash();
     try
     {
         SafeFreeCredentials credentials = SslSessionsCache.TryCachedCredential(certHash, this.m_ProtocolFlags, this.m_EncryptionPolicy);
         if (credentials != null)
         {
             this.m_CredentialsHandle = credentials;
             this.m_ServerCertificate = serverCertificate;
             return true;
         }
         SecureCredential secureCredential = new SecureCredential(4, certificate2, SecureCredential.Flags.Zero, this.m_ProtocolFlags, this.m_EncryptionPolicy);
         this.m_CredentialsHandle = this.AcquireCredentialsHandle(CredentialUse.Inbound, ref secureCredential);
         thumbPrint = certHash;
         this.m_ServerCertificate = serverCertificate;
     }
     finally
     {
         if (serverCertificate != certificate2)
         {
             certificate2.Reset();
         }
     }
     return false;
 }
 private SafeFreeCredentials AcquireCredentialsHandle(CredentialUse credUsage, ref SecureCredential secureCredential)
 {
     SafeFreeCredentials credentials;
     try
     {
         using (WindowsIdentity.Impersonate(IntPtr.Zero))
         {
             credentials = SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, "Microsoft Unified Security Protocol Provider", credUsage, secureCredential);
         }
     }
     catch
     {
         credentials = SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, "Microsoft Unified Security Protocol Provider", credUsage, secureCredential);
     }
     return credentials;
 }
Esempio n. 18
0
 public SecureCredential(int version, X509Certificate certificate, SecureCredential.Flags flags, SchProtocols protocols)
 {
     // default values required for a struct
     rootStore = phMappers = palgSupportedAlgs = certContextArray = IntPtr.Zero;
     cCreds = cMappers = cSupportedAlgs = 0;
     dwMinimumCipherStrength = dwMaximumCipherStrength = 0;
     dwSessionLifespan = reserved = 0;
     this.version = version;
     dwFlags = flags;
     grbitEnabledProtocols = protocols;
     if (certificate != null) {
         certContextArray = certificate.Handle;
         cCreds = 1;
     }
 }