public void Reset()
 {
     this.m_applicationPolicy = new OidCollection();
     this.m_certificatePolicy = new OidCollection();
     this.m_revocationMode = X509RevocationMode.Online;
     this.m_revocationFlag = X509RevocationFlag.ExcludeRoot;
     this.m_verificationFlags = X509VerificationFlags.NoFlag;
     this.m_verificationTime = DateTime.Now;
     this.m_timeout = new TimeSpan(0, 0, 0);
     this.m_extraStore = new X509Certificate2Collection();
 }
 public bool? Verify(X509VerificationFlags flags, out Exception exception)
 {
     if (flags != X509VerificationFlags.NoFlag)
     {
         // TODO (#2204): Add support for X509VerificationFlags, or throw PlatformNotSupportedException.
         throw new NotSupportedException(SR.WorkInProgress);
     }
     
     exception = null;
     return ChainStatus.Length == 0;
 }
        private void CheckCert2(X509Chain c)
        {
            X509VerificationFlags success_mask = X509VerificationFlags.IgnoreNotTimeValid | X509VerificationFlags.AllowUnknownCertificateAuthority;

            Assert.AreEqual(((c.ChainPolicy.VerificationFlags & success_mask) == success_mask), c.Build(cert2), "Build");
            Assert.AreEqual(1, c.ChainElements.Count, "ChainElements");
            Assert.AreEqual(String.Empty, c.ChainElements[0].Information, "ChainElements[0].Information");
            Assert.AreEqual(cert2, c.ChainElements[0].Certificate, "ChainElements[0].Certificate");

            CheckChainStatus(X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.NotTimeValid, c.ChainStatus, "c.ChainStatus");
            CheckChainStatus(X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.NotTimeValid, c.ChainElements[0].ChainElementStatus, "c.ChainElements[0].ChainElementStatus");
        }
Beispiel #4
0
 public void Reset()
 {
     _applicationPolicy  = null;
     _certificatePolicy  = null;
     _extraStore         = null;
     _customTrustStore   = null;
     _revocationMode     = X509RevocationMode.Online;
     _revocationFlag     = X509RevocationFlag.ExcludeRoot;
     _verificationFlags  = X509VerificationFlags.NoFlag;
     _trustMode          = X509ChainTrustMode.System;
     VerificationTime    = DateTime.Now;
     UrlRetrievalTimeout = TimeSpan.Zero; // default timeout
 }
        private static bool HasUnsuppressedError(X509VerificationFlags flags, X509ChainElement element, bool isEndEntity)
        {
            foreach (X509ChainStatus status in element.ChainElementStatus)
            {
                if (status.Status == X509ChainStatusFlags.NoError)
                {
                    return false;
                }

                Debug.Assert(
                    (status.Status & (status.Status - 1)) == 0,
                    "Only one bit is set in status.Status");

                // The Windows certificate store API only checks the time error for a "peer trust" certificate,
                // but we don't have a concept for that in Unix.  If we did, we'd need to do that logic that here.
                // Note also that that logic is skipped if CERT_CHAIN_POLICY_IGNORE_PEER_TRUST_FLAG is set.

                X509VerificationFlags? suppressionFlag;

                if (status.Status == X509ChainStatusFlags.RevocationStatusUnknown)
                {
                    if (isEndEntity)
                    {
                        suppressionFlag = X509VerificationFlags.IgnoreEndRevocationUnknown;
                    }
                    else if (IsSelfSigned(element.Certificate))
                    {
                        suppressionFlag = X509VerificationFlags.IgnoreRootRevocationUnknown;
                    }
                    else
                    {
                        suppressionFlag = X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown;
                    }
                }
                else
                {
                    suppressionFlag = GetSuppressionFlag(status.Status);
                }

                // If an error was found, and we do NOT have the suppression flag for it enabled,
                // we have an unsuppressed error, so return true. (If there's no suppression for a given code,
                // we (by definition) don't have that flag set.
                if (!suppressionFlag.HasValue ||
                    (flags & suppressionFlag) == 0)
                {
                    return true;
                }
            }

            return false;
        }
Beispiel #6
0
        private static bool HasUnsuppressedError(X509VerificationFlags flags, X509ChainElement element, bool isEndEntity)
        {
            foreach (X509ChainStatus status in element.ChainElementStatus)
            {
                if (status.Status == X509ChainStatusFlags.NoError)
                {
                    return(false);
                }

                Debug.Assert(
                    (status.Status & (status.Status - 1)) == 0,
                    "Only one bit is set in status.Status");

                // The Windows certificate store API only checks the time error for a "peer trust" certificate,
                // but we don't have a concept for that in Unix.  If we did, we'd need to do that logic that here.
                // Note also that that logic is skipped if CERT_CHAIN_POLICY_IGNORE_PEER_TRUST_FLAG is set.

                X509VerificationFlags?suppressionFlag;

                if (status.Status == X509ChainStatusFlags.RevocationStatusUnknown)
                {
                    if (isEndEntity)
                    {
                        suppressionFlag = X509VerificationFlags.IgnoreEndRevocationUnknown;
                    }
                    else if (IsSelfSigned(element.Certificate))
                    {
                        suppressionFlag = X509VerificationFlags.IgnoreRootRevocationUnknown;
                    }
                    else
                    {
                        suppressionFlag = X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown;
                    }
                }
                else
                {
                    suppressionFlag = GetSuppressionFlag(status.Status);
                }

                // If an error was found, and we do NOT have the suppression flag for it enabled,
                // we have an unsuppressed error, so return true. (If there's no suppression for a given code,
                // we (by definition) don't have that flag set.
                if (!suppressionFlag.HasValue ||
                    (flags & suppressionFlag) == 0)
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #7
0
 public bool VerifyChain(out X509Chain chain, X509VerificationFlags flags = X509VerificationFlags.NoFlag)
 {
     chain = null;
     if (MerchantCertificate == null || PKIType == Payment.PKIType.None)
     {
         return(false);
     }
     chain = new X509Chain();
     chain.ChainPolicy.VerificationFlags = flags;
     foreach (var additional in AdditionalCertificates)
     {
         chain.ChainPolicy.ExtraStore.Add(additional);
     }
     return(chain.Build(MerchantCertificate));
 }
Beispiel #8
0
        public static bool Verify(X509ChainElement[] chainElements, X509VerificationFlags flags)
        {
            bool isEndEntity = true;

            foreach (X509ChainElement element in chainElements)
            {
                if (HasUnsuppressedError(flags, element, isEndEntity))
                {
                    return(false);
                }

                isEndEntity = false;
            }

            return(true);
        }
Beispiel #9
0
        public bool?Verify(X509VerificationFlags flags, out Exception exception)
        {
            exception = null;
            bool isEndEntity = true;

            foreach (X509ChainElement element in ChainElements)
            {
                if (HasUnsuppressedError(flags, element, isEndEntity))
                {
                    return(false);
                }

                isEndEntity = false;
            }

            return(true);
        }
        public bool? Verify(X509VerificationFlags flags, out Exception exception)
        {
            exception = null;
            bool isEndEntity = true;

            foreach (X509ChainElement element in ChainElements)
            {
                if (HasUnsuppressedError(flags, element, isEndEntity))
                {
                    return false;
                }

                isEndEntity = false;
            }

            return true;
        }
Beispiel #11
0
            public bool?Verify(X509VerificationFlags flags, out Exception?exception)
            {
                Debug.Assert(_chainContext != null);
                exception = null;

                if (!_isValid)
                {
                    // There is no way to bypass certain validation - time, trusted root, name,
                    // policy constraint - on Android. It will not build any chain without these
                    // all being valid. This will be an empty chain with PartialChain status.
                    Debug.Assert(ChainElements !.Length == 0);
                    Debug.Assert(ChainStatus !.Length > 0 && (ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain);
                    return(false);
                }

                return(UnixChainVerifier.Verify(ChainElements !, flags));
            }
        private static void ValidateCertPath(X509Certificate2Collection trustAnchors, X509Certificate2 certificate, bool verifyCertTimesAgainstSystemTime)
        {
            X509VerificationFlags flags = X509VerificationFlags.AllowUnknownCertificateAuthority;

            if (!verifyCertTimesAgainstSystemTime)
            {
                // do not verify certificates against local system time.
                flags |= X509VerificationFlags.IgnoreNotTimeValid;
            }

            X509Chain chain = new X509Chain {
                ChainPolicy = { VerificationFlags = flags }
            };

            bool isChainValid = chain.Build(certificate);

            if (!isChainValid)
            {
                List <string> errors = new List <string>();

                foreach (X509ChainStatus status in chain.ChainStatus)
                {
                    errors.Add(string.Format("{0} ({1})", status.StatusInformation, status.Status));
                }

                string certificateErrorsString = errors.Count == 0 ? "Unknown errors." : string.Join(", ", errors.ToArray());
                throw new PkiVerificationFailedException("Trust chain did not complete to the known authority anchor. Errors: " + certificateErrorsString);
            }

            foreach (X509ChainElement chainElement in chain.ChainElements)
            {
                foreach (X509Certificate2 cert in trustAnchors)
                {
                    if (chainElement.Certificate.Thumbprint == cert.Thumbprint)
                    {
                        return;
                    }
                }
            }

            throw new PkiVerificationFailedException("Trust chain did not complete to the known authority anchor. Thumbprints did not match.", null,
                                                     GetCertInfoString(trustAnchors, chain.ChainElements));
        }
Beispiel #13
0
        /// <summary>
        /// Does not throw on api error. Returns default(bool?) and sets "exception" instead.
        /// </summary>
        public bool?Verify(X509VerificationFlags flags, out Exception?exception)
        {
            exception = null;

            unsafe
            {
                Interop.Crypt32.CERT_CHAIN_POLICY_PARA para = default;
                para.cbSize  = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_PARA);
                para.dwFlags = (uint)flags;

                Interop.Crypt32.CERT_CHAIN_POLICY_STATUS status = default;
                status.cbSize = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_STATUS);

                if (!Interop.crypt32.CertVerifyCertificateChainPolicy(ChainPolicy.CERT_CHAIN_POLICY_BASE, _chain, ref para, ref status))
                {
                    int errorCode = Marshal.GetLastPInvokeError();
                    exception = errorCode.ToCryptographicException();
                    return(default(bool?));
                }
                return(status.dwError == 0);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Does not throw on api error. Returns default(bool?) and sets "exception" instead.
        /// </summary>
        public bool?Verify(X509VerificationFlags flags, out Exception exception)
        {
            exception = null;

            unsafe
            {
                CERT_CHAIN_POLICY_PARA para = new CERT_CHAIN_POLICY_PARA();
                para.cbSize  = sizeof(CERT_CHAIN_POLICY_PARA);
                para.dwFlags = (int)flags;

                CERT_CHAIN_POLICY_STATUS status = new CERT_CHAIN_POLICY_STATUS();
                status.cbSize = sizeof(CERT_CHAIN_POLICY_STATUS);

                if (!Interop.crypt32.CertVerifyCertificateChainPolicy(ChainPolicy.CERT_CHAIN_POLICY_BASE, _chain, ref para, ref status))
                {
                    int errorCode = Interop.CPError.GetLastWin32Error();
                    exception = errorCode.ToCryptographicException();
                    return(default(bool?));
                }
                return(status.dwError == 0);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Does not throw on api error. Returns default(bool?) and sets "exception" instead. 
        /// </summary>
        public bool? Verify(X509VerificationFlags flags, out Exception exception)
        {
            exception = null;

            CERT_CHAIN_POLICY_PARA para = new CERT_CHAIN_POLICY_PARA()
            {
                cbSize = Marshal.SizeOf<CERT_CHAIN_POLICY_PARA>(),
                dwFlags = (int)flags,
            };

            CERT_CHAIN_POLICY_STATUS status = new CERT_CHAIN_POLICY_STATUS()
            {
                cbSize = Marshal.SizeOf<CERT_CHAIN_POLICY_STATUS>(),
            };

            if (!Interop.crypt32.CertVerifyCertificateChainPolicy(ChainPolicy.CERT_CHAIN_POLICY_BASE, _chain, ref para, ref status))
            {
                int errorCode = Marshal.GetLastWin32Error();
                exception = errorCode.ToCryptographicException();
                return default(bool?);
            }
            return status.dwError == 0;
        }
Beispiel #16
0
        /// <summary>
        /// Does not throw on api error. Returns default(bool?) and sets "exception" instead.
        /// </summary>
        public bool?Verify(X509VerificationFlags flags, out Exception exception)
        {
            exception = null;

            CERT_CHAIN_POLICY_PARA para = new CERT_CHAIN_POLICY_PARA()
            {
                cbSize  = Marshal.SizeOf <CERT_CHAIN_POLICY_PARA>(),
                dwFlags = (int)flags,
            };

            CERT_CHAIN_POLICY_STATUS status = new CERT_CHAIN_POLICY_STATUS()
            {
                cbSize = Marshal.SizeOf <CERT_CHAIN_POLICY_STATUS>(),
            };

            if (!Interop.crypt32.CertVerifyCertificateChainPolicy(ChainPolicy.CERT_CHAIN_POLICY_BASE, _chain, ref para, ref status))
            {
                int errorCode = Marshal.GetLastWin32Error();
                exception = errorCode.ToCryptographicException();
                return(default(bool?));
            }
            return(status.dwError == 0);
        }
Beispiel #17
0
        /// <summary>
        /// Validate certificate against policy chain
        /// </summary>
        /// <param name="revocationFlag"></param>
        /// <param name="revocationMode"></param>
        /// <param name="retrievalTimeout"></param>
        /// <param name="verificationFlags"></param>
        /// <returns></returns>
        public bool Verificate(X509RevocationFlag revocationFlag, X509RevocationMode revocationMode, TimeSpan retrievalTimeout, X509VerificationFlags verificationFlags)
        {
            //chain information of the selected certificate.
            chain = new X509Chain();
            chain.ChainPolicy.RevocationFlag      = revocationFlag;
            chain.ChainPolicy.RevocationMode      = revocationMode;
            chain.ChainPolicy.UrlRetrievalTimeout = retrievalTimeout;
            chain.ChainPolicy.VerificationFlags   = verificationFlags;

            return(chain.Build(certificate));
        }
Beispiel #18
0
 public bool?Verify(X509VerificationFlags flags, out Exception exception)
 {
     exception = new NotImplementedException();
     return(null);
 }
        protected override PropertyBagDataItem[] GetOutputData(DataItemBase[] inputDataItems)
        {
            TcpClient tcpClient;
            SslStream sslStream  = null;
            int       remotePort = -1;

            if (!string.IsNullOrWhiteSpace(Schema))
            {
                try { remotePort = new Uri($"{Schema}://{FullyQualifiedDomainName}").Port; }
                catch (Exception e)
                {
                    ModInit.Logger.WriteWarning($"Unable to get port number from {Schema} schema. Will retry using explicit port number (if available).\r\nError message: {e.Message}", this);
                }
            }
            if (remotePort <= 0 && Port > 0)
            {
                remotePort = Port;
            }
            if (remotePort <= 0)
            {
                ModInit.Logger.WriteWarning($"Unable to get port number from. Test is skipped.", this);
                return(null);
            }
            List <SslProtocols> SupportedSslProtocols = new List <SslProtocols>();
            X509Certificate2    remoteCert            = null;

            try
            {
                bool authSuccess = false;
                foreach (SslProtocols protocolType in Enum.GetValues(typeof(SslProtocols)))
                {
                    if (protocolType == SslProtocols.None || protocolType == SslProtocols.Default) // need explicit values only
                    {
                        continue;
                    }
                    try
                    {
                        tcpClient = new TcpClient(FullyQualifiedDomainName, remotePort);
                        sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(RecordCertificateProperties))
                        {
                            ReadTimeout  = 15000,
                            WriteTimeout = 15000
                        };
                    }
                    catch (Exception e)
                    {
                        ModInit.Logger.WriteWarning($"Cannot connect to {FullyQualifiedDomainName}:{remotePort} to test certificate. No test performed.\r\nError message: {e.Message}", this);
                        try
                        {
                            if (sslStream != null)
                            {
                                sslStream.Dispose();
                                sslStream = null;
                            }
                        }
                        catch { }
                        return(null);
                    }
                    try
                    {
                        sslStream.AuthenticateAsClient(FullyQualifiedDomainName, null, protocolType, false);
                        if (remoteCert == null) // get first available
                        {
                            remoteCert = new X509Certificate2(sslStream.RemoteCertificate.GetRawCertData());
                        }
                        SupportedSslProtocols.Add(protocolType);
                        authSuccess = true;
                    }
                    catch
                    {
                    }
                    finally
                    {
                        if (sslStream != null)
                        {
                            sslStream.Dispose();
                            sslStream = null;
                        }
                    }
                    // then continue to try all of them
                }
                if (!authSuccess || remoteCert == null)
                {
                    ModInit.Logger.WriteWarning($"Unable to create SSL connection to {FullyQualifiedDomainName}:{remotePort}. Secure protocol might be not supported.", this);
                    return(null); // cannot create and SSL stream
                }
                // dump some cert properties in a property bag
                Dictionary <string, object> bagItem = new Dictionary <string, object>
                {
                    { "DaysToExpire", Math.Round(remoteCert.NotAfter.Subtract(DateTime.UtcNow).TotalDays, 2) },
                    { "StartDate", remoteCert.NotBefore.ToString("yyyy-MM-dd HH:mm:ss") },
                    { "EndDate", remoteCert.NotAfter.ToString("yyyy-MM-dd HH:mm:ss") },
                    { "Issuer", remoteCert.Issuer },
                    { "Subject", remoteCert.Subject },
                    { "SerialNumber", remoteCert.SerialNumber },
                    { "SignatureAlgorithm", remoteCert.SignatureAlgorithm.FriendlyName },
                    { "RemotePort", remotePort },
                    { "HasDisabledProtocols", SupportedSslProtocols.Any(sp => DisabledSSLProtocols.Any(dp => sp == dp)) },
                    { "DontSupportProtocols", !SupportedSslProtocols.Any(sp => AllowedSSLProtocols.Any(ap => sp == ap)) },
                    { "Thumbprint", remoteCert.Thumbprint }
                };
                string supportedSSLProtocolList = "";
                foreach (SslProtocols proto in SupportedSslProtocols)
                {
                    supportedSSLProtocolList += $"{proto}; ";
                }
                bagItem.Add("SupportedSslProtocols", supportedSSLProtocolList);
                if (DisabledHash.TrueForAll(x => x.Value != remoteCert.SignatureAlgorithm.Value))
                {
                    bagItem.Add("SignatureAlgorithmDisabled", "false");
                }
                else
                {
                    bagItem.Add("SignatureAlgorithmDisabled", "true");
                }
                if (PolicyErrors == SslPolicyErrors.None)
                {
                    bagItem.Add("PolicyErrors", "NONE");
                }
                else
                {
                    bagItem.Add("PolicyErrors", PolicyErrors.ToString());
                }

                // Verify the cert chain
                var certificateChain = new X509Chain(true); // Use Machine Context
                certificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                certificateChain.ChainPolicy.RevocationMode = IgnoreRevocationCheck ? X509RevocationMode.NoCheck : X509RevocationMode.Online;
                if (ApplicationPolicy != null && ApplicationPolicy.Count > 0)
                {
                    foreach (Oid apOid in ApplicationPolicy)
                    {
                        certificateChain.ChainPolicy.ApplicationPolicy.Add(apOid);
                    }
                }
                if (CertificatePolicy != null && CertificatePolicy.Count > 0)
                {
                    foreach (Oid caOid in CertificatePolicy)
                    {
                        certificateChain.ChainPolicy.CertificatePolicy.Add(caOid);
                    }
                }

                X509VerificationFlags flags = X509VerificationFlags.NoFlag;
                if (AllowUnknownCertificateAuthority)
                {
                    flags |= X509VerificationFlags.AllowUnknownCertificateAuthority;
                }
                if (IgnoreCertificateAuthorityRevocationUnknown)
                {
                    flags |= X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown;
                }
                if (IgnoreCtlNotTimeValid)
                {
                    flags |= X509VerificationFlags.IgnoreCtlNotTimeValid;
                }
                if (IgnoreCtlSignerRevocationUnknown)
                {
                    flags |= X509VerificationFlags.IgnoreCtlSignerRevocationUnknown;
                }
                if (IgnoreEndRevocationUnknown)
                {
                    flags |= X509VerificationFlags.IgnoreEndRevocationUnknown;
                }
                if (IgnoreInvalidBasicConstraints)
                {
                    flags |= X509VerificationFlags.IgnoreInvalidBasicConstraints;
                }
                if (IgnoreInvalidName)
                {
                    flags |= X509VerificationFlags.IgnoreInvalidName;
                }
                if (IgnoreInvalidPolicy)
                {
                    flags |= X509VerificationFlags.IgnoreInvalidPolicy;
                }
                if (IgnoreNotTimeNested)
                {
                    flags |= X509VerificationFlags.IgnoreNotTimeNested;
                }
                if (IgnoreNotTimeValid)
                {
                    flags |= X509VerificationFlags.IgnoreNotTimeValid;
                }
                if (IgnoreRootRevocationUnknown)
                {
                    flags |= X509VerificationFlags.IgnoreRootRevocationUnknown;
                }
                if (IgnoreWrongUsage)
                {
                    flags |= X509VerificationFlags.IgnoreWrongUsage;
                }

                certificateChain.ChainPolicy.VerificationFlags = flags;
                certificateChain.Build(remoteCert);
                if (certificateChain.ChainStatus.Length == 0)
                {
                    bagItem.Add("CertificateIsValid", "true");
                    bagItem.Add("CertificateStatus", "");
                }
                else
                {
                    bagItem.Add("CertificateIsValid", "false");
                    string strStatusMessage = "";
                    foreach (X509ChainStatus status in certificateChain.ChainStatus)
                    {
                        strStatusMessage += status.StatusInformation + "; ";
                    }
                    bagItem.Add("CertificateStatus", strStatusMessage);
                }

                return(new List <PropertyBagDataItem>()
                {
                    CreatePropertyBag(bagItem)
                }.ToArray());
            }
            catch (Exception e)
            {
                ModuleErrorSignalReceiver(ModuleErrorSeverity.DataLoss, ModuleErrorCriticality.ThrowAndContinue, e, $"Unexpected exception while testing secure connection to the {TestDisplayName} test object related to the {FullyQualifiedDomainName}:{TargetIndex} destination object.");
                return(null);
            }
        }
 public bool? Verify(X509VerificationFlags flags, out Exception exception)
 {
     exception = new NotImplementedException();
     return null;
 }
        protected bool ContextServerCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (Tracer.IsDebugEnabled)
            {
                string name = null;
                if (certificate is X509Certificate2)
                {
                    X509Certificate2 cert = certificate as X509Certificate2;
                    name = cert.SubjectName.Name;
                }
                Tracer.DebugFormat("Cert DN {0}; Cert Subject {1}; Cert Issuer {2}; SSLPolicyErrors [{3}]", name, certificate?.Subject ?? "null", certificate?.Issuer ?? "null", sslPolicyErrors.ToString());
                try
                {
                    X509VerificationFlags verFlags = chain.ChainPolicy.VerificationFlags;
                    X509RevocationMode    revMode  = chain.ChainPolicy.RevocationMode;
                    X509RevocationFlag    revFlags = chain.ChainPolicy.RevocationFlag;
                    StringBuilder         sb       = new StringBuilder();
                    sb.Append("ChainStatus={");
                    int size = sb.Length;
                    foreach (X509ChainStatus status in chain.ChainStatus)
                    {
                        X509ChainStatusFlags csflags = status.Status;
                        sb.AppendFormat("Info={0}; flags=0x{1:X}; flagNames=[{2}]", status.StatusInformation, csflags, csflags.ToString());
                        sb.Append(", ");
                    }
                    if (size != sb.Length)
                    {
                        sb.Remove(sb.Length - 2, 2);
                    }
                    sb.Append("}");

                    Tracer.DebugFormat("X.509 Cert Chain, Verification Flags {0:X} {1}, Revocation Mode {2}, Revocation Flags {3}, Status {4} ",
                                       verFlags, verFlags.ToString(), revMode.ToString(), revFlags.ToString(), sb.ToString());
                }
                catch (Exception ex)
                {
                    Tracer.ErrorFormat("Error displaying Remote Cert fields. Cause: {0}", ex);
                }
            }

            bool?valid = null;

            if (ServerCertificateValidateCallback != null)
            {
                try
                {
                    if (Tracer.IsDebugEnabled)
                    {
                        Tracer.DebugFormat("Calling application callback for Remote Certificate Validation.");
                    }
                    valid = ServerCertificateValidateCallback(sender, certificate, chain, sslPolicyErrors);
                }
                catch (Exception ex)
                {
                    Tracer.InfoFormat("Caught Exception from application callback for Remote Certificate Validation. Exception : {0}", ex);
                    throw ex;
                }
            }
            else
            {
                if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.RemoteCertificateNameMismatch &&
                    !String.IsNullOrWhiteSpace(this.ServerName))
                {
                    if (certificate.Subject.IndexOf(string.Format("CN={0}",
                                                                  this.ServerName), StringComparison.InvariantCultureIgnoreCase) > -1)
                    {
                        sslPolicyErrors &= ~(SslPolicyErrors.RemoteCertificateNameMismatch);
                    }
                }
                if (sslPolicyErrors == SslPolicyErrors.None)
                {
                    valid = true;
                }
                else
                {
                    Tracer.WarnFormat("SSL certificate {0} validation error : {1}", certificate.Subject, sslPolicyErrors.ToString());
                    valid = this.AcceptInvalidBrokerCert;
                }
            }
            return(valid ?? this.AcceptInvalidBrokerCert);
        }
Beispiel #22
0
        ///////////////////////////////////////////////////////////////////////

        public static ReturnCode VerifyChain(
            Assembly assembly,
            X509Certificate2 certificate2,
            X509VerificationFlags verificationFlags,
            X509RevocationMode revocationMode,
            X509RevocationFlag revocationFlag,
            ref Result error
            )
        {
            if (certificate2 != null)
            {
                try
                {
                    X509Chain chain = X509Chain.Create();

                    if (chain != null)
                    {
                        X509ChainPolicy chainPolicy = chain.ChainPolicy;

                        if (chainPolicy != null)
                        {
                            //
                            // NOTE: Setup the chain policy settings as specified
                            //       by the caller.
                            //
                            chainPolicy.VerificationFlags = verificationFlags;
                            chainPolicy.RevocationMode    = revocationMode;
                            chainPolicy.RevocationFlag    = revocationFlag;

                            if (chain.Build(certificate2))
                            {
                                return(ReturnCode.Ok);
                            }
                            else
                            {
                                StringList list = new StringList();

                                if (chain.ChainStatus != null)
                                {
                                    foreach (X509ChainStatus status in chain.ChainStatus)
                                    {
                                        list.Add(
                                            status.Status.ToString(),
                                            status.StatusInformation);
                                    }

                                    if (assembly != null)
                                    {
                                        error = String.Format(
                                            "assembly {0}: {1}",
                                            FormatOps.WrapOrNull(assembly),
                                            list.ToString());
                                    }
                                    else
                                    {
                                        error = list;
                                    }
                                }
                                else
                                {
                                    if (assembly != null)
                                    {
                                        error = String.Format(
                                            "assembly {0}: invalid chain status",
                                            FormatOps.WrapOrNull(assembly));
                                    }
                                    else
                                    {
                                        error = "invalid chain status";
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (assembly != null)
                            {
                                error = String.Format(
                                    "assembly {0}: invalid chain policy",
                                    FormatOps.WrapOrNull(assembly));
                            }
                            else
                            {
                                error = "invalid chain policy";
                            }
                        }
                    }
                    else
                    {
                        if (assembly != null)
                        {
                            error = String.Format(
                                "assembly {0}: invalid chain",
                                FormatOps.WrapOrNull(assembly));
                        }
                        else
                        {
                            error = "invalid chain";
                        }
                    }
                }
                catch (Exception e)
                {
                    if (assembly != null)
                    {
                        error = String.Format(
                            "assembly {0}: {1}",
                            FormatOps.WrapOrNull(assembly), e);
                    }
                    else
                    {
                        error = e;
                    }
                }
            }
            else
            {
                if (assembly != null)
                {
                    error = String.Format(
                        "assembly {0}: invalid certificate",
                        FormatOps.WrapOrNull(assembly));
                }
                else
                {
                    error = "invalid certificate";
                }
            }

            return(ReturnCode.Error);
        }
Beispiel #23
0
 public void Reset()
 {
     ApplicationPolicy = new OidCollection();
     CertificatePolicy = new OidCollection();
     _revocationMode = X509RevocationMode.Online;
     _revocationFlag = X509RevocationFlag.ExcludeRoot;
     _verificationFlags = X509VerificationFlags.NoFlag;
     VerificationTime = DateTime.Now;
     UrlRetrievalTimeout = new TimeSpan(0, 0, 0); // default timeout
     ExtraStore = new X509Certificate2Collection();
 }
Beispiel #24
0
        public bool VerifyChain(X509VerificationFlags flags = X509VerificationFlags.NoFlag)
        {
            X509Chain chain;

            return(VerifyChain(out chain, flags));
        }
        public IsCertificateValidRule(DateTime signatureDate, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, X509VerificationFlags verificationFlags)
        {
            Description   = "Certificado foi validado pela unidade autenticadora";
            Chain         = new X509Chain();
            SignatureDate = signatureDate;
            _Messages     = new List <string>();

            var validarCadeia = true;

            if (ConfigurationManager.AppSettings["ASSINATURA_DIGITAL_VALIDAR_REVOGACAO"] != default(string))
            {
                bool.TryParse(ConfigurationManager.AppSettings["ASSINATURA_DIGITAL_VALIDAR_REVOGACAO"], out validarCadeia);

                if (!validarCadeia)
                {
                    revocationMode = X509RevocationMode.NoCheck;
                }
            }

            Chain.ChainPolicy.RevocationMode    = revocationMode;
            Chain.ChainPolicy.RevocationFlag    = revocationFlag;
            Chain.ChainPolicy.VerificationFlags = verificationFlags;

            if (TrustedRootsThumbprints == null)
            {
                TrustedRootsThumbprints = ConfigurationManager
                                          .AppSettings
                                          .AllKeys
                                          .Where(o => o.StartsWith("trusted_root_"))
                                          .Select(o => ConfigurationManager.AppSettings[o].ToLower());
            }
        }
Beispiel #26
0
        public bool?Verify(X509VerificationFlags flags, out Exception exception)
        {
            exception = null;

            return(ChainVerifier.Verify(ChainElements, flags));
        }
		// methods

		public void Reset ()
		{
			_apps = new OidCollection ();
			_cert = new OidCollection ();
			_store = new X509Certificate2Collection ();
			_rflag = X509RevocationFlag.ExcludeRoot;
			_mode = X509RevocationMode.Online;
			_timeout = new TimeSpan (0);
			_vflags = X509VerificationFlags.NoFlag;
			_vtime = DateTime.Now;
		}
Beispiel #28
0
        /// <summary>
        /// Validate certificate against policy chain
        /// </summary>
        /// <param name="certificate">certificate</param>
        /// <param name="revocationFlag">revocation flag</param>
        /// <param name="revocationMode">revocation mode</param>
        /// <param name="retrievalTimeout">retrieval timeout</param>
        /// <param name="verificationFlags">verification flags</param>
        /// <returns>certificate verification result</returns>
        public static CertificateVerificationResult Verify(X509Certificate2 certificate, X509RevocationFlag revocationFlag, X509RevocationMode revocationMode, TimeSpan retrievalTimeout, X509VerificationFlags verificationFlags)
        {
            //chain information of the selected certificate.
            var chain = new X509Chain();

            chain.ChainPolicy.RevocationFlag      = revocationFlag;
            chain.ChainPolicy.RevocationMode      = revocationMode;
            chain.ChainPolicy.UrlRetrievalTimeout = retrievalTimeout;
            chain.ChainPolicy.VerificationFlags   = verificationFlags;

            var isValid = chain.Build(certificate);

            return(new CertificateVerificationResult
            {
                IsCertificateValid = isValid,
                ChainStatus = chain.ChainStatus
            });
        }
		public WindowsCertificateServiceProvider(X509VerificationFlags verificationFlags = X509VerificationFlags.NoFlag,
												 X509RevocationMode revocationMode = X509RevocationMode.Online)
		{
			_VerificationFlags = verificationFlags;
			_RevocationMode = revocationMode;
		}
Beispiel #30
0
 public WindowsCertificateServiceProvider(X509VerificationFlags verificationFlags = X509VerificationFlags.NoFlag,
                                          X509RevocationMode revocationMode       = X509RevocationMode.Online)
 {
     _VerificationFlags = verificationFlags;
     _RevocationMode    = revocationMode;
 }
Beispiel #31
0
		// methods

		public void Reset ()
		{
			apps = new OidCollection ();
			cert = new OidCollection ();
			store2 = null;
			rflag = X509RevocationFlag.ExcludeRoot;
			mode = X509RevocationMode.Online;
			timeout = TimeSpan.Zero;
			vflags = X509VerificationFlags.NoFlag;
			vtime = DateTime.Now;
		}
Beispiel #32
0
        private static void CheckCertificateChain(X509Certificate2 certificate, X509Chain certificateChain, OidCollection oidCheckList, X509RevocationFlag revocationFlags, X509VerificationFlags verificationFlags, int exitCode, ref bool success, ref int signedExitCode)
        {
            TimeSpan UrlRetrievalTimeout = TimeSpan.FromSeconds(60);
            Oid      CodeSigningOid      = new Oid("1.3.6.1.5.5.7.3.3");

            certificateChain.ChainPolicy.RevocationFlag      = revocationFlags;
            certificateChain.ChainPolicy.UrlRetrievalTimeout = UrlRetrievalTimeout;
            certificateChain.ChainPolicy.RevocationMode      = X509RevocationMode.Online;
            certificateChain.ChainPolicy.VerificationFlags   = verificationFlags;

            foreach (Oid Item in oidCheckList)
            {
                certificateChain.ChainPolicy.CertificatePolicy.Add(Item);
            }

            bool IsEndCertificateValid = certificateChain.Build(certificate);

            if (!IsEndCertificateValid)
            {
                signedExitCode = exitCode;
                success        = false;
            }
        }
        public static BooleanReason VerifyCertificate(X509Certificate2 certificate, X509RevocationFlag revocationFlag, X509RevocationMode mode, TimeSpan timeout, X509VerificationFlags verificationFlags)
        {
            try
            {
                var chain = new X509Chain
                    {
                        ChainPolicy =
                            {
                                RevocationFlag = revocationFlag,
                                RevocationMode = mode,
                                VerificationFlags = verificationFlags,
                                UrlRetrievalTimeout = timeout
                            }
                    };

                if (!chain.Build(certificate))
                {
                    if (!IsChainOk(chain))
                        return new BooleanReason(false, "Could not verify certificate");
                }

                return new BooleanReason(true, "certificate verified");
            }
            catch (Exception e)
            {
                return new BooleanReason(false, "An issue occurred while verifying certificate: {0}", e.Message);
            }
        }