Exemple #1
0
		public FetchCertificate(X509FindType criteria, object match)
		{
			Criteria = criteria;
			MatchesValue = match;
			StoreLocation = StoreLocation.LocalMachine;
			StoreName = StoreName.My;
		}
 public IOfferInfrastructure FromStore(X509FindType findType, string findValue)
 {
     var certOp = new CertificateFromStoreOperation(findType, findValue);
     var compositeSequence = _infrastructureSequence.NewCompositeSequence(certOp);
     certOp.Configure(new RemoteCompositeBuilder(compositeSequence, _webDeploy));
     return _infrastructureBuilder;
 }
        public void SetCertificate(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue)
        {
            if (findValue == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
            }
            ThrowIfImmutable();
            var dotNetCertificate = SecurityUtils.GetCertificateFromStore(storeName, storeLocation, findType, findValue, null);
            IReadOnlyList<Certificate> uwpCertificates;
            try
            {
                uwpCertificates = GetCertificatesFromWinRTStore(dotNetCertificate);
            }
            catch (Exception)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(SecurityUtils.CreateCertificateLoadException(
                    storeName, storeLocation, findType, findValue, null, 0));
            }

            if (uwpCertificates.Count != 1)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(SecurityUtils.CreateCertificateLoadException(
                    storeName, storeLocation, findType, findValue, null, uwpCertificates.Count));
            }

            AttachUwpCertificate(dotNetCertificate, uwpCertificates[0]);
            _certificate = dotNetCertificate;
        }
        /// <summary>
        /// Gets the find value.
        /// </summary>
        /// <param name="findType">Type of the find.</param>
        /// <param name="value">The value.</param>
        /// <returns>The find value formated as string.</returns>
        public static string GetFindValue(X509FindType findType, X509Certificate2 value)
        {
            string findValue = null;

            switch (findType)
            {
                case X509FindType.FindBySubjectDistinguishedName:
                    findValue = GetSubjectDistinguishedName(value.SubjectName.Name);
                    break;
                case X509FindType.FindByThumbprint:
                    findValue = value.Thumbprint;
                    break;
                case X509FindType.FindBySubjectName:
                    findValue = value.SubjectName.Name;
                    break;
                case X509FindType.FindBySerialNumber:
                    findValue = value.SerialNumber;
                    break;
                default:
                    findValue = value.ToString(false);
                    break;
            }

            return findValue;
        }
 /// <summary>
 /// Will deploy certificate found by find type and find value from the local certificate store, to remote certificate store on server.
 /// </summary>
 /// <param name="findType"></param>
 /// <param name="findValue"></param>
 /// <returns></returns>
 public static IOfferRemoteConfiguration FromStore(this IOfferSslInfrastructure sslInfra, X509FindType findType, string findValue)
 {
     var infraBuilder = ((SslInfrastructureBuilder) sslInfra).InfrastructureBuilder;
     var certOp = new CertificateFromStoreOperation(findType, findValue);
     Configure.Operation(infraBuilder, certOp);
     return infraBuilder;
 }
        internal static bool TryResolveCertificate(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, out X509Certificate2 certificate)
        {
            X509Store store = new X509Store(storeName, storeLocation);
            store.Open(OpenFlags.ReadOnly);

            certificate = null;
            X509Certificate2Collection certs = null;
            X509Certificate2Collection matches = null;
            try
            {
                certs = store.Certificates;
                matches = certs.Find(findType, findValue, false);

                // Throwing InvalidOperationException here, following WCF precedent. 
                // Might be worth introducing a more specific exception here.
                if (matches.Count == 1)
                {
                    certificate = new X509Certificate2(matches[0]);
                    return true;
                }
            }
            finally
            {
                CryptoHelper.ResetAllCertificates(matches);
                CryptoHelper.ResetAllCertificates(certs);
                store.Close();
            }

            return false;
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="LocalMachineCertificateFactory"/> class.
		/// </summary>
		/// <param name="certificateSubject">The certificate subject.</param>
		/// <param name="findType"></param>
		public LocalMachineCertificateFactory(string certificateSubject, X509FindType findType)
		{
			_certificateSubject = certificateSubject;
			_findType = findType;

			ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;
		}
        public X509SecurityTokenProvider(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue)
        {
            if (findValue == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
            }

            X509CertificateStore store = new X509CertificateStore(storeName, storeLocation);
            X509Certificate2Collection certificates = null;
            try
            {
                store.Open(OpenFlags.ReadOnly);
                certificates = store.Find(findType, findValue, false);
                if (certificates.Count < 1)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.CannotFindCert, storeName, storeLocation, findType, findValue)));
                }
                if (certificates.Count > 1)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.FoundMultipleCerts, storeName, storeLocation, findType, findValue)));
                }

                this.certificate = new X509Certificate2(certificates[0]);
            }
            finally
            {
                SecurityUtils.ResetAllCertificates(certificates);
                store.Close();
            }
        }
        public static X509Certificate2 Load(StoreName name, StoreLocation location, X509FindType type, string findValue)
        {
            if (string.IsNullOrWhiteSpace(findValue))
                throw new ArgumentNullException("findValue");
            
            var store = new X509Store(name, location);
            store.Open(OpenFlags.ReadOnly);
            try
            {
                var certificates = store.Certificates.Find(type, findValue, false);

                if (certificates.Count != 1)
                {
                    throw new InvalidOperationException(
                        string.Format(CultureInfo.InvariantCulture,
                        "Finding certificate with [StoreName:{0}, StoreLocation:{1}, X509FindType: {2}, FindValue: {3}] matched {4} certificates. A unique match is required.",
                        name, location, type, findValue, certificates.Count));
                }

                return certificates[0];
            }
            finally
            {
                store.Close();
            }
        }
		/// <summary>
		/// Creates a custom certificate search directive, based on the specified find type and value.
		/// </summary>
		/// <param name="findType"></param>
		/// <param name="findValue"></param>
		/// <returns></returns>
		public static CertificateSearchDirective CreateCustom(X509FindType findType, string findValue)
		{
			return new CertificateSearchDirective
			{
				FindType = findType,
				FindValue = findValue
			};
		}
Exemple #11
0
 public SecurityBehavior(ServiceSecurity mode,StoreLocation storeLocation,StoreName storeName,X509FindType findType,string subjectName)
 {
     m_Mode = mode;
      m_StoreLocation = storeLocation;
      m_StoreName = storeName;
      m_FindType = findType;
      m_SubjectName = subjectName;
 }
 private IEnumerable<X509Certificate2> Find(X509FindType findType, string criteria, bool validOnly) {
     try {
         return _storeWrapper.Find(findType, criteria, validOnly);
     } finally {
         if (_storeWrapper != null) {
             _storeWrapper.Close();
         }
     }
 }
 public void SetCertificate(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue)
 {
     if (findValue == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
     }
     ThrowIfImmutable();
     _certificate = SecurityUtils.GetCertificateFromStore(storeName, storeLocation, findType, findValue, null);
 }
		public void SetCertificate (StoreLocation storeLocation,
			StoreName storeName, X509FindType findType,
			object findValue)
		{
#if !MOBILE
			certificate = ConfigUtil.CreateCertificateFrom (storeLocation, storeName, findType, findValue);
#else
			throw new NotImplementedException ();
#endif
		}
Exemple #15
0
        public void ConfigureAnonymousMessageSecurity(StoreLocation location,StoreName storeName,X509FindType findType,object findValue)
        {
            Credentials.ServiceCertificate.SetCertificate(location,storeName,findType,findValue);
             Authorization.PrincipalPermissionMode = PrincipalPermissionMode.None;

             foreach(ServiceEndpoint endpoint in Description.Endpoints)
             {
            ServiceBusHelper.ConfigureBinding(endpoint.Binding);
             }
        }
        /// <summary>
        ///     Retrieves a certificate from the certificate store.
        /// </summary>
        /// <param name="location">The location.</param>
        /// <param name="name">The name.</param>
        /// <param name="findType">Type of the find.</param>
        /// <param name="value">The value.</param>
        /// <returns>A X509Certificate2</returns>
        public static X509Certificate2 GetCertificateFromStore(StoreLocation location, StoreName name,
            X509FindType findType, object value)
        {
            var store = new X509Store(name, location);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                // work around possible bug in framework
                if (findType == X509FindType.FindByThumbprint)
                {
                    var thumbprint = value.ToString();
                    thumbprint = thumbprint.Trim();
                    thumbprint = thumbprint.Replace(" ", "");

                    foreach (var cert in store.Certificates)
                    {
                        if (string.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase) ||
                            string.Equals(cert.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return cert;
                        }
                    }
                }
                if (findType == X509FindType.FindBySerialNumber)
                {
                    var serial = value.ToString();
                    serial = serial.Trim();
                    serial = serial.Replace(" ", "");

                    foreach (var cert in store.Certificates)
                    {
                        if (string.Equals(cert.SerialNumber, serial, StringComparison.OrdinalIgnoreCase) ||
                            string.Equals(cert.SerialNumber, serial, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return cert;
                        }
                    }
                }

                var certs = store.Certificates.Find(findType, value, false);

                if (certs.Count != 1)
                {
                    throw new InvalidOperationException(string.Format("Certificate not found: {0}", value));
                }

                return certs[0];
            }
            finally
            {
                store.Close();
            }
        }
        public IOfferRemoteDeployment FromStore(X509FindType findType, string findValue, Action<IOfferCertificateOptions> options)
        {
            var certOptions = new CertificateOptions();
            if (options != null)
            {
                options(certOptions);
            }

            var certOp = new CertificateFromStoreOperation(findType, findValue, certOptions);
            var compositeSequence = _remoteSequence.NewCompositeSequence(certOp);
            certOp.Configure(new RemoteCompositeBuilder(compositeSequence, _webDeploy));
            return _remoteDeploymentBuilder;
        }
        /// <summary>
        /// Will deploy certificate found by find type and find value from the local certificate store, to remote certificate store on server with provided options.
        /// </summary>
        /// <param name="findType"></param>
        /// <param name="findValue"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IOfferRemoteDeployment FromStore(this IOfferRemoteCertDeployment remoteCert, X509FindType findType, string findValue, Action<IOfferCertificateOptions> options)
        {
            var certOptions = new CertificateOptions();
            if (options != null)
            {
                options(certOptions);
            }

            var remoteCertBuilder = ((RemoteCertDeploymentBuilder) remoteCert).RemoteDeployment;
            var certOp = new CertificateFromStoreOperation(findType, findValue, certOptions);
            Configure.Operation(remoteCertBuilder, certOp);
            return remoteCertBuilder;
        }
 public void SetScopedCertificate(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue, Uri targetService)
 {
     if (findValue == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
     }
     if (targetService == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("targetService");
     }
     this.ThrowIfImmutable();
     X509Certificate2 certificate = System.ServiceModel.Security.SecurityUtils.GetCertificateFromStore(storeName, storeLocation, findType, findValue, null);
     this.ScopedCertificates[targetService] = certificate;
 }
        internal static X509Certificate2 ResolveCertificate(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue)
        {
            X509Certificate2 certificate = null;

            // Throwing InvalidOperationException here, following WCF precedent. 
            // Might be worth introducing a more specific exception here.
            if (!TryResolveCertificate(storeName, storeLocation, findType, findValue, out certificate))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR.GetString(SR.ID1025, storeName, storeLocation, findType, findValue)));
            }

            return certificate;
        }
		public X509SecurityTokenProvider (StoreLocation storeLocation,
			StoreName storeName, X509FindType findType, object findValue)
		{
			if (findValue == null)
				throw new ArgumentNullException ("findValue");

			store = new X509Store (storeName, storeLocation);
			store.Open (OpenFlags.ReadOnly);
			foreach (X509Certificate2 hit in store.Certificates.Find (findType, findValue, true)) {
				if (cert != null)
					throw new SecurityTokenException ("X509SecurityTokenProvider does not allow such certificate specification that indicates more than one certificate. Use more specific find value.");
				cert = hit;
			}
		}
        /// <summary>
        /// Call the Saml Helper Class and get the "Post" value, which can then be posted to the web page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static string CreateSamlResponse(string recipient, string issuer, string domain, string subject, StoreLocation storeLocation, StoreName storeName, X509FindType findType, string certLocation, string certPassword, string certFindKey, Dictionary<string, string> attributes, string target)
        {
            string postData = "";

            // Set Parameters to the method call to either the configuration value or a default value
            SigningHelper.SignatureType signatureType = SigningHelper.SignatureType.Response;

            postData = SamlHelper.GetPostSamlResponse(recipient,
                        issuer, domain, subject,
                        storeLocation, storeName, findType,
                        certLocation, certPassword, certFindKey,
                        attributes, signatureType);

            return postData;
        }
        public void Copy(X509InitiatorCertificateClientElement from)
        {
            if (this.IsReadOnly())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigReadOnly)));
            }
            if (null == from)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("from");
            }

            this.FindValue = from.FindValue;
            this.StoreLocation = from.StoreLocation;
            this.StoreName = from.StoreName;
            this.X509FindType = from.X509FindType;
        }
        public IOfferIisWebSiteOptions AddHttpsBinding(X509FindType findType, string findName, Action<IOfferBindingOptions> bindingOptions)
        {
            var options = new BindingOptions();
            bindingOptions(options);

            var httpsOptions = new BindingOptions.SslBindingOptionsValues
                                   {
                                       FindType = findType,
                                       FindName = findName,
                                       BindingOptions = options.Values,
                                       CertLocation = CertLocation.Store
                                   };

            _values.HttpsBindings.Add(httpsOptions);
            return this;
        }
 static X509Certificate2Collection FilterCertificates(X509Certificate2Collection found, X509FindType findType, object findValue)
 {
     if (found.Count > 1 && findType == X509FindType.FindBySubjectName)
     {
         X509Certificate2Collection foundBuffer = new X509Certificate2Collection();
         foreach (var item in found)
         {
             if (item.Subject == $"CN={findValue}")
             {
                 foundBuffer.Add(item);
             }
         }
         return foundBuffer;
     }
     return found;
 }
Exemple #26
0
		public X509Certificate2 LoadCertificate(string storeName, StoreLocation
		storeLocation, X509FindType findType, string value)
		{
			// The following code gets the cert from the keystore
			X509Store store = CreateStoreObject(storeName, storeLocation);
			store.Open(OpenFlags.ReadOnly);
			X509Certificate2Collection certCollection =
					 store.Certificates.Find(findType,
					 value, false);
			X509Certificate2Enumerator enumerator = certCollection.GetEnumerator();
			X509Certificate2 cert = null;
			while (enumerator.MoveNext())
			{
				cert = enumerator.Current;
			}
			return cert;
		}
 /// <summary>
 /// 
 /// </summary>
 /// <param name="findType"></param>
 /// <param name="findName"></param>
 /// <returns></returns>
 protected static bool CheckCertificate( X509FindType findType , string findName)
 {
     try
     {
         X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
         store.Open(OpenFlags.MaxAllowed);
         X509Certificate2Collection certs = store.Certificates.Find(findType, findName, false);
         if (certs.Count == 0 || certs[0].NotAfter < DateTime.Now)
         {
             return false;
         }
         return true;
     }
     catch ( Exception ex )
     {
         LogHelper.WriteException(ex);
         return false;
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="findBy"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static X509Certificate2 FindCertificateAcrossCertStore(X509FindType findBy, string value)
        {
            var certColl = new X509Certificate2Collection();
            foreach (var e in (StoreName[])Enum.GetValues(typeof(StoreName)))
            {
                var store = new X509Store(e, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly);

                certColl.AddRange(store.Certificates.Find(findBy, value, false));

                store.Close();

                if (certColl.Count != 0)
                {
                    return certColl[0];
                }
            }

            throw new Exception("Certificate not found: " + value);
        }
 private static X509Certificate2 GetCertificate(StoreName storeName,
                                                StoreLocation storeLocation,
                                                X509FindType findByThumbprint,
                                                object findValue)
 {
     var store = new X509Store(storeName, storeLocation);
     try
     {
         store.Open(OpenFlags.ReadOnly);
         return
             store.Certificates
                  .Find(findByThumbprint, findValue, validOnly: false)
                  .Cast<X509Certificate2>()
                  .FirstOrDefault();
     }
     finally
     {
         store.Close();
     }
 }
Exemple #30
0
      public void ConfigureMessageSecurity(StoreLocation location,StoreName storeName,X509FindType findType,object findValue,bool useProviders,string applicationName)
      {
         Credentials.ServiceCertificate.SetCertificate(location,storeName,findType,findValue);

         foreach(ServiceEndpoint endpoint in Description.Endpoints)
         {    
            ServiceBusHelper.ConfigureBinding(endpoint.Binding,false);
         }
         if(useProviders)
         {
            Authorization.PrincipalPermissionMode = PrincipalPermissionMode.UseAspNetRoles;
            Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.MembershipProvider;

            SecurityBehavior.EnableRoleManager();

            string application;

            if(String.IsNullOrEmpty(applicationName))
            {
               applicationName = Membership.ApplicationName;
            }
            if(String.IsNullOrEmpty(applicationName) || applicationName == "/")
            {
               if(String.IsNullOrEmpty(Assembly.GetEntryAssembly().GetName().Name))
               {
                  application = AppDomain.CurrentDomain.FriendlyName;
               }
               else
               {
                  application = Assembly.GetEntryAssembly().GetName().Name;
               }
            }
            else
            {
               application = applicationName;
            }
            Membership.ApplicationName = application;
            Roles.ApplicationName = application;
         }
      }
Exemple #31
0
        /// <summary>
        /// Returns a Base64 Encoded String with the SamlResponse in it.
        /// </summary>
        /// <param name="recipient">Recipient</param>
        /// <param name="issuer">Issuer</param>
        /// <param name="subject">Subject</param>
        /// <param name="certLocation">Certificate Location</param>
        /// <param name="certPassword">Certificate Password</param>
        /// <param name="attributes">A list of attributes to pass</param>
        /// <returns></returns>
        public static string GetPostSamlResponse(string recipient, string issuer, string domain, string subject,
                                                 StoreLocation storeLocation, StoreName storeName, X509FindType findType, string certFile, string certPassword, object findValue,
                                                 Dictionary <string, string> attributes, SigningHelper.SignatureType signatureType)
        {
            ResponseType response = new ResponseType();

            // Create Response
            response.ResponseID = "_" + Guid.NewGuid().ToString();

            response.MajorVersion = "1";
            response.MinorVersion = "1";
            response.IssueInstant = System.DateTime.UtcNow;
            response.Recipient    = recipient;

            StatusType status = new StatusType();

            status.StatusCode       = new StatusCodeType();
            status.StatusCode.Value = new XmlQualifiedName("Success", "urn:oasis:names:tc:SAML:1.0:protocol");

            response.Status = status;

            // Create Assertion
            AssertionType assertionType = SamlHelper.CreateSaml11Assertion(
                issuer.Trim(), domain.Trim(), subject.Trim(), attributes);

            response.Assertion = new AssertionType[] { assertionType };

            //Serialize
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("samlp", "urn:oasis:names:tc:SAML:1.0:protocol");
            ns.Add("saml", "urn:oasis:names:tc:SAML:1.0:assertion");
            XmlSerializer responseSerializer =
                new XmlSerializer(response.GetType());
            StringWriter      stringWriter = new StringWriter();
            XmlWriterSettings settings     = new XmlWriterSettings();

            settings.OmitXmlDeclaration = true;
            settings.Indent             = true;
            settings.Encoding           = Encoding.UTF8;

            XmlWriter responseWriter = XmlTextWriter.Create(stringWriter, settings);

            responseSerializer.Serialize(responseWriter, response, ns);
            responseWriter.Close();

            string samlString = stringWriter.ToString();

            stringWriter.Close();
            // Sign the document
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(samlString);
            X509Certificate2 cert = null;

            if (System.IO.File.Exists(certFile))
            {
                cert = new X509Certificate2(certFile, certPassword);
            }
            else
            {
                X509Store store = new X509Store(storeName, storeLocation);
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection coll = store.Certificates.Find(findType, findValue, true);
                if (coll.Count < 1)
                {
                    throw new ArgumentException("Unable to locate certificate");
                }
                cert = coll[0];
                store.Close();
            }
            XmlElement signature = SigningHelper.SignDoc(
                doc, cert, "ResponseID", response.ResponseID);

            doc.DocumentElement.InsertBefore(signature,
                                             doc.DocumentElement.ChildNodes[0]);

            if (SamlHelper.Logger.IsDebugEnabled)
            {
                SamlHelper.Logger.DebugFormat(
                    "Saml Assertion before encoding = {0}",
                    doc.OuterXml.ToString());
            }
            // Base64Encode and URL Encode
            byte[] base64EncodedBytes =
                Encoding.UTF8.GetBytes(doc.OuterXml);

            string returnValue = System.Convert.ToBase64String(
                base64EncodedBytes);

            return(returnValue);
        }
Exemple #32
0
        public static X509Certificate2Collection FindMatchingCertificates(
            StoreLocation storeLocation,
            string storeName,
            X509FindType findType,
            string findValue,
            string secondaryFindValue,
            bool doTakeMostRecentOnly)
        {
            X509Store store;

            var certificates = new X509Certificate2Collection();

            if (string.IsNullOrWhiteSpace(storeName) ||
                string.IsNullOrWhiteSpace(findValue))
            {
                Console.WriteLine("PaasCoordinator: No certificate configured");

                // Fall back to 'anonymous' self-signed certificate so that WRP's web host
                // does not reject the connection for lacking a cert. This certificate is
                // installed by the ServiceFabric extension when no cluster security is configured.
                // It is not trusted in any way, and only works when cert security is disabled for
                // the cluster resource.

                // CoreCLR Does not support StoreLocation.LocalMachine, hence using StoreLocation.CurrentUser
#if DotNetCoreClrLinux
                store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
#else
                store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
#endif
                try
                {
                    store.Open(OpenFlags.ReadOnly);

                    var certCollections = store.Certificates.Find(
                        X509FindType.FindBySubjectDistinguishedName,
                        "AnonymousCertDistiguishedName",
                        false /*load self-signed cert*/);

                    if (certCollections.Count > 0)
                    {
                        certificates.Add(certCollections[0]);
                    }
                }
                finally
                {
#if DotNetCoreClrLinux
                    store.Dispose();
#else
                    store.Close();
#endif
                }

                return(certificates);
            }

            IsCertificateAMatchForFindValue matchCert;
            switch (findType)
            {
            case X509FindType.FindByThumbprint:
                matchCert = IsMatchByThumbprint;
                break;

            case X509FindType.FindBySubjectName:
                matchCert = IsMatchBySubjectCommonName;
                break;

            default:
                throw new ArgumentException("Unsupported X509FindType: '{0}'; supported values are FindByThumbprint and FindBySubjectName", findType.ToString());
            }

            // SFRP is generating ClusterManifests setting this value to StoreLocation.LocalMachine
            // Using hard-coded value of StoreLocation.CurrentUser for TP9 till SFRP is updated to set this value appropriately.
#if DotNetCoreClrLinux
            using (store = new X509Store(storeName, StoreLocation.CurrentUser))
#else
            using (store = new X509Store(storeName, storeLocation))
#endif
            {
                X509Certificate2 selectedCert = null;
                try
                {
                    bool     excludeExpiredCerts = true; // todo [dragosav]: update when enabling support for expired certs
                    bool     isTimeValidCert     = false;
                    bool     isExpiredCert       = false;
                    bool     anyMatchFound       = false;
                    DateTime now = DateTime.Now;        // cert validity is presented in local time.

                    store.Open(OpenFlags.ReadOnly);

                    var findValues = new List <string>()
                    {
                        findValue
                    };
                    if (!string.IsNullOrEmpty(secondaryFindValue))
                    {
                        findValues.Add(secondaryFindValue);
                    }

                    foreach (var value in findValues)
                    {
                        Console.WriteLine("Finding matching certificates for find value '{0}'; excludeExpiredCerts = '{1}'", findValue, excludeExpiredCerts);
                        foreach (var enumeratedCert in store.Certificates)
                        {
                            isExpiredCert   = DateTime.Compare(now, enumeratedCert.NotAfter) > 0;
                            isTimeValidCert = !(excludeExpiredCerts && isExpiredCert) &&
                                              DateTime.Compare(now, enumeratedCert.NotBefore) >= 0;
                            if (matchCert(enumeratedCert, value) &&
                                isTimeValidCert)
                            {
                                anyMatchFound = true;

                                Console.WriteLine("Found matching certificate: Thumbprint {0}, NotBefore {1}, NotAfter {2}, Subject {3}",
                                                  enumeratedCert.Thumbprint,
                                                  enumeratedCert.NotBefore,
                                                  enumeratedCert.NotAfter,
                                                  enumeratedCert.Subject);

                                if (!doTakeMostRecentOnly)
                                {
                                    // if taking all, add it here and continue
                                    certificates.Add(enumeratedCert);
                                    continue;
                                }

                                // Select the most recent and farthest valid matching cert.
                                // This should make it predictible if certificate is compromised and it needs to be replaced with a newer one.
                                if (selectedCert == null ||
                                    selectedCert.NotBefore < enumeratedCert.NotBefore)
                                {
                                    selectedCert = enumeratedCert;
                                }
                                else if (selectedCert.NotBefore == enumeratedCert.NotBefore &&
                                         !selectedCert.Thumbprint.Equals(enumeratedCert.Thumbprint))
                                {
                                    // if both were issued at the same time, prefer the farthest valid
                                    selectedCert = selectedCert.NotAfter >= enumeratedCert.NotAfter ? selectedCert : enumeratedCert;
                                }
                            }
                        }
                    }

                    if (selectedCert != null &&
                        doTakeMostRecentOnly)
                    {
                        Console.WriteLine("Selected certificate: Thumbprint {0}, NotBefore {1}, NotAfter {2}, Subject {3}",
                                          selectedCert.Thumbprint,
                                          selectedCert.NotBefore,
                                          selectedCert.NotAfter,
                                          selectedCert.Subject);

                        certificates.Add(selectedCert);
                    }
                    else
                    {
                        Console.WriteLine("No {0} certificate found: StoreName {1}, StoreLocation {2}, FindType {3}, FindValue {4}",
                                          anyMatchFound ? "valid" : "matching",
                                          storeName,
                                          storeLocation,
                                          findType,
                                          findValue);
                    }
                }
                finally
                {
#if DotNetCoreClrLinux
                    store.Dispose();
#else
                    store.Close();
#endif
                }
            }

            if (certificates.Count == 0)
            {
                throw new InvalidOperationException("Could not load primary and secondary certificate");
            }

            return(certificates);
        }
 /// <summary>
 /// Can only call before openning the host
 /// </summary>
 public static void SetSecurityBehavior(this ServiceHost host, ServiceSecurity mode, StoreLocation storeLocation, StoreName storeName, X509FindType findType, string serviceCertificateName, bool useAspNetProviders, string applicationName)
 {
     SetSecurityBehavior(host, mode, storeLocation, storeName, findType, serviceCertificateName, useAspNetProviders, applicationName, false);
 }
Exemple #34
0
 public static void FindWithBadOids(X509FindType findType, string badOid)
 {
     RunExceptionTest <ArgumentException>(findType, badOid);
 }
Exemple #35
0
        /// <summary>
        /// Will deploy certificate found by find type and find value from the local certificate store, to remote certificate store on server with provided options.
        /// </summary>
        /// <param name="findType"></param>
        /// <param name="findValue"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IOfferRemoteConfiguration FromStore(this IOfferSslInfrastructure sslInfra, X509FindType findType, string findValue, Action <IOfferCertificateOptions> options)
        {
            var infraBuilder = ((SslInfrastructureBuilder)sslInfra).InfrastructureBuilder;
            var certOpt      = new CertificateOptions();

            options(certOpt);

            var certOp = new CertificateFromStoreOperation(findType, findValue, certOpt);

            OperationExecutor.Execute((RemoteBuilder)sslInfra, certOp);
            return(infraBuilder);
        }
 private static X509Certificate2 FindCertificate(string commonName, X509Certificate2Collection collection, X509FindType x509FindType = X509FindType.FindBySubjectName)
 => collection
 .Find(x509FindType, commonName, false)
 .Cast <X509Certificate2>()
 .FirstOrDefault();
 public void SetDefaultCertificate(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue)
 {
     if (findValue == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
     }
     ThrowIfImmutable();
     _defaultCertificate = SecurityUtils.GetCertificateFromStore(storeName, storeLocation, findType, findValue, null);
 }
Exemple #38
0
        public static X509Certificate2Collection FindFromCollection(
            X509Certificate2Collection coll,
            X509FindType findType,
            object findValue,
            bool validOnly)
        {
            X509Certificate2Collection results = new X509Certificate2Collection();

            using (IFindPal findPal = OpenPal(coll, results, validOnly))
            {
                switch (findType)
                {
                case X509FindType.FindByThumbprint:
                {
                    byte[] thumbPrint = ConfirmedCast <string>(findValue).DecodeHexString();
                    findPal.FindByThumbprint(thumbPrint);
                    break;
                }

                case X509FindType.FindBySubjectName:
                {
                    string subjectName = ConfirmedCast <string>(findValue);
                    findPal.FindBySubjectName(subjectName);
                    break;
                }

                case X509FindType.FindBySubjectDistinguishedName:
                {
                    string subjectDistinguishedName = ConfirmedCast <string>(findValue);
                    findPal.FindBySubjectDistinguishedName(subjectDistinguishedName);
                    break;
                }

                case X509FindType.FindByIssuerName:
                {
                    string issuerName = ConfirmedCast <string>(findValue);
                    findPal.FindByIssuerName(issuerName);
                    break;
                }

                case X509FindType.FindByIssuerDistinguishedName:
                {
                    string issuerDistinguishedName = ConfirmedCast <string>(findValue);
                    findPal.FindByIssuerDistinguishedName(issuerDistinguishedName);
                    break;
                }

                case X509FindType.FindBySerialNumber:
                {
                    string decimalOrHexString = ConfirmedCast <string>(findValue);

                    // FindBySerialNumber allows the input format to be either in
                    // hex or decimal. Since we can't know which one was intended,
                    // it compares against both interpretations and treats a match
                    // of either as a successful find.

                    // string is big-endian, BigInteger constructor requires little-endian.
                    byte[] hexBytes = decimalOrHexString.DecodeHexString();
                    Array.Reverse(hexBytes);

                    BigInteger hexValue     = PositiveBigIntegerFromByteArray(hexBytes);
                    BigInteger decimalValue = LaxParseDecimalBigInteger(decimalOrHexString);
                    findPal.FindBySerialNumber(hexValue, decimalValue);
                    break;
                }

                case X509FindType.FindByTimeValid:
                {
                    DateTime dateTime = ConfirmedCast <DateTime>(findValue);
                    findPal.FindByTimeValid(dateTime);
                    break;
                }

                case X509FindType.FindByTimeNotYetValid:
                {
                    DateTime dateTime = ConfirmedCast <DateTime>(findValue);
                    findPal.FindByTimeNotYetValid(dateTime);
                    break;
                }

                case X509FindType.FindByTimeExpired:
                {
                    DateTime dateTime = ConfirmedCast <DateTime>(findValue);
                    findPal.FindByTimeExpired(dateTime);
                    break;
                }

                case X509FindType.FindByTemplateName:
                {
                    string expected = ConfirmedCast <string>(findValue);
                    findPal.FindByTemplateName(expected);
                    break;
                }

                case X509FindType.FindByApplicationPolicy:
                {
                    string oidValue = ConfirmedOidValue(findPal, findValue, OidGroup.Policy);
                    findPal.FindByApplicationPolicy(oidValue);
                    break;
                }

                case X509FindType.FindByCertificatePolicy:
                {
                    string oidValue = ConfirmedOidValue(findPal, findValue, OidGroup.Policy);
                    findPal.FindByCertificatePolicy(oidValue);
                    break;
                }

                case X509FindType.FindByExtension:
                {
                    string oidValue = ConfirmedOidValue(findPal, findValue, OidGroup.ExtensionOrAttribute);
                    findPal.FindByExtension(oidValue);
                    break;
                }

                case X509FindType.FindByKeyUsage:
                {
                    X509KeyUsageFlags keyUsage = ConfirmedX509KeyUsage(findValue);
                    findPal.FindByKeyUsage(keyUsage);
                    break;
                }

                case X509FindType.FindBySubjectKeyIdentifier:
                {
                    byte[] keyIdentifier = ConfirmedCast <string>(findValue).DecodeHexString();
                    findPal.FindBySubjectKeyIdentifier(keyIdentifier);
                    break;
                }

                default:
                    throw new CryptographicException(SR.Cryptography_X509_InvalidFindType);
                }
            }

            return(results);
        }
 /// <summary>
 /// Can only call before using the proxy for the first time
 /// </summary>
 public static void SetCertificate <T>(this ClientBase <T> proxy, StoreLocation storeLocation, StoreName storeName, X509FindType findType, string clientCertificateName) where T : class
 {
     if (proxy.State == CommunicationState.Opened)
     {
         throw new InvalidOperationException("Proxy channel is already opened");
     }
     if (String.IsNullOrEmpty(clientCertificateName) == false)
     {
         proxy.ClientCredentials.ClientCertificate.SetCertificate(storeLocation, storeName, findType, clientCertificateName);
     }
     proxy.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;
 }
 /// <summary>
 /// Removes the cert.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="storeLoc">The store loc.</param>
 /// <param name="fType">Type of the f.</param>
 /// <param name="findValue">The find value.</param>
 public static void RemoveCert(StoreName name, StoreLocation storeLoc, X509FindType fType, object findValue)
 {
     RemoveCert(name.ToString(), storeLoc, fType, findValue);
 }
 /// <summary>
 /// Removes the cert.
 /// </summary>
 /// <param name="storeName">Name of the store.</param>
 /// <param name="fType">Type of the f.</param>
 /// <param name="findValue">The find value.</param>
 public static void RemoveCert(string storeName, X509FindType fType, object findValue)
 {
     RemoveCert(storeName, StoreLocation.LocalMachine, fType, findValue);
 }
        /// <summary>
        /// GetPostSamlResponse - Returns a Base64 Encoded String with the SamlResponse in it.
        /// </summary>
        /// <param name="recipient">Recipient</param>
        /// <param name="issuer">Issuer</param>
        /// <param name="domain">Domain</param>
        /// <param name="subject">Subject</param>
        /// <param name="storeLocation">Certificate Store Location</param>
        /// <param name="storeName">Certificate Store Name</param>
        /// <param name="findType">Certificate Find Type</param>
        /// <param name="certLocation">Certificate Location</param>
        /// <param name="findValue">Certificate Find Value</param>
        /// <param name="certFile">Certificate File (used instead of the above Certificate Parameters)</param>
        /// <param name="certPassword">Certificate Password (used instead of the above Certificate Parameters)</param>
        /// <param name="attributes">A list of attributes to pass</param>
        /// <param name="signatureType">Whether to sign Response or Assertion</param>
        /// <returns>A base64Encoded string with a SAML response.</returns>
        public static string BuildPostSamlResponse(string recipient, string issuer, string domain, string subject,
                                                   StoreLocation storeLocation, StoreName storeName, X509FindType findType, string certFile, string certPassword, object findValue,
                                                   Dictionary <string, string> attributes, SigningHelper.SignatureType signatureType)
        {
            ResponseType response = new ResponseType();

            // Response Main Area
            response.ID           = "_" + Guid.NewGuid().ToString();
            response.Destination  = recipient;
            response.Version      = "2.0";
            response.IssueInstant = System.DateTime.UtcNow;

            NameIDType issuerForResponse = new NameIDType();

            issuerForResponse.Value = issuer.Trim();

            response.Issuer = issuerForResponse;

            StatusType status = new StatusType();

            status.StatusCode       = new StatusCodeType();
            status.StatusCode.Value = "urn:oasis:names:tc:SAML:2.0:status:Success";

            response.Status = status;

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("saml2p", "urn:oasis:names:tc:SAML:2.0:protocol");
            ns.Add("saml2", "urn:oasis:names:tc:SAML:2.0:assertion");

            XmlSerializer responseSerializer =
                new XmlSerializer(response.GetType());

            StringWriter      stringWriter = new StringWriter();
            XmlWriterSettings settings     = new XmlWriterSettings();

            settings.OmitXmlDeclaration = true;
            settings.Indent             = true;
            settings.Encoding           = Encoding.UTF8;

            XmlWriter responseWriter = XmlTextWriter.Create(stringWriter, settings);

            string samlString = string.Empty;

            AssertionType assertionType = Saml2Helper.CreateSamlAssertion(
                issuer.Trim(), recipient.Trim(), domain.Trim(), subject.Trim(), attributes);

            response.Items = new AssertionType[] { assertionType };

            responseSerializer.Serialize(responseWriter, response, ns);
            responseWriter.Close();

            samlString = stringWriter.ToString();

            samlString = samlString.Replace("SubjectConfirmationData",
                                            string.Format("SubjectConfirmationData NotOnOrAfter=\"{0:o}\" Recipient=\"{1}\"",
                                                          DateTime.UtcNow.AddMinutes(5), recipient));

            samlString = samlString.Replace("<saml2:Assertion ", "<saml2:Assertion xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\" ");

            samlString = samlString.Replace("<saml2:AuthnContextClassRef>AuthnContextClassRef</saml2:AuthnContextClassRef>", "<saml2:AuthnContextClassRef>" + issuer + "</saml2:AuthnContextClassRef>");

            stringWriter.Close();

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(samlString);
            X509Certificate2 cert = null;

            if (System.IO.File.Exists(certFile))
            {
                cert = new X509Certificate2(certFile, certPassword);
            }
            else
            {
                X509Store store = new X509Store(storeName, storeLocation);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection CertCol = store.Certificates;


                X509Certificate2Collection coll = store.Certificates.Find(findType, findValue.ToString(), false);

                if (coll.Count < 1)
                {
                    throw new ArgumentException("Unable to locate certificate");
                }
                cert = coll[0];
                store.Close();
            }

            XmlElement signature = SigningHelper.SignDoc(doc, cert, response.ID);

            doc.DocumentElement.InsertBefore(signature,
                                             doc.DocumentElement.ChildNodes[1]);

            string responseStr = doc.OuterXml;

            byte[] base64EncodedBytes =
                Encoding.UTF8.GetBytes(responseStr);

            string returnValue = System.Convert.ToBase64String(
                base64EncodedBytes);

            return(returnValue);
        }
 /// <summary>
 /// Removes the cert.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="fType">Type of the f.</param>
 /// <param name="findValue">The find value.</param>
 public static void RemoveCert(StoreName name, X509FindType fType, object findValue)
 {
     RemoveCert(name.ToString(), StoreLocation.CurrentUser, fType, findValue);
 }
 /// <summary>
 /// Removes the cert.
 /// </summary>
 /// <param name="storeLoc">The store loc.</param>
 /// <param name="fType">Type of the f.</param>
 /// <param name="findValue">The find value.</param>
 public static void RemoveCert(StoreLocation storeLoc, X509FindType fType, object findValue)
 {
     RemoveCert(StoreName.My, storeLoc, fType, findValue);
 }
Exemple #45
0
 internal static bool TryGetCertificateFromStore(StoreName storeName, StoreLocation storeLocation,
                                                 X509FindType findType, object findValue, EndpointAddress target, out X509Certificate2 certificate)
 {
     certificate = GetCertificateFromStoreCore(storeName, storeLocation, findType, findValue, target, false);
     return(certificate != null);
 }
Exemple #46
0
        public static IEnumerable <string> TryFindCertificate(
            string machineIpOrFqdn,
            StoreName storeName,
            IEnumerable <string> findValues,
            X509FindType findType,
            out IEnumerable <X509Certificate2> foundCertificates,
            ITraceLogger traceLogger = null)
        {
            machineIpOrFqdn.MustNotBeNull("machineIpOrFqdn");

            // The validation on each thumbprint string will be covered by RDBug 7682650.
            findValues.ToArray().MustNotBeEmptyCollection("findValues");

            List <X509Certificate2> tmpFoundCertificates = new List <X509Certificate2>();

            foundCertificates = Enumerable.Empty <X509Certificate2>();
            List <string> result = new List <string>();
            X509Store     store  = null;

            string strStoreName = storeName.ToString();

            if (machineIpOrFqdn != string.Empty)
            {
                strStoreName = machineIpOrFqdn + "\\" + storeName;
            }

            try
            {
                try
                {
                    store = new X509Store(strStoreName, StoreLocation.LocalMachine);
                    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                }
                catch (CryptographicException ex)
                {
                    // if the exception is access denied error, check if the read permission on the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurePipeServers\winreg
                    // of the remote node machineIpOrFqdn has been granted to the caller account.
                    if (traceLogger != null)
                    {
                        traceLogger.WriteWarning(X509CertificateUtility.TraceType, ex.ToString());
                    }

                    return(findValues);
                }

                foreach (string findValue in findValues)
                {
                    X509Certificate2Collection certs = store.Certificates.Find(findType, findValue, validOnly: false);
                    if (certs != null && findType == X509FindType.FindBySubjectName)
                    {
                        certs.MatchExactSubject(findValue);
                    }

                    if (certs == null || certs.Count == 0)
                    {
                        result.Add(findValue);
                    }
                    else
                    {
                        tmpFoundCertificates.Add(findType == X509FindType.FindByThumbprint ? certs[0] : certs.LatestExpired());
                    }
                }

                foundCertificates = tmpFoundCertificates;
                return(result);
            }
            finally
            {
                // In .net 4.6, X509Store is changed to implement IDisposable.
                // But unfortunately, SF today is built on .net 4.5
                if (store != null)
                {
                    store.Close();
                }
            }
        }
Exemple #47
0
        public void SetServiceCertificate(object findValue, StoreLocation location, StoreName storeName, X509FindType findType)
        {
            ClientCredentials behavior = Endpoint.Behaviors.Find <ClientCredentials>();

            behavior.ServiceCertificate.SetDefaultCertificate(location, storeName, findType, findValue);
            if (Endpoint.Address.Identity == null)
            {
                Uri address = Endpoint.Address.Uri;
                EndpointIdentity identity = new DnsEndpointIdentity(findValue.ToString());
                Endpoint.Address = new EndpointAddress(address, identity);
            }
        }
        /// <summary>
        /// Call the Saml Helper Class and get the "Post" value, which can then be posted to the web page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPostAssertion_Click(object sender, EventArgs e)
        {
            try {
                this.Cursor = Cursors.WaitCursor;

                // Set Attributes
                Dictionary <string, string> attributes = new Dictionary <string, string>();

                foreach (ConfigurationData.AttributesRow row in configurationData.Attributes.Rows)
                {
                    attributes.Add(row.Name, row.Value);
                }

                string postData = "";
                // Set Parameters to the method call to either the configuration value or a default value
                StoreLocation storeLocation = configurationData.Configuration.Rows[0]["CertStoreLocation"].ToString().Length > 0 ? (StoreLocation)Enum.Parse(typeof(StoreLocation),
                                                                                                                                                             configurationData.Configuration.Rows[0]["CertStoreLocation"].ToString()) : StoreLocation.LocalMachine;
                StoreName storeName = configurationData.Configuration.Rows[0]["CertStoreName"].ToString().Length > 0 ? (StoreName)Enum.Parse(typeof(StoreName),
                                                                                                                                             configurationData.Configuration.Rows[0]["CertStoreName"].ToString()) : StoreName.Root;
                X509FindType findType = configurationData.Configuration.Rows[0]["CertFindMethod"].ToString().Length > 0 ? (X509FindType)Enum.Parse(typeof(X509FindType),
                                                                                                                                                   configurationData.Configuration.Rows[0]["CertFindMethod"].ToString()) : X509FindType.FindByThumbprint;
                string certFileLocation = configurationData.Configuration.Rows[0]["CertFileLocation"].ToString().Length > 0 ?
                                          configurationData.Configuration.Rows[0]["CertFileLocation"].ToString() : null;
                string certPassword = configurationData.Configuration.Rows[0]["CertPassword"].ToString().Length > 0 ?
                                      configurationData.Configuration.Rows[0]["CertPassword"].ToString() : null;
                string certFindKey   = configurationData.Configuration.Rows[0]["CertFindKey"].ToString();
                bool   signResponse  = this.rbSignResponse.Checked;
                bool   signAssertion = this.rbSignAssertion.Checked;
                bool   signVU475445  = this.rbSignVU475445.Checked;
                SigningHelper.SignatureType signatureType = SigningHelper.SignatureType.Response;
                if (signAssertion)
                {
                    signatureType = SigningHelper.SignatureType.Assertion;
                }
                else if (signVU475445)
                {
                    signatureType = SigningHelper.SignatureType.TestVU475445;
                }
                //if (
                // Get SAML Post Value
                if (rb_v1.Checked)
                {
                    postData = String.Format("SAMLResponse={0}&TARGET={1}",
                                             System.Web.HttpUtility.UrlEncode(
                                                 davidsp8.common.Security.Saml11.SamlHelper.GetPostSamlResponse(txtRecipient.Text,
                                                                                                                txtIssuer.Text, txtDomain.Text, txtSubject.Text,
                                                                                                                storeLocation, storeName, findType,
                                                                                                                certFileLocation, certPassword, certFindKey,
                                                                                                                attributes, signatureType)),
                                             txtTarget.Text);
                }
                if (rb_v2.Checked)
                {
                    postData = String.Format("SAMLResponse={0}&RelayState={1}",
                                             System.Web.HttpUtility.UrlEncode(
                                                 davidsp8.common.Security.Saml20.SamlHelper.GetPostSamlResponse(txtRecipient.Text,
                                                                                                                txtIssuer.Text, txtDomain.Text, txtSubject.Text,
                                                                                                                storeLocation, storeName, findType,
                                                                                                                certFileLocation, certPassword, certFindKey,
                                                                                                                attributes, signatureType)),
                                             System.Web.HttpUtility.UrlEncode(txtTarget.Text));
                }

                Logger.DebugFormat(
                    "PostData = {0}", postData);

                webBrowser1.Navigate(this.txtRecipient.Text, "_self",
                                     Encoding.UTF8.GetBytes(postData),
                                     "Content-Type: application/x-www-form-urlencoded");

                webBrowser1.Visible = true;
                webBrowser1.BringToFront();
                btnShowBrowser.Text = "Hide Browser";
            } catch (UriFormatException ex) {
                MessageBox.Show(ex.Message);
            } catch (Exception ex) {
                Logger.Error(ex.Message, ex);
                MessageBox.Show(ex.Message);
            } finally {
                this.Cursor = Cursors.Default;
            }
        }
 private static X509Certificate2 LoadCertificateFromStore(string commonName, StoreName storeName, StoreLocation storeLocation, X509FindType x509FindType = X509FindType.FindBySubjectName)
 {
     //Log.Logger.Information($"Attempting to locate certificate by {x509FindType} = '{commonName}' from store '{storeLocation}/{storeName}'");
     using (var store = new X509Store(storeName, storeLocation))
     {
         store.Open(OpenFlags.ReadOnly);
         return(FindCertificate(commonName, store.Certificates, x509FindType));
     }
 }
 public X509CertificatesFinder(StoreLocation location, StoreName name, X509FindType findType)
 {
     _location = location;
     _name     = name;
     _findType = findType;
 }
Exemple #51
0
        static internal X509Certificate2 GetCertificate(StoreName storeName, StoreLocation storeLocation, string key, X509FindType findType)
        {
            X509Certificate2 result;

            X509Store store = new X509Store(storeName, storeLocation);

            store.Open(OpenFlags.ReadOnly);
            try
            {
                X509Certificate2Collection matches;
                matches = store.Certificates.Find(findType, key, false);
                if (matches.Count > 1)
                {
                    throw new InvalidOperationException(String.Format("More than one certificate with key '{0}' found in the store.", key));
                }
                if (matches.Count == 0)
                {
                    throw new InvalidOperationException(String.Format("No certificates with key '{0}' found in the store.", key));
                }
                result = matches[0];
            }
            finally
            {
                store.Close();
            }

            return(result);
        }
 /// <summary>
 /// Gets the cert.
 /// </summary>
 /// <param name="sLoc">The s loc.</param>
 /// <param name="fType">Type of the f.</param>
 /// <param name="findValue">The find value.</param>
 /// <param name="bValidOnly">if set to <c>true</c> [b valid only].</param>
 /// <returns></returns>
 public static X509Certificate2 GetCert(StoreLocation sLoc, X509FindType fType, object findValue, bool bValidOnly)
 {
     return(GetCert(StoreName.My.ToString(), sLoc, fType, findValue, bValidOnly));
 }
        public void SetScopedCertificate(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue, Uri targetService)
        {
            if (findValue == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
            }
            if (targetService == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("targetService");
            }
            ThrowIfImmutable();
            X509Certificate2 certificate = SecurityUtils.GetCertificateFromStore(storeName, storeLocation, findType, findValue, null);

            ScopedCertificates[targetService] = certificate;
        }
        public static void SetSecurityBehavior(this ServiceHost host, ServiceSecurity mode, StoreLocation storeLocation, StoreName storeName, X509FindType findType, string serviceCertificateName, bool useAspNetProviders, string applicationName, bool impersonateAll)
        {
            if (host.State == CommunicationState.Opened)
            {
                throw new InvalidOperationException("Host is already opened");
            }
            SecurityBehavior securityBehavior = new SecurityBehavior(mode, storeLocation, storeName, findType, serviceCertificateName);

            securityBehavior.UseAspNetProviders = useAspNetProviders;
            securityBehavior.ApplicationName    = applicationName;
            securityBehavior.ImpersonateAll     = impersonateAll;

            host.Description.Behaviors.Add(securityBehavior);
        }
Exemple #55
0
        public static X509Certificate2 CreateCertificateFrom(StoreLocation storeLocation, StoreName storeName, X509FindType findType, Object findValue)
        {
            var store = new X509Store(storeName, storeLocation);

            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
            try {
                foreach (var c in store.Certificates.Find(findType, findValue, false))
                {
                    return(c);
                }
                throw new InvalidOperationException(String.Format("Specified X509 certificate with find type {0} and find value {1} was not found in X509 store {2} location {3}", findType, findValue, storeName, storeLocation));
            } finally {
                store.Close();
            }
        }
 /// <summary>
 /// GetPostSamlResponse - Returns a Base64 Encoded String with the SamlResponse in it with a Default Signature type.
 /// </summary>
 /// <param name="recipient">Recipient</param>
 /// <param name="issuer">Issuer</param>
 /// <param name="domain">Domain</param>
 /// <param name="subject">Subject</param>
 /// <param name="storeLocation">Certificate Store Location</param>
 /// <param name="storeName">Certificate Store Name</param>
 /// <param name="findType">Certificate Find Type</param>
 /// <param name="certLocation">Certificate Location</param>
 /// <param name="findValue">Certificate Find Value</param>
 /// <param name="certFile">Certificate File (used instead of the above Certificate Parameters)</param>
 /// <param name="certPassword">Certificate Password (used instead of the above Certificate Parameters)</param>
 /// <param name="attributes">A list of attributes to pass</param>
 /// <returns>A base64Encoded string with a SAML response.</returns>
 public static string BuildPostSamlResponse(string recipient, string issuer, string domain, string subject,
                                            StoreLocation storeLocation, StoreName storeName, X509FindType findType, string certFile, string certPassword, object findValue,
                                            Dictionary <string, string> attributes)
 {
     return(BuildPostSamlResponse(recipient, issuer, domain, subject, storeLocation, storeName, findType, certFile, certPassword, findValue, attributes,
                                  SigningHelper.SignatureType.Response));
 }
        /// <summary>
        /// Can only call before using the proxy for the first time
        /// </summary>
        public static void SecureProxy <T>(this ClientBase <T> proxy, StoreLocation storeLocation, StoreName storeName, X509FindType findType, string clientCertificateName) where T : class
        {
            if (proxy.State == CommunicationState.Opened)
            {
                throw new InvalidOperationException("Proxy channel is already opened");
            }
            SetCertificate(proxy, storeLocation, storeName, findType, clientCertificateName);
            ServiceEndpoint[] endpoints = { proxy.Endpoint };

            proxy.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;

            SecurityBehavior.ConfigureBusinessToBusiness(endpoints);
        }
 /// <summary>
 /// Gets the cert.
 /// </summary>
 /// <param name="sName">Name of the s.</param>
 /// <param name="fType">Type of the f.</param>
 /// <param name="findValue">The find value.</param>
 /// <param name="bValidOnly">if set to <c>true</c> [b valid only].</param>
 /// <returns></returns>
 public static X509Certificate2 GetCert(StoreName sName, X509FindType fType, object findValue, bool bValidOnly)
 {
     return(GetCert(sName.ToString(), StoreLocation.LocalMachine, fType, findValue, bValidOnly));
 }
Exemple #59
0
 public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="UUID"></param>
        /// <param name="Destination"></param>
        /// <param name="ConsumerServiceURL"></param>
        /// <param name="certFile"></param>
        /// <param name="certPassword"></param>
        /// <param name="storeLocation"></param>
        /// <param name="storeName"></param>
        /// <param name="findType"></param>
        /// <param name="findValue"></param>
        /// <param name="signatureType"></param>
        /// <returns></returns>
        public static string BuildPostSamlRequest(string UUID, string Destination, string ConsumerServiceURL, int SecurityLevel,
                                                  string certFile, string certPassword,
                                                  StoreLocation storeLocation, StoreName storeName,
                                                  X509FindType findType, object findValue, SigningHelper.SignatureType signatureType, string IdentityProvider, int Enviroment)
        {
            AuthnRequestType MyRequest = new AuthnRequestType();

            MyRequest.ID      = UUID;
            MyRequest.Version = "2.0";
            DateTime now         = DateTime.UtcNow;
            DateTime after       = now.AddMinutes(10);
            string   nowString   = String.Empty;
            string   afterString = String.Empty;

            if (IdentityProvider.Contains("sielte"))
            {
                // SIELTE
                nowString   = now.AddMinutes(-2).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
                afterString = after.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
            }
            else
            {
                // POSTE - TIM - INFOCERT
                nowString   = now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
                afterString = after.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
            }
            MyRequest.IssueInstant = nowString;
            if (SecurityLevel > 1)
            {
                MyRequest.ForceAuthn          = true;
                MyRequest.ForceAuthnSpecified = true;
            }
            MyRequest.Destination = Destination;

            MyRequest.AssertionConsumerServiceIndex           = (ushort)Enviroment; // 1 for dev // 0 for production
            MyRequest.AssertionConsumerServiceIndexSpecified  = true;
            MyRequest.AttributeConsumingServiceIndex          = 1;
            MyRequest.AttributeConsumingServiceIndexSpecified = true;

            NameIDType IssuerForRequest = new NameIDType();

            IssuerForRequest.Value         = ConsumerServiceURL.Trim();
            IssuerForRequest.Format        = "urn:oasis:names:tc:SAML:2.0:nameid-format:entity";
            IssuerForRequest.NameQualifier = ConsumerServiceURL;
            MyRequest.Issuer = IssuerForRequest;

            NameIDPolicyType NameIdPolicyForRequest = new NameIDPolicyType();

            NameIdPolicyForRequest.Format               = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient";
            NameIdPolicyForRequest.AllowCreate          = true;
            NameIdPolicyForRequest.AllowCreateSpecified = true;
            MyRequest.NameIDPolicy = NameIdPolicyForRequest;

            ConditionsType Conditional = new ConditionsType();

            if (IdentityProvider.Contains("sielte"))
            {
                // SIELTE
                Conditional.NotBefore = nowString;
            }
            else
            {
                // POSTE - TIM - INFOCERT
                Conditional.NotBefore = now.AddMinutes(-2).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
            }

            Conditional.NotBeforeSpecified    = true;
            Conditional.NotOnOrAfter          = afterString;
            Conditional.NotOnOrAfterSpecified = true;
            MyRequest.Conditions = Conditional;

            RequestedAuthnContextType RequestedAuthn = new RequestedAuthnContextType();

            RequestedAuthn.Comparison          = AuthnContextComparisonType.minimum;
            RequestedAuthn.ComparisonSpecified = true;
            RequestedAuthn.ItemsElementName    = new ItemsChoiceType7[] { ItemsChoiceType7.AuthnContextClassRef };
            RequestedAuthn.Items            = new string[] { "https://www.spid.gov.it/SpidL" + SecurityLevel.ToString() };
            MyRequest.RequestedAuthnContext = RequestedAuthn;

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("saml2p", "urn:oasis:names:tc:SAML:2.0:protocol");
            //ns.Add("saml2", "urn:oasis:names:tc:SAML:2.0:assertion");

            XmlSerializer responseSerializer = new XmlSerializer(MyRequest.GetType());

            StringWriter      stringWriter = new StringWriter();
            XmlWriterSettings settings     = new XmlWriterSettings();

            settings.OmitXmlDeclaration = true;
            settings.Indent             = true;
            settings.Encoding           = Encoding.UTF8;

            XmlWriter responseWriter = XmlTextWriter.Create(stringWriter, settings);

            responseSerializer.Serialize(responseWriter, MyRequest, ns);
            responseWriter.Close();

            string samlString = string.Empty;

            samlString = stringWriter.ToString();

            stringWriter.Close();

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(samlString);
            X509Certificate2 cert = null;

            if (System.IO.File.Exists(certFile))
            {
                cert = new X509Certificate2(certFile, certPassword);
            }
            else
            {
                X509Store store = new X509Store(storeName, storeLocation);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection CertCol = store.Certificates;

                X509Certificate2Collection coll = store.Certificates.Find(findType, findValue.ToString(), false);

                if (coll.Count < 1)
                {
                    throw new ArgumentException("Unable to locate certificate");
                }
                cert = coll[0];
                store.Close();
            }

            XmlElement signature = SigningHelper.SignDoc(doc, cert, UUID);

            doc.DocumentElement.InsertBefore(signature, doc.DocumentElement.ChildNodes[1]);

            string responseStr = doc.OuterXml;

            //byte[] base64EncodedBytes =
            //    Encoding.UTF8.GetBytes(responseStr);

            //string returnValue = System.Convert.ToBase64String(
            //    base64EncodedBytes);

            return("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + responseStr);
        }