Ejemplo n.º 1
0
        public static LinkIDAuthnResponse parse(ResponseType response)
        {
            String userId = null;
            Dictionary <String, List <LinkIDAttribute> > attributes = new Dictionary <string, List <LinkIDAttribute> >();

            foreach (object item in response.Items)
            {
                AssertionType assertion = (AssertionType)item;
                SubjectType   subject   = assertion.Subject;
                NameIDType    nameId    = (NameIDType)subject.Items[0];
                userId = nameId.Value;

                foreach (StatementAbstractType statement in assertion.Items)
                {
                    if (statement is AttributeStatementType)
                    {
                        AttributeStatementType attributeStatement = (AttributeStatementType)statement;
                        attributes = getAttributes(attributeStatement);
                    }
                }
            }

            LinkIDPaymentResponse      paymentResponse      = findPaymentResponse(response);
            LinkIDExternalCodeResponse externalCodeResponse = findExternalCodeResponse(response);

            return(new LinkIDAuthnResponse(userId, attributes, paymentResponse, externalCodeResponse));
        }
Ejemplo n.º 2
0
        private static ICollection <Claim> BuildClaims(AssertionType assertion)
        {
            var claims = new List <Claim>();
            var nameId = assertion.Subject.Items.FirstOrDefault(i => i is NameIDType) as NameIDType;

            if (nameId != null)
            {
                claims.Add(new Claim(ClaimTypes.NameIdentifier, nameId.Value));
            }

            if (assertion.Items != null)
            {
                var attributeStatement = assertion.Items.FirstOrDefault(i => i is AttributeStatementType) as AttributeStatementType;
                if (attributeStatement != null)
                {
                    var attributes = attributeStatement.Items.Where(i => i is AttributeType).Cast <AttributeType>();
                    foreach (var attribute in attributes)
                    {
                        string name = attribute.Name;
                        if (MappingSamlAttributeToClaim.ContainsKey(attribute.Name))
                        {
                            name = MappingSamlAttributeToClaim[attribute.Name];
                        }

                        foreach (var attributeValue in attribute.AttributeValue)
                        {
                            claims.Add(new Claim(name, attributeValue.ToString()));
                        }
                    }
                }
            }

            return(claims);
        }
Ejemplo n.º 3
0
 public static void ValidateAssertionAttributes(AssertionType assertion)
 {
     if (string.IsNullOrEmpty(assertion.Version))
     {
         throw new Exception("Assertion element must have Version attribute");
     }
     if (assertion.Version != "2.0")
     {
         throw new Exception("Application supports only Saml 2.0");
     }
     if (string.IsNullOrEmpty(assertion.ID))
     {
         throw new Exception("Assertion element must have ID attribute");
     }
     if (assertion.ID.Length < 16)
     {
         throw new Exception("Assertion ID length must be atleast 128 bits in length");
     }
     if (assertion.IssueInstant >= DateTime.UtcNow)
     {
         throw new Exception("Assertion issue instant must be prior to current instant");
     }
     if (assertion.Issuer.Value != "https://localhost:44351")
     {
         throw new Exception("Issuer is not valid");
     }
 }
 public CounterBenchmarkSetting(string counterName, AssertionType assertionType, Assertion assertion)
 {
     Contract.Requires(!string.IsNullOrEmpty(counterName));
     CounterName   = new CounterMetricName(counterName);
     AssertionType = assertionType;
     Assertion     = assertion;
 }
        private static void getAttributeValues(ResponseType response, Dictionary <String, List <LinkIDAttribute> > attributeMap)
        {
            if (null == response.Items || response.Items.Length == 0)
            {
                throw new RuntimeException("No assertions in response");
            }
            AssertionType assertion = (AssertionType)response.Items[0];

            if (null == assertion.Items || assertion.Items.Length == 0)
            {
                throw new RuntimeException("No statements in response assertion");
            }
            AttributeStatementType attributeStatement = (AttributeStatementType)assertion.Items[0];

            foreach (Object attributeObject in attributeStatement.Items)
            {
                AttributeType   attributeType = (AttributeType)attributeObject;
                LinkIDAttribute attribute     = Saml2AuthUtil.getAttribute(attributeType);

                List <LinkIDAttribute> attributes;
                if (!attributeMap.ContainsKey(attribute.attributeName))
                {
                    attributes = new List <LinkIDAttribute>();
                }
                else
                {
                    attributes = attributeMap[attribute.attributeName];
                }
                attributes.Add(attribute);
                attributeMap.Remove(attribute.attributeName);
                attributeMap.Add(attribute.attributeName, attributes);
            }
        }
Ejemplo n.º 6
0
        public AssertionData(AssertionType assertion)
        {
            // Find the attribute statement within the assertion
            AttributeStatementType ast = null;

            foreach (StatementAbstractType sat in assertion.Items)
            {
                if (sat.GetType().Equals(typeof(AttributeStatementType)))
                {
                    ast = (AttributeStatementType)sat;
                }
            }

            if (ast == null)
            {
                throw new ApplicationException("Invalid SAML Assertion: Missing Attribute Values");
            }

            SAMLAttributes = new Dictionary <string, string>();

            // Do what needs to be done to pull specific attributes out for sending on
            // For now assuming this is a simple list of string key and string values

            foreach (AttributeType at in ast.Items)
            {
                SAMLAttributes.Add(at.Name, ((XmlNode[])at.AttributeValue[0])[1].Value);
            }
        }
Ejemplo n.º 7
0
 public Assertion(string description, string value, AssertionType assertionType, AssertionMethod assertionMethod)
 {
     Description     = description;
     Value           = value;
     AssertionType   = assertionType;
     AssertionMethod = assertionMethod;
 }
Ejemplo n.º 8
0
        internal static void InvokeAssertionGreater <T>(AssertionType assertionType, T lhs, T rhs, string lhsText,
                                                        string rhsText, string functionName, string fileName, int lineNumber) where T : IComparable <T>
        {
            string message =
                string.Format("{0} must be greater than {1}.\nThe actual values are as follows.\n{0}: {2}\n{1}: {3}",
                              lhsText, rhsText, lhs, rhs);

            Assert.OnAssertionFailure(assertionType, "Greater", functionName, fileName, lineNumber, message);
        }
Ejemplo n.º 9
0
        internal static void InvokeAssertionAligned(AssertionType assertionType, ulong value, int alignment,
                                                    string valueText, string alignmentText, string functionName, string fileName, int lineNumber)
        {
            string message =
                string.Format("{0} must be {1}-bytes aligned.\nThe actual values are as follows.\n{0}: {2}\n{1}: {3}",
                              valueText, alignmentText, value, alignment);

            Assert.OnAssertionFailure(assertionType, "Aligned", functionName, fileName, lineNumber, message);
        }
Ejemplo n.º 10
0
        internal static void InvokeAssertionInRange(AssertionType assertionType, int value, int lower, int upper,
                                                    string valueText, string lowerText, string upperText, string functionName, string fileName, int lineNumber)
        {
            string message =
                string.Format(
                    "{0} must be within the range [{1}, {2})\nThe actual values are as follows.\n{0}: {3}\n{1}: {4}\n{2}: {5}",
                    valueText, lowerText, upperText, value, lower, upper);

            Assert.OnAssertionFailure(assertionType, "RangeCheck", functionName, fileName, lineNumber, message);
        }
Ejemplo n.º 11
0
        internal static void InvokeAssertionWithinMinMax(AssertionType assertionType, long value, long min, long max,
                                                         string valueText, string minText, string maxText, string functionName, string fileName, int lineNumber)
        {
            string message =
                string.Format(
                    "{0} must satisfy the condition min:{1} and max:{2}\nThe actual values are as follows.\n{0}: {3}\n{1}: {4}\n{2}: {5}",
                    valueText, minText, maxText, value, min, max);

            Assert.OnAssertionFailure(assertionType, "MinMaxCheck", functionName, fileName, lineNumber, message);
        }
Ejemplo n.º 12
0
        /*[Test]
         * [Ignore("")]
         * public void TestSosiGWExchangeViaApi2()
         * {
         *  var sc = SealCard.Create(MakeAssertion());
         *  using (var stsClient = new SosiGwCardClient("SosiGW"))
         *  {
         *      var d = stsClient.ExchangeAssertion(sc, "http://sundhed.dk/") as GenericXmlSecurityToken;
         *      var elm = d.TokenXml;
         *  }
         * }*/

        private static Security MakeSecurity(AssertionType assertion)
        {
            return(new Security
            {
                id = Guid.NewGuid().ToString("D"),
                Timestamp = new Timestamp {
                    Created = DateTimeEx.UtcNowRound - TimeSpan.FromMinutes(5)
                },
                Assertion = assertion
            });
        }
Ejemplo n.º 13
0
        private AssertionType GetAssertionFromXMLDoc(XmlDocument SAMLXML)
        {
            XmlNamespaceManager ns = new XmlNamespaceManager(SAMLXML.NameTable);

            ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            XmlElement xeAssertion = SAMLXML.DocumentElement.SelectSingleNode("saml:Assertion", ns) as XmlElement;

            XmlSerializer serializer = new XmlSerializer(typeof(AssertionType));
            AssertionType assertion  = (AssertionType)serializer.Deserialize(new XmlNodeReader(xeAssertion));

            return(assertion);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Add an assertion.
        /// </summary>
        /// <param name="callback"></param>
        /// <returns></returns>
        public SamlResponseBuilder AddAssertion(Action <AssertionBuilder> callback)
        {
            var assertion = new AssertionType
            {
                Version      = Constants.SamlVersion,
                ID           = $"assertion_{Guid.NewGuid()}",
                IssueInstant = DateTime.UtcNow
            };
            var builder = new AssertionBuilder(assertion);

            callback(builder);
            _response.Items = _response.Items.Add(assertion);
            return(this);
        }
Ejemplo n.º 15
0
 public static void ValidateAssertion(AssertionType assertion, ServiceProviderModel serviceProvider)
 {
     try
     {
         SamlValidationHelper.ValidateAssertionAttributes(assertion);
         SamlValidationHelper.ValidateSubject(assertion.Subject, serviceProvider);
         SamlValidationHelper.ValidateConditions(assertion.Conditions, serviceProvider);
         SamlValidationHelper.ValidateStatements(assertion.Items, serviceProvider);
     }
     catch (Exception ex)
     {
         throw new Exception("Authentication failed", ex);
     }
 }
Ejemplo n.º 16
0
        public (string, string) GetUsernameAndAuthIdFromBase64EncodedString(StringValues base64EncodedResponse)
        {
            string       decodedResponse = SecurityHelper.DecodeFromBase64(base64EncodedResponse);
            XmlDocument  xmlResponseWithEncryptedAssertion = SamlHelper.GetXmlFromString(decodedResponse);
            ResponseType responseWithEncryptedAssertion    = SamlHelper.ConvertXmlToModel <ResponseType>(xmlResponseWithEncryptedAssertion);

            SamlValidationHelper.VerifyResponse(responseWithEncryptedAssertion);

            XmlDocument   xmlAssertion = SecurityHelper.DecryptAssertion(xmlResponseWithEncryptedAssertion);
            AssertionType assertion    = SamlHelper.ConvertXmlToModel <AssertionType>(xmlAssertion);

            SamlValidationHelper.ValidateAssertion(assertion, _serviceProvider.Value);

            return(SamlHelper.Username, SamlHelper.AuthnRequestID);
        }
            public AssertionData(AssertionType assertion)
            {
                // Find the attribute statement within the assertion
                AttributeStatementType ast = null;

                foreach (StatementAbstractType sat in assertion.Items)
                {
                    if (sat.GetType().Equals(typeof(AttributeStatementType)))
                    {
                        ast = (AttributeStatementType)sat;
                    }
                }

                if (ast == null)
                {
                    throw new ApplicationException("Invalid SAML Assertion: Missing Attribute Values");
                }

                SAMLAttributes = new Dictionary <string, string>();

                // Do what needs to be done to pull specific attributes out for sending on
                // For now assuming this is a simple list of string key and string values
                foreach (AttributeType at in ast.Items)
                {
                    SAMLAttributes.Add(at.Name, at.AttributeValue.ToString());
                    //switch (at.Name)
                    //{
                    //    case "UserID":
                    //        if (at.AttributeValue.Length > 0) UserID = at.AttributeValue[0].ToString();
                    //        break;
                    //    case "UserFirstName":
                    //        if (at.AttributeValue.Length > 0) UserFirstName = int.Parse(at.AttributeValue[0].ToString());
                    //        break;
                    //    case "UserLastName":
                    //        if (at.AttributeValue.Length > 0) UserLastName = at.AttributeValue[0].ToString();
                    //        break;
                    //    case "UserDisplayName":
                    //        if (at.AttributeValue.Length > 0) UserDisplayName = at.AttributeValue[0].ToString();
                    //        break;
                    //    case "UserEmail":
                    //        if (at.AttributeValue.Length > 0) UserEmail = at.AttributeValue[0].ToString();
                    //        break;
                    //    case "GroupID":
                    //        if (at.AttributeValue.Length > 0) GroupID = int.Parse(at.AttributeValue[0].ToString());
                    //        break;
                    //}
                }
            }
Ejemplo n.º 18
0
        /// <summary>
        /// Checks whether the issuer of the SAML is trusted and whether the user is known and authenticated successfully.
        /// </summary>
        private bool TokenValid(string samlXML, out string username)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ResponseType));
            ResponseType  response   = (ResponseType)serializer.Deserialize(new StringReader(samlXML));

            bool issuerTrusted = trustedSAMLIdProviders.Contains(response.Issuer.Value);
            bool statusSuccess = response.Status.StatusCode.Value.Equals("urn:oasis:names:tc:SAML:2.0:status:Success");
            bool userIsKnown   = false;

            username = null;

            //Find assertion
            AssertionType assertion = null;

            foreach (var item in response.Items)
            {
                if (item is AssertionType)
                {
                    assertion = item as AssertionType;
                }
            }

            //Find the username
            if (assertion != null)
            {
                foreach (var item in assertion.Subject.Items)
                {
                    if (item is NameIDType)
                    {
                        if (!string.IsNullOrEmpty(((NameIDType)item).Value))
                        {
                            userIsKnown = federatedUsers.Contains(((NameIDType)item).Value);
                            username    = ((NameIDType)item).Value;
                        }
                    }
                }
            }

            if (issuerTrusted && statusSuccess && userIsKnown)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            switch (context.Request.HttpMethod)
            {
            case "POST":
                // Checking to verify that a SAML Assertion is included
                if (context.Request.Params["SAMLResponse"] == null)
                {
                    context.Response.Redirect("ServiceProviderError.aspx");
                }

                // Checking for the intended resource
                if (context.Request.Params["RelayState"] == null)
                {
                    context.Response.Redirect("ServiceProviderError.aspx");
                }

                // pull Base 64 encoded XML saml assertion from Request and decode it
                XmlDocument SAMLXML            = new XmlDocument();
                String      SAMLResponseString = System.Text.Encoding.UTF8.GetString(
                    Convert.FromBase64String(context.Request.Params["SAMLResponse"].ToString()));
                SAMLXML.LoadXml(SAMLResponseString);

                // Validate X509 Certificate Signature
                if (!ValidateX509CertificateSignature(SAMLXML))
                {
                    context.Response.Redirect("ServiceProviderError.aspx");
                }

                // Finding
                AssertionType assertion = GetAssertionFromXMLDoc(SAMLXML);
                if (assertion.Issuer.Value == ConfigurationManager.AppSettings["CertIssuer"])
                {
                    AssertionData SSOData = new AssertionData(assertion);
                }

                // At this point any specific work that needs to be done to establish user context with
                // the SSOData should be executed before redirecting the user browser to the target
                context.Response.Redirect(context.Request.Params["RelayState"].ToString());

                break;
            }
        }
        private static string GetExceptionMessage(AssertionType assertion, string[] affectedParameterNames)
        {
            string format = null;

            switch (assertion)
            {
            case AssertionType.AssertNotNull:
                format = Properties.Resources.AssertionFailedExceptionNotNull;
                break;

            case AssertionType.AssertNotEmpty:
                format = Properties.Resources.AssertionFailedExceptionNotEmpty;
                break;

            case AssertionType.Invalid:
            default:
                format = Properties.Resources.AssertionFailedGenericMessage;
                break;
            }

            return(string.Format(format, affectedParameterNames));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssertionFailedException"/> class.
 /// </summary>
 /// <param name="assertion">Type of the assertion.</param>
 /// <param name="affectedParameterNames">The affected parameter names.</param>
 public AssertionFailedException(AssertionType assertion, string[] affectedParameterNames)
     : this(Properties.Resources.AssertionFailedGenericMessage, assertion, affectedParameterNames)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssertionFailedException"/> class.
 /// </summary>
 /// <param name="message">The message to display if the assertion has failed.</param>
 /// <param name="assertion">Type of the assertion.</param>
 /// <param name="affectedParameterNames">The affected parameter names.</param>
 public AssertionFailedException(string message, AssertionType assertion, string[] affectedParameterNames)
     : base(message)
 {
     this.Assertion = assertion;
     this.AffectedParameterNames = affectedParameterNames;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssertionFailedException"/> class.
 /// </summary>
 /// <param name="assertion">Type of the assertion.</param>
 /// <param name="affectedParameterNames">The affected parameter names.</param>
 public AssertionFailedException(AssertionType assertion, string[] affectedParameterNames)
     : this(Properties.Resources.AssertionFailedGenericMessage, assertion, affectedParameterNames)
 {
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Creates a SAML 2.0 Assertion Segment for a Response
        /// Simple implmenetation assuming a list of string key and value pairs
        /// </summary>
        /// <param name="Issuer"></param>
        /// <param name="AssertionExpirationMinutes"></param>
        /// <param name="Audience"></param>
        /// <param name="Subject"></param>
        /// <param name="Recipient"></param>
        /// <param name="Attributes">Dictionary of string key, string value pairs</param>
        /// <returns>Assertion to sign and include in Response</returns>
        private static AssertionType CreateSAML20Assertion(string Issuer,
                                                           int AssertionExpirationMinutes,
                                                           string Audience,
                                                           string Subject,
                                                           string Recipient,
                                                           Dictionary <string, string> Attributes)
        {
            AssertionType NewAssertion = new AssertionType()
            {
                Version      = "2.0",
                IssueInstant = DateTime.Now,//DateTime.UtcNow,
                ID           = "_" + System.Guid.NewGuid().ToString()
            };

            // Create Issuer
            NewAssertion.Issuer = new NameIDType()
            {
                Value = Issuer.Trim()
            };

            // Create Assertion Subject
            SubjectType subject = new SubjectType();
            NameIDType  subjectNameIdentifier = new NameIDType()
            {
                Value = Subject.Trim(), Format = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
            };
            SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType()
            {
                Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer", SubjectConfirmationData = new SubjectConfirmationDataType()
                {
                    NotOnOrAfter = DateTime.Now.AddMinutes(AssertionExpirationMinutes), Recipient = Recipient
                }
            };                                                                                                                                                                                                                                                                                           //{ NotOnOrAfter = DateTime.UtcNow.AddMinutes(AssertionExpirationMinutes), Recipient = Recipient } };

            subject.Items        = new object[] { subjectNameIdentifier, subjectConfirmation };
            NewAssertion.Subject = subject;

            // Create Assertion Conditions
            ConditionsType conditions = new ConditionsType();

            conditions.NotBefore             = DateTime.Now;                                        //DateTime.UtcNow;
            conditions.NotBeforeSpecified    = true;
            conditions.NotOnOrAfter          = DateTime.Now.AddMinutes(AssertionExpirationMinutes); //DateTime.UtcNow.AddMinutes(AssertionExpirationMinutes);
            conditions.NotOnOrAfterSpecified = true;
            conditions.Items = new ConditionAbstractType[] { new AudienceRestrictionType()
                                                             {
                                                                 Audience = new string[] { Audience.Trim() }
                                                             } };
            NewAssertion.Conditions = conditions;

            // Add AuthnStatement and Attributes as Items
            AuthnStatementType authStatement = new AuthnStatementType()
            {
                AuthnInstant = DateTime.Now, SessionIndex = NewAssertion.ID
            };                                                                                                                           //{ AuthnInstant = DateTime.UtcNow, SessionIndex = NewAssertion.ID };
            AuthnContextType context = new AuthnContextType();

            context.ItemsElementName   = new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef };
            context.Items              = new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified" };
            authStatement.AuthnContext = context;

            AttributeStatementType attributeStatement = new AttributeStatementType();

            attributeStatement.Items = new AttributeType[Attributes.Count];
            int i = 0;

            foreach (KeyValuePair <string, string> attribute in Attributes)
            {
                attributeStatement.Items[i] = new AttributeType()
                {
                    Name           = attribute.Key,
                    AttributeValue = new object[] { attribute.Value },
                    NameFormat     = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
                };
                i++;
            }

            NewAssertion.Items = new StatementAbstractType[] { authStatement, attributeStatement };

            return(NewAssertion);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Creates a Version 1.1 Saml Assertion
        /// </summary>
        /// <param name="issuer">Issuer</param>
        /// <param name="subject">Subject</param>
        /// <param name="attributes">Attributes</param>
        /// <returns>returns a Version 1.1 Saml Assertion</returns>
        private static AssertionType CreateSamlAssertion(string issuer, string recipient, string domain, string subject, Dictionary <string, string> attributes)
        {
            // Here we create some SAML assertion with ID and Issuer name.
            AssertionType assertion = new AssertionType();

            assertion.ID = "_" + Guid.NewGuid().ToString();

            NameIDType issuerForAssertion = new NameIDType();

            issuerForAssertion.Value = issuer.Trim();

            assertion.Issuer  = issuerForAssertion;
            assertion.Version = "2.0";

            assertion.IssueInstant = System.DateTime.UtcNow;

            //Not before, not after conditions
            ConditionsType conditions = new ConditionsType();

            conditions.NotBefore             = DateTime.UtcNow;
            conditions.NotBeforeSpecified    = true;
            conditions.NotOnOrAfter          = DateTime.UtcNow.AddMinutes(5);
            conditions.NotOnOrAfterSpecified = true;

            AudienceRestrictionType audienceRestriction = new AudienceRestrictionType();

            audienceRestriction.Audience = new string[] { domain.Trim() };

            conditions.Items = new ConditionAbstractType[] { audienceRestriction };

            //Name Identifier to be used in Saml Subject
            NameIDType nameIdentifier = new NameIDType();

            nameIdentifier.NameQualifier = domain.Trim();
            nameIdentifier.Value         = subject.Trim();

            SubjectConfirmationType     subjectConfirmation     = new SubjectConfirmationType();
            SubjectConfirmationDataType subjectConfirmationData = new SubjectConfirmationDataType();

            subjectConfirmation.Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer";
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            //
            // Create some SAML subject.
            SubjectType samlSubject = new SubjectType();

            AttributeStatementType attrStatement = new AttributeStatementType();
            AuthnStatementType     authStatement = new AuthnStatementType();

            authStatement.AuthnInstant = DateTime.UtcNow;
            AuthnContextType context = new AuthnContextType();

            context.ItemsElementName   = new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef };
            context.Items              = new object[] { "AuthnContextClassRef" };
            authStatement.AuthnContext = context;

            samlSubject.Items = new object[] { nameIdentifier, subjectConfirmation };

            assertion.Subject = samlSubject;

            IPHostEntry ipEntry =
                Dns.GetHostEntry(System.Environment.MachineName);

            SubjectLocalityType subjectLocality = new SubjectLocalityType();

            subjectLocality.Address = ipEntry.AddressList[0].ToString();

            attrStatement.Items = new AttributeType[attributes.Count];
            int i = 0;

            // Create userName SAML attributes.
            foreach (KeyValuePair <string, string> attribute in attributes)
            {
                AttributeType attr = new AttributeType();
                attr.Name              = attribute.Key;
                attr.NameFormat        = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic";
                attr.AttributeValue    = new object[] { attribute.Value };
                attrStatement.Items[i] = attr;
                i++;
            }
            assertion.Conditions = conditions;

            assertion.Items = new StatementAbstractType[] { authStatement, attrStatement };

            return(assertion);
        }
Ejemplo n.º 26
0
 internal static void InvokeAssertionNotNull(AssertionType assertionType, string valueText, string functionName,
                                             string fileName, int lineNumber)
 {
     Assert.OnAssertionFailure(assertionType, "NotNull", functionName, fileName, lineNumber,
                               $"{valueText} must not be nullptr.");
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssertionFailedException"/> class.
 /// </summary>
 /// <param name="message">The message to display if the assertion has failed.</param>
 /// <param name="assertion">Type of the assertion.</param>
 /// <param name="affectedParameterNames">The affected parameter names.</param>
 public AssertionFailedException(string message, AssertionType assertion, string[] affectedParameterNames)
     : base(message)
 {
     this.Assertion = assertion;
     this.AffectedParameterNames = affectedParameterNames;
 }
        private static string GetExceptionMessage(AssertionType assertion, string[] affectedParameterNames)
        {
            string format=null;
            switch (assertion)
            {
                case AssertionType.AssertNotNull:
                    format= Properties.Resources.AssertionFailedExceptionNotNull;
                    break;
                case AssertionType.AssertNotEmpty:
                    format= Properties.Resources.AssertionFailedExceptionNotEmpty;
                    break;
                case AssertionType.Invalid:
                default:
                    format= Properties.Resources.AssertionFailedGenericMessage;
                    break;
            }

            return string.Format(format, affectedParameterNames);
        }
 public AssertionBehavior(AssertionType type, bool inversion)
 {
     Type      = type;
     Inversion = inversion;
 }
Ejemplo n.º 30
0
        /// <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 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();

            // 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;

            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 = SamlHelper.CreateSamlAssertion(
                issuer.Trim(), recipient.Trim(), domain.Trim(), subject.Trim(), attributes);

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

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

            samlString = stringWriter.ToString();

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

            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);
                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, "ID",
                                      (signatureType == SigningHelper.SignatureType.Response || signatureType == SigningHelper.SignatureType.TestVU475445) ? response.ID : assertionType.ID);

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

            if (SamlHelper.Logger.IsDebugEnabled)
            {
                SamlHelper.Logger.DebugFormat(
                    "Saml Assertion before encoding = {0}",
                    doc.OuterXml.ToString());
            }

            string responseStr = doc.OuterXml;

            // 2018Ma06 Special Post-signature Maniuplation postsignature to inject comment into subject.
            if (signatureType == SigningHelper.SignatureType.TestVU475445)
            {
                string sub        = subject.Trim();
                int    half       = sub.Length / 2;
                string firstHalf  = sub.Substring(0, half);
                string secondHalf = sub.Substring(half);
                responseStr = responseStr.Replace(sub, firstHalf + "<!--VU475445-->" + secondHalf);
                int breaker = 1;
            }


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

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

            return(returnValue);
        }
		public void AssertElement(AssertionType type, String assertion, HtmlElement element)
		{
			startSWATFixtureIfNotInOne();
			//_assertion = "|AssertElementExists|expression|" + assertionBox.Text + "|" + _srcElement.tagName + "|";
			switch (type)
			{
				case AssertionType.ElementExists:
					_sb.Append("|AssertElementExists|Expression|");
					break;
				case AssertionType.ElementDoesNotExist:
					_sb.Append("|AssertElementDoesNotExist|Expression|");
					break;
			}
            //assertion = replaceSpecialCharacters(assertion);
			_sb.Append(assertion + "|" + element.TagName + "|");
			writeCommand(getStringBuilderValueAndReset());
		}
Ejemplo n.º 32
0
    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);
    }
 private void okButton_Click(object sender, EventArgs e)
 {
     _assertion = assertionBox.Text;
     _assertionType = assertExistButton.Checked ? AssertionType.ElementExists : AssertionType.ElementDoesNotExist;         
 }
Ejemplo n.º 34
0
 //A state can be a lookbehind start
 public ENFA_LookbehindStart(ENFA_Controller controller, AssertionType assertionType, ENFA_GroupingStart parent) : base(controller, parent)
 {
     _assertionType = assertionType;
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Handles the sign in.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="SecurityTokenException">No token validator was found for the given token.</exception>
        private async Task <HandleRequestResult> HandleSignIn()
        {
            if (Request.Method != HttpMethods.Post)
            {
                return(HandleRequestResult.Fail("Request method must be an HTTP-Post Method"));
            }

            var form = await Request.ReadFormAsync();

            var response   = form[Saml2Constants.Parameters.SamlResponse];
            var relayState = form[Saml2Constants.Parameters.RelayState].ToString()?.DeflateDecompress();

            AuthenticationProperties authenticationProperties = Options.StateDataFormat.Unprotect(relayState);

            try
            {
                if (authenticationProperties == null)
                {
                    if (!Options.AllowUnsolicitedLogins)
                    {
                        return(HandleRequestResult.Fail("Unsolicited logins are not allowed."));
                    }
                }

                if (authenticationProperties.Items.TryGetValue(CorrelationProperty, out string correlationId) &&
                    !ValidateCorrelationId(authenticationProperties))
                {
                    return(HandleRequestResult.Fail("Correlation failed.", authenticationProperties));
                }

                string       base64EncodedSamlResponse = response;
                ResponseType idpSamlResponseToken      = _saml2Service.GetSamlResponseToken(base64EncodedSamlResponse, Saml2Constants.ResponseTypes.AuthnResponse, Options);

                IRequestCookieCollection cookies = Request.Cookies;
                string originalSamlRequestId     = cookies[cookies.Keys.FirstOrDefault(key => key.StartsWith(Options.AuthenticationScheme))];

                _saml2Service.CheckIfReplayAttack(idpSamlResponseToken.InResponseTo, originalSamlRequestId);
                _saml2Service.CheckStatus(idpSamlResponseToken);

                string token = _saml2Service.GetAssertion(idpSamlResponseToken, Options);

                AssertionType assertion     = new AssertionType();
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(AssertionType));
                using (MemoryStream memStm = new MemoryStream(Encoding.UTF8.GetBytes(token)))
                {
                    assertion = (AssertionType)xmlSerializer.Deserialize(memStm);
                }

                if (Options.WantAssertionsSigned)
                {
                    var doc = new XmlDocument
                    {
                        XmlResolver        = null,
                        PreserveWhitespace = true
                    };
                    doc.LoadXml(token);

                    if (!_saml2Service.ValidateX509CertificateSignature(doc, Options))
                    {
                        throw new Exception("Assertion signature is not valid");
                    }
                }

                AuthnStatementType session = new AuthnStatementType();

                if (assertion.Items.Any(x => x.GetType() == typeof(AuthnStatementType)))
                {
                    session = (AuthnStatementType)assertion.Items.FirstOrDefault(x => x.GetType() == typeof(AuthnStatementType));
                }

                if (assertion.Subject.Items.Any(x => x.GetType() == typeof(NameIDType)))
                {
                    Options.NameIDType = (NameIDType)assertion.Subject.Items.FirstOrDefault(x => x.GetType() == typeof(NameIDType));
                }

                if (_configuration == null)
                {
                    _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
                }

                var             tvp         = Options.TokenValidationParameters.Clone();
                var             validator   = Options.Saml2SecurityTokenHandler;
                ClaimsPrincipal principal   = null;
                SecurityToken   parsedToken = null;

                var issuers = new[] { _configuration.Issuer };
                tvp.ValidateIssuerSigningKey = Options.WantAssertionsSigned;
                tvp.ValidateTokenReplay      = !Options.IsPassive;
                tvp.ValidateIssuer           = true;
                tvp.ValidateAudience         = true;
                tvp.ValidIssuers             = (tvp.ValidIssuers == null ? issuers : tvp.ValidIssuers.Concat(issuers));
                tvp.IssuerSigningKeys        = (tvp.IssuerSigningKeys == null ? _configuration.SigningKeys : tvp.IssuerSigningKeys.Concat(_configuration.SigningKeys));

                if (!Options.WantAssertionsSigned) // in case they aren't signed
                {
                    tvp.RequireSignedTokens = false;
                }

                if (validator.CanReadToken(token))
                {
                    principal = validator.ValidateToken(token, tvp, out parsedToken);
                }

                if (principal == null)
                {
                    throw new SecurityTokenException("No token validator was found for the given token.");
                }

                if (Options.UseTokenLifetime && parsedToken != null)
                {
                    // Override any session persistence to match the token lifetime.
                    var issued = parsedToken.ValidFrom;
                    if (issued != DateTime.MinValue)
                    {
                        authenticationProperties.IssuedUtc = issued.ToUniversalTime();
                    }
                    var expires = parsedToken.ValidTo;
                    if (expires != DateTime.MinValue)
                    {
                        authenticationProperties.ExpiresUtc = expires.ToUniversalTime();
                    }
                    authenticationProperties.AllowRefresh = false;
                }

                ClaimsIdentity identity = new ClaimsIdentity(principal.Claims, Scheme.Name);

                session.SessionIndex = !String.IsNullOrEmpty(session.SessionIndex) ? session.SessionIndex : assertion.ID;
                //get the session index from assertion so you can use it to logout later
                identity.AddClaim(new Claim(Saml2ClaimTypes.SessionIndex, session.SessionIndex));
                identity.AddClaim(new Claim(ClaimTypes.Name, principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value));

                string redirectUrl = !string.IsNullOrEmpty(authenticationProperties.RedirectUri) ? authenticationProperties.RedirectUri : Options.CallbackPath.ToString();
                Context.Response.Redirect(redirectUrl, true);
                Context.User = new ClaimsPrincipal(identity);
                await Context.SignInAsync(Options.SignInScheme, Context.User, authenticationProperties);

                return(HandleRequestResult.Success(new AuthenticationTicket(Context.User, authenticationProperties, Scheme.Name)));
            }
            catch (Exception exception)
            {
                return(HandleRequestResult.Fail(exception, authenticationProperties));
            }
        }