コード例 #1
0
        /// <summary>
        /// Creates the security token
        /// </summary>
        /// <param name="timeout">Maximum amount of time the method is supposed to take. Ignored in this implementation.</param>
        /// <returns>A SecurityToken corresponding the SAML assertion and proof key specified at construction time</returns>
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            // Create a SamlSecurityToken from the provided assertion
            SamlSecurityToken samlToken = new SamlSecurityToken(assertion);

            // Create a SecurityTokenSerializer that will be used to serialize the SamlSecurityToken
            WSSecurityTokenSerializer ser = new WSSecurityTokenSerializer();

            // Create a memory stream to write the serialized token into
            // Use an initial size of 64Kb
            MemoryStream s = new MemoryStream(UInt16.MaxValue);

            // Create an XmlWriter over the stream
            XmlWriter xw = XmlWriter.Create(s);

            // Write the SamlSecurityToken into the stream
            ser.WriteToken(xw, samlToken);

            // Seek back to the beginning of the stream
            s.Seek(0, SeekOrigin.Begin);

            // Load the serialized token into a DOM
            XmlDocument dom = new XmlDocument();

            dom.Load(s);

            // Create a KeyIdentifierClause for the SamlSecurityToken
            SamlAssertionKeyIdentifierClause samlKeyIdentifierClause = samlToken.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>();

            // Return a GenericXmlToken from the XML for the SamlSecurityToken, the proof token, the valid from
            // and valid until times from the assertion and the key identifier clause created above
            return(new GenericXmlSecurityToken(dom.DocumentElement, proofToken, assertion.Conditions.NotBefore, assertion.Conditions.NotOnOrAfter, samlKeyIdentifierClause, samlKeyIdentifierClause, null));
        }
コード例 #2
0
        private static void SerializeCachedToken(Stream stream, Uri target, Uri issuer, GenericXmlSecurityToken token)
        {
            XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.UTF8);

            xmlTextWriter.WriteStartElement("Entry");
            xmlTextWriter.WriteElementString("Target", target.AbsoluteUri);
            xmlTextWriter.WriteElementString("Issuer", (issuer == null) ? "" : issuer.AbsoluteUri);
            xmlTextWriter.WriteStartElement("Token");
            xmlTextWriter.WriteStartElement("XML");
            token.TokenXml.WriteTo(xmlTextWriter);
            xmlTextWriter.WriteEndElement();
            SymmetricSecurityKey symmetricSecurityKey = (SymmetricSecurityKey)token.SecurityKeys[0];

            xmlTextWriter.WriteElementString("Key", Convert.ToBase64String(symmetricSecurityKey.GetSymmetricKey()));
            xmlTextWriter.WriteElementString("Id", token.Id);
            xmlTextWriter.WriteElementString("ValidFrom", Convert.ToString(token.ValidFrom));
            xmlTextWriter.WriteElementString("ValidTo", Convert.ToString(token.ValidTo));
            WSSecurityTokenSerializer wssecurityTokenSerializer = new WSSecurityTokenSerializer();

            xmlTextWriter.WriteStartElement("InternalTokenReference");
            wssecurityTokenSerializer.WriteKeyIdentifierClause(xmlTextWriter, token.InternalTokenReference);
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteStartElement("ExternalTokenReference");
            wssecurityTokenSerializer.WriteKeyIdentifierClause(xmlTextWriter, token.ExternalTokenReference);
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.Flush();
            stream.Flush();
        }
コード例 #3
0
        private static void PopulateCache(Dictionary <IssuedTokenCacheBase.Key, GenericXmlSecurityToken> cache, Stream stream)
        {
            XmlTextReader xmlTextReader = new XmlTextReader(stream);

            while (xmlTextReader.IsStartElement("Entry"))
            {
                xmlTextReader.ReadStartElement();
                Uri    target = new Uri(xmlTextReader.ReadElementString("Target"));
                string text   = xmlTextReader.ReadElementString("Issuer");
                Uri    issuer = string.IsNullOrEmpty(text) ? null : new Uri(text);
                xmlTextReader.ReadStartElement("Token");
                xmlTextReader.ReadStartElement("XML");
                XmlDocument xmlDocument = new XmlDocument();
                XmlElement  tokenXml    = xmlDocument.ReadNode(xmlTextReader) as XmlElement;
                xmlTextReader.ReadEndElement();
                byte[] key = Convert.FromBase64String(xmlTextReader.ReadElementString("Key"));
                xmlTextReader.ReadElementString("Id");
                DateTime effectiveTime  = Convert.ToDateTime(xmlTextReader.ReadElementString("ValidFrom"));
                DateTime expirationTime = Convert.ToDateTime(xmlTextReader.ReadElementString("ValidTo"));
                WSSecurityTokenSerializer wssecurityTokenSerializer = new WSSecurityTokenSerializer();
                xmlTextReader.ReadStartElement("InternalTokenReference");
                SecurityKeyIdentifierClause internalTokenReference = wssecurityTokenSerializer.ReadKeyIdentifierClause(xmlTextReader);
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadStartElement("ExternalTokenReference");
                SecurityKeyIdentifierClause externalTokenReference = wssecurityTokenSerializer.ReadKeyIdentifierClause(xmlTextReader);
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadEndElement();
                List <IAuthorizationPolicy> list  = new List <IAuthorizationPolicy>();
                GenericXmlSecurityToken     value = new GenericXmlSecurityToken(tokenXml, new BinarySecretSecurityToken(key), effectiveTime, expirationTime, internalTokenReference, externalTokenReference, new ReadOnlyCollection <IAuthorizationPolicy>(list));
                cache.Add(new IssuedTokenCacheBase.Key(target, issuer), value);
            }
        }
コード例 #4
0
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            SecurityToken securityToken;
            SamlAssertion samlAssertion;

            if (base.TokenRequirement.KeyType == SecurityKeyType.SymmetricKey)
            {
                securityToken = SamlSecurityTokenProvider.CreateSymmetricProofToken(base.TokenRequirement.KeySize);
                samlAssertion = this.CreateSamlAssertionWithSymmetricKey((BinarySecretSecurityToken)securityToken);
            }
            else
            {
                if (base.TokenRequirement.KeyType != SecurityKeyType.AsymmetricKey)
                {
                    throw new ArgumentOutOfRangeException("KeyType");
                }
                securityToken = SamlSecurityTokenProvider.CreateAsymmetricProofToken();
                samlAssertion = this.CreateSamlAssertionWithAsymmetricKey(securityToken);
            }
            SamlSecurityToken samlSecurityToken = new SamlSecurityToken(samlAssertion);
            XmlDocument       xmlDocument       = new XmlDocument();

            using (XmlWriter xmlWriter = xmlDocument.CreateNavigator().AppendChild())
            {
                WSSecurityTokenSerializer wSSecurityTokenSerializer = new WSSecurityTokenSerializer();
                wSSecurityTokenSerializer.WriteToken(xmlWriter, samlSecurityToken);
            }
            SamlAssertionKeyIdentifierClause samlAssertionKeyIdentifierClause = samlSecurityToken.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>();

            return(new GenericXmlSecurityToken(xmlDocument.DocumentElement, securityToken, samlAssertion.Conditions.NotBefore, samlAssertion.Conditions.NotOnOrAfter, samlAssertionKeyIdentifierClause, samlAssertionKeyIdentifierClause, null));
        }
コード例 #5
0
        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement("RequestSecurityTokenResponse", "http://schemas.xmlsoap.org/ws/2005/02/trust");
            if (base.TokenType != null && base.TokenType.Length > 0)
            {
                writer.WriteStartElement("TokenType", "http://schemas.xmlsoap.org/ws/2005/02/trust");
                writer.WriteString(base.TokenType);
                writer.WriteEndElement();
            }
            WSSecurityTokenSerializer wssecurityTokenSerializer = new WSSecurityTokenSerializer();

            if (this.RequestedSecurityToken != null)
            {
                writer.WriteStartElement("RequestedSecurityToken", "http://schemas.xmlsoap.org/ws/2005/02/trust");
                wssecurityTokenSerializer.WriteToken(writer, this.RequestedSecurityToken);
                writer.WriteEndElement();
            }
            if (this.RequestedAttachedReference != null)
            {
                writer.WriteStartElement("RequestedAttachedReference", "http://schemas.xmlsoap.org/ws/2005/02/trust");
                wssecurityTokenSerializer.WriteKeyIdentifierClause(writer, this.RequestedAttachedReference);
                writer.WriteEndElement();
            }
            if (this.RequestedUnattachedReference != null)
            {
                writer.WriteStartElement("RequestedUnattachedReference", "http://schemas.xmlsoap.org/ws/2005/02/trust");
                wssecurityTokenSerializer.WriteKeyIdentifierClause(writer, this.RequestedUnattachedReference);
                writer.WriteEndElement();
            }
            if (base.AppliesTo != null)
            {
                writer.WriteStartElement("AppliesTo", "http://schemas.xmlsoap.org/ws/2004/09/policy");
                base.AppliesTo.WriteTo(AddressingVersion.WSAddressing10, writer);
                writer.WriteEndElement();
            }
            if (this.RequestedProofToken != null)
            {
                writer.WriteStartElement("RequestedProofToken", "http://schemas.xmlsoap.org/ws/2005/02/trust");
                wssecurityTokenSerializer.WriteToken(writer, this.RequestedProofToken);
                writer.WriteEndElement();
            }
            if (this.IssuerEntropy != null && this.ComputeKey)
            {
                writer.WriteStartElement("RequestedProofToken", "http://schemas.xmlsoap.org/ws/2005/02/trust");
                writer.WriteStartElement("ComputedKey", "http://schemas.xmlsoap.org/ws/2005/02/trust");
                writer.WriteValue("http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1");
                writer.WriteEndElement();
                writer.WriteEndElement();
                if (this.IssuerEntropy != null)
                {
                    writer.WriteStartElement("Entropy", "http://schemas.xmlsoap.org/ws/2005/02/trust");
                    wssecurityTokenSerializer.WriteToken(writer, this.IssuerEntropy);
                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement();
        }
コード例 #6
0
        private static string SerializeToken(SamlAssertion assertion)
        {
            SamlSecurityToken token = new SamlSecurityToken(assertion);

            SamlSerializer            serializer      = new SamlSerializer();
            WSSecurityTokenSerializer tokenSerializer = new WSSecurityTokenSerializer();
            StringWriter stringWriter = new StringWriter();

            XmlTextWriter xmltextWriter = new XmlTextWriter(stringWriter);

            serializer.WriteToken(token, xmltextWriter, tokenSerializer);

            return(stringWriter.ToString());
        }
コード例 #7
0
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            SamlSecurityToken         samlSecurityToken         = new SamlSecurityToken(this.assertion);
            WSSecurityTokenSerializer wssecurityTokenSerializer = new WSSecurityTokenSerializer();
            MemoryStream memoryStream = new MemoryStream(65535);
            XmlWriter    writer       = XmlWriter.Create(memoryStream);

            wssecurityTokenSerializer.WriteToken(writer, samlSecurityToken);
            memoryStream.Seek(0L, SeekOrigin.Begin);
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.Load(memoryStream);
            SamlAssertionKeyIdentifierClause samlAssertionKeyIdentifierClause = samlSecurityToken.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>();

            return(new GenericXmlSecurityToken(xmlDocument.DocumentElement, this.proofToken, this.assertion.Conditions.NotBefore, this.assertion.Conditions.NotOnOrAfter, samlAssertionKeyIdentifierClause, samlAssertionKeyIdentifierClause, null));
        }
コード例 #8
0
        /// <summary>
        /// Validates a Kerberos WSS user token.
        /// </summary>
        private SecurityToken ParseAndVerifyKerberosToken(byte[] tokenData)
        {
            XmlDocument   document = new XmlDocument();
            XmlNodeReader reader   = null;

            try
            {
                document.InnerXml = new UTF8Encoding().GetString(tokenData).Trim();
                reader            = new XmlNodeReader(document.DocumentElement);

                SecurityToken securityToken            = new WSSecurityTokenSerializer().ReadToken(reader, null);
                KerberosReceiverSecurityToken receiver = securityToken as KerberosReceiverSecurityToken;

                KerberosSecurityTokenAuthenticator authenticator = new KerberosSecurityTokenAuthenticator();

                if (authenticator.CanValidateToken(receiver))
                {
                    authenticator.ValidateToken(receiver);
                }

                return(securityToken);
            }
            catch (Exception e)
            {
                // construct translation object with default text.
                TranslationInfo info = new TranslationInfo(
                    "InvalidKerberosToken",
                    "en-US",
                    "'{0}' is not a valid Kerberos token.",
                    document.DocumentElement.LocalName);

                // create an exception with a vendor defined sub-code.
                throw new ServiceResultException(new ServiceResult(
                                                     e,
                                                     StatusCodes.BadIdentityTokenRejected,
                                                     "InvalidKerberosToken",
                                                     Namespaces.Hsl,
                                                     new LocalizedText(info)));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
コード例 #9
0
        public Microsoft.ResourceManagement.WebServices.Client.ContextualSecurityToken GetContextTokenFromResponse(ContextMessageProperty context)
        {
            Microsoft.ResourceManagement.WebServices.Client.ContextualSecurityToken returnToken = null;
            if (RequestedSecurityToken != null)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(new XmlNodeReader(RequestedSecurityToken));
                XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
                nsManager.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

                DateTime effectiveTime = DateTime.Parse(
                    RequestedSecurityToken.SelectSingleNode(
                        "saml:Conditions/@NotBefore",
                        nsManager
                        ).Value);
                DateTime expirationTime = DateTime.Parse(
                    RequestedSecurityToken.SelectSingleNode(
                        "saml:Conditions/@NotOnOrAfter",
                        nsManager
                        ).Value);
                WSSecurityTokenSerializer serializer          = new WSSecurityTokenSerializer();
                SecurityToken             requestedProofToken =
                    serializer.ReadToken(
                        new XmlNodeReader(this.RequestedProofToken),
                        new SecurityContextSecurityTokenResolver(Int32.MaxValue, false));
                SecurityKeyIdentifierClause requestedUnattachedReference =
                    serializer.ReadKeyIdentifierClause(new XmlNodeReader(RequestedUnattachedReference));
                SecurityKeyIdentifierClause requestedAttachedReference =
                    serializer.ReadKeyIdentifierClause(new XmlNodeReader(RequestedAttachedReference));

                returnToken = new ContextualSecurityToken(
                    new GenericXmlSecurityToken(
                        RequestedSecurityToken,
                        requestedProofToken,
                        effectiveTime,
                        expirationTime,
                        requestedUnattachedReference,
                        requestedAttachedReference,
                        new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>())
                        ), context);
            }
            return(returnToken);
        }
コード例 #10
0
ファイル: Saml11Helper.cs プロジェクト: alejandroamrein/bhl
        public static string SerializeSamlToken(SamlSecurityToken token)
        {
            var samlBuilder = new StringBuilder();

            using (var writer = XmlWriter.Create(samlBuilder))
            {
                try
                {
                    var keyInfoSerializer = new WSSecurityTokenSerializer();
                    keyInfoSerializer.WriteToken(writer, token);
                    Console.WriteLine("Saml Token Successfully Created");
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to seralize token");
                }
            }
            return(samlBuilder.ToString());
        }
コード例 #11
0
        public static string SerializeToken(SecurityToken token, bool urlEncode = false)
        {
            StringBuilder sb = new StringBuilder();

            if (token is GenericXmlSecurityToken)
            {
                WSSecurityTokenSerializer wss = new WSSecurityTokenSerializer(SecurityVersion.WSSecurity11);
                XmlWriter writer = XmlWriter.Create(sb);
                wss.WriteToken(writer, token);
            }
            else
            {
                SecurityTokenHandlerCollection handlers = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;
                handlers.WriteToken(new XmlTextWriter(new StringWriter(sb)), token);
            }

            string serialized = sb.ToString();

            return(urlEncode ? HttpUtility.UrlEncode(serialized) : serialized);
        }
コード例 #12
0
        static void PopulateCache(Dictionary <Key, GenericXmlSecurityToken> cache, Stream stream)
        {
            XmlTextReader reader = new XmlTextReader(stream);

            while (reader.IsStartElement("Entry"))
            {
                reader.ReadStartElement();
                Uri    target    = new Uri(reader.ReadElementString("Target"));
                string issuerStr = reader.ReadElementString("Issuer");
                Uri    issuer    = string.IsNullOrEmpty(issuerStr) ? null : new Uri(issuerStr);

                reader.ReadStartElement("Token");
                reader.ReadStartElement("XML");
                XmlDocument doc      = new XmlDocument();
                XmlElement  tokenXml = doc.ReadNode(reader) as XmlElement;
                reader.ReadEndElement();
                byte[] key = Convert.FromBase64String(reader.ReadElementString("Key"));
                reader.ReadElementString("Id");
                DateTime validFrom = Convert.ToDateTime(reader.ReadElementString("ValidFrom"));
                DateTime validTo   = Convert.ToDateTime(reader.ReadElementString("ValidTo"));
                WSSecurityTokenSerializer serializer = new WSSecurityTokenSerializer();
                reader.ReadStartElement("InternalTokenReference");
                SecurityKeyIdentifierClause internalReference = serializer.ReadKeyIdentifierClause(reader);
                reader.ReadEndElement();
                reader.ReadStartElement("ExternalTokenReference");
                SecurityKeyIdentifierClause externalReference = serializer.ReadKeyIdentifierClause(reader);
                reader.ReadEndElement();
                reader.ReadEndElement(); // token
                reader.ReadEndElement(); // entry

                List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>();
                GenericXmlSecurityToken     token    = new GenericXmlSecurityToken(tokenXml, new BinarySecretSecurityToken(key), validFrom, validTo, internalReference, externalReference,
                                                                                   new ReadOnlyCollection <IAuthorizationPolicy>(policies));
                cache.Add(new Key(target, issuer), token);
            }
        }
コード例 #13
0
        internal static bool TryCreate(SecurityBindingElement sbe, bool isSecureTransportMode, bool isReliableSession, MessageSecurityVersion version, out FederatedMessageSecurityOverHttp messageSecurity)
        {
            Fx.Assert(null != sbe, string.Empty);

            messageSecurity = null;

            // do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings

            if (!sbe.IncludeTimestamp)
            {
                return(false);
            }

            if (sbe.SecurityHeaderLayout != SecurityProtocolFactory.defaultSecurityHeaderLayout)
            {
                return(false);
            }

            bool emitBspAttributes = true;

            // Do not check MessageSecurityVersion: it maybe changed by the wrapper element and gets checked later in the SecuritySection.AreBindingsMatching()

            SecurityBindingElement bootstrapSecurity;

            bool establishSecurityContext = SecurityBindingElement.IsSecureConversationBinding(sbe, true, out bootstrapSecurity);

            bootstrapSecurity = establishSecurityContext ? bootstrapSecurity : sbe;

            if (isSecureTransportMode && !(bootstrapSecurity is TransportSecurityBindingElement))
            {
                return(false);
            }

            bool negotiateServiceCredential = DefaultNegotiateServiceCredential;
            IssuedSecurityTokenParameters issuedTokenParameters;

            if (isSecureTransportMode)
            {
                if (!SecurityBindingElement.IsIssuedTokenOverTransportBinding(bootstrapSecurity, out issuedTokenParameters))
                {
                    return(false);
                }
            }
            else
            {
                // We should have passed 'true' as RequireCancelation to be consistent with other standard bindings.
                // However, to limit the change for Orcas, we scope down to just newer version of WSSecurityPolicy.
                if (SecurityBindingElement.IsIssuedTokenForSslBinding(bootstrapSecurity, version.SecurityPolicyVersion != SecurityPolicyVersion.WSSecurityPolicy11, out issuedTokenParameters))
                {
                    negotiateServiceCredential = true;
                }
                else if (SecurityBindingElement.IsIssuedTokenForCertificateBinding(bootstrapSecurity, out issuedTokenParameters))
                {
                    negotiateServiceCredential = false;
                }
                else
                {
                    return(false);
                }
            }

            if ((issuedTokenParameters.KeyType == SecurityKeyType.BearerKey) &&
                (version.TrustVersion == TrustVersion.WSTrustFeb2005))
            {
                return(false);
            }

            Collection <XmlElement>   nonAlgorithmRequestParameters;
            WSSecurityTokenSerializer versionSpecificSerializer = new WSSecurityTokenSerializer(version.SecurityVersion,
                                                                                                version.TrustVersion,
                                                                                                version.SecureConversationVersion,
                                                                                                emitBspAttributes,
                                                                                                null, null, null);
            SecurityStandardsManager versionSpecificStandardsManager = new SecurityStandardsManager(version, versionSpecificSerializer);

            if (!issuedTokenParameters.DoAlgorithmsMatch(sbe.DefaultAlgorithmSuite,
                                                         versionSpecificStandardsManager,
                                                         out nonAlgorithmRequestParameters))
            {
                return(false);
            }
            messageSecurity = new FederatedMessageSecurityOverHttp();

            messageSecurity.AlgorithmSuite             = sbe.DefaultAlgorithmSuite;
            messageSecurity.NegotiateServiceCredential = negotiateServiceCredential;
            messageSecurity.EstablishSecurityContext   = establishSecurityContext;
            messageSecurity.IssuedTokenType            = issuedTokenParameters.TokenType;
            messageSecurity.IssuerAddress         = issuedTokenParameters.IssuerAddress;
            messageSecurity.IssuerBinding         = issuedTokenParameters.IssuerBinding;
            messageSecurity.IssuerMetadataAddress = issuedTokenParameters.IssuerMetadataAddress;
            messageSecurity.IssuedKeyType         = issuedTokenParameters.KeyType;
            foreach (ClaimTypeRequirement c in issuedTokenParameters.ClaimTypeRequirements)
            {
                messageSecurity.ClaimTypeRequirements.Add(c);
            }
            foreach (XmlElement p in nonAlgorithmRequestParameters)
            {
                messageSecurity.TokenRequestParameters.Add(p);
            }
            if (issuedTokenParameters.AlternativeIssuerEndpoints != null && issuedTokenParameters.AlternativeIssuerEndpoints.Count > 0)
            {
                return(false);
            }
            return(true);
        }
コード例 #14
0
        // Methods of BodyWriter
        /// <summary>
        /// Writes out an XML representation of the instance.
        /// </summary>
        /// <param name="writer">The writer to be used to write out the XML content</param>
        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            // Write out the wst:RequestSecurityTokenResponse start tag
            writer.WriteStartElement(Constants.Trust.Elements.RequestSecurityTokenResponse, Constants.Trust.NamespaceUri);

            // If we have a non-null, non-empty tokenType...
            if (this.TokenType != null && this.TokenType.Length > 0)
            {
                // Write out the wst:TokenType start tag
                writer.WriteStartElement(Constants.Trust.Elements.TokenType, Constants.Trust.NamespaceUri);
                // Write out the tokenType string
                writer.WriteString(this.TokenType);
                writer.WriteEndElement(); // wst:TokenType
            }

            // Create a serializer that knows how to write out security tokens
            WSSecurityTokenSerializer ser = new WSSecurityTokenSerializer();

            // If we have a requestedSecurityToken...
            if (this.requestedSecurityToken != null)
            {
                // Write out the wst:RequestedSecurityToken start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestedSecurityToken, Constants.Trust.NamespaceUri);
                // Write out the requested token using the serializer
                ser.WriteToken(writer, requestedSecurityToken);
                writer.WriteEndElement(); // wst:RequestedSecurityToken
            }

            // If we have a requestedAttachedReference...
            if (this.requestedAttachedReference != null)
            {
                // Write out the wst:RequestedAttachedReference start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestedAttachedReference, Constants.Trust.NamespaceUri);
                // Write out the reference using the serializer
                ser.WriteKeyIdentifierClause(writer, this.requestedAttachedReference);
                writer.WriteEndElement(); // wst:RequestedAttachedReference
            }

            // If we have a requestedUnattachedReference...
            if (this.requestedUnattachedReference != null)
            {
                // Write out the wst:RequestedUnattachedReference start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestedUnattachedReference, Constants.Trust.NamespaceUri);
                // Write out the reference using the serializer
                ser.WriteKeyIdentifierClause(writer, this.requestedUnattachedReference);
                writer.WriteEndElement(); // wst:RequestedAttachedReference
            }

            // If we have a non-null appliesTo
            if (this.AppliesTo != null)
            {
                // Write out the wsp:AppliesTo start tag
                writer.WriteStartElement(Constants.Policy.Elements.AppliesTo, Constants.Policy.NamespaceUri);
                // Write the appliesTo in WS-Addressing 1.0 format
                this.AppliesTo.WriteTo(AddressingVersion.WSAddressing10, writer);
                writer.WriteEndElement(); // wsp:AppliesTo
            }

            // If the requestedProofToken is non-null, then the STS is providing all the key material...
            if (this.requestedProofToken != null)
            {
                // Write the wst:RequestedProofToken start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestedProofToken, Constants.Trust.NamespaceUri);
                // Write the proof token using the serializer
                ser.WriteToken(writer, requestedProofToken);
                writer.WriteEndElement(); // wst:RequestedSecurityToken
            }

            // If issuerEntropy is non-null and computeKey is true, then combined entropy is being used...
            if (this.issuerEntropy != null && this.computeKey)
            {
                // Write the wst:RequestedProofToken start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestedProofToken, Constants.Trust.NamespaceUri);
                // Write the wst:ComputeKey start tag
                writer.WriteStartElement(Constants.Trust.Elements.ComputedKey, Constants.Trust.NamespaceUri);
                // Write the PSHA1 algorithm value
                writer.WriteValue(Constants.Trust.ComputedKeyAlgorithms.PSHA1);
                writer.WriteEndElement(); // wst:ComputedKey
                writer.WriteEndElement(); // wst:RequestedSecurityToken

                // Write the wst:Entropy start tag
                writer.WriteStartElement(Constants.Trust.Elements.Entropy, Constants.Trust.NamespaceUri);
                // Write the issuerEntropy out using the serializer
                ser.WriteToken(writer, this.issuerEntropy);
                writer.WriteEndElement(); // wst:Entropy
            }

            writer.WriteEndElement(); // wst:RequestSecurityTokenResponse
        }
コード例 #15
0
        /// <summary>
        /// Build the contents of the SAML token
        /// </summary>
        /// <param name="writer"><b>XmlDictionaryWriter</b> to write the contents of this token to</param>
        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            // Subject
            SamlSubject subject = new SamlSubject();

            if (this.useKey != null)
            {
                // Add the key and the Holder-Of-Key confirmation method
                subject.KeyIdentifier = this.useKey;
                subject.ConfirmationMethods.Add(SamlConstants.HolderOfKey);
            }
            else
            {
                // This is a bearer token
                subject.ConfirmationMethods.Add(SamlConstants.SenderVouches);
            }


            // Attributes, statements, conditions, and assertions
            List <SamlStatement> statements = new List <SamlStatement>();
            List <SamlAttribute> attributes = GetTokenAttributes();


            statements.Add(new SamlAuthenticationStatement(subject, Constants.Saml.AuthenticationMethods.Unspecified, DateTime.Now, null, null, null));
            statements.Add(new SamlAttributeStatement(subject, attributes));
            SamlConditions conditions = new SamlConditions(DateTime.Now, (DateTime.Now + TimeSpan.FromHours(8.0)));
            SamlAssertion  assertion  = new SamlAssertion("uuid-" + Guid.NewGuid(), Program.Issuer, DateTime.Now, conditions, null, statements);

            // Build the signing token
            SecurityToken         signingToken       = new X509SecurityToken(Program.SigningCertificate);
            SecurityKeyIdentifier keyIdentifier      = new SecurityKeyIdentifier(signingToken.CreateKeyIdentifierClause <X509RawDataKeyIdentifierClause>());
            SigningCredentials    signingCredentials = new SigningCredentials(signingToken.SecurityKeys[0], SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, keyIdentifier);

            assertion.SigningCredentials = signingCredentials;

            // Build the SAML token
            SamlSecurityToken           token               = new SamlSecurityToken(assertion);
            SecurityKeyIdentifierClause attachedReference   = token.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>();
            SecurityKeyIdentifierClause unattachedReference = token.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>();

            //
            // Write the XML
            //
            //writer = XmlDictionaryWriter.CreateTextWriter(File.CreateText("output.xml").BaseStream);

            // RSTR
            writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestSecurityTokenResponse, Constants.WSTrust.NamespaceUri.Uri);
            if (context != null)
            {
                writer.WriteAttributeString(Constants.WSTrust.Attributes.Context, context);
            }

            // TokenType
            writer.WriteElementString(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.TokenType, Constants.WSTrust.NamespaceUri.Uri, Constants.WSTrust.TokenTypes.Saml10Assertion);

            // RequestedSecurityToken (the SAML token)
            SecurityTokenSerializer tokenSerializer = new WSSecurityTokenSerializer();

            writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestedSecurityToken, Constants.WSTrust.NamespaceUri.Uri);
            tokenSerializer.WriteToken(writer, token);
            writer.WriteEndElement();

            // RequestedAttachedReference
            writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestedAttachedReference, Constants.WSTrust.NamespaceUri.Uri);
            tokenSerializer.WriteKeyIdentifierClause(writer, attachedReference);
            writer.WriteEndElement();

            // RequestedUnattachedReference
            writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestedUnattachedReference, Constants.WSTrust.NamespaceUri.Uri);
            tokenSerializer.WriteKeyIdentifierClause(writer, unattachedReference);
            writer.WriteEndElement();

            // RequestedDisplayToken (display token)
            string displayTokenNS = "http://schemas.xmlsoap.org/ws/2005/05/identity";

            writer.WriteStartElement("wsid", "RequestedDisplayToken", displayTokenNS);
            writer.WriteStartElement("wsid", "DisplayToken", displayTokenNS);
            foreach (SamlAttribute attribute in attributes)
            {
                writer.WriteStartElement("wsid", "DisplayClaim", displayTokenNS);
                writer.WriteAttributeString("Uri", attribute.Namespace + "/" + attribute.Name);
                writer.WriteStartElement("wsid", "DisplayTag", displayTokenNS);
                writer.WriteValue(attribute.Name);
                writer.WriteEndElement();
                writer.WriteStartElement("wsid", "Description", displayTokenNS);
                writer.WriteValue(attribute.Namespace + "/" + attribute.Name);
                writer.WriteEndElement();
                foreach (string attributeValue in attribute.AttributeValues)
                {
                    writer.WriteStartElement("wsid", "DisplayValue", displayTokenNS);
                    writer.WriteValue(attributeValue);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteEndElement();

            // RSTR End
            writer.WriteEndElement();

            //writer.Close();
        }
コード例 #16
0
 public WSTrustSecurityTokenService()
 {
     serializer = WSSecurityTokenSerializer.DefaultInstance;
 }
コード例 #17
0
        internal SecurityBindingElement CreateSecurityBindingElement(bool isSecureTransportMode,
                                                                     bool isReliableSession,
                                                                     MessageSecurityVersion version)
        {
            if ((this.IssuedKeyType == SecurityKeyType.BearerKey) &&
                (version.TrustVersion == TrustVersion.WSTrustFeb2005))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.BearerKeyIncompatibleWithWSFederationHttpBinding)));
            }

            if (isReliableSession && !this.EstablishSecurityContext)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecureConversationRequiredByReliableSession)));
            }

            SecurityBindingElement result;
            bool emitBspAttributes = true;
            IssuedSecurityTokenParameters issuedParameters = new IssuedSecurityTokenParameters(this.IssuedTokenType, this.IssuerAddress, this.IssuerBinding);

            issuedParameters.IssuerMetadataAddress = this.issuerMetadataAddress;
            issuedParameters.KeyType = this.IssuedKeyType;
            if (this.IssuedKeyType == SecurityKeyType.SymmetricKey)
            {
                issuedParameters.KeySize = this.AlgorithmSuite.DefaultSymmetricKeyLength;
            }
            else
            {
                issuedParameters.KeySize = 0;
            }
            foreach (ClaimTypeRequirement c in this.claimTypeRequirements)
            {
                issuedParameters.ClaimTypeRequirements.Add(c);
            }
            foreach (XmlElement p in this.TokenRequestParameters)
            {
                issuedParameters.AdditionalRequestParameters.Add(p);
            }
            WSSecurityTokenSerializer versionSpecificSerializer = new WSSecurityTokenSerializer(version.SecurityVersion,
                                                                                                version.TrustVersion,
                                                                                                version.SecureConversationVersion,
                                                                                                emitBspAttributes,
                                                                                                null, null, null);
            SecurityStandardsManager versionSpecificStandardsManager = new SecurityStandardsManager(version, versionSpecificSerializer);

            issuedParameters.AddAlgorithmParameters(this.AlgorithmSuite, versionSpecificStandardsManager, this.issuedKeyType);

            SecurityBindingElement issuedTokenSecurity;

            if (isSecureTransportMode)
            {
                issuedTokenSecurity = SecurityBindingElement.CreateIssuedTokenOverTransportBindingElement(issuedParameters);
            }
            else
            {
                if (negotiateServiceCredential)
                {
                    // We should have passed 'true' as RequireCancelation to be consistent with other standard bindings.
                    // However, to limit the change for Orcas, we scope down to just newer version of WSSecurityPolicy.
                    issuedTokenSecurity = SecurityBindingElement.CreateIssuedTokenForSslBindingElement(issuedParameters, version.SecurityPolicyVersion != SecurityPolicyVersion.WSSecurityPolicy11);
                }
                else
                {
                    issuedTokenSecurity = SecurityBindingElement.CreateIssuedTokenForCertificateBindingElement(issuedParameters);
                }
            }

            issuedTokenSecurity.MessageSecurityVersion = version;
            issuedTokenSecurity.DefaultAlgorithmSuite  = this.AlgorithmSuite;

            if (this.EstablishSecurityContext)
            {
                result = SecurityBindingElement.CreateSecureConversationBindingElement(issuedTokenSecurity, true);
            }
            else
            {
                result = issuedTokenSecurity;
            }

            result.MessageSecurityVersion = version;
            result.DefaultAlgorithmSuite  = this.AlgorithmSuite;
            result.IncludeTimestamp       = true;

            if (!isReliableSession)
            {
                result.LocalServiceSettings.ReconnectTransportOnFailure = false;
                result.LocalClientSettings.ReconnectTransportOnFailure  = false;
            }
            else
            {
                result.LocalServiceSettings.ReconnectTransportOnFailure = true;
                result.LocalClientSettings.ReconnectTransportOnFailure  = true;
            }

            if (this.establishSecurityContext)
            {
                // issue the transition SCT for a short duration only
                issuedTokenSecurity.LocalServiceSettings.IssuedCookieLifetime = SpnegoTokenAuthenticator.defaultServerIssuedTransitionTokenLifetime;
            }

            return(result);
        }
コード例 #18
0
        private Collection <XmlElement> NormalizeAdditionalParameters(Collection <XmlElement> additionalParameters,
                                                                      TrustDriver driver,
                                                                      bool clientSideClaimTypeRequirementsSpecified)
        {
            // Ensure STS trust version is one of the currently supported versions: Feb 05 / Trust 1.3
            Fx.Assert(((driver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005) ||
                       (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)),
                      "Unsupported trust version specified for the STS.");

            // We have a mismatch. Make a local copy of additionalParameters for making any potential modifications
            // as part of normalization
            Collection <XmlElement> tmpCollection = new Collection <XmlElement>();

            foreach (XmlElement e in additionalParameters)
            {
                tmpCollection.Add(e);
            }


            // 1. For Trust 1.3 EncryptionAlgorithm, CanonicalizationAlgorithm and KeyWrapAlgorithm should not be
            //    specified as top-level element if "SecondaryParameters" element already specifies this.
            if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)
            {
                Fx.Assert(driver.GetType() == typeof(WSTrustDec2005.DriverDec2005), "Invalid Trust Driver specified for Trust 1.3.");

                XmlElement encryptionAlgorithmElement       = null;
                XmlElement canonicalizationAlgorithmElement = null;
                XmlElement keyWrapAlgorithmElement          = null;
                XmlElement secondaryParameter = null;

                for (int i = 0; i < tmpCollection.Count; ++i)
                {
                    if (driver.IsEncryptionAlgorithmElement(tmpCollection[i], out string algorithm))
                    {
                        encryptionAlgorithmElement = tmpCollection[i];
                    }
                    else if (driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithm))
                    {
                        canonicalizationAlgorithmElement = tmpCollection[i];
                    }
                    else if (driver.IsKeyWrapAlgorithmElement(tmpCollection[i], out algorithm))
                    {
                        keyWrapAlgorithmElement = tmpCollection[i];
                    }
                    else if (((WSTrustDec2005.DriverDec2005)driver).IsSecondaryParametersElement(tmpCollection[i]))
                    {
                        secondaryParameter = tmpCollection[i];
                    }
                }

                if (secondaryParameter != null)
                {
                    foreach (XmlNode node in secondaryParameter.ChildNodes)
                    {
                        if (node is XmlElement child)
                        {
                            if (driver.IsEncryptionAlgorithmElement(child, out string algorithm) && (encryptionAlgorithmElement != null))
                            {
                                tmpCollection.Remove(encryptionAlgorithmElement);
                            }
                            else if (driver.IsCanonicalizationAlgorithmElement(child, out algorithm) && (canonicalizationAlgorithmElement != null))
                            {
                                tmpCollection.Remove(canonicalizationAlgorithmElement);
                            }
                            else if (driver.IsKeyWrapAlgorithmElement(child, out algorithm) && (keyWrapAlgorithmElement != null))
                            {
                                tmpCollection.Remove(keyWrapAlgorithmElement);
                            }
                        }
                    }
                }
            }

            // 2. Check for Mismatch.
            //      a. Trust Feb 2005 -> Trust 1.3. do the following,
            //          (i) Copy EncryptionAlgorithm and CanonicalizationAlgorithm as the top-level elements.
            //              Note, this is in contradiction to step 1. But we don't have a choice here as we cannot say from the
            //              Additional Parameters section in the config what came from the service and what came from the client.
            //          (ii) Convert SignWith and EncryptWith elements to Trust 1.3 namespace.
            //      b. For Trust 1.3 -> Trust Feb 2005, do the following,
            //          (i) Find EncryptionAlgorithm, CanonicalizationAlgorithm from inside the "SecondaryParameters" element.
            //              If found, then promote these as the top-level elements replacing the existing values.
            //          (ii) Convert the SignWith and EncryptWith elements to the Trust Feb 2005 namespace and drop the KeyWrapAlgorithm
            //               element.

            // make an optimistic check to detect mismatched trust-versions between STS and RP
            bool mismatch = (((driver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005) &&
                              !CollectionContainsElementsWithTrustNamespace(additionalParameters, TrustFeb2005Strings.Namespace)) ||
                             ((driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13) &&
                              !CollectionContainsElementsWithTrustNamespace(additionalParameters, TrustDec2005Strings.Namespace)));

            // if no mismatch, return unmodified collection
            if (!mismatch)
            {
                return(tmpCollection);
            }

            // 2.a
            // If we are talking to a Trust 1.3 STS, replace any Feb '05 algorithm parameters with their Trust 1.3 counterparts
            if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)
            {
                SecurityStandardsManager trustFeb2005StandardsManager = SecurityStandardsManager.DefaultInstance;
                // the following cast is guaranteed to succeed
                WSTrustFeb2005.DriverFeb2005 trustFeb2005Driver = (WSTrustFeb2005.DriverFeb2005)trustFeb2005StandardsManager.TrustDriver;

                for (int i = 0; i < tmpCollection.Count; i++)
                {
                    if (trustFeb2005Driver.IsSignWithElement(tmpCollection[i], out string algorithmParameter))
                    {
                        tmpCollection[i] = driver.CreateSignWithElement(algorithmParameter);
                    }
                    else if (trustFeb2005Driver.IsEncryptWithElement(tmpCollection[i], out algorithmParameter))
                    {
                        tmpCollection[i] = driver.CreateEncryptWithElement(algorithmParameter);
                    }
                    else if (trustFeb2005Driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithmParameter))
                    {
                        tmpCollection[i] = driver.CreateEncryptionAlgorithmElement(algorithmParameter);
                    }
                    else if (trustFeb2005Driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithmParameter))
                    {
                        tmpCollection[i] = driver.CreateCanonicalizationAlgorithmElement(algorithmParameter);
                    }
                }
            }
            else
            {
                // 2.b
                // We are talking to a Feb 05 STS. Filter out any SecondaryParameters element.
                Collection <XmlElement>   childrenToPromote = null;
                WSSecurityTokenSerializer trust13Serializer = new WSSecurityTokenSerializer(SecurityVersion.WSSecurity11,
                                                                                            TrustVersion.WSTrust13,
                                                                                            SecureConversationVersion.WSSecureConversation13,
                                                                                            true, null, null, null);
                SecurityStandardsManager trust13StandardsManager = new SecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, trust13Serializer);
                // the following cast is guaranteed to succeed
                WSTrustDec2005.DriverDec2005 trust13Driver = (WSTrustDec2005.DriverDec2005)trust13StandardsManager.TrustDriver;

                foreach (XmlElement parameter in tmpCollection)
                {
                    // check if SecondaryParameters is present
                    if (trust13Driver.IsSecondaryParametersElement(parameter))
                    {
                        childrenToPromote = new Collection <XmlElement>();
                        // walk SecondaryParameters and collect any 'non-standard' children
                        foreach (XmlNode innerNode in parameter.ChildNodes)
                        {
                            if ((innerNode is XmlElement innerElement) && CanPromoteToRoot(innerElement, trust13Driver, clientSideClaimTypeRequirementsSpecified))
                            {
                                childrenToPromote.Add(innerElement);
                            }
                        }

                        // remove SecondaryParameters element
                        tmpCollection.Remove(parameter);

                        // we are done - break out of the loop
                        break;
                    }
                }

                // Probe of standard Trust elements and remember them.
                if ((childrenToPromote != null) && (childrenToPromote.Count > 0))
                {
                    XmlElement encryptionElement              = null;
                    XmlElement canonicalizationElement        = null;
                    XmlElement requiredClaimsElement          = null;
                    Collection <XmlElement> processedElements = new Collection <XmlElement>();

                    foreach (XmlElement e in childrenToPromote)
                    {
                        if ((encryptionElement == null) && trust13Driver.IsEncryptionAlgorithmElement(e, out string encryptionAlgorithm))
                        {
                            encryptionElement = driver.CreateEncryptionAlgorithmElement(encryptionAlgorithm);
                            processedElements.Add(e);
                        }
                        else if ((canonicalizationElement == null) && trust13Driver.IsCanonicalizationAlgorithmElement(e, out string canonicalizationAlgoritm))
                        {
                            canonicalizationElement = driver.CreateCanonicalizationAlgorithmElement(canonicalizationAlgoritm);
                            processedElements.Add(e);
                        }
                        else if ((requiredClaimsElement == null) && trust13Driver.TryParseRequiredClaimsElement(e, out Collection <XmlElement> requiredClaims))
                        {
                            requiredClaimsElement = driver.CreateRequiredClaimsElement(requiredClaims);
                            processedElements.Add(e);
                        }
                    }

                    for (int i = 0; i < processedElements.Count; ++i)
                    {
                        childrenToPromote.Remove(processedElements[i]);
                    }

                    XmlElement keyWrapAlgorithmElement = null;

                    // Replace the appropriate elements.
                    for (int i = 0; i < tmpCollection.Count; ++i)
                    {
                        if (trust13Driver.IsSignWithElement(tmpCollection[i], out string algorithmParameter))
                        {
                            tmpCollection[i] = driver.CreateSignWithElement(algorithmParameter);
                        }
                        else if (trust13Driver.IsEncryptWithElement(tmpCollection[i], out algorithmParameter))
                        {
                            tmpCollection[i] = driver.CreateEncryptWithElement(algorithmParameter);
                        }
                        else if (trust13Driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithmParameter) && (encryptionElement != null))
                        {
                            tmpCollection[i]  = encryptionElement;
                            encryptionElement = null;
                        }
                        else if (trust13Driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithmParameter) && (canonicalizationElement != null))
                        {
                            tmpCollection[i]        = canonicalizationElement;
                            canonicalizationElement = null;
                        }
                        else if (trust13Driver.IsKeyWrapAlgorithmElement(tmpCollection[i], out algorithmParameter) && (keyWrapAlgorithmElement == null))
                        {
                            keyWrapAlgorithmElement = tmpCollection[i];
                        }
                        else if (trust13Driver.TryParseRequiredClaimsElement(tmpCollection[i], out Collection <XmlElement> reqClaims) && (requiredClaimsElement != null))
                        {
                            tmpCollection[i]      = requiredClaimsElement;
                            requiredClaimsElement = null;
                        }
                    }

                    if (keyWrapAlgorithmElement != null)
                    {
                        // Remove KeyWrapAlgorithmElement as this is not define in Trust Feb 2005.
                        tmpCollection.Remove(keyWrapAlgorithmElement);
                    }

                    // Add the remaining elements to the additionaParameters list to the end.
                    if (encryptionElement != null)
                    {
                        tmpCollection.Add(encryptionElement);
                    }

                    if (canonicalizationElement != null)
                    {
                        tmpCollection.Add(canonicalizationElement);
                    }

                    if (requiredClaimsElement != null)
                    {
                        tmpCollection.Add(requiredClaimsElement);
                    }

                    if (childrenToPromote.Count > 0)
                    {
                        // There are some non-standard elements. Just bump them to the top-level element.
                        for (int i = 0; i < childrenToPromote.Count; ++i)
                        {
                            tmpCollection.Add(childrenToPromote[i]);
                        }
                    }
                }
            }

            return(tmpCollection);
        }
        internal SecurityBindingElement CreateSecurityBindingElement(bool isSecureTransportMode, bool isReliableSession, MessageSecurityVersion version)
        {
            SecurityBindingElement element;
            SecurityBindingElement element3;

            if ((this.IssuedKeyType == SecurityKeyType.BearerKey) && (version.TrustVersion == TrustVersion.WSTrustFeb2005))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("BearerKeyIncompatibleWithWSFederationHttpBinding")));
            }
            if (isReliableSession && !this.EstablishSecurityContext)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SecureConversationRequiredByReliableSession")));
            }
            bool emitBspRequiredAttributes = true;
            IssuedSecurityTokenParameters issuedTokenParameters = new IssuedSecurityTokenParameters(this.IssuedTokenType, this.IssuerAddress, this.IssuerBinding)
            {
                IssuerMetadataAddress = this.issuerMetadataAddress,
                KeyType = this.IssuedKeyType
            };

            if (this.IssuedKeyType == SecurityKeyType.SymmetricKey)
            {
                issuedTokenParameters.KeySize = this.AlgorithmSuite.DefaultSymmetricKeyLength;
            }
            else
            {
                issuedTokenParameters.KeySize = 0;
            }
            foreach (ClaimTypeRequirement requirement in this.claimTypeRequirements)
            {
                issuedTokenParameters.ClaimTypeRequirements.Add(requirement);
            }
            foreach (XmlElement element2 in this.TokenRequestParameters)
            {
                issuedTokenParameters.AdditionalRequestParameters.Add(element2);
            }
            WSSecurityTokenSerializer tokenSerializer  = new WSSecurityTokenSerializer(version.SecurityVersion, version.TrustVersion, version.SecureConversationVersion, emitBspRequiredAttributes, null, null, null);
            SecurityStandardsManager  standardsManager = new SecurityStandardsManager(version, tokenSerializer);

            issuedTokenParameters.AddAlgorithmParameters(this.AlgorithmSuite, standardsManager, this.issuedKeyType);
            if (isSecureTransportMode)
            {
                element3 = SecurityBindingElement.CreateIssuedTokenOverTransportBindingElement(issuedTokenParameters);
            }
            else if (this.negotiateServiceCredential)
            {
                element3 = SecurityBindingElement.CreateIssuedTokenForSslBindingElement(issuedTokenParameters, version.SecurityPolicyVersion != SecurityPolicyVersion.WSSecurityPolicy11);
            }
            else
            {
                element3 = SecurityBindingElement.CreateIssuedTokenForCertificateBindingElement(issuedTokenParameters);
            }
            element3.MessageSecurityVersion = version;
            element3.DefaultAlgorithmSuite  = this.AlgorithmSuite;
            if (this.EstablishSecurityContext)
            {
                element = SecurityBindingElement.CreateSecureConversationBindingElement(element3, true);
            }
            else
            {
                element = element3;
            }
            element.MessageSecurityVersion = version;
            element.DefaultAlgorithmSuite  = this.AlgorithmSuite;
            element.IncludeTimestamp       = true;
            if (!isReliableSession)
            {
                element.LocalServiceSettings.ReconnectTransportOnFailure = false;
                element.LocalClientSettings.ReconnectTransportOnFailure  = false;
            }
            else
            {
                element.LocalServiceSettings.ReconnectTransportOnFailure = true;
                element.LocalClientSettings.ReconnectTransportOnFailure  = true;
            }
            if (this.establishSecurityContext)
            {
                element3.LocalServiceSettings.IssuedCookieLifetime = NegotiationTokenAuthenticator <SspiNegotiationTokenAuthenticatorState> .defaultServerIssuedTransitionTokenLifetime;
            }
            return(element);
        }
        internal static bool TryCreate(SecurityBindingElement sbe, bool isSecureTransportMode, bool isReliableSession, MessageSecurityVersion version, out FederatedMessageSecurityOverHttp messageSecurity)
        {
            bool flag;
            bool flag2;
            bool flag3;
            IssuedSecurityTokenParameters parameters;
            Collection <XmlElement>       collection;

            messageSecurity = null;
            if (sbe.IncludeTimestamp)
            {
                SecurityBindingElement element;
                if (sbe.SecurityHeaderLayout != SecurityHeaderLayout.Strict)
                {
                    return(false);
                }
                flag    = true;
                flag2   = SecurityBindingElement.IsSecureConversationBinding(sbe, true, out element);
                element = flag2 ? element : sbe;
                if (isSecureTransportMode && !(element is TransportSecurityBindingElement))
                {
                    return(false);
                }
                flag3 = true;
                if (isSecureTransportMode)
                {
                    if (!SecurityBindingElement.IsIssuedTokenOverTransportBinding(element, out parameters))
                    {
                        return(false);
                    }
                    goto Label_0078;
                }
                if (SecurityBindingElement.IsIssuedTokenForSslBinding(element, version.SecurityPolicyVersion != SecurityPolicyVersion.WSSecurityPolicy11, out parameters))
                {
                    flag3 = true;
                    goto Label_0078;
                }
                if (SecurityBindingElement.IsIssuedTokenForCertificateBinding(element, out parameters))
                {
                    flag3 = false;
                    goto Label_0078;
                }
            }
            return(false);

Label_0078:
            if ((parameters.KeyType == SecurityKeyType.BearerKey) && (version.TrustVersion == TrustVersion.WSTrustFeb2005))
            {
                return(false);
            }
            WSSecurityTokenSerializer tokenSerializer  = new WSSecurityTokenSerializer(version.SecurityVersion, version.TrustVersion, version.SecureConversationVersion, flag, null, null, null);
            SecurityStandardsManager  standardsManager = new SecurityStandardsManager(version, tokenSerializer);

            if (!parameters.DoAlgorithmsMatch(sbe.DefaultAlgorithmSuite, standardsManager, out collection))
            {
                return(false);
            }
            messageSecurity = new FederatedMessageSecurityOverHttp();
            messageSecurity.AlgorithmSuite             = sbe.DefaultAlgorithmSuite;
            messageSecurity.NegotiateServiceCredential = flag3;
            messageSecurity.EstablishSecurityContext   = flag2;
            messageSecurity.IssuedTokenType            = parameters.TokenType;
            messageSecurity.IssuerAddress         = parameters.IssuerAddress;
            messageSecurity.IssuerBinding         = parameters.IssuerBinding;
            messageSecurity.IssuerMetadataAddress = parameters.IssuerMetadataAddress;
            messageSecurity.IssuedKeyType         = parameters.KeyType;
            foreach (ClaimTypeRequirement requirement in parameters.ClaimTypeRequirements)
            {
                messageSecurity.ClaimTypeRequirements.Add(requirement);
            }
            foreach (XmlElement element2 in collection)
            {
                messageSecurity.TokenRequestParameters.Add(element2);
            }
            if ((parameters.AlternativeIssuerEndpoints != null) && (parameters.AlternativeIssuerEndpoints.Count > 0))
            {
                return(false);
            }
            return(true);
        }
        private Collection <XmlElement> NormalizeAdditionalParameters(Collection <XmlElement> additionalParameters, TrustDriver driver, bool clientSideClaimTypeRequirementsSpecified)
        {
            Collection <XmlElement> collection = new Collection <XmlElement>();

            foreach (XmlElement element in additionalParameters)
            {
                collection.Add(element);
            }
            if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)
            {
                XmlElement item     = null;
                XmlElement element3 = null;
                XmlElement element4 = null;
                XmlElement element5 = null;
                for (int i = 0; i < collection.Count; i++)
                {
                    string str;
                    if (driver.IsEncryptionAlgorithmElement(collection[i], out str))
                    {
                        item = collection[i];
                    }
                    else if (driver.IsCanonicalizationAlgorithmElement(collection[i], out str))
                    {
                        element3 = collection[i];
                    }
                    else if (driver.IsKeyWrapAlgorithmElement(collection[i], out str))
                    {
                        element4 = collection[i];
                    }
                    else if (((WSTrustDec2005.DriverDec2005)driver).IsSecondaryParametersElement(collection[i]))
                    {
                        element5 = collection[i];
                    }
                }
                if (element5 != null)
                {
                    foreach (System.Xml.XmlNode node in element5.ChildNodes)
                    {
                        XmlElement element6 = node as XmlElement;
                        if (element6 != null)
                        {
                            string encryptionAlgorithm = null;
                            if (driver.IsEncryptionAlgorithmElement(element6, out encryptionAlgorithm) && (item != null))
                            {
                                collection.Remove(item);
                            }
                            else if (driver.IsCanonicalizationAlgorithmElement(element6, out encryptionAlgorithm) && (element3 != null))
                            {
                                collection.Remove(element3);
                            }
                            else if (driver.IsKeyWrapAlgorithmElement(element6, out encryptionAlgorithm) && (element4 != null))
                            {
                                collection.Remove(element4);
                            }
                        }
                    }
                }
            }
            if (((driver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005) && !this.CollectionContainsElementsWithTrustNamespace(additionalParameters, "http://schemas.xmlsoap.org/ws/2005/02/trust")) || ((driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13) && !this.CollectionContainsElementsWithTrustNamespace(additionalParameters, "http://docs.oasis-open.org/ws-sx/ws-trust/200512")))
            {
                if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)
                {
                    WSTrustFeb2005.DriverFeb2005 feb = (WSTrustFeb2005.DriverFeb2005)SecurityStandardsManager.DefaultInstance.TrustDriver;
                    for (int j = 0; j < collection.Count; j++)
                    {
                        string signatureAlgorithm = string.Empty;
                        if (feb.IsSignWithElement(collection[j], out signatureAlgorithm))
                        {
                            collection[j] = driver.CreateSignWithElement(signatureAlgorithm);
                        }
                        else if (feb.IsEncryptWithElement(collection[j], out signatureAlgorithm))
                        {
                            collection[j] = driver.CreateEncryptWithElement(signatureAlgorithm);
                        }
                        else if (feb.IsEncryptionAlgorithmElement(collection[j], out signatureAlgorithm))
                        {
                            collection[j] = driver.CreateEncryptionAlgorithmElement(signatureAlgorithm);
                        }
                        else if (feb.IsCanonicalizationAlgorithmElement(collection[j], out signatureAlgorithm))
                        {
                            collection[j] = driver.CreateCanonicalizationAlgorithmElement(signatureAlgorithm);
                        }
                    }
                    return(collection);
                }
                Collection <XmlElement>      collection2     = null;
                WSSecurityTokenSerializer    tokenSerializer = new WSSecurityTokenSerializer(SecurityVersion.WSSecurity11, TrustVersion.WSTrust13, SecureConversationVersion.WSSecureConversation13, true, null, null, null);
                SecurityStandardsManager     manager2        = new SecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, tokenSerializer);
                WSTrustDec2005.DriverDec2005 trustDriver     = (WSTrustDec2005.DriverDec2005)manager2.TrustDriver;
                foreach (XmlElement element7 in collection)
                {
                    if (trustDriver.IsSecondaryParametersElement(element7))
                    {
                        collection2 = new Collection <XmlElement>();
                        foreach (System.Xml.XmlNode node2 in element7.ChildNodes)
                        {
                            XmlElement innerElement = node2 as XmlElement;
                            if ((innerElement != null) && this.CanPromoteToRoot(innerElement, trustDriver, clientSideClaimTypeRequirementsSpecified))
                            {
                                collection2.Add(innerElement);
                            }
                        }
                        collection.Remove(element7);
                        break;
                    }
                }
                if ((collection2 != null) && (collection2.Count > 0))
                {
                    XmlElement element9  = null;
                    string     str4      = string.Empty;
                    XmlElement element10 = null;
                    string     canonicalizationAlgorithm = string.Empty;
                    XmlElement element11 = null;
                    Collection <XmlElement> requiredClaims = null;
                    Collection <XmlElement> collection4    = new Collection <XmlElement>();
                    foreach (XmlElement element12 in collection2)
                    {
                        if ((element9 == null) && trustDriver.IsEncryptionAlgorithmElement(element12, out str4))
                        {
                            element9 = driver.CreateEncryptionAlgorithmElement(str4);
                            collection4.Add(element12);
                        }
                        else if ((element10 == null) && trustDriver.IsCanonicalizationAlgorithmElement(element12, out canonicalizationAlgorithm))
                        {
                            element10 = driver.CreateCanonicalizationAlgorithmElement(canonicalizationAlgorithm);
                            collection4.Add(element12);
                        }
                        else if ((element11 == null) && trustDriver.TryParseRequiredClaimsElement(element12, out requiredClaims))
                        {
                            element11 = driver.CreateRequiredClaimsElement(requiredClaims);
                            collection4.Add(element12);
                        }
                    }
                    for (int k = 0; k < collection4.Count; k++)
                    {
                        collection2.Remove(collection4[k]);
                    }
                    XmlElement element13 = null;
                    for (int m = 0; m < collection.Count; m++)
                    {
                        string str6;
                        if (trustDriver.IsSignWithElement(collection[m], out str6))
                        {
                            collection[m] = driver.CreateSignWithElement(str6);
                        }
                        else if (trustDriver.IsEncryptWithElement(collection[m], out str6))
                        {
                            collection[m] = driver.CreateEncryptWithElement(str6);
                        }
                        else if (trustDriver.IsEncryptionAlgorithmElement(collection[m], out str6) && (element9 != null))
                        {
                            collection[m] = element9;
                            element9      = null;
                        }
                        else if (trustDriver.IsCanonicalizationAlgorithmElement(collection[m], out str6) && (element10 != null))
                        {
                            collection[m] = element10;
                            element10     = null;
                        }
                        else if (trustDriver.IsKeyWrapAlgorithmElement(collection[m], out str6) && (element13 == null))
                        {
                            element13 = collection[m];
                        }
                        else
                        {
                            Collection <XmlElement> collection5;
                            if (trustDriver.TryParseRequiredClaimsElement(collection[m], out collection5) && (element11 != null))
                            {
                                collection[m] = element11;
                                element11     = null;
                            }
                        }
                    }
                    if (element13 != null)
                    {
                        collection.Remove(element13);
                    }
                    if (element9 != null)
                    {
                        collection.Add(element9);
                    }
                    if (element10 != null)
                    {
                        collection.Add(element10);
                    }
                    if (element11 != null)
                    {
                        collection.Add(element11);
                    }
                    if (collection2.Count <= 0)
                    {
                        return(collection);
                    }
                    for (int n = 0; n < collection2.Count; n++)
                    {
                        collection.Add(collection2[n]);
                    }
                }
            }
            return(collection);
        }
コード例 #22
0
        // Methods of BodyWriter
        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement(Constants.Trust.Elements.RequestSecurityTokenResponse, Constants.Trust.NamespaceUri);

            if (this.TokenType != null && this.TokenType.Length > 0)
            {
                writer.WriteStartElement(Constants.Trust.Elements.TokenType, Constants.Trust.NamespaceUri);
                writer.WriteString(this.TokenType);
                writer.WriteEndElement(); // wst:TokenType
            }

            WSSecurityTokenSerializer ser = new WSSecurityTokenSerializer();

            if (this.RequestedSecurityToken != null)
            {
                writer.WriteStartElement(Constants.Trust.Elements.RequestedSecurityToken, Constants.Trust.NamespaceUri);
                ser.WriteToken(writer, this.RequestedSecurityToken);
                writer.WriteEndElement(); // wst:RequestedSecurityToken
            }

            if (this.RequestedAttachedReference != null)
            {
                writer.WriteStartElement(Constants.Trust.Elements.RequestedAttachedReference, Constants.Trust.NamespaceUri);
                ser.WriteKeyIdentifierClause(writer, this.RequestedAttachedReference);
                writer.WriteEndElement(); // wst:RequestedAttachedReference
            }

            if (this.RequestedUnattachedReference != null)
            {
                writer.WriteStartElement(Constants.Trust.Elements.RequestedUnattachedReference, Constants.Trust.NamespaceUri);
                ser.WriteKeyIdentifierClause(writer, this.RequestedUnattachedReference);
                writer.WriteEndElement(); // wst:RequestedAttachedReference
            }

            if (this.AppliesTo != null)
            {
                writer.WriteStartElement(Constants.Policy.Elements.AppliesTo, Constants.Policy.NamespaceUri);
                this.AppliesTo.WriteTo(AddressingVersion.WSAddressing10, writer);
                writer.WriteEndElement(); // wsp:AppliesTo
            }

            if (this.RequestedProofToken != null)// Issuer entropy; write RPT only
            {
                writer.WriteStartElement(Constants.Trust.Elements.RequestedProofToken, Constants.Trust.NamespaceUri);
                ser.WriteToken(writer, this.RequestedProofToken);
                writer.WriteEndElement(); // wst:RequestedSecurityToken
            }

            if (this.IssuerEntropy != null && this.ComputeKey) // Combined entropy; write RPT and Entropy
            {
                writer.WriteStartElement(Constants.Trust.Elements.RequestedProofToken, Constants.Trust.NamespaceUri);
                writer.WriteStartElement(Constants.Trust.Elements.ComputedKey, Constants.Trust.NamespaceUri);
                writer.WriteValue(Constants.Trust.ComputedKeyAlgorithms.PSHA1);
                writer.WriteEndElement(); // wst:ComputedKey
                writer.WriteEndElement(); // wst:RequestedSecurityToken

                if (this.IssuerEntropy != null)
                {
                    writer.WriteStartElement(Constants.Trust.Elements.Entropy, Constants.Trust.NamespaceUri);
                    ser.WriteToken(writer, this.IssuerEntropy);
                    writer.WriteEndElement(); // wst:Entropy
                }
            }

            writer.WriteEndElement(); // wst:RequestSecurityTokenResponse
        }
コード例 #23
0
ファイル: UserIdentity.cs プロジェクト: benvert/pfe
        /// <summary cref="IUserIdentity.GetIdentityToken" />
        public UserIdentityToken GetIdentityToken()
        {
            // check for anonymous.
            if (m_token == null)
            {
                AnonymousIdentityToken token = new AnonymousIdentityToken();
                token.PolicyId = m_policyId;
                return(token);
            }

            // return a user name token.
            UserNameSecurityToken usernameToken = m_token as UserNameSecurityToken;

            if (usernameToken != null)
            {
                UserNameIdentityToken token = new UserNameIdentityToken();
                token.PolicyId          = m_policyId;
                token.UserName          = usernameToken.UserName;
                token.DecryptedPassword = usernameToken.Password;
                return(token);
            }

            // return an X509 token.
            X509SecurityToken x509Token = m_token as X509SecurityToken;

            if (x509Token != null)
            {
                X509IdentityToken token = new X509IdentityToken();
                token.PolicyId        = m_policyId;
                token.CertificateData = x509Token.Certificate.GetRawCertData();
                token.Certificate     = x509Token.Certificate;
                return(token);
            }

            // handle SAML token.
            SamlSecurityToken samlToken = m_token as SamlSecurityToken;

            if (samlToken != null)
            {
                MemoryStream  ostrm  = new MemoryStream();
                XmlTextWriter writer = new XmlTextWriter(ostrm, new UTF8Encoding());

                try
                {
                    SamlSerializer serializer = new SamlSerializer();
                    serializer.WriteToken(samlToken, writer, WSSecurityTokenSerializer.DefaultInstance);
                }
                finally
                {
                    writer.Close();
                }

                IssuedIdentityToken wssToken = new IssuedIdentityToken();
                wssToken.PolicyId           = m_policyId;
                wssToken.DecryptedTokenData = ostrm.ToArray();

                return(wssToken);
            }

            // return a WSS token by default.
            if (m_token != null)
            {
                MemoryStream ostrm  = new MemoryStream();
                XmlWriter    writer = new XmlTextWriter(ostrm, new UTF8Encoding());

                try
                {
                    WSSecurityTokenSerializer serializer = new WSSecurityTokenSerializer();
                    serializer.WriteToken(writer, m_token);
                }
                finally
                {
                    writer.Close();
                }

                IssuedIdentityToken wssToken = new IssuedIdentityToken();
                wssToken.PolicyId           = m_policyId;
                wssToken.DecryptedTokenData = ostrm.ToArray();

                return(wssToken);
            }

            return(null);
        }