internal X509ClientCertificateAuthentication()
 {
     this.certificateValidationMode = X509CertificateValidationMode.ChainTrust;
     this.revocationMode = X509RevocationMode.Online;
     this.trustedStoreLocation = StoreLocation.LocalMachine;
     this.includeWindowsGroups = true;
 }
Ejemplo n.º 2
0
 internal static unsafe int BuildChain(IntPtr hChainEngine, System.Security.Cryptography.SafeCertContextHandle pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, ref SafeCertChainHandle ppChainContext)
 {
     if (pCertContext == null || pCertContext.IsInvalid)
         throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_InvalidContextHandle"), "pCertContext");
     SafeCertStoreHandle hAdditionalStore = SafeCertStoreHandle.InvalidHandle;
     if (extraStore != null && extraStore.Count > 0)
         hAdditionalStore = X509Utils.ExportToMemoryStore(extraStore);
     CAPI.CERT_CHAIN_PARA pChainPara = new CAPI.CERT_CHAIN_PARA();
     pChainPara.cbSize = (uint)Marshal.SizeOf((object)pChainPara);
     SafeLocalAllocHandle localAllocHandle1 = SafeLocalAllocHandle.InvalidHandle;
     if (applicationPolicy != null && applicationPolicy.Count > 0)
     {
         pChainPara.RequestedUsage.dwType = 0U;
         pChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint)applicationPolicy.Count;
         localAllocHandle1 = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy);
         pChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = localAllocHandle1.DangerousGetHandle();
     }
     SafeLocalAllocHandle localAllocHandle2 = SafeLocalAllocHandle.InvalidHandle;
     if (certificatePolicy != null && certificatePolicy.Count > 0)
     {
         pChainPara.RequestedIssuancePolicy.dwType = 0U;
         pChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint)certificatePolicy.Count;
         localAllocHandle2 = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy);
         pChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = localAllocHandle2.DangerousGetHandle();
     }
     pChainPara.dwUrlRetrievalTimeout = (uint)timeout.Milliseconds;
     System.Runtime.InteropServices.ComTypes.FILETIME pTime = new System.Runtime.InteropServices.ComTypes.FILETIME();
     *(long*)&pTime = verificationTime.ToFileTime();
     uint dwFlags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag);
     if (!CAPI.CAPISafe.CertGetCertificateChain(hChainEngine, pCertContext, ref pTime, hAdditionalStore, ref pChainPara, dwFlags, IntPtr.Zero, out ppChainContext))
         return Marshal.GetHRForLastWin32Error();
     localAllocHandle1.Dispose();
     localAllocHandle2.Dispose();
     return 0;
 }
 public static ManifestSignatureInformationCollection VerifySignature(ActivationContext application, ManifestKinds manifests, X509RevocationFlag revocationFlag, X509RevocationMode revocationMode)
 {
     if (application == null)
     {
         throw new ArgumentNullException("application");
     }
     if ((revocationFlag < X509RevocationFlag.EndCertificateOnly) || (X509RevocationFlag.ExcludeRoot < revocationFlag))
     {
         throw new ArgumentOutOfRangeException("revocationFlag");
     }
     if ((revocationMode < X509RevocationMode.NoCheck) || (X509RevocationMode.Offline < revocationMode))
     {
         throw new ArgumentOutOfRangeException("revocationMode");
     }
     List<ManifestSignatureInformation> signatureInformation = new List<ManifestSignatureInformation>();
     if ((manifests & ManifestKinds.Deployment) == ManifestKinds.Deployment)
     {
         ManifestSignedXml xml = new ManifestSignedXml(GetManifestXml(application, ManifestKinds.Deployment), ManifestKinds.Deployment);
         signatureInformation.Add(xml.VerifySignature(revocationFlag, revocationMode));
     }
     if ((manifests & ManifestKinds.Application) == ManifestKinds.Application)
     {
         ManifestSignedXml xml2 = new ManifestSignedXml(GetManifestXml(application, ManifestKinds.Application), ManifestKinds.Application);
         signatureInformation.Add(xml2.VerifySignature(revocationFlag, revocationMode));
     }
     return new ManifestSignatureInformationCollection(signatureInformation);
 }
Ejemplo n.º 4
0
        public static void AddCrlForCertificate(
            X509Certificate2 cert,
            SafeX509StoreHandle store,
            X509RevocationMode revocationMode,
            DateTime verificationTime,
            ref TimeSpan remainingDownloadTime)
        {
            // In Offline mode, accept any cached CRL we have.
            // "CRL is Expired" is a better match for Offline than "Could not find CRL"
            if (revocationMode != X509RevocationMode.Online)
            {
                verificationTime = DateTime.MinValue;
            }

            if (AddCachedCrl(cert, store, verificationTime))
            {
                return;
            }

            // Don't do any work if we're over limit or prohibited from fetching new CRLs
            if (remainingDownloadTime <= TimeSpan.Zero ||
                revocationMode != X509RevocationMode.Online)
            {
                return;
            }

            DownloadAndAddCrl(cert, store, ref remainingDownloadTime);
        }
Ejemplo n.º 5
0
 private static void CheckRevocationMode(X509RevocationMode revocationMode)
 {
     if (revocationMode != X509RevocationMode.NoCheck)
     {
         // TODO (#2203): Add support for revocation once networking is ready.
         throw new NotImplementedException(SR.WorkInProgress);
     }
 }
 internal X509ServiceCertificateAuthentication(X509ServiceCertificateAuthentication other)
 {
     this.certificateValidationMode = other.certificateValidationMode;
     this.customCertificateValidator = other.customCertificateValidator;
     this.revocationMode = other.revocationMode;
     this.trustedStoreLocation = other.trustedStoreLocation;
     this.isReadOnly = other.isReadOnly;
 }
 internal X509ServiceCertificateAuthentication(X509ServiceCertificateAuthentication other)
 {
     _certificateValidationMode = other._certificateValidationMode;
     _customCertificateValidator = other._customCertificateValidator;
     _revocationMode = other._revocationMode;
     _trustedStoreLocation = other._trustedStoreLocation;
     _isReadOnly = other._isReadOnly;
 }
Ejemplo n.º 8
0
 public SslConnectionOptions(QuicConnection connection, bool isClient, string?targetHost, bool certificateRequired, X509RevocationMode revocationMode, RemoteCertificateValidationCallback?validationCallback)
 {
     _connection          = connection;
     _isClient            = isClient;
     _targetHost          = targetHost;
     _certificateRequired = certificateRequired;
     _revocationMode      = revocationMode;
     _validationCallback  = validationCallback;
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Does not throw on error. Returns null ChainPal instead.
        /// </summary>
        public static ChainPal BuildChain(
            bool useMachineContext,
            ICertificatePal cert,
            X509Certificate2Collection extraStore,
            OidCollection applicationPolicy,
            OidCollection certificatePolicy,
            X509RevocationMode revocationMode,
            X509RevocationFlag revocationFlag,
            DateTime verificationTime,
            TimeSpan timeout)
        {
            CertificatePal certificatePal = (CertificatePal)cert;

            unsafe
            {
                using (SafeCertStoreHandle extraStoreHandle = ConvertExtraStoreToSafeHandle(extraStore))
                {
                    CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA();
                    chainPara.cbSize = Marshal.SizeOf <CERT_CHAIN_PARA>();

                    int applicationPolicyCount;
                    using (SafeHandle applicationPolicyOids = applicationPolicy.ToLpstrArray(out applicationPolicyCount))
                    {
                        if (!applicationPolicyOids.IsInvalid)
                        {
                            chainPara.RequestedUsage.dwType = CertUsageMatchType.USAGE_MATCH_TYPE_AND;
                            chainPara.RequestedUsage.Usage.cUsageIdentifier     = applicationPolicyCount;
                            chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyOids.DangerousGetHandle();
                        }

                        int certificatePolicyCount;
                        using (SafeHandle certificatePolicyOids = certificatePolicy.ToLpstrArray(out certificatePolicyCount))
                        {
                            if (!certificatePolicyOids.IsInvalid)
                            {
                                chainPara.RequestedIssuancePolicy.dwType = CertUsageMatchType.USAGE_MATCH_TYPE_AND;
                                chainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier     = certificatePolicyCount;
                                chainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyOids.DangerousGetHandle();
                            }

                            chainPara.dwUrlRetrievalTimeout = (int)Math.Floor(timeout.TotalMilliseconds);

                            FILETIME       ft          = FILETIME.FromDateTime(verificationTime);
                            CertChainFlags flags       = MapRevocationFlags(revocationMode, revocationFlag);
                            ChainEngine    chainEngine = useMachineContext ? ChainEngine.HCCE_LOCAL_MACHINE : ChainEngine.HCCE_CURRENT_USER;

                            SafeX509ChainHandle chain;
                            if (!Interop.crypt32.CertGetCertificateChain(chainEngine, certificatePal.CertContext, &ft, extraStoreHandle, ref chainPara, flags, IntPtr.Zero, out chain))
                            {
                                return(null);
                            }
                            return(new ChainPal(chain));
                        }
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public static IChainPal BuildChain(
            bool useMachineContext,
            ICertificatePal cert,
            X509Certificate2Collection extraStore,
            OidCollection applicationPolicy,
            OidCollection certificatePolicy,
            X509RevocationMode revocationMode,
            X509RevocationFlag revocationFlag,
            DateTime verificationTime,
            TimeSpan timeout)
        {
            // An input value of 0 on the timeout is "take all the time you need".
            if (timeout == TimeSpan.Zero)
            {
                timeout = TimeSpan.MaxValue;
            }

            // Let Unspecified mean Local, so only convert if the source was UTC.
            //
            // Converge on Local instead of UTC because OpenSSL is going to assume we gave it
            // local time.
            if (verificationTime.Kind == DateTimeKind.Utc)
            {
                verificationTime = verificationTime.ToLocalTime();
            }

            TimeSpan remainingDownloadTime = timeout;
            var leaf = new X509Certificate2(cert.Handle);
            var downloaded = new HashSet<X509Certificate2>();
            var systemTrusted = new HashSet<X509Certificate2>();

            HashSet<X509Certificate2> candidates = OpenSslX509ChainProcessor.FindCandidates(
                leaf,
                extraStore,
                downloaded,
                systemTrusted,
                ref remainingDownloadTime);

            IChainPal chain = OpenSslX509ChainProcessor.BuildChain(
                leaf,
                candidates,
                downloaded,
                systemTrusted,
                applicationPolicy,
                certificatePolicy,
                revocationMode,
                revocationFlag,
                verificationTime,
                ref remainingDownloadTime);

            if (chain.ChainStatus.Length == 0 && downloaded.Count > 0)
            {
                SaveIntermediateCertificates(chain.ChainElements, downloaded);
            }

            return chain;
        }
 internal IssuedTokenServiceCredential()
 {
     this.audienceUriMode           = System.IdentityModel.Selectors.AudienceUriMode.Always;
     this.certificateValidationMode = X509CertificateValidationMode.ChainTrust;
     this.revocationMode            = X509RevocationMode.Online;
     this.trustedStoreLocation      = StoreLocation.LocalMachine;
     this.allowedAudienceUris       = new List <string>();
     this.knownCertificates         = new List <X509Certificate2>();
 }
 internal X509ClientCertificateAuthentication(X509ClientCertificateAuthentication other)
 {
     this.certificateValidationMode = other.certificateValidationMode;
     this.customCertificateValidator = other.customCertificateValidator;
     this.includeWindowsGroups = other.includeWindowsGroups;
     this.mapClientCertificateToWindowsAccount = other.mapClientCertificateToWindowsAccount;
     this.trustedStoreLocation = other.trustedStoreLocation;
     this.revocationMode = other.revocationMode;
     this.isReadOnly = other.isReadOnly;
 }
 public RemoteServiceProviderArgs(
     string baseUrl,
     string configurationClassName,
     int maxReceivedMessageSize,
     X509CertificateValidationMode certificateValidationMode,
     X509RevocationMode revocationMode)
     : this(baseUrl, null, configurationClassName, maxReceivedMessageSize, certificateValidationMode,
            revocationMode, null)
 {
 }
Ejemplo n.º 14
0
 internal X509ClientCertificateAuthentication(X509ClientCertificateAuthentication other)
 {
     _certificateValidationMode            = other._certificateValidationMode;
     _customCertificateValidator           = other._customCertificateValidator;
     _includeWindowsGroups                 = other._includeWindowsGroups;
     _mapClientCertificateToWindowsAccount = other._mapClientCertificateToWindowsAccount;
     _trustedStoreLocation                 = other._trustedStoreLocation;
     _revocationMode = other._revocationMode;
     _isReadOnly     = other._isReadOnly;
 }
Ejemplo n.º 15
0
 internal X509ClientCertificateAuthentication(X509ClientCertificateAuthentication other)
 {
     this.certificateValidationMode            = other.certificateValidationMode;
     this.customCertificateValidator           = other.customCertificateValidator;
     this.includeWindowsGroups                 = other.includeWindowsGroups;
     this.mapClientCertificateToWindowsAccount = other.mapClientCertificateToWindowsAccount;
     this.trustedStoreLocation                 = other.trustedStoreLocation;
     this.revocationMode = other.revocationMode;
     this.isReadOnly     = other.isReadOnly;
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Does not throw on error. Returns null ChainPal instead.
        /// </summary>
        public static ChainPal BuildChain(
            bool useMachineContext,
            ICertificatePal cert,
            X509Certificate2Collection extraStore,
            OidCollection applicationPolicy,
            OidCollection certificatePolicy,
            X509RevocationMode revocationMode,
            X509RevocationFlag revocationFlag,
            DateTime verificationTime,
            TimeSpan timeout)
        {
            CertificatePal certificatePal = (CertificatePal)cert;

            unsafe
            {
                using (SafeCertStoreHandle extraStoreHandle = ConvertExtraStoreToSafeHandle(extraStore))
                {
                    CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA();
                    chainPara.cbSize = Marshal.SizeOf<CERT_CHAIN_PARA>();

                    int applicationPolicyCount;
                    using (SafeHandle applicationPolicyOids = applicationPolicy.ToLpstrArray(out applicationPolicyCount))
                    {
                        if (!applicationPolicyOids.IsInvalid)
                        {
                            chainPara.RequestedUsage.dwType = CertUsageMatchType.USAGE_MATCH_TYPE_AND;
                            chainPara.RequestedUsage.Usage.cUsageIdentifier = applicationPolicyCount;
                            chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyOids.DangerousGetHandle();
                        }

                        int certificatePolicyCount;
                        using (SafeHandle certificatePolicyOids = certificatePolicy.ToLpstrArray(out certificatePolicyCount))
                        {
                            if (!certificatePolicyOids.IsInvalid)
                            {
                                chainPara.RequestedIssuancePolicy.dwType = CertUsageMatchType.USAGE_MATCH_TYPE_AND;
                                chainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = certificatePolicyCount;
                                chainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyOids.DangerousGetHandle();
                            }

                            chainPara.dwUrlRetrievalTimeout = (int)Math.Floor(timeout.TotalMilliseconds);

                            FILETIME ft = FILETIME.FromDateTime(verificationTime);
                            CertChainFlags flags = MapRevocationFlags(revocationMode, revocationFlag);
                            ChainEngine chainEngine = useMachineContext ? ChainEngine.HCCE_LOCAL_MACHINE : ChainEngine.HCCE_CURRENT_USER;

                            SafeX509ChainHandle chain;
                            if (!Interop.crypt32.CertGetCertificateChain(chainEngine, certificatePal.CertContext, &ft, extraStoreHandle, ref chainPara, flags, IntPtr.Zero, out chain))
                                return null;
                            return new ChainPal(chain);
                        }
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public static bool Validate(StoreName name, StoreLocation location, X509RevocationMode mode,
                                    X509RevocationFlag flag, X509Certificate2 clientCertificate, string thumbprint)
        {
            X509Certificate2 chainedCertificate = GetCertificate(name, location, thumbprint);

            if (clientCertificate == null || chainedCertificate == null)
            {
                return(false);
            }

            X509Store store = new X509Store(name, location);

            try
            {
                X509Chain       chain  = new X509Chain();
                X509ChainPolicy policy = new X509ChainPolicy {
                    RevocationMode = mode, RevocationFlag = flag
                };
                chain.ChainPolicy = policy;

                if (!chain.Build(clientCertificate))
                {
                    return(false);
                }

                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection collection = store.Certificates;

                foreach (var item in chain.ChainElements)
                {
                    X509Certificate2Collection certs = collection.Find(X509FindType.FindByThumbprint,
                                                                       item.Certificate.Thumbprint, true);

                    if (certs == null || certs.Count == 0)
                    {
                        return(false);
                    }

                    foreach (X509Certificate2 cert in certs)
                    {
                        if (cert.Thumbprint == chainedCertificate.Thumbprint && cert.NotAfter < DateTime.Now &&
                            cert.NotBefore > DateTime.Now)
                        {
                            return(true);
                        }
                    }
                }

                return(false);
            }
            finally
            {
                store.Close();
            }
        }
Ejemplo n.º 18
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;
        }
 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();
 }
Ejemplo n.º 20
0
        // methods

        public void Reset()
        {
            apps    = new Collection <DerObjectIdentifier> ();
            cert    = new Collection <DerObjectIdentifier> ();
            store   = new X509Certificate2Collection();
            rflag   = X509RevocationFlag.ExcludeRoot;
            mode    = X509RevocationMode.Online;
            timeout = TimeSpan.Zero;
            vflags  = X509VerificationFlags.NoFlag;
            vtime   = DateTime.Now;
        }
Ejemplo n.º 21
0
 public void Reset()
 {
     m_applicationPolicy = new OidCollection();
     m_certificatePolicy = new OidCollection();
     m_revocationMode    = X509RevocationMode.Online;
     m_revocationFlag    = X509RevocationFlag.ExcludeRoot;
     m_verificationFlags = X509VerificationFlags.NoFlag;
     m_verificationTime  = DateTime.Now;
     m_timeout           = new TimeSpan(0, 0, 0); // default timeout
     m_extraStore        = new X509Certificate2Collection();
 }
 internal X509ServiceCertificateAuthentication(X509ServiceCertificateAuthentication other)
 {
     this.certificateValidationMode = X509CertificateValidationMode.ChainTrust;
     this.revocationMode = X509RevocationMode.Online;
     this.trustedStoreLocation = StoreLocation.CurrentUser;
     this.certificateValidationMode = other.certificateValidationMode;
     this.customCertificateValidator = other.customCertificateValidator;
     this.revocationMode = other.revocationMode;
     this.trustedStoreLocation = other.trustedStoreLocation;
     this.isReadOnly = other.isReadOnly;
 }
Ejemplo n.º 23
0
        public static IChainPal BuildChain(
            bool useMachineContext,
            ICertificatePal cert,
            X509Certificate2Collection extraStore,
            OidCollection applicationPolicy,
            OidCollection certificatePolicy,
            X509RevocationMode revocationMode,
            X509RevocationFlag revocationFlag,
            DateTime verificationTime,
            TimeSpan timeout)
        {
            // An input value of 0 on the timeout is "take all the time you need".
            if (timeout == TimeSpan.Zero)
            {
                timeout = TimeSpan.MaxValue;
            }

            // Let Unspecified mean Local, so only convert if the source was UTC.
            //
            // Converge on Local instead of UTC because OpenSSL is going to assume we gave it
            // local time.
            if (verificationTime.Kind == DateTimeKind.Utc)
            {
                verificationTime = verificationTime.ToLocalTime();
            }

            TimeSpan                remainingDownloadTime = timeout;
            X509Certificate2        leaf       = new X509Certificate2(cert.Handle);
            List <X509Certificate2> downloaded = new List <X509Certificate2>();

            List <X509Certificate2> candidates = OpenSslX509ChainProcessor.FindCandidates(
                leaf,
                extraStore,
                downloaded,
                ref remainingDownloadTime);

            IChainPal chain = OpenSslX509ChainProcessor.BuildChain(
                leaf,
                candidates,
                downloaded,
                applicationPolicy,
                certificatePolicy,
                revocationMode,
                revocationFlag,
                verificationTime,
                ref remainingDownloadTime);

            if (chain.ChainStatus.Length == 0 && downloaded.Count > 0)
            {
                SaveIntermediateCertificates(chain.ChainElements, downloaded);
            }

            return(chain);
        }
Ejemplo n.º 24
0
 public void Reset()
 {
     _applicationPolicy  = null;
     _certificatePolicy  = null;
     _extraStore         = null;
     _revocationMode     = X509RevocationMode.Online;
     _revocationFlag     = X509RevocationFlag.ExcludeRoot;
     _verificationFlags  = X509VerificationFlags.NoFlag;
     VerificationTime    = DateTime.Now;
     UrlRetrievalTimeout = TimeSpan.Zero; // default timeout
 }
Ejemplo n.º 25
0
 /// <summary>Resets the <see cref="T:System.Security.Cryptography.X509Certificates.X509ChainPolicy" /> members to their default values.</summary>
 public void Reset()
 {
     this.apps    = new OidCollection();
     this.cert    = new OidCollection();
     this.store   = new X509Certificate2Collection();
     this.rflag   = X509RevocationFlag.ExcludeRoot;
     this.mode    = X509RevocationMode.Online;
     this.timeout = TimeSpan.Zero;
     this.vflags  = X509VerificationFlags.NoFlag;
     this.vtime   = DateTime.Now;
 }
Ejemplo n.º 26
0
 internal X509PeerCertificateAuthentication(X509PeerCertificateAuthentication other)
 {
     this.certificateValidationMode  = X509CertificateValidationMode.PeerOrChainTrust;
     this.revocationMode             = X509RevocationMode.Online;
     this.trustedStoreLocation       = StoreLocation.CurrentUser;
     this.certificateValidationMode  = other.certificateValidationMode;
     this.customCertificateValidator = other.customCertificateValidator;
     this.revocationMode             = other.revocationMode;
     this.trustedStoreLocation       = other.trustedStoreLocation;
     this.isReadOnly = other.isReadOnly;
 }
Ejemplo n.º 27
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));
        }
Ejemplo n.º 28
0
        public X509Chain GetChain(X509RevocationMode RevocationMode, bool AllowUnknownCA)
        {
            X509Chain chain = new X509Chain();

            chain.ChainPolicy.RevocationMode = RevocationMode;
            if (AllowUnknownCA)
            {
                chain.ChainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;
            }
            chain.Build(_Certificate);
            return(chain);
        }
Ejemplo n.º 29
0
 internal static partial IChainPal?BuildChain(
     bool useMachineContext,
     ICertificatePal cert,
     X509Certificate2Collection?extraStore,
     OidCollection?applicationPolicy,
     OidCollection?certificatePolicy,
     X509RevocationMode revocationMode,
     X509RevocationFlag revocationFlag,
     X509Certificate2Collection?customTrustStore,
     X509ChainTrustMode trustMode,
     DateTime verificationTime,
     TimeSpan timeout,
     bool disableAia);
Ejemplo n.º 30
0
 public static IChainPal BuildChain(
     bool useMachineContext,
     ICertificatePal cert,
     X509Certificate2Collection extraStore,
     OidCollection applicationPolicy,
     OidCollection certificatePolicy,
     X509RevocationMode revocationMode,
     X509RevocationFlag revocationFlag,
     DateTime verificationTime,
     TimeSpan timeout)
 {
     return new OpenSslX509ChainProcessor();
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Determines if the given certificate has a valid certificate chain.
        /// </summary>
        public static bool HasValidChain(X509Certificate2 certificate, X509RevocationMode revocationMode = X509RevocationMode.NoCheck)
        {
            var chain = new X509Chain
            {
                ChainPolicy =
                {
                    RevocationFlag = X509RevocationFlag.EntireChain,
                    RevocationMode = revocationMode
                }
            };

            return(chain.Build(certificate));
        }
Ejemplo n.º 32
0
 internal IssuedTokenServiceCredential(IssuedTokenServiceCredential other)
 {
     _audienceUriMode            = other._audienceUriMode;
     _allowedAudienceUris        = new List <string>(other._allowedAudienceUris);
     _samlSerializer             = other._samlSerializer;
     _knownCertificates          = new List <X509Certificate2>(other._knownCertificates);
     _certificateValidationMode  = other._certificateValidationMode;
     _customCertificateValidator = other._customCertificateValidator;
     _trustedStoreLocation       = other._trustedStoreLocation;
     _revocationMode             = other._revocationMode;
     _allowUntrustedRsaIssuers   = other._allowUntrustedRsaIssuers;
     _isReadOnly = other._isReadOnly;
 }
Ejemplo n.º 33
0
 internal IssuedTokenServiceCredential(IssuedTokenServiceCredential other)
 {
     this.audienceUriMode            = other.audienceUriMode;
     this.allowedAudienceUris        = new List <string>(other.allowedAudienceUris);
     this.samlSerializer             = other.samlSerializer;
     this.knownCertificates          = new List <X509Certificate2>(other.knownCertificates);
     this.certificateValidationMode  = other.certificateValidationMode;
     this.customCertificateValidator = other.customCertificateValidator;
     this.trustedStoreLocation       = other.trustedStoreLocation;
     this.revocationMode             = other.revocationMode;
     this.allowUntrustedRsaIssuers   = other.allowUntrustedRsaIssuers;
     this.isReadOnly = other.isReadOnly;
 }
Ejemplo n.º 34
0
 static ChainValidationHelper()
 {
     revocation_mode = X509RevocationMode.NoCheck;
     try {
         string str = Environment.GetEnvironmentVariable("MONO_X509_REVOCATION_MODE");
         if (String.IsNullOrEmpty(str))
         {
             return;
         }
         revocation_mode = (X509RevocationMode)Enum.Parse(typeof(X509RevocationMode), str, true);
     } catch {
     }
 }
Ejemplo n.º 35
0
 public static IChainPal BuildChain(
     bool useMachineContext,
     ICertificatePal cert,
     X509Certificate2Collection extraStore,
     OidCollection applicationPolicy,
     OidCollection certificatePolicy,
     X509RevocationMode revocationMode,
     X509RevocationFlag revocationFlag,
     DateTime verificationTime,
     TimeSpan timeout)
 {
     return(new OpenSslX509ChainProcessor());
 }
 internal IssuedTokenServiceCredential(IssuedTokenServiceCredential other)
 {
     this.audienceUriMode = other.audienceUriMode;
     this.allowedAudienceUris = new List<string>(other.allowedAudienceUris);
     this.samlSerializer = other.samlSerializer;
     this.knownCertificates = new List<X509Certificate2>(other.knownCertificates);
     this.certificateValidationMode = other.certificateValidationMode;
     this.customCertificateValidator = other.customCertificateValidator;
     this.trustedStoreLocation = other.trustedStoreLocation;
     this.revocationMode = other.revocationMode;
     this.allowUntrustedRsaIssuers = other.allowUntrustedRsaIssuers;
     this.isReadOnly = other.isReadOnly;
 }
Ejemplo n.º 37
0
        public static IChainPal BuildChain(
            bool useMachineContext,
            ICertificatePal cert,
            X509Certificate2Collection?extraStore,
            OidCollection applicationPolicy,
            OidCollection certificatePolicy,
            X509RevocationMode revocationMode,
            X509RevocationFlag revocationFlag,
            X509Certificate2Collection customTrustStore,
            X509ChainTrustMode trustMode,
            DateTime verificationTime,
            TimeSpan timeout)
        {
            // If the time was given in Universal, it will stay Universal.
            // If the time was given in Local, it will be converted.
            // If the time was given in Unspecified, it will be assumed local, and converted.
            //
            // This matches the "assume Local unless explicitly Universal" implicit contract.
            verificationTime = verificationTime.ToUniversalTime();

            // The Windows (and other-Unix-PAL) behavior is to allow network until network operations
            // have exceeded the specified timeout.  For Apple it's either on (and AIA fetching works),
            // or off (and AIA fetching doesn't work).  And once an SSL policy is used, or revocation is
            // being checked, the value is on anyways.
            const bool       allowNetwork = true;
            SecTrustChainPal chainPal     = new SecTrustChainPal();

            try
            {
                chainPal.OpenTrustHandle(
                    cert,
                    extraStore,
                    revocationMode,
                    customTrustStore,
                    trustMode);

                chainPal.Execute(
                    verificationTime,
                    allowNetwork,
                    applicationPolicy,
                    certificatePolicy,
                    revocationFlag);
            }
            catch
            {
                chainPal.Dispose();
                throw;
            }

            return(chainPal);
        }
Ejemplo n.º 38
0
 public void Reset()
 {
     _applicationPolicy          = null;
     _certificatePolicy          = null;
     _extraStore                 = null;
     _customTrustStore           = null;
     DisableCertificateDownloads = false;
     _revocationMode             = X509RevocationMode.Online;
     _revocationFlag             = X509RevocationFlag.ExcludeRoot;
     _verificationFlags          = X509VerificationFlags.NoFlag;
     _trustMode          = X509ChainTrustMode.System;
     VerificationTime    = DateTime.Now;
     UrlRetrievalTimeout = TimeSpan.Zero; // default timeout
 }
Ejemplo n.º 39
0
        internal static uint MapRevocationFlags(X509RevocationMode revocationMode, X509RevocationFlag revocationFlag)
        {
            uint num = 0U;

            if (revocationMode == X509RevocationMode.NoCheck)
            {
                return(num);
            }
            if (revocationMode == X509RevocationMode.Offline)
            {
                num |= (uint)int.MinValue;
            }
            return(revocationFlag != X509RevocationFlag.EndCertificateOnly ? (revocationFlag != X509RevocationFlag.EntireChain ? num | 1073741824U : num | 536870912U) : num | 268435456U);
        }
Ejemplo n.º 40
0
    private X509ChainPolicy BuildChainPolicy(X509Certificate2 certificate)
    {
        // Now build the chain validation options.
        X509RevocationFlag revocationFlag = Options.RevocationFlag;
        X509RevocationMode revocationMode = Options.RevocationMode;

        if (certificate.IsSelfSigned())
        {
            // Turn off chain validation, because we have a self signed certificate.
            revocationFlag = X509RevocationFlag.EntireChain;
            revocationMode = X509RevocationMode.NoCheck;
        }

        var chainPolicy = new X509ChainPolicy
        {
            RevocationFlag = revocationFlag,
            RevocationMode = revocationMode,
        };

        if (Options.ValidateCertificateUse)
        {
            chainPolicy.ApplicationPolicy.Add(ClientCertificateOid);
        }

        if (certificate.IsSelfSigned())
        {
            chainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;
            chainPolicy.VerificationFlags |= X509VerificationFlags.IgnoreEndRevocationUnknown;
            chainPolicy.ExtraStore.Add(certificate);
        }
        else
        {
            if (Options.CustomTrustStore != null)
            {
                chainPolicy.CustomTrustStore.AddRange(Options.CustomTrustStore);
            }

            chainPolicy.TrustMode = Options.ChainTrustValidationMode;
        }

        chainPolicy.ExtraStore.AddRange(Options.AdditionalChainCertificates);

        if (!Options.ValidateValidityPeriod)
        {
            chainPolicy.VerificationFlags |= X509VerificationFlags.IgnoreNotTimeValid;
        }

        return(chainPolicy);
    }
 public ServiceChannelConfigurationArgs(
     Type channelFactoryClass,
     Uri serviceUri,
     bool authenticationRequired,
     int maxReceivedMessageSize,
     X509CertificateValidationMode certificateValidationMode,
     X509RevocationMode revocationMode)
 {
     this.ChannelFactoryClass       = channelFactoryClass;
     this.ServiceUri                = serviceUri;
     this.AuthenticationRequired    = authenticationRequired;
     this.MaxReceivedMessageSize    = maxReceivedMessageSize;
     this.CertificateValidationMode = certificateValidationMode;
     this.RevocationMode            = revocationMode;
 }
 public ServiceChannelConfigurationArgs(
     Type channelFactoryClass,
     Uri serviceUri,
     bool authenticationRequired,
     int maxReceivedMessageSize,
     X509CertificateValidationMode certificateValidationMode,
     X509RevocationMode revocationMode)
 {
     this.ChannelFactoryClass = channelFactoryClass;
     this.ServiceUri = serviceUri;
     this.AuthenticationRequired = authenticationRequired;
     this.MaxReceivedMessageSize = maxReceivedMessageSize;
     this.CertificateValidationMode = certificateValidationMode;
     this.RevocationMode = revocationMode;
 }
Ejemplo n.º 43
0
            public State(QuicListenerOptions options)
            {
                ConnectionConfiguration = SafeMsQuicConfigurationHandle.Create(options);
                if (options.ServerAuthenticationOptions != null)
                {
                    RemoteCertificateRequired           = options.ServerAuthenticationOptions.ClientCertificateRequired;
                    RevocationMode                      = options.ServerAuthenticationOptions.CertificateRevocationCheckMode;
                    RemoteCertificateValidationCallback = options.ServerAuthenticationOptions.RemoteCertificateValidationCallback;
                }

                AcceptConnectionQueue = Channel.CreateBounded <MsQuicConnection>(new BoundedChannelOptions(options.ListenBacklog)
                {
                    SingleReader = true,
                    SingleWriter = true
                });
            }
Ejemplo n.º 44
0
 public static IChainPal BuildChain(
     bool useMachineContext,
     ICertificatePal cert,
     X509Certificate2Collection?extraStore,
     OidCollection applicationPolicy,
     OidCollection certificatePolicy,
     X509RevocationMode revocationMode,
     X509RevocationFlag revocationFlag,
     X509Certificate2Collection customTrustStore,
     X509ChainTrustMode trustMode,
     DateTime verificationTime,
     TimeSpan timeout,
     bool disableAia)
 {
     throw new NotImplementedException(nameof(BuildChain));
 }
Ejemplo n.º 45
0
 internal static partial IChainPal?BuildChain(
     bool useMachineContext,
     ICertificatePal cert,
     X509Certificate2Collection?extraStore,
     OidCollection?applicationPolicy,
     OidCollection?certificatePolicy,
     X509RevocationMode revocationMode,
     X509RevocationFlag revocationFlag,
     X509Certificate2Collection?customTrustStore,
     X509ChainTrustMode trustMode,
     DateTime verificationTime,
     TimeSpan timeout,
     bool disableAia)
 {
     throw new PlatformNotSupportedException(SR.SystemSecurityCryptographyX509Certificates_PlatformNotSupported);
 }
        public ExpectedJwtSecurityTokenRequirement
        (
            uint? tokenSize = null, Int32? clock = null, uint? life = null, X509CertificateValidator cert = null, string name = JwtConstants.ReservedClaims.Sub, string role = null, X509RevocationMode? revMode = null, X509CertificateValidationMode? certMode = null, StoreLocation? storeLoc = null, ExpectedException expectedException = null,
            string handler = JwtSecurityTokenHandlerType, string requirement = Elements.JwtSecurityTokenRequirement,
            string attributeEx1 = "", string attributeEx2 = "", string attributeEx3 = "", string attributeEx4 = "",
            string elementEx1 = comment, string elementEx2 = comment, string elementEx3 = comment, string elementEx4 = comment, string elementEx5 = comment, string elementEx6 = comment,
            string elementClose = closeRequirement

        )
        {
            MaxTokenSizeInBytes = tokenSize;
            NameClaimType = name;
            RoleClaimType = role;
            CertValidator = cert;
            ClockSkewInSeconds = clock;
            DefaultTokenLifetimeInMinutes = life;
            CertRevocationMode = revMode;
            CertValidationMode = certMode;
            CertStoreLocation = storeLoc;
            ExpectedException = expectedException ?? ExpectedException.NoExceptionExpected;
            string[] sParams = 
            {
                handler,
                requirement,
                CertRevocationMode == null ? string.Empty : Attribute( Attributes.RevocationMode, CertRevocationMode.Value.ToString() ),
                attributeEx1,
                CertValidationMode == null ? string.Empty : Attribute( Attributes.ValidationMode, CertValidationMode.Value.ToString() ),
                attributeEx2,
                CertValidator == null ? string.Empty : Attribute( Attributes.Validator, CertValidator.GetType().ToString() +", System.IdentityModel.Tokens.Jwt.Tests" ),
                attributeEx3,
                CertStoreLocation == null ? string.Empty : Attribute( Attributes.TrustedStoreLocation, CertStoreLocation.ToString() ),
                attributeEx4,
                elementEx1,
                ClockSkewInSeconds == null ? string.Empty : ElementValue( Elements.MaxClockSkewInMinutes, ClockSkewInSeconds.Value.ToString() ),
                elementEx2,
                MaxTokenSizeInBytes == null ? string.Empty : ElementValue( Elements.MaxTokenSizeInBytes, MaxTokenSizeInBytes.Value.ToString() ),
                elementEx3,
                DefaultTokenLifetimeInMinutes == null ? string.Empty : ElementValue( Elements.DefaultTokenLifetimeInMinutes, DefaultTokenLifetimeInMinutes.Value.ToString() ),
                elementEx4,
                NameClaimType == null ? string.Empty : ElementValue( Elements.NameClaimType, NameClaimType ),
                elementEx5,
                RoleClaimType == null ? string.Empty : ElementValue( Elements.RoleClaimType, RoleClaimType ),
                elementEx6,
                elementClose,
            };
            Config = string.Format(ElementTemplate, sParams);
        }
 private static unsafe void BuildChain(IntPtr hChainEngine, IntPtr pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, out System.IdentityModel.SafeCertChainHandle ppChainContext)
 {
     System.IdentityModel.SafeCertStoreHandle hAdditionalStore = ExportToMemoryStore(extraStore, pCertContext);
     System.IdentityModel.CAPI.CERT_CHAIN_PARA pChainPara = new System.IdentityModel.CAPI.CERT_CHAIN_PARA {
         cbSize = (uint) Marshal.SizeOf(typeof(System.IdentityModel.CAPI.CERT_CHAIN_PARA))
     };
     SafeHGlobalHandle invalidHandle = SafeHGlobalHandle.InvalidHandle;
     SafeHGlobalHandle handle3 = SafeHGlobalHandle.InvalidHandle;
     try
     {
         if ((applicationPolicy != null) && (applicationPolicy.Count > 0))
         {
             pChainPara.RequestedUsage.dwType = 0;
             pChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint) applicationPolicy.Count;
             invalidHandle = CopyOidsToUnmanagedMemory(applicationPolicy);
             pChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = invalidHandle.DangerousGetHandle();
         }
         if ((certificatePolicy != null) && (certificatePolicy.Count > 0))
         {
             pChainPara.RequestedIssuancePolicy.dwType = 0;
             pChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint) certificatePolicy.Count;
             handle3 = CopyOidsToUnmanagedMemory(certificatePolicy);
             pChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = handle3.DangerousGetHandle();
         }
         pChainPara.dwUrlRetrievalTimeout = (uint) timeout.Milliseconds;
         System.Runtime.InteropServices.ComTypes.FILETIME pTime = new System.Runtime.InteropServices.ComTypes.FILETIME();
         *((long*) &pTime) = verificationTime.ToFileTime();
         uint dwFlags = MapRevocationFlags(revocationMode, revocationFlag);
         if (!System.IdentityModel.CAPI.CertGetCertificateChain(hChainEngine, pCertContext, ref pTime, hAdditionalStore, ref pChainPara, dwFlags, IntPtr.Zero, out ppChainContext))
         {
             int hr = Marshal.GetLastWin32Error();
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(hr));
         }
     }
     finally
     {
         if (invalidHandle != null)
         {
             invalidHandle.Dispose();
         }
         if (handle3 != null)
         {
             handle3.Dispose();
         }
         hAdditionalStore.Close();
     }
 }
        public ServiceChannelConfigurationArgs(
            Type channelFactoryClass,
            Uri serviceUri,
            bool authenticationRequired,
            long maxReceivedMessageSize,
            X509CertificateValidationMode certificateValidationMode,
            X509RevocationMode revocationMode)
        {
            this.ChannelFactoryClass = channelFactoryClass;
            this.ServiceUri = serviceUri;
            this.AuthenticationRequired = authenticationRequired;
            this.MaxReceivedMessageSize = maxReceivedMessageSize;
            this.CertificateValidationMode = certificateValidationMode;
            this.RevocationMode = revocationMode;
        	this.SendTimeoutSeconds = 0;
			this.TransferMode = TransferMode.Buffered;
        }
Ejemplo n.º 49
0
        // this method maps X509RevocationFlag to crypto API flags.
        internal static uint MapRevocationFlags (X509RevocationMode revocationMode, X509RevocationFlag revocationFlag) {
            uint dwFlags = 0;
            if (revocationMode == X509RevocationMode.NoCheck)
                return dwFlags;

            if (revocationMode == X509RevocationMode.Offline)
                dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY;

            if (revocationFlag == X509RevocationFlag.EndCertificateOnly)
                dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_END_CERT;
            else if (revocationFlag == X509RevocationFlag.EntireChain)
                dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_CHAIN;
            else
                dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;

            return dwFlags;
        }
        public X509CertificateValidatorEx(
            X509CertificateValidationMode certificateValidationMode,
            X509RevocationMode revocationMode,
            StoreLocation trustedStoreLocation)
        {
            this.certificateValidationMode = certificateValidationMode;

            switch (this.certificateValidationMode)
            {
                case X509CertificateValidationMode.None:
                    {
                        this.validator = X509CertificateValidator.None;
                        break;
                    }

                case X509CertificateValidationMode.PeerTrust:
                    {
                        this.validator = X509CertificateValidator.PeerTrust;
                        break;
                    }

                case X509CertificateValidationMode.ChainTrust:
                    {
                        bool useMachineContext = trustedStoreLocation == StoreLocation.LocalMachine;
                        this.chainPolicy = new X509ChainPolicy();
                        this.chainPolicy.RevocationMode = revocationMode;

                        this.validator = X509CertificateValidator.CreateChainTrustValidator(useMachineContext, this.chainPolicy);
                        break;
                    }

                case X509CertificateValidationMode.PeerOrChainTrust:
                    {
                        bool useMachineContext = trustedStoreLocation == StoreLocation.LocalMachine;
                        this.chainPolicy = new X509ChainPolicy();
                        this.chainPolicy.RevocationMode = revocationMode;

                        this.validator = X509CertificateValidator.CreatePeerOrChainTrustValidator(useMachineContext, this.chainPolicy);
                        break;
                    }

                case X509CertificateValidationMode.Custom:
                default:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4256)));
            }
        }
        public static IAppBuilder UseClientCertificateAuthentication(this IAppBuilder app, X509RevocationMode revocationMode = X509RevocationMode.Online, bool createExtendedClaims = false)
        {
            var policy = new X509ChainPolicy
            {
                RevocationMode = revocationMode
            };

            var validator = X509CertificateValidator.CreateChainTrustValidator(true, policy);

            var options = new ClientCertificateAuthenticationOptions
            {
                Validator = validator,
                CreateExtendedClaimSet = createExtendedClaims
            };

            return app.UseClientCertificateAuthentication(options);
        }
Ejemplo n.º 52
0
        public static IChainPal BuildChain(
            bool useMachineContext,
            ICertificatePal cert,
            X509Certificate2Collection extraStore,
            OidCollection applicationPolicy,
            OidCollection certificatePolicy,
            X509RevocationMode revocationMode,
            X509RevocationFlag revocationFlag,
            DateTime verificationTime,
            TimeSpan timeout)
        {
            CheckRevocationMode(revocationMode);

            // An input value of 0 on the timeout is "take all the time you need".
            if (timeout == TimeSpan.Zero)
            {
                timeout = TimeSpan.MaxValue;
            }

            TimeSpan remainingDownloadTime = timeout;
            X509Certificate2 leaf = new X509Certificate2(cert.Handle);
            List<X509Certificate2> downloaded = new List<X509Certificate2>();

            List<X509Certificate2> candidates = OpenSslX509ChainProcessor.FindCandidates(
                leaf,
                extraStore,
                downloaded,
                ref remainingDownloadTime);

            IChainPal chain = OpenSslX509ChainProcessor.BuildChain(
                leaf,
                candidates,
                downloaded,
                applicationPolicy,
                certificatePolicy,
                verificationTime);

            if (chain.ChainStatus.Length == 0 && downloaded.Count > 0)
            {
                SaveIntermediateCertificates(chain.ChainElements, downloaded);
            }

            return chain;
        }
        public X509CertificateValidatorEx(X509CertificateValidationMode certificateValidationMode, X509RevocationMode revocationMode, StoreLocation trustedStoreLocation)
        {
            this.certificateValidationMode = certificateValidationMode;
            switch (this.certificateValidationMode)
            {
                case X509CertificateValidationMode.None:
                    {
                        this.validator = X509CertificateValidator.None;
                        break;
                    }

                case X509CertificateValidationMode.PeerTrust:
                    {
                        this.validator = X509CertificateValidator.PeerTrust;
                        break;
                    }

                case X509CertificateValidationMode.ChainTrust:
                    {
                        bool useMachineContext = trustedStoreLocation == StoreLocation.LocalMachine;
                        this.chainPolicy = new X509ChainPolicy();
                        this.chainPolicy.RevocationMode = revocationMode;

                        this.validator = X509CertificateValidator.CreateChainTrustValidator(useMachineContext, this.chainPolicy);
                        break;
                    }

                case X509CertificateValidationMode.PeerOrChainTrust:
                    {
                        bool useMachineContext = trustedStoreLocation == StoreLocation.LocalMachine;
                        this.chainPolicy = new X509ChainPolicy();
                        this.chainPolicy.RevocationMode = revocationMode;

                        this.validator = X509CertificateValidator.CreatePeerOrChainTrustValidator(useMachineContext, this.chainPolicy);
                        break;
                    }

                default:
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10637, this.certificateValidationMode));
            }
        }
Ejemplo n.º 54
0
		static SystemCertificateValidator ()
		{
#if MONOTOUCH
			is_macosx = true;
#elif MONODROID
			is_macosx = false;
#else
			is_macosx = System.IO.File.Exists (OSX509Certificates.SecurityLibrary);
#endif

#if !MOBILE
			revocation_mode = X509RevocationMode.NoCheck;
			try {
				string str = Environment.GetEnvironmentVariable ("MONO_X509_REVOCATION_MODE");
				if (String.IsNullOrEmpty (str))
					return;
				revocation_mode = (X509RevocationMode)Enum.Parse (typeof(X509RevocationMode), str, true);
			} catch {
			}
#endif
		}
 private X509Chain BuildSignatureChain(X509Native.AXL_AUTHENTICODE_SIGNER_INFO signer, XmlElement licenseNode, X509RevocationFlag revocationFlag, X509RevocationMode revocationMode)
 {
     X509Chain chain = null;
     if (signer.dwError == -2146762487)
     {
         XmlElement element = licenseNode.SelectSingleNode("r:issuer/ds:Signature/ds:KeyInfo/ds:X509Data", this.m_namespaceManager) as XmlElement;
         if (element != null)
         {
             X509Certificate2 certificate = new X509Certificate2(Convert.FromBase64String(element.InnerText.Trim()));
             chain = new X509Chain {
                 ChainPolicy = { RevocationFlag = revocationFlag, RevocationMode = revocationMode }
             };
             chain.Build(certificate);
         }
         return chain;
     }
     if (signer.pChainContext != IntPtr.Zero)
     {
         chain = new X509Chain(signer.pChainContext);
     }
     return chain;
 }
        private X509Chain BuildSignatureChain(X509Native.AXL_AUTHENTICODE_SIGNER_INFO signer,
                                              XmlElement licenseNode,
                                              X509RevocationFlag revocationFlag,
                                              X509RevocationMode revocationMode) {
            Debug.Assert(licenseNode != null, "licenseNode != null");

            X509Chain signatureChain = null;

            if (signer.pChainContext != IntPtr.Zero) {
                signatureChain = new X509Chain(signer.pChainContext);
            }
            else if (signer.dwError == (int)SignatureVerificationResult.UntrustedRootCertificate) {
                // CertVerifyAuthenticodeLicense will not return the certificate chain for self signed certificates
                // so we'll need to extract the certificate from the signature ourselves.

                XmlElement x509Data = licenseNode.SelectSingleNode("r:issuer/ds:Signature/ds:KeyInfo/ds:X509Data",
                                                                   m_namespaceManager) as XmlElement;
                if (x509Data != null) {
                    XmlNodeList certificateNodes = x509Data.SelectNodes("ds:X509Certificate", m_namespaceManager);

                    // A manifest could have many X509Certificate nodes in its X509Data, which may include the
                    // signing certificate, links on the chain to a root, or certificates not used at all in
                    // the chain.  Since we don't know which certificate actually did the signing, we only
                    // process the chain if we have a single certificate.
                    if (certificateNodes.Count == 1 && certificateNodes[0] is XmlElement) {
                        byte[] rawCertificate = Convert.FromBase64String(certificateNodes[0].InnerText.Trim());
                        X509Certificate2 signingCertificate = new X509Certificate2(rawCertificate);

                        signatureChain = new X509Chain();
                        signatureChain.ChainPolicy.RevocationFlag = revocationFlag;
                        signatureChain.ChainPolicy.RevocationMode = revocationMode;

                        signatureChain.Build(signingCertificate);
                    }
                }
            }

            return signatureChain;
        }
Ejemplo n.º 57
0
        internal static unsafe int VerifyCertificate (Cryptography.SafeCertContextHandle pCertContext,
                                                      OidCollection applicationPolicy,
                                                      OidCollection certificatePolicy,
                                                      X509RevocationMode revocationMode,
                                                      X509RevocationFlag revocationFlag,
                                                      DateTime verificationTime,
                                                      TimeSpan timeout,
                                                      X509Certificate2Collection extraStore,
                                                      IntPtr pszPolicy,
                                                      IntPtr pdwErrorStatus) {
            if (pCertContext == null || pCertContext.IsInvalid)
                throw new ArgumentException("pCertContext");

            CAPI.CERT_CHAIN_POLICY_PARA PolicyPara = new CAPI.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_PARA)));
            CAPI.CERT_CHAIN_POLICY_STATUS PolicyStatus = new CAPI.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_STATUS)));

            // Build the chain.
            SafeX509ChainHandle pChainContext = SafeX509ChainHandle.InvalidHandle;
            int hr = X509Chain.BuildChain(new IntPtr(CAPI.HCCE_CURRENT_USER),
                                          pCertContext, 
                                          extraStore,
                                          applicationPolicy, 
                                          certificatePolicy,
                                          revocationMode,
                                          revocationFlag,
                                          verificationTime,
                                          timeout,
                                          ref pChainContext);
            if (hr != CAPI.S_OK)
                return hr;

            // Verify the chain using the specified policy.
            if (CAPI.CertVerifyCertificateChainPolicy(pszPolicy, pChainContext, ref PolicyPara, ref PolicyStatus)) {
                if (pdwErrorStatus != IntPtr.Zero)
                    *(uint*) pdwErrorStatus = PolicyStatus.dwError;

                if (PolicyStatus.dwError != 0)
                    return CAPI.S_FALSE;
            } else {
                // The API failed.
                return Marshal.GetHRForLastWin32Error();
            }

            return CAPI.S_OK;
        }
        public static IChainPal BuildChain(
            X509Certificate2 leaf,
            HashSet<X509Certificate2> candidates,
            HashSet<X509Certificate2> downloaded,
            HashSet<X509Certificate2> systemTrusted,
            OidCollection applicationPolicy,
            OidCollection certificatePolicy,
            X509RevocationMode revocationMode,
            X509RevocationFlag revocationFlag,
            DateTime verificationTime,
            ref TimeSpan remainingDownloadTime)
        {
            X509ChainElement[] elements;
            List<X509ChainStatus> overallStatus = new List<X509ChainStatus>();
            WorkingChain workingChain = new WorkingChain();
            Interop.Crypto.X509StoreVerifyCallback workingCallback = workingChain.VerifyCallback;

            // An X509_STORE is more comparable to Cryptography.X509Certificate2Collection than to
            // Cryptography.X509Store. So read this with OpenSSL eyes, not CAPI/CNG eyes.
            //
            // (If you need to think of it as an X509Store, it's a volatile memory store)
            using (SafeX509StoreHandle store = Interop.Crypto.X509StoreCreate())
            using (SafeX509StoreCtxHandle storeCtx = Interop.Crypto.X509StoreCtxCreate())
            {
                Interop.Crypto.CheckValidOpenSslHandle(store);
                Interop.Crypto.CheckValidOpenSslHandle(storeCtx);

                bool lookupCrl = revocationMode != X509RevocationMode.NoCheck;

                foreach (X509Certificate2 cert in candidates)
                {
                    OpenSslX509CertificateReader pal = (OpenSslX509CertificateReader)cert.Pal;

                    if (!Interop.Crypto.X509StoreAddCert(store, pal.SafeHandle))
                    {
                        throw Interop.Crypto.CreateOpenSslCryptographicException();
                    }

                    if (lookupCrl)
                    {
                        CrlCache.AddCrlForCertificate(
                            cert,
                            store,
                            revocationMode,
                            verificationTime,
                            ref remainingDownloadTime);

                        // If we only wanted the end-entity certificate CRL then don't look up
                        // any more of them.
                        lookupCrl = revocationFlag != X509RevocationFlag.EndCertificateOnly;
                    }
                }

                if (revocationMode != X509RevocationMode.NoCheck)
                {
                    if (!Interop.Crypto.X509StoreSetRevocationFlag(store, revocationFlag))
                    {
                        throw Interop.Crypto.CreateOpenSslCryptographicException();
                    }
                }

                SafeX509Handle leafHandle = ((OpenSslX509CertificateReader)leaf.Pal).SafeHandle;

                if (!Interop.Crypto.X509StoreCtxInit(storeCtx, store, leafHandle))
                {
                    throw Interop.Crypto.CreateOpenSslCryptographicException();
                }

                Interop.Crypto.X509StoreCtxSetVerifyCallback(storeCtx, workingCallback);
                Interop.Crypto.SetX509ChainVerifyTime(storeCtx, verificationTime);

                int verify = Interop.Crypto.X509VerifyCert(storeCtx);

                if (verify < 0)
                {
                    throw Interop.Crypto.CreateOpenSslCryptographicException();
                }

                // Because our callback tells OpenSSL that every problem is ignorable, it should tell us that the
                // chain is just fine (unless it returned a negative code for an exception)
                Debug.Assert(verify == 1, "verify == 1");

                using (SafeX509StackHandle chainStack = Interop.Crypto.X509StoreCtxGetChain(storeCtx))
                {
                    int chainSize = Interop.Crypto.GetX509StackFieldCount(chainStack);
                    elements = new X509ChainElement[chainSize];
                    int maybeRootDepth = chainSize - 1;

                    // The leaf cert is 0, up to (maybe) the root at chainSize - 1
                    for (int i = 0; i < chainSize; i++)
                    {
                        List<X509ChainStatus> status = new List<X509ChainStatus>();

                        List<Interop.Crypto.X509VerifyStatusCode> elementErrors =
                            i < workingChain.Errors.Count ? workingChain.Errors[i] : null;

                        if (elementErrors != null)
                        {
                            AddElementStatus(elementErrors, status, overallStatus);
                        }

                        IntPtr elementCertPtr = Interop.Crypto.GetX509StackField(chainStack, i);

                        if (elementCertPtr == IntPtr.Zero)
                        {
                            throw Interop.Crypto.CreateOpenSslCryptographicException();
                        }

                        // Duplicate the certificate handle
                        X509Certificate2 elementCert = new X509Certificate2(elementCertPtr);

                        // If the last cert is self signed then it's the root cert, do any extra checks.
                        if (i == maybeRootDepth && IsSelfSigned(elementCert))
                        {
                            // If the root certificate was downloaded or the system
                            // doesn't trust it, it's untrusted.
                            if (downloaded.Contains(elementCert) ||
                                !systemTrusted.Contains(elementCert))
                            {
                                AddElementStatus(
                                    Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_UNTRUSTED,
                                    status,
                                    overallStatus);
                            }
                        }

                        elements[i] = new X509ChainElement(elementCert, status.ToArray(), "");
                    }
                }
            }

            GC.KeepAlive(workingCallback);

            if ((certificatePolicy != null && certificatePolicy.Count > 0) ||
                (applicationPolicy != null && applicationPolicy.Count > 0))
            {
                List<X509Certificate2> certsToRead = new List<X509Certificate2>();

                foreach (X509ChainElement element in elements)
                {
                    certsToRead.Add(element.Certificate);
                }

                CertificatePolicyChain policyChain = new CertificatePolicyChain(certsToRead);

                bool failsPolicyChecks = false;

                if (certificatePolicy != null)
                {
                    if (!policyChain.MatchesCertificatePolicies(certificatePolicy))
                    {
                        failsPolicyChecks = true;
                    }
                }

                if (applicationPolicy != null)
                {
                    if (!policyChain.MatchesApplicationPolicies(applicationPolicy))
                    {
                        failsPolicyChecks = true;
                    }
                }

                if (failsPolicyChecks)
                {
                    X509ChainElement leafElement = elements[0];

                    X509ChainStatus chainStatus = new X509ChainStatus
                    {
                        Status = X509ChainStatusFlags.NotValidForUsage,
                        StatusInformation = SR.Chain_NoPolicyMatch,
                    };

                    var elementStatus = new List<X509ChainStatus>(leafElement.ChainElementStatus.Length + 1);
                    elementStatus.AddRange(leafElement.ChainElementStatus);

                    AddUniqueStatus(elementStatus, ref chainStatus);
                    AddUniqueStatus(overallStatus, ref chainStatus);

                    elements[0] = new X509ChainElement(
                        leafElement.Certificate,
                        elementStatus.ToArray(),
                        leafElement.Information);
                }
            }

            return new OpenSslX509ChainProcessor
            {
                ChainStatus = overallStatus.ToArray(),
                ChainElements = elements,
            };
        }
Ejemplo n.º 59
0
        internal static unsafe int BuildChain (IntPtr hChainEngine,
                                               SafeCertContextHandle pCertContext,
                                               X509Certificate2Collection extraStore,
                                               OidCollection applicationPolicy,
                                               OidCollection certificatePolicy,
                                               X509RevocationMode revocationMode,
                                               X509RevocationFlag revocationFlag,
                                               DateTime verificationTime,
                                               TimeSpan timeout,
                                               ref SafeCertChainHandle ppChainContext) {
            if (pCertContext == null || pCertContext.IsInvalid)
                throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_InvalidContextHandle"), "pCertContext");

            SafeCertStoreHandle hCertStore = SafeCertStoreHandle.InvalidHandle;
            if (extraStore != null && extraStore.Count > 0)
                hCertStore = X509Utils.ExportToMemoryStore(extraStore);

            CAPI.CERT_CHAIN_PARA ChainPara = new CAPI.CERT_CHAIN_PARA();

            // Initialize the structure size.
            ChainPara.cbSize = (uint) Marshal.SizeOf(ChainPara);

            // Application policy
            SafeLocalAllocHandle applicationPolicyHandle = SafeLocalAllocHandle.InvalidHandle;
            if (applicationPolicy != null && applicationPolicy.Count > 0) {
                ChainPara.RequestedUsage.dwType = CAPI.USAGE_MATCH_TYPE_AND;
                ChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint) applicationPolicy.Count;
                applicationPolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy);
                ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyHandle.DangerousGetHandle();
            }

            // Certificate policy
            SafeLocalAllocHandle certificatePolicyHandle = SafeLocalAllocHandle.InvalidHandle;
            if (certificatePolicy != null && certificatePolicy.Count > 0) {
                ChainPara.RequestedIssuancePolicy.dwType = CAPI.USAGE_MATCH_TYPE_AND;
                ChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint) certificatePolicy.Count;
                certificatePolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy);
                ChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyHandle.DangerousGetHandle();
            }

            ChainPara.dwUrlRetrievalTimeout = (uint) timeout.Milliseconds;

            _FILETIME ft = new _FILETIME();
            *((long*) &ft) = verificationTime.ToFileTime();

            uint flags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag);

            // Build the chain.
            if (!CAPI.CAPISafe.CertGetCertificateChain(hChainEngine,
                                                       pCertContext,
                                                       ref ft,
                                                       hCertStore,
                                                       ref ChainPara,
                                                       flags,
                                                       IntPtr.Zero,
                                                       ref ppChainContext))
                return Marshal.GetHRForLastWin32Error();

            applicationPolicyHandle.Dispose();
            certificatePolicyHandle.Dispose();

            return CAPI.S_OK;
        }
 internal static unsafe int BuildChain(IntPtr hChainEngine, System.Security.Cryptography.SafeCertContextHandle pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, ref SafeCertChainHandle ppChainContext)
 {
     CAPIBase.CERT_CHAIN_PARA cert_chain_para;
     if ((pCertContext == null) || pCertContext.IsInvalid)
     {
         throw new ArgumentException(SR.GetString("Cryptography_InvalidContextHandle"), "pCertContext");
     }
     System.Security.Cryptography.SafeCertStoreHandle invalidHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
     if ((extraStore != null) && (extraStore.Count > 0))
     {
         invalidHandle = System.Security.Cryptography.X509Certificates.X509Utils.ExportToMemoryStore(extraStore);
     }
     cert_chain_para = new CAPIBase.CERT_CHAIN_PARA {
         cbSize = (uint) Marshal.SizeOf(cert_chain_para)
     };
     SafeLocalAllocHandle handle2 = SafeLocalAllocHandle.InvalidHandle;
     if ((applicationPolicy != null) && (applicationPolicy.Count > 0))
     {
         cert_chain_para.RequestedUsage.dwType = 0;
         cert_chain_para.RequestedUsage.Usage.cUsageIdentifier = (uint) applicationPolicy.Count;
         handle2 = System.Security.Cryptography.X509Certificates.X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy);
         cert_chain_para.RequestedUsage.Usage.rgpszUsageIdentifier = handle2.DangerousGetHandle();
     }
     SafeLocalAllocHandle handle3 = SafeLocalAllocHandle.InvalidHandle;
     if ((certificatePolicy != null) && (certificatePolicy.Count > 0))
     {
         cert_chain_para.RequestedIssuancePolicy.dwType = 0;
         cert_chain_para.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint) certificatePolicy.Count;
         handle3 = System.Security.Cryptography.X509Certificates.X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy);
         cert_chain_para.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = handle3.DangerousGetHandle();
     }
     cert_chain_para.dwUrlRetrievalTimeout = (uint) timeout.Milliseconds;
     System.Runtime.InteropServices.ComTypes.FILETIME pTime = new System.Runtime.InteropServices.ComTypes.FILETIME();
     *((long*) &pTime) = verificationTime.ToFileTime();
     uint dwFlags = System.Security.Cryptography.X509Certificates.X509Utils.MapRevocationFlags(revocationMode, revocationFlag);
     if (!CAPISafe.CertGetCertificateChain(hChainEngine, pCertContext, ref pTime, invalidHandle, ref cert_chain_para, dwFlags, IntPtr.Zero, ref ppChainContext))
     {
         return Marshal.GetHRForLastWin32Error();
     }
     handle2.Dispose();
     handle3.Dispose();
     return 0;
 }