/// <summary>
        /// Displays an error page.
        /// </summary>
        /// <param name="context">The current HTTP context.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <param name="overrideConfigSetting">if set to <c>true</c> [override config setting].</param>
        public void HandleError(HttpContext context, string errorMessage, bool overrideConfigSetting)
        {
            Trace.TraceData(TraceEventType.Error, "Error: " + errorMessage);

            Boolean showError       = SAML20FederationConfig.GetConfig().ShowError;
            String  DEFAULT_MESSAGE = "Unable to validate SAML message!";

            if (!string.IsNullOrEmpty(ErrorBehaviour) && ErrorBehaviour.Equals(dk.nita.saml20.config.ErrorBehaviour.THROWEXCEPTION.ToString()))
            {
                if (showError)
                {
                    throw new Saml20Exception(errorMessage);
                }
                else
                {
                    throw new Saml20Exception(DEFAULT_MESSAGE);
                }
            }
            else
            {
                ErrorPage page = new ErrorPage();
                page.OverrideConfig = overrideConfigSetting;
                page.ErrorText      = (showError) ? errorMessage?.Replace("\n", "<br />") : DEFAULT_MESSAGE;
                page.ProcessRequest(context);
                context.Response.End();
            }
        }
        /// <summary>
        /// Gets the certificate specifications.
        /// </summary>
        /// <param name="endpoint">The endpoint.</param>
        /// <returns>A list of certificate validation specifications for this endpoint</returns>
        public static List <ICertificateSpecification> GetCertificateSpecifications(IDPEndPoint endpoint)
        {
            List <ICertificateSpecification> specs = new List <ICertificateSpecification>();

            if (endpoint.CertificateValidation != null && endpoint.CertificateValidation.CertificateValidations != null &&
                endpoint.CertificateValidation.CertificateValidations.Count > 0)
            {
                foreach (CertificateValidationElement elem in endpoint.CertificateValidation.CertificateValidations)
                {
                    try
                    {
                        ICertificateSpecification val = (ICertificateSpecification)Activator.CreateInstance(Type.GetType(elem.type));
                        specs.Add(val);
                    }catch (Exception e)
                    {
                        Trace.TraceData(TraceEventType.Error, e.ToString());
                    }
                }
            }

            if (specs.Count == 0)
            {
                //Add default specification
                specs.Add(new DefaultCertificateSpecification());
            }

            return(specs);
        }
        /// <summary>
        /// Determines whether the specified certificate is considered valid according to the RFC3280 specification.
        ///
        /// </summary>
        /// <param name="certificate">The certificate to validate.</param>
        /// <returns>
        ///     <c>true</c> if valid; otherwise, <c>false</c>.
        /// </returns>
        public bool IsSatisfiedBy(X509Certificate2 certificate)
        {
            bool            useMachineContext = false;
            X509ChainPolicy chainPolicy       = new X509ChainPolicy();

            if (!DefaultCertificateSpecification.ChainValidation)
            {
                Trace.TraceData(TraceEventType.Verbose, "Not verifying certificate chain");
                chainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
            }
            else
            {
                Trace.TraceData(TraceEventType.Verbose, "Verifying certificate chain");
            }
            chainPolicy.RevocationMode = X509RevocationMode.NoCheck;//.Online;
            X509CertificateValidator defaultCertificateValidator = X509CertificateValidator.CreateChainTrustValidator(useMachineContext, chainPolicy);

            try
            {
                defaultCertificateValidator.Validate(certificate);
                return(true);
            }
            catch (Exception e)
            {
                Trace.TraceData(TraceEventType.Warning, string.Format(Tracing.CertificateIsNotRFC3280Valid, certificate.SubjectName.Name, certificate.Thumbprint, e));
            }

            return(false);
        }
        void Cleanup(object state)
        {
            try
            {
                ExecuteSqlCommand(cmd =>
                {
                    cmd.CommandText =
                        $@"delete from {_schema}.SessionProperties where ExpiresAtUtc < @time
delete from {
                                _schema
                            }.UserAssociations where SessionId not in (select distinct SessionId from {
                                _schema
                            }.SessionProperties)";
                    cmd.Parameters.AddWithValue("@time", DateTime.UtcNow);
                    cmd.ExecuteNonQuery();
                });
            }
            catch (Exception ex)
            {
                Trace.TraceData(TraceEventType.Warning,
                                $"{nameof(SqlServerSessionStoreProvider)}: Cleanup of sessionstore failed: {ex}");
            }
            finally
            {
                _cleanupTimer.Change(_cleanupInterval, Timeout.InfiniteTimeSpan);
            }
        }
Esempio n. 5
0
 public void LogEntry(Direction dir, Operation op, string msg, string data, string userHostAddress, string idpId, string assertionId, string sessionId)
 {
     if (Trace.ShouldTrace(TraceEventType.Information))
     {
         var str = String.Format("Session id: {6}, Direction: {0}, Operation: {1}, User IP: {2}, Idp ID: {3}, Assertion ID: {4}, Message: {5}, Data: {7}", dir, op, userHostAddress, idpId, assertionId, msg, sessionId, data != null ? data : "");
         //_source.TraceData(TraceEventType.Information, 0, str);
         Trace.TraceData(TraceEventType.Information, str);
     }
 }
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.SamlContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public override void ProcessRequest(SamlHttpContext context)
        {
            try
            {
                Trace.TraceMethodCalled(GetType(), "ProcessRequest()");
                SAML20FederationConfig config = SAML20FederationConfig.GetConfig();

                if (config == null)
                {
                    throw new Saml20Exception("Missing SAML20Federation config section in web.config.");
                }

                Saml20ServiceEndpoint endp
                    = config.ServiceProvider.serviceEndpoints.Find(delegate(Saml20ServiceEndpoint ep) { return(ep.endpointType == EndpointType.SIGNON); });

                if (endp == null)
                {
                    throw new Saml20Exception("Signon endpoint not found in configuration");
                }

                string returnUrl = config.ServiceProvider.Server + endp.localPath + "?r=1";

                SamlHttpCookie samlIdp = context.Request.Cookies[CommonDomainCookie.COMMON_DOMAIN_COOKIE_NAME];

                if (samlIdp != null)
                {
                    returnUrl += "&_saml_idp=" + HttpUtility.UrlEncode(samlIdp.Value);

                    if (Trace.ShouldTrace(TraceEventType.Information))
                    {
                        Trace.TraceData(TraceEventType.Information, string.Format(Tracing.CDC, samlIdp.Value));
                    }

                    AuditLogging.logEntry(Direction.OUT, Operation.AUTHNREQUEST_REDIRECT,
                                          "Redirection to Signon endpoint found in Common Domain Cookie: " + samlIdp.Value);
                }
                else
                {
                    AuditLogging.logEntry(Direction.OUT, Operation.AUTHNREQUEST_REDIRECT,
                                          "Redirection to Signon endpoint, no Common Domain Cookie found: " + returnUrl);
                }
                context.Response.Redirect(returnUrl);
            }
            catch (Exception ex)
            {
                HandleError(context, ex);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Determines whether the specified certificate is considered valid according to the RFC3280 specification.
        ///
        /// </summary>
        /// <param name="certificate">The certificate to validate.</param>
        /// <returns>
        ///     <c>true</c> if valid; otherwise, <c>false</c>.
        /// </returns>
        public bool IsSatisfiedBy(X509Certificate2 certificate)
        {
            bool            useMachineContext = false;
            X509ChainPolicy chainPolicy       = new X509ChainPolicy();

            chainPolicy.RevocationMode = X509RevocationMode.Online;
            X509CertificateValidator defaultCertificateValidator = X509CertificateValidator.CreateChainTrustValidator(useMachineContext, chainPolicy);

            try
            {
                defaultCertificateValidator.Validate(certificate);
                return(true);
            }catch (Exception e)
            {
                Trace.TraceData(TraceEventType.Warning, string.Format(Tracing.CertificateIsNotRFC3280Valid, certificate.SubjectName.Name, certificate.Thumbprint, e));
            }

            return(false);
        }
        /// <summary>
        /// Determines whether the specified certificate is considered valid by this specification.
        /// Always returns true. No online validation attempted.
        /// </summary>
        /// <param name="certificate">The certificate to validate.</param>
        /// <returns>
        ///     <c>true</c>.
        /// </returns>
        public bool IsSatisfiedBy(X509Certificate2 certificate)
        {
            X509ChainPolicy chainPolicy = new X509ChainPolicy();

            chainPolicy.RevocationMode    = X509RevocationMode.NoCheck;
            chainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
            X509CertificateValidator defaultCertificateValidator = X509CertificateValidator.CreateChainTrustValidator(false, chainPolicy);

            try
            {
                defaultCertificateValidator.Validate(certificate);
                return(true);
            }
            catch (Exception e)
            {
                Trace.TraceData(TraceEventType.Warning, string.Format(Tracing.CertificateIsNotRFC3280Valid, certificate.SubjectName.Name, certificate.Thumbprint, e));
            }

            return(false);
        }
        /// <summary>
        /// Determines whether the specified certificate is considered valid according to the RFC3280 specification.
        ///
        /// </summary>
        /// <param name="certificate">The certificate to validate.</param>
        /// <param name="failureReason">If the process fails, the reason is outputted in this variable</param>
        /// <returns>
        ///     <c>true</c> if valid; otherwise, <c>false</c>.
        /// </returns>
        public bool IsSatisfiedBy(X509Certificate2 certificate, out string failureReason)
        {
            bool            useMachineContext = false;
            X509ChainPolicy chainPolicy       = new X509ChainPolicy();

            chainPolicy.RevocationMode = X509RevocationMode.Online;
            X509CertificateValidator defaultCertificateValidator = X509CertificateValidator.CreateChainTrustValidator(useMachineContext, chainPolicy);

            try
            {
                defaultCertificateValidator.Validate(certificate);
                failureReason = null;
                return(true);
            }catch (Exception e)
            {
                failureReason = $"Validating chain with online revocation check failed for certificate '{certificate.Thumbprint}': {e}";
                Trace.TraceData(TraceEventType.Warning, string.Format(Tracing.CertificateIsNotRFC3280Valid, certificate.SubjectName.Name, certificate.Thumbprint, e));
            }

            return(false);
        }
Esempio n. 10
0
 private static RSACryptoServiceProvider ConvertProviderType(RSACryptoServiceProvider rsa)
 {
     // ProviderType == 1 is PROV_RSA_FULL provider type that only supports SHA1. Change it to PROV_RSA_AES=24 that supports SHA2 also.
     // https://github.com/Microsoft/referencesource/blob/master/System.IdentityModel/System/IdentityModel/Tokens/X509AsymmetricSecurityKey.cs#L54
     if (rsa != null && rsa.CspKeyContainerInfo.ProviderType == 1)
     {
         if (Trace.ShouldTrace(TraceEventType.Verbose))
         {
             Trace.TraceData(TraceEventType.Verbose,
                             "Changed provider type from " + rsa.CspKeyContainerInfo.ProviderType + " to 24");
         }
         CspParameters csp = new CspParameters();
         csp.ProviderType     = 24;
         csp.KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName;
         csp.KeyNumber        = (int)rsa.CspKeyContainerInfo.KeyNumber;
         if (rsa.CspKeyContainerInfo.MachineKeyStore)
         {
             csp.Flags = CspProviderFlags.UseMachineKeyStore;
         }
         csp.Flags |= CspProviderFlags.UseExistingKey;
         rsa        = new RSACryptoServiceProvider(csp);
     }
     return(rsa);
 }