Example #1
0
        private void WriteResponse(HttpContext context, string destination, ResponseType responseSAML, string relayState)
        {
            try
            {
                // That UrlEncode should be used to encode only un-trusted values used within URLs such
                // as in query string values. If the URL itself is the source of un-trusted input, then
                // input validation with regular expressions should be used.
                // Fonte: Microsoft Anti-Cross Site Scripting Library V1.5 - User Guide, p-10.
                Regex regex = new Regex(@"^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+=&%\$#_]*)?$", RegexOptions.IgnoreCase);
                if (!regex.IsMatch(destination))
                {
                    throw new ValidationException("A url contém um valor de entrada possivelmente perigoso, que pode indicar uma tentativa de comprometer a segurança do aplicativo.");
                }

                string samlResponse = SAMLUtility.SerializeToXmlString(responseSAML);
                samlResponse = HttpUtility.UrlEncode(samlResponse);
                string data = string.Format("SAMLResponse={0}&RelayState={1}", samlResponse, relayState);
                retorno.UrlRedirect      = destination;
                retorno.UrlRedirectParam = data;
                UtilBO.MessageJSON(context.Response.Output, retorno);
            }
            catch
            {
                throw;
            }
        }
Example #2
0
        private void CreateSAMLResponse()
        {
            IDProvider config = IDProvider.GetConfig();

            SAMLResponse.ID           = SAMLUtility.GenerateID();
            SAMLResponse.Version      = SAMLUtility.VERSION;
            SAMLResponse.IssueInstant = DateTime.UtcNow.AddMinutes(10);
            SAMLResponse.InResponseTo = SAMLRequest.ID;

            SAMLResponse.Issuer       = new NameIDType();
            SAMLResponse.Issuer.Value = config.id;

            SAMLResponse.Status            = new StatusType();
            SAMLResponse.Status.StatusCode = new StatusCodeType();

            // Atualiza Cookie de sistemas autenticados e configura Status
            HttpCookie cookie = this.Context.Request.Cookies["SistemasLogged"];

            if (cookie != null)
            {
                // Carrega a Entidade SYS_Sistema apartir do caminho de logout
                SYS_Sistema entitySistema = new SYS_Sistema {
                    sis_caminhoLogout = ((NameIDType)SAMLRequest.Item).Value
                };
                if (SYS_SistemaBO.GetSelectBy_sis_caminho(entitySistema, SYS_SistemaBO.TypePath.logout))
                {
                    // Remove o sistema do Cookie
                    cookie.Values.Remove(entitySistema.sis_id.ToString());
                    // Atualiza dados do Cookie
                    this.Context.Response.Cookies.Set(cookie);

                    if (!cookie.Values.AllKeys.Contains(entitySistema.sis_id.ToString()))
                    {
                        SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.Success;
                        SAMLResponse.Status.StatusMessage    = "A solicitação foi realizada com sucesso.";
                    }
                    else
                    {
                        SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.RequestDenied;
                        SAMLResponse.Status.StatusMessage    = "Não foi possível atender a solicitação, o sistema emissor da requisição não está autenticado.";
                    }
                }
                else
                {
                    SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.RequestDenied;
                    SAMLResponse.Status.StatusMessage    = "Não foi possível atender a solicitação, sistema emissor da requisição não está cadastrado corretamente.";;
                }
            }
            else
            {
                SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.RequestDenied;
                SAMLResponse.Status.StatusMessage    = "Não foi possível atender a solicitação.";
            }

            HttpPostBinding binding = new HttpPostBinding(SAMLResponse, HttpUtility.UrlDecode(this.Context.Request[HttpBindingConstants.RelayState]));

            binding.SendResponse(this.Context, HttpUtility.UrlDecode(this.Context.Request[HttpBindingConstants.RelayState]), SAMLTypeSSO.logout);
        }
    private void CreateSAMLResponse()
    {
        FormsIdentity id = null;

        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    id = (FormsIdentity)HttpContext.Current.User.Identity;
                }
            }
        }

        DateTime notBefore    = (id != null ? id.Ticket.IssueDate.ToUniversalTime() : DateTime.UtcNow);
        DateTime notOnOrAfter = (id != null ? id.Ticket.Expiration.ToUniversalTime() : DateTime.UtcNow.AddMinutes(30));

        IDProvider config = IDProvider.GetConfig();

        SAMLResponse.Status                  = new StatusType();
        SAMLResponse.Status.StatusCode       = new StatusCodeType();
        SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.Success;

        AssertionType assert = new AssertionType();

        assert.ID           = SAMLUtility.GenerateID();
        assert.IssueInstant = DateTime.UtcNow.AddMinutes(10);

        assert.Issuer       = new NameIDType();
        assert.Issuer.Value = config.id;

        SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType();

        subjectConfirmation.Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer";
        subjectConfirmation.SubjectConfirmationData              = new SubjectConfirmationDataType();
        subjectConfirmation.SubjectConfirmationData.Recipient    = SAMLRequest.Issuer;
        subjectConfirmation.SubjectConfirmationData.InResponseTo = SAMLRequest.Request.ID;
        subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = notOnOrAfter;

        NameIDType nameID = new NameIDType();

        nameID.Format = SAMLUtility.NameIdentifierFormats.Transient;
        nameID.Value  = (id != null ? id.Name : UtilBO.FormatNameFormsAuthentication(this.__SessionWEB.__UsuarioWEB.Usuario));

        assert.Subject       = new SubjectType();
        assert.Subject.Items = new object[] { subjectConfirmation, nameID };

        assert.Conditions                       = new ConditionsType();
        assert.Conditions.NotBefore             = notBefore;
        assert.Conditions.NotOnOrAfter          = notOnOrAfter;
        assert.Conditions.NotBeforeSpecified    = true;
        assert.Conditions.NotOnOrAfterSpecified = true;

        AudienceRestrictionType audienceRestriction = new AudienceRestrictionType();

        audienceRestriction.Audience = new string[] { SAMLRequest.Issuer };
        assert.Conditions.Items      = new ConditionAbstractType[] { audienceRestriction };

        AuthnStatementType authnStatement = new AuthnStatementType();

        authnStatement.AuthnInstant = DateTime.UtcNow;
        authnStatement.SessionIndex = SAMLUtility.GenerateID();

        authnStatement.AuthnContext       = new AuthnContextType();
        authnStatement.AuthnContext.Items =
            new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" };

        authnStatement.AuthnContext.ItemsElementName =
            new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef };

        StatementAbstractType[] statementAbstract = new StatementAbstractType[] { authnStatement };
        assert.Items       = statementAbstract;
        SAMLResponse.Items = new object[] { assert };

        string xmlResponse = SAMLUtility.SerializeToXmlString(SAMLResponse);

        XmlDocument doc = new XmlDocument();

        doc.LoadXml(xmlResponse);
        XmlSignatureUtils.SignDocument(doc, assert.ID);
        SAMLResponse = SAMLUtility.DeserializeFromXmlString <ResponseType>(doc.InnerXml);

        HttpPostBinding binding = new HttpPostBinding(SAMLResponse, HttpUtility.UrlDecode(Request[HttpBindingConstants.RelayState]));

        binding.SendResponse(this.Context, HttpUtility.UrlDecode(SAMLRequest.AssertionConsumerServiceURL), SAMLTypeSSO.signon);
    }
Example #4
0
        public new void ProcessRequest(HttpContext context)
        {
            try
            {
                // ***** RESPONSE *****
                if (!String.IsNullOrEmpty(context.Request[HttpBindingConstants.SAMLResponse]))
                {
                    // Recupera Response
                    string      samlresponse = context.Request[HttpBindingConstants.SAMLResponse];
                    XmlDocument doc          = new XmlDocument();
                    doc.PreserveWhitespace = true;
                    doc.LoadXml(samlresponse);

                    // Verifica Signature do Response
                    if (XmlSignatureUtils.VerifySignature(doc))
                    {
                        SAMLResponse = SAMLUtility.DeserializeFromXmlString <ResponseType>(doc.InnerXml);
                        if (SAMLResponse.Items.Length > 0)
                        {
                            for (int i = 0; i < SAMLResponse.Items.Length; i++)
                            {
                                if (SAMLResponse.Items[i] is AssertionType)
                                {
                                    NameIDType    nameID    = null;
                                    AssertionType assertion = (AssertionType)SAMLResponse.Items[i];
                                    for (int j = 0; j < assertion.Subject.Items.Length; j++)
                                    {
                                        if (assertion.Subject.Items[j] is NameIDType)
                                        {
                                            nameID = (NameIDType)assertion.Subject.Items[j];
                                        }
                                    }
                                    if (nameID != null)
                                    {
                                        SignHelper.AutenticarUsuarioDaRespostaDoSaml(nameID.Value);
                                    }
                                }

                                // Armazena dados do sistema emissor do Request
                                // em Cookie de sistemas autenticados
                                AddSAMLCookie(context);
                            }
                        }
                        context.Response.Redirect(HttpUtility.UrlDecode(context.Request[HttpBindingConstants.RelayState]), false);
                    }
                    else
                    {
                        throw new ValidationException("Não foi possível encontrar assinatura.");
                    }
                }
                // ***** REQUEST *****
                else if (!String.IsNullOrEmpty(context.Request[HttpBindingConstants.SAMLRequest]))
                {
                    throw new NotImplementedException();
                }
                else
                {
                    // Carrega as configurações do ServiceProvider
                    ServiceProvider         config = ServiceProvider.GetConfig();
                    ServiceProviderEndpoint spend  = SAMLUtility.GetServiceProviderEndpoint(config.ServiceEndpoint, SAMLTypeSSO.signon);

                    // Verifica configuração do ServiceProvider para signon
                    if (spend == null)
                    {
                        throw new ValidationException("Não foi possível encontrar as configurações do ServiceProvider para signon.");
                    }

                    // Verifica se usuário está autenticado, caso não envia um Resquest solicitando autenticação
                    if (!UsuarioWebIsValid())
                    {
                        SAMLRequest        = new SAMLAuthnRequest();
                        SAMLRequest.Issuer = config.id;
                        SAMLRequest.AssertionConsumerServiceURL = context.Request.Url.AbsoluteUri;

                        HttpRedirectBinding binding = new HttpRedirectBinding(SAMLRequest, spend.localpath);
                        binding.SendRequest(context, spend.redirectUrl);
                    }
                    else
                    {
                        HttpContext.Current.Response.Redirect(spend.localpath, false);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                    }
                }
            }
            catch (ValidationException ex)
            {
                ErrorMessage(ex.Message);
            }
            catch (Exception ex)
            {
                ApplicationWEB._GravaErro(ex);

                ErrorMessage("Não foi possível atender a solicitação.");
            }
        }
Example #5
0
        public new void ProcessRequest(HttpContext context)
        {
            try
            {
                // ***** REQUEST *****
                if (!String.IsNullOrEmpty(context.Request[HttpBindingConstants.SAMLRequest]))
                {
                    // Recupera LogoutRequest
                    StringBuilder result = new StringBuilder();

                    byte[]       encoded      = Convert.FromBase64String(HttpUtility.UrlDecode(context.Request[HttpBindingConstants.SAMLRequest]).Replace(" ", "+"));
                    MemoryStream memoryStream = new MemoryStream(encoded);
                    using (DeflateStream stream = new DeflateStream(memoryStream, CompressionMode.Decompress))
                    {
                        StreamReader reader = new StreamReader(new BufferedStream(stream), Encoding.GetEncoding("iso-8859-1"));
                        reader.Peek();
                        result.Append(reader.ReadToEnd());
                        stream.Close();
                    }
                    SAMLRequest = SAMLUtility.DeserializeFromXmlString <LogoutRequestType>(result.ToString());

                    AtribuirSessionSisIDLogout(((NameIDType)SAMLRequest.Item).Value);

                    // Criação e configuração LogoutResponse
                    SAMLResponse = new ResponseType();
                    CreateSAMLResponse();
                }
                // ***** RESPONSE *****
                else if (!String.IsNullOrEmpty(context.Request[HttpBindingConstants.SAMLResponse]))
                {
                    throw new NotImplementedException();
                }
                else
                {
                    AtribuirSessionSisIDLogout(String.Concat(ApplicationWEB._DiretorioVirtual, "Logout.ashx"));

                    __SessionWEB.SistemasRequestLogout++;

                    //Se existir link de retorno na primeira vez, significa que o sistema que iniciou o processo de logout
                    //enviou na queryString o endereço que deve ser redirecionado após terminar todo o processo.
                    if (!String.IsNullOrEmpty(context.Request["SistemaUrlLogout"]) && __SessionWEB.SistemasRequestLogout == 1)
                    {
                        __SessionWEB.SistemaUrlLogout_QueryString = context.Request["SistemaUrlLogout"];
                    }

                    // Verifica se existe sistemas autenticados em Cookie para realizar logout
                    HttpCookie cookie = context.Request.Cookies["SistemasLogged"];
                    if (cookie != null &&
                        cookie.Values.AllKeys.Count(p => p != null) > 0)
                    {
                        SYS_Sistema entitySistema = SYS_SistemaBO.GetEntity(new SYS_Sistema {
                            sis_id = Convert.ToInt32(cookie.Values.AllKeys.First())
                        });
                        HttpContext.Current.Response.Redirect(entitySistema.sis_caminhoLogout, false);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                    }
                    else
                    {
                        HttpCookie cookieBH = context.Request.Cookies["BH"];
                        if (cookieBH != null &&
                            !String.IsNullOrEmpty(IdentitySettingsConfig.IDSSettings.LogoutUrlAVA))
                        {
                            HttpContext.Current.Response.Redirect(IdentitySettingsConfig.IDSSettings.LogoutUrlAVA, false);
                            HttpContext.Current.ApplicationInstance.CompleteRequest();
                        }
                        else
                        {
                            RedirecionarParaLogoutIdentityServer(context);
                        }
                    }
                }
            }
            catch (ValidationException ex)
            {
                ApplicationWEB._GravaErro(ex);
                //ErrorMessage(ex.Message);
                RedirecionarParaLogoutIdentityServer(context);
            }
            catch (Exception ex)
            {
                ApplicationWEB._GravaErro(ex);
                //ErrorMessage("Não foi possível atender a solicitação.");
                RedirecionarParaLogoutIdentityServer(context);
            }
        }