Find() public method

Finds a certificate in a store.
public Find ( ) : Task
return Task
Ejemplo n.º 1
0
        /// <summary>
        /// Returns the issuers for the certificate.
        /// </summary>
        /// <param name="certificate">The certificate.</param>
        /// <param name="issuers">The issuers.</param>
        /// <returns></returns>
        public async Task <bool> GetIssuers(X509Certificate2 certificate, List <CertificateIdentifier> issuers)
        {
            bool isTrusted = false;
            CertificateIdentifier issuer = null;

            do
            {
                issuer = await GetIssuer(certificate, m_trustedCertificateList, m_trustedCertificateStore, true);

                if (issuer == null)
                {
                    issuer = await GetIssuer(certificate, m_issuerCertificateList, m_issuerCertificateStore, true);
                }
                else
                {
                    isTrusted = true;
                }

                if (issuer != null)
                {
                    issuers.Add(issuer);
                    certificate = await issuer.Find(false);

                    // check for root.
                    if (Utils.CompareDistinguishedName(certificate.Subject, certificate.Issuer))
                    {
                        break;
                    }
                }
            }while (issuer != null);

            return(isTrusted);
        }
        /// <summary>
        /// Initializes the object with an X509 certificate identifier
        /// </summary>
        public UserIdentity(CertificateIdentifier certificateId)
        {
            if (certificateId == null) throw new ArgumentNullException("certificateId");

            Task<X509Certificate2> task = certificateId.Find();
            task.Wait();
            X509Certificate2 certificate = task.Result;
            if (certificate != null)
            {
                Initialize(certificate);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initializes the object with an X509 certificate identifier
        /// </summary>
        public UserIdentity(CertificateIdentifier certificateId)
        {
            if (certificateId == null)
            {
                throw new ArgumentNullException("certificateId");
            }

            X509Certificate2 certificate = certificateId.Find().Result;

            if (certificate != null)
            {
                Initialize(certificate);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes the object with an X509 certificate identifier
        /// </summary>
        private void Initialize(CertificateIdentifier certificateId)
        {
            if (certificateId == null)
            {
                throw new ArgumentNullException("certificateId");
            }

            X509Certificate2 certificate = certificateId.Find();

            if (certificate != null)
            {
                Initialize(new X509SecurityToken(certificate));
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Returns the issuers for the certificates.
        /// </summary>
        public async Task <bool> GetIssuers(X509Certificate2Collection certificates, List <CertificateIdentifier> issuers)
        {
            bool isTrusted = false;
            CertificateIdentifier issuer      = null;
            X509Certificate2      certificate = certificates[0];

            CertificateIdentifierCollection collection = new CertificateIdentifierCollection();

            for (int ii = 1; ii < certificates.Count; ii++)
            {
                collection.Add(new CertificateIdentifier(certificates[ii]));
            }

            do
            {
                issuer = await GetIssuer(certificate, m_trustedCertificateList, m_trustedCertificateStore, true);

                if (issuer == null)
                {
                    issuer = await GetIssuer(certificate, m_issuerCertificateList, m_issuerCertificateStore, true);

                    if (issuer == null)
                    {
                        issuer = await GetIssuer(certificate, collection, null, true);
                    }
                }

                if (issuer != null)
                {
                    isTrusted = true;

                    issuers.Add(issuer);
                    certificate = await issuer.Find(false);

                    // check for root.
                    if (Utils.CompareDistinguishedName(certificate.Subject, certificate.Issuer))
                    {
                        break;
                    }
                }
                else
                {
                    isTrusted = false;
                }
            }while (issuer != null);

            return(isTrusted);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes the object with an X509 certificate identifier
        /// </summary>
        public UserIdentity(CertificateIdentifier certificateId)
        {
            if (certificateId == null)
            {
                throw new ArgumentNullException("certificateId");
            }

            Task <X509Certificate2> task = certificateId.Find();

            task.Wait();
            X509Certificate2 certificate = task.Result;

            if (certificate != null)
            {
                Initialize(certificate);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes the object with an X509 certificate identifier
        /// </summary>
        public UserIdentity(CertificateIdentifier certificateId)
        {
            if (certificateId == null)
            {
                throw new ArgumentNullException("certificateId");
            }

            Task <X509Certificate2> task = certificateId.Find();

            task.Wait();
            X509Certificate2 certificate = task.Result;

            if (certificate != null)
            {
                X509IdentityToken token = new X509IdentityToken();
                token.CertificateData = certificate.RawData;
                token.Certificate     = certificate;
                Initialize(token);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Creates a SAML token for the specified email address.
        /// </summary>
        public static UserIdentity CreateSAMLToken(string emailAddress)
        {
            // Normally this would be done by a server that is capable of verifying that
            // the user is a legimate holder of email address. Using a local certficate to
            // signed the SAML token is a short cut that would never be done in a real system.
            CertificateIdentifier userid = new CertificateIdentifier();

            userid.StoreType = CertificateStoreType.Windows;
            userid.StorePath = "LocalMachine\\My";
            userid.SubjectName = "UA Sample Client";

            X509Certificate2 certificate = userid.Find();
            X509SecurityToken signingToken = new X509SecurityToken(certificate);

            // Create list of confirmation strings
            List<string> confirmations = new List<string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer");

            // Create SAML subject statement based on issuer member variable, confirmation string collection 
            // local variable and proof key identifier parameter
            SamlSubject subject = new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress);

            // Create a list of SAML attributes
            List<SamlAttribute> attributes = new List<SamlAttribute>();
            Claim claim = Claim.CreateNameClaim(emailAddress);
            attributes.Add(new SamlAttribute(claim));

            // Create list of SAML statements
            List<SamlStatement> statements = new List<SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on 
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            DateTime validFrom = DateTime.UtcNow;
            DateTime validTo = DateTime.UtcNow.AddHours(12);

            SamlConditions conditions = new SamlConditions(validFrom, validTo);

            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion(
                "_" + Guid.NewGuid().ToString(),
                signingToken.Certificate.Subject,
                validFrom,
                conditions,
                null,
                statements);

            SecurityKey signingKey = new System.IdentityModel.Tokens.RsaSecurityKey((RSA)signingToken.Certificate.PrivateKey);

            // Set the signing credentials for the SAML assertion
            assertion.SigningCredentials = new SigningCredentials(
                signingKey,
                System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha1Signature,
                System.IdentityModel.Tokens.SecurityAlgorithms.Sha1Digest,
                new SecurityKeyIdentifier(signingToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>()));

            return new UserIdentity(new SamlSecurityToken(assertion));
        }
        /// <summary>
        /// Initializes the validator from the configuration for a token policy.
        /// </summary>
        /// <param name="issuerCertificate">The issuer certificate.</param>
        private SecurityTokenResolver CreateSecurityTokenResolver(CertificateIdentifier issuerCertificate)
        {
            if (issuerCertificate == null)
            {
                throw new ArgumentNullException("issuerCertificate");
            }

            // find the certificate.
            X509Certificate2 certificate = issuerCertificate.Find(false);

            if (certificate == null)
            {
                throw ServiceResultException.Create(
                    StatusCodes.BadCertificateInvalid,
                    "Could not find issuer certificate: {0}",
                    issuerCertificate);
            }

            // create a security token representing the certificate.
            List<SecurityToken> tokens = new List<SecurityToken>();
            tokens.Add(new X509SecurityToken(certificate));

            // create issued token resolver.
            SecurityTokenResolver tokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                new System.Collections.ObjectModel.ReadOnlyCollection<SecurityToken>(tokens),
                false);

            return tokenResolver;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Returns the issuers for the certificates.
        /// </summary>
        public bool GetIssuersWithChainSupportEnabled(X509Certificate2Collection certificates,
                                                      List <CertificateIdentifier> issuers)
        {
            bool isTrusted                    = false;
            bool isChainComplete              = false;
            CertificateIdentifier issuer      = null;
            X509Certificate2      certificate = certificates[0];

            // application certificate is trusted
            CertificateIdentifier trustedCertificate = GetTrustedCertificate(certificate);

            if (trustedCertificate != null)
            {
                isTrusted = true;
            }

            if (Utils.CompareDistinguishedName(certificate.Subject, certificate.Issuer))
            {
                if (!isTrusted)
                {
                    throw ServiceResultException.Create(
                              StatusCodes.BadCertificateUntrusted,
                              "Self Signed Certificate is not trusted.\r\nIssuerName: {0}",
                              certificate.IssuerName.Name);
                }

                return(isTrusted);
            }

            CertificateIdentifierCollection collection = new CertificateIdentifierCollection();

            for (int ii = 1; ii < certificates.Count; ii++)
            {
                collection.Add(new CertificateIdentifier(certificates[ii]));
            }

            do
            {
                issuer = GetIssuer(certificate, m_trustedCertificateList, m_trustedCertificateStore, true);
                if (issuer != null)
                {
                    isTrusted = true;
                }

                if (issuer == null)
                {
                    issuer = GetIssuer(certificate, m_issuerCertificateList, m_issuerCertificateStore, true);

                    if (issuer == null)
                    {
                        issuer = GetIssuer(certificate, collection, null, true);
                    }
                }

                if (issuer != null)
                {
                    //isTrusted = true;

                    issuers.Add(issuer);
                    certificate = issuer.Find(false);

                    // check for root.
                    if (Utils.CompareDistinguishedName(certificate.Subject, certificate.Issuer))
                    {
                        isChainComplete = true;
                        break;
                    }
                }
                else
                {
                    isTrusted = false;
                }
            } while (issuer != null);

            if (!isChainComplete)
            {
                throw ServiceResultException.Create(
                          StatusCodes.BadSecurityChecksFailed,
                          "Certificate chain not complete.\r\nSubjectName: {0}\r\nIssuerName: {1}",
                          certificates[0].SubjectName.Name,
                          certificates[0].IssuerName.Name);
            }

            if (!isTrusted)
            {
                throw ServiceResultException.Create(
                          StatusCodes.BadCertificateUntrusted,
                          "Certificate issuer is not trusted.\r\nSubjectName: {0}\r\nIssuerName: {1}",
                          certificates[0].SubjectName.Name,
                          certificates[0].IssuerName.Name);
            }

            return(isTrusted);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Checks for a valid application instance certificate.
        /// </summary>
        /// <param name="silent">if set to <c>true</c> no dialogs will be displayed.</param>
        /// <param name="minimumKeySize">Minimum size of the key.</param>
        public void CheckApplicationInstanceCertificate(
            bool silent,
            ushort minimumKeySize)
        {
            Utils.Trace(Utils.TraceMasks.Information, "Checking application instance certificate.");

            ApplicationConfiguration configuration = null;

            if (m_applicationConfiguration == null)
            {
                LoadApplicationConfiguration(silent);
            }

            configuration = m_applicationConfiguration;
            bool createNewCertificate = true;

            // find the existing certificate.
            CertificateIdentifier id = configuration.SecurityConfiguration.ApplicationCertificate;

            if (id == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "Configuration file does not specify a certificate.");
            }

            X509Certificate2 certificate = id.Find(true);

            // check that it is ok.
            if (certificate != null)
            {
                createNewCertificate = !CheckApplicationInstanceCertificate(configuration, certificate, silent, minimumKeySize);
            }
            else
            {
                // check for missing private key.
                certificate = id.Find(false);

                if (certificate != null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "Cannot access certificate private key. Subject={0}", certificate.Subject);
                }

                // check for missing thumbprint.
                if (!String.IsNullOrEmpty(id.Thumbprint))
                {
                    if (!String.IsNullOrEmpty(id.SubjectName))
                    {
                        CertificateIdentifier id2 = new CertificateIdentifier();
                        id2.StoreType = id.StoreType;
                        id2.StorePath = id.StorePath;
                        id2.SubjectName = id.SubjectName;

                        certificate = id2.Find(true);
                    }

                    if (certificate != null)
                    {
                        string message = Utils.Format(
                            "Thumbprint was explicitly specified in the configuration." +
                            "\r\nAnother certificate with the same subject name was found." +
                            "\r\nUse it instead?\r\n" +
                            "\r\nRequested: {0}" +
                            "\r\nFound: {1}",
                            id.SubjectName,
                            certificate.Subject);

                        throw ServiceResultException.Create(StatusCodes.BadConfigurationError, message);
                    }
                    else
                    {
                        string message = Utils.Format("Thumbprint was explicitly specified in the configuration. Cannot generate a new certificate.");
                        throw ServiceResultException.Create(StatusCodes.BadConfigurationError, message);
                    }
                }
                else
                {
                    if (String.IsNullOrEmpty(id.SubjectName))
                    {
                        string message = Utils.Format("Both SubjectName and Thumbprint are not specified in the configuration. Cannot generate a new certificate.");
                        throw ServiceResultException.Create(StatusCodes.BadConfigurationError, message);
                    }
                }
            }
            
            // create a new certificate.
            if (createNewCertificate)
            {
                certificate = CreateApplicationInstanceCertificate(configuration, minimumKeySize, 600);
            }

            // ensure it is trusted.
            else
            {
                AddToTrustedStore(configuration, certificate);
            }

            // add to discovery server.
            if (configuration.ApplicationType == ApplicationType.Server || configuration.ApplicationType == ApplicationType.ClientAndServer)
            {
                try
                {
                    AddToDiscoveryServerTrustList(certificate, null, null, configuration.SecurityConfiguration.TrustedPeerCertificates);
                }
                catch (Exception e)
                {
                    Utils.Trace(e, "Could not add certificate to LDS trust list.");
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes the object with an X509 certificate identifier
        /// </summary>
        private void Initialize(CertificateIdentifier certificateId)
        {
            if (certificateId == null) throw new ArgumentNullException("certificateId");

            X509Certificate2 certificate = certificateId.Find();

            if (certificate != null)
            {
                Initialize(new X509SecurityToken(certificate));
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Creates a minimal endpoint description which allows a client to connect to a server.
        /// </summary>
        /// <remarks>
        /// In most cases the client will use the server's discovery endpoint to fetch the information
        /// constained in this structure.
        /// </remarks>
        public static EndpointDescription CreateEndpointDescription()
        {
            // create the endpoint description.
            EndpointDescription endpointDescription = new EndpointDescription();
            
           endpointDescription.EndpointUrl = Utils.Format("http://{0}:61211/UA/SampleClient", System.Net.Dns.GetHostName());
           // endpointDescription.EndpointUrl = Utils.Format("opc.tcp://{0}:51210/UA/SampleServer", System.Net.Dns.GetHostName());
           // endpointDescription.EndpointUrl = Utils.Format("http://{0}:51211/UA/SampleServer/None", System.Net.Dns.GetHostName());
           // endpointDescription.EndpointUrl = Utils.Format("http://{0}:51211/UA/SampleServer", System.Net.Dns.GetHostName());
            
            // specify the security policy to use.
            // endpointDescription.SecurityPolicyUri = SecurityPolicies.None;
            // endpointDescription.SecurityMode      = MessageSecurityMode.None;;
            endpointDescription.SecurityPolicyUri = SecurityPolicies.Basic128Rsa15;
            endpointDescription.SecurityMode      = MessageSecurityMode.SignAndEncrypt;
            
            // specify the transport profile.
             endpointDescription.TransportProfileUri = Profiles.WsHttpXmlOrBinaryTransport;
            // endpointDescription.TransportProfileUri = Profiles.WsHttpXmlTransport;
            // endpointDescription.TransportProfileUri = Profiles.UaTcpTransport;

            endpointDescription.Server.DiscoveryUrls.Add(Utils.Format("http://{0}:61211/UA/SampleClient/discovery", System.Net.Dns.GetHostName()));

            // load the the server certificate from the local certificate store.
            CertificateIdentifier certificateIdentifier = new CertificateIdentifier();

            certificateIdentifier.StoreType = CertificateStoreType.Windows;
            certificateIdentifier.StorePath = "LocalMachine\\My";
            certificateIdentifier.SubjectName = "UA Sample Client";
            
            X509Certificate2 serverCertificate = certificateIdentifier.Find();

            if (serverCertificate == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadCertificateInvalid, "Could not find server certificate: {0}", certificateIdentifier.SubjectName);
            }

            endpointDescription.ServerCertificate = serverCertificate.RawData;

            return endpointDescription;
        }