/// <summary>
 /// Initializes a new instance of the <see cref="BaseFault"/> class with the supplied values.
 /// </summary>
 /// <remarks>If the supplied date is not in UTC, the value will be coerced.</remarks>
 /// <param name="utc">The <see cref="Timestamp"/> value.</param>
 /// <param name="originator">The optional <see cref="Originator"/> value.</param>
 /// <param name="errorCode">The optional <see cref="ErrorCode"/> value.</param>
 /// <param name="descriptions">The optional <see cref="Description"/> elements. Any null items are filtered.</param>
 protected BaseFaultFull(DateTime utc, EndpointAddress originator, ErrorCode errorCode, IEnumerable <Description> descriptions)
     : this(utc)
 {
     this.originator   = originator == null ? null : EndpointAddress10.FromEndpointAddress(originator);
     this.errorCode    = errorCode;
     this.descriptions = new DescriptionCollection(descriptions);
 }
Beispiel #2
0
        public void CanSetProperties()
        {
            var endpoint   = EndpointAddress10.FromEndpointAddress(new EndpointAddress("http://someUri"));
            var errorCode  = new ErrorCode(new Uri("http://foo"));
            var now        = DateTime.UtcNow;
            var faultCause = (new Mock <BaseFaultFull>()).Object;

            var mock = new Mock <BaseFaultFull>(now);

            mock.CallBase = true;

            BaseFaultFull target = mock.Object;

            Assert.IsNull(target.ErrorCode);  // Sanity check
            Assert.IsNull(target.FaultCause); // Sanity check
            Assert.IsNull(target.Originator); // Sanity check

            target.ErrorCode = errorCode;
            Assert.That(target.ErrorCode, Is.SameAs(errorCode));
            target.ErrorCode = null;
            Assert.That(target.ErrorCode, Is.Null);

            target.FaultCause = faultCause;
            Assert.That(target.FaultCause, Is.SameAs(faultCause));
            target.FaultCause = null;
            Assert.That(target.FaultCause, Is.Null);

            target.Originator = endpoint;
            Assert.That(target.Originator, Is.SameAs(endpoint));
            target.Originator = null;
            Assert.That(target.Originator, Is.Null);
        }
 public RegistrationCoordinatorResponseInvalidMetadataSchema11(CoordinationContext context, ControlProtocol protocol, EndpointAddress coordinatorService) : base(context, protocol)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RegistrationCoordinatorResponseInvalidMetadata11TraceRecord";
     if (coordinatorService != null)
     {
         this.coordinatorService = EndpointAddress10.FromEndpointAddress(coordinatorService);
     }
 }
Beispiel #4
0
        public void IXmlSerializableGetSchema()
        {
            // actually it just returns null.
            EndpointAddress10 e  = EndpointAddress10.FromEndpointAddress(new EndpointAddress("http://localhost:8080"));
            XmlSchema         xs = ((IXmlSerializable)e).GetSchema();

            Assert.IsNull(xs);
        }
Beispiel #5
0
 public RegisterFailureRecordSchema11(string transactionId, ControlProtocol protocol, EndpointAddress protocolService, string reason) : base(transactionId, protocol, reason)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RegisterFailure11TraceRecord";
     if (protocolService != null)
     {
         this.protocolService = EndpointAddress10.FromEndpointAddress(protocolService);
     }
 }
 public VolatileEnlistmentInDoubtRecordSchema11(Guid enlistmentId, EndpointAddress replyTo) : base(enlistmentId)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/VolatileEnlistmentInDoubt11TraceRecord";
     if (replyTo != null)
     {
         this.replyTo = EndpointAddress10.FromEndpointAddress(replyTo);
     }
 }
 public RecoverCoordinatorRecordSchema11(string transactionId, EndpointAddress coordinatorService) : base(transactionId)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RecoverCoordinator11TraceRecord";
     if (coordinatorService != null)
     {
         this.coordinatorService = EndpointAddress10.FromEndpointAddress(coordinatorService);
     }
 }
Beispiel #8
0
 public RecoverParticipantRecordSchema11(string transactionId, Guid enlistmentId, EndpointAddress participantService) : base(transactionId, enlistmentId)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RecoverParticipant11TraceRecord";
     if (participantService != null)
     {
         this.participantService = EndpointAddress10.FromEndpointAddress(participantService);
     }
 }
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            this.ReadStartElement(reader);

            while (reader.NodeType != XmlNodeType.EndElement)
            {
                if (reader.IsStartElement("Timestamp", Constants.WsBaseFaults.Namespace))
                {
                    this.timestamp = reader.ReadElementContentAsDateTime();
                }
                else if (reader.IsStartElement("Originator", Constants.WsBaseFaults.Namespace))
                {
                    var epa = reader.ReadOuterXml();
                    using (var stringReader = new StringReader(epa))
                    {
                        var innerReader = XmlReader.Create(stringReader);
                        using (var dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(innerReader))
                        {
                            this.originator = EndpointAddress10.FromEndpointAddress(EndpointAddress.ReadFrom(dictionaryReader));
                        }
                    }
                }
                else if (reader.IsStartElement("ErrorCode", Constants.WsBaseFaults.Namespace))
                {
                    this.errorCode = this.CreateErrorCode(reader);
                }
                else if (reader.IsStartElement("Description", Constants.WsBaseFaults.Namespace))
                {
                    var description = new Description(reader);
                    this.descriptions.Add(description);
                }
                else if (reader.IsStartElement("FaultCause", Constants.WsBaseFaults.Namespace))
                {
                    if (reader.IsEmptyElement)
                    {
                        continue;
                    }

                    using (var stringReader = new StringReader(reader.ReadInnerXml()))
                    {
                        var innerReader = XmlReader.Create(stringReader);
                        innerReader.Read();
                        this.faultCause = CreateFaultCause(innerReader);
                    }
                }
                else
                {
                    this.ProcessAdditionalElements(reader);
                }
            }
            reader.ReadEndElement();
        }
Beispiel #10
0
        public void ReadFromE10Error()
        {
            //Address is from August2004 namespace, but reading it with EndpointAddress10
            string              xml    = @"<a:ReplyTo xmlns:a='http://schemas.xmlsoap.org/ws/2004/08/addressing'><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo>";
            XmlReader           src    = XmlReader.Create(new StringReader(xml));
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateDictionaryReader(src);

            EndpointAddress10 e10 = EndpointAddress10.FromEndpointAddress(new EndpointAddress(("http://test")));

            ((IXmlSerializable)e10).ReadXml(reader);
        }
Beispiel #11
0
        public void ReadFromE10Error2()
        {
            //Missing <Address> element
            string              xml    = @"<a:ReplyTo xmlns:a='http://www.w3.org/2005/08/addressing'>http://www.w3.org/2005/08/addressing/anonymous</a:ReplyTo>";
            XmlReader           src    = XmlReader.Create(new StringReader(xml));
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateDictionaryReader(src);

            EndpointAddress10 e10 = EndpointAddress10.FromEndpointAddress(new EndpointAddress(("http://test")));

            ((IXmlSerializable)e10).ReadXml(reader);
        }
        public static CorrelationCallbackContext CreateCorrelationCallbackContext(MessageProperties messageProperties)
        {
            CallbackContextMessageProperty property;

            if (CallbackContextMessageProperty.TryGet(messageProperties, out property))
            {
                EndpointAddress address;
                IDictionary <string, string> dictionary;
                property.GetListenAddressAndContext(out address, out dictionary);
                return(new CorrelationCallbackContext {
                    ListenAddress = EndpointAddress10.FromEndpointAddress(address), Context = dictionary
                });
            }
            return(null);
        }
Beispiel #13
0
        public void ReadFromE10()
        {
            string              xml    = @"<a:ReplyTo xmlns:a='http://www.w3.org/2005/08/addressing'><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo>";
            XmlReader           src    = XmlReader.Create(new StringReader(xml));
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateDictionaryReader(src);

            EndpointAddress10 e10 = EndpointAddress10.FromEndpointAddress(new EndpointAddress(("http://test")));

            ((IXmlSerializable)e10).ReadXml(reader);

            EndpointAddress a = e10.ToEndpointAddress();

            Assert.AreEqual("http://schemas.microsoft.com/2005/12/ServiceModel/Addressing/Anonymous", a.Uri.AbsoluteUri, "#1");
            Assert.IsTrue(a.IsAnonymous, "#2");
        }
Beispiel #14
0
        public void GetSchema()
        {
            // actually it just returns null. That makes sense
            // since there's no way to include reasonable claim
            // schemas.
            EndpointAddress10.FromEndpointAddress(new EndpointAddress("http://localhost:8080"));
            XmlSchemaSet     xss = new XmlSchemaSet();
            XmlQualifiedName q   = EndpointAddress10.GetSchema(xss);

            Assert.AreEqual(1, xss.Count, "#1");
            Assert.AreEqual("EndpointReferenceType", q.Name, "#2");
            Assert.AreEqual("http://www.w3.org/2005/08/addressing", q.Namespace, "#2");
            foreach (XmlSchema xs in xss.Schemas())
            {
                Assert.AreEqual("http://www.w3.org/2005/08/addressing", xs.TargetNamespace, "#4");
            }
        }
Beispiel #15
0
        public static CorrelationCallbackContext CreateCorrelationCallbackContext(MessageProperties messageProperties)
        {
            CallbackContextMessageProperty callbackMessageContextProperty;

            if (CallbackContextMessageProperty.TryGet(messageProperties, out callbackMessageContextProperty))
            {
                EndpointAddress listenAddress;
                IDictionary <string, string> context;
                callbackMessageContextProperty.GetListenAddressAndContext(out listenAddress, out context);

                return(new CorrelationCallbackContext
                {
                    ListenAddress = EndpointAddress10.FromEndpointAddress(listenAddress),
                    Context = context
                });
            }
            return(null);
        }
        private void SetReturnAddress(object sender, EventArgs e)
        {
            EndpointAddress epr = ContextManager.CreateEndpointAddress(ReturnUri, this.ReceiveWorkItemComplete);

            ReturnAddress = EndpointAddress10.FromEndpointAddress(epr);
            Dictionary <string, string> context = epr.Headers[0].GetValue <Dictionary <string, string> >();

            StringBuilder contextString = new StringBuilder();

            foreach (KeyValuePair <string, string> pair in context)
            {
                contextString.Append(pair.Key);
                contextString.Append(":");
                contextString.Append(pair.Value);
            }

            DebugOutput("[ClientWorkflow:SetReturnAddress] " + contextString.ToString());
        }
        public static void WriteEndPointAddress(DiscoveryVersion discoveryVersion, EndpointAddress endpointAddress, XmlWriter writer)
        {
            Fx.Assert(discoveryVersion != null, "The discoveryVersion must be non null");
            Fx.Assert(writer != null, "The writer must be non null");

            if (discoveryVersion == DiscoveryVersion.WSDiscoveryApril2005 || discoveryVersion == DiscoveryVersion.WSDiscoveryCD1)
            {
                EndpointAddressAugust2004 endpoint = EndpointAddressAugust2004.FromEndpointAddress(endpointAddress);
                discoveryVersion.Implementation.EprSerializer.WriteObject(writer, endpoint);
            }
            else if (discoveryVersion == DiscoveryVersion.WSDiscovery11)
            {
                EndpointAddress10 endpoint = EndpointAddress10.FromEndpointAddress(endpointAddress);
                discoveryVersion.Implementation.EprSerializer.WriteObject(writer, endpoint);
            }
            else
            {
                Fx.Assert("The discoveryVersion parameter cannot be null.");
            }
        }
Beispiel #18
0
        public void SerializeDeserialize()
        {
            StringWriter sw = new StringWriter();

            EndpointAddress10 e = EndpointAddress10.FromEndpointAddress(new EndpointAddress("http://*****:*****@"<?xml version=""1.0"" encoding=""utf-16""?><EndpointReference xmlns=""http://www.w3.org/2005/08/addressing""><Address>http://localhost:8080/</Address></EndpointReference>", sw.ToString());
            StringReader sr = new StringReader(sw.ToString());

            using (XmlReader xr = XmlReader.Create(sr)) {
                xs.Deserialize(xr);
            }
        }
Beispiel #19
0
        void AddEndpointAddressHeader(string name, string ns, EndpointAddress address)
        {
            if (address == null)
            {
                return;
            }
            if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressing10))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddress10.FromEndpointAddress(address)));
            }
#if !MOBILE
            else if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressingAugust2004))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddressAugust2004.FromEndpointAddress(address)));
            }
#endif
            else
            {
                throw new InvalidOperationException("WS-Addressing header is not allowed for AddressingVersion.None");
            }
        }
Beispiel #20
0
        public static void Main()
        {
            // <Snippet1>
            // Create an EndpointAddress with a specified address.
            EndpointAddress epa1 = new EndpointAddress("http://localhost/ServiceModelSamples");

            Console.WriteLine("The URI of the EndpointAddress is {0}:", epa1.Uri);
            Console.WriteLine();

            //Initialize an EndpointAddress10 from the endpointAddress.
            EndpointAddress10 epa10 = EndpointAddress10.FromEndpointAddress(epa1);

            //Serialize and then deserializde the Endpoint10 type.

            //Convert the EndpointAddress10 back into an EndpointAddress.
            EndpointAddress epa2 = epa10.ToEndpointAddress();

            Console.WriteLine("The URI of the EndpointAddress is still {0}:", epa2.Uri);
            Console.WriteLine();
            // </Snippet1>
        }
Beispiel #21
0
        void AddEndpointAddressHeader(string name, string ns, EndpointAddress address)
        {
            RemoveAll("FaultTo", Constants.WsaNamespace);
            if (address == null)
            {
                return;
            }
            if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressing10))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddress10.FromEndpointAddress(address)));
            }
#if !NET_2_1
            else if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressingAugust2004))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddressAugust2004.FromEndpointAddress(address)));
            }
#endif
            else
            {
                throw new InvalidOperationException("WS-Addressing header is not allowed for AddressingVersion.None");
            }
        }
Beispiel #22
0
        public void ReadWriteXml()
        {
            StringWriter sw = new StringWriter();

            EndpointAddress10 e = EndpointAddress10.FromEndpointAddress(new EndpointAddress("http://*****:*****@"<?xml version=""1.0"" encoding=""utf-16""?><Address xmlns=""http://www.w3.org/2005/08/addressing"">http://localhost:8080/</Address>", sw.ToString());

            // unlike WriteXml, ReadXml expects the root element.
            StringReader sr = new StringReader(@"<EndpointReference xmlns=""http://www.w3.org/2005/08/addressing""><Address>http://localhost:8080/</Address></EndpointReference>");

            using (XmlReader xr = XmlReader.Create(sr)) {
                ((IXmlSerializable)e).ReadXml(xr);
            }

            sr = new StringReader(@"<EndpointReference xmlns=""http://www.w3.org/2005/08/addressing""><Address>http://localhost:8080/</Address></EndpointReference>");
            using (XmlReader xr = XmlReader.Create(sr))
                EndpointAddress.ReadFrom(AddressingVersion.WSAddressing10, xr);
        }
            protected override BodyWriter GetFirstOutgoingMessageBody(FederatedTokenProviderState negotiationState, out MessageProperties messageProperties)
            {
                messageProperties = null;
                RequestSecurityToken rst = new RequestSecurityToken(this.StandardsManager);

                if (this.addTargetServiceAppliesTo)
                {
                    if (this.MessageVersion.Addressing == AddressingVersion.WSAddressing10)
                    {
                        rst.SetAppliesTo <EndpointAddress10>(
                            EndpointAddress10.FromEndpointAddress(negotiationState.TargetAddress),
                            DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), DataContractSerializerDefaults.MaxItemsInObjectGraph));
                    }
                    else if (this.MessageVersion.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        rst.SetAppliesTo <EndpointAddressAugust2004>(
                            EndpointAddressAugust2004.FromEndpointAddress(negotiationState.TargetAddress),
                            DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), DataContractSerializerDefaults.MaxItemsInObjectGraph));
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, this.MessageVersion.Addressing)));
                    }
                }
                rst.Context = negotiationState.Context;
                if (!this.isKeySizePresentInRstProperties)
                {
                    rst.KeySize = this.keySize;
                }
                Collection <XmlElement> newRequestProperties = new Collection <XmlElement>();

                if (this.requestProperties != null)
                {
                    for (int i = 0; i < this.requestProperties.Count; ++i)
                    {
                        newRequestProperties.Add(this.requestProperties[i]);
                    }
                }
                if (!isKeyTypePresentInRstProperties)
                {
                    XmlElement keyTypeElement = this.StandardsManager.TrustDriver.CreateKeyTypeElement(this.keyType);
                    newRequestProperties.Insert(0, keyTypeElement);
                }
                if (this.keyType == SecurityKeyType.SymmetricKey)
                {
                    byte[] requestorEntropy = negotiationState.GetRequestorEntropy();
                    rst.SetRequestorEntropy(requestorEntropy);
                }
                else if (this.keyType == SecurityKeyType.AsymmetricKey)
                {
                    RsaKeyIdentifierClause rsaClause     = new RsaKeyIdentifierClause(negotiationState.Rsa);
                    SecurityKeyIdentifier  keyIdentifier = new SecurityKeyIdentifier(rsaClause);
                    newRequestProperties.Add(this.StandardsManager.TrustDriver.CreateUseKeyElement(keyIdentifier, this.StandardsManager));
                    RsaSecurityTokenParameters rsaParameters = new RsaSecurityTokenParameters();
                    rsaParameters.InclusionMode      = SecurityTokenInclusionMode.Never;
                    rsaParameters.RequireDerivedKeys = false;
                    SupportingTokenSpecification rsaSpec = new SupportingTokenSpecification(negotiationState.RsaSecurityToken, EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, SecurityTokenAttachmentMode.Endorsing, rsaParameters);
                    messageProperties = new MessageProperties();
                    SecurityMessageProperty security = new SecurityMessageProperty();
                    security.OutgoingSupportingTokens.Add(rsaSpec);
                    messageProperties.Security = security;
                }
                if (this.keyType == SecurityKeyType.SymmetricKey && this.KeyEntropyMode == SecurityKeyEntropyMode.CombinedEntropy)
                {
                    newRequestProperties.Add(this.StandardsManager.TrustDriver.CreateComputedKeyAlgorithmElement(this.StandardsManager.TrustDriver.ComputedKeyAlgorithm));
                }
                rst.RequestProperties = newRequestProperties;
                rst.MakeReadOnly();
                return(rst);
            }
        protected override BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out NegotiationTokenAuthenticatorState negotiationState)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            if (requestSecurityToken == null)
            {
                throw TraceUtility.ThrowHelperArgumentNull("requestSecurityToken", request);
            }
            try
            {
                if (requestSecurityToken.RequestType != null && requestSecurityToken.RequestType != this.StandardsManager.TrustDriver.RequestTypeIssue)
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.InvalidRstRequestType, requestSecurityToken.RequestType)), request);
                }
                if (requestSecurityToken.TokenType != null && requestSecurityToken.TokenType != this.SecurityContextTokenUri)
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.CannotIssueRstTokenType, requestSecurityToken.TokenType)), request);
                }

                EndpointAddress        appliesTo;
                DataContractSerializer appliesToSerializer;
                string appliesToName;
                string appliesToNamespace;
                requestSecurityToken.GetAppliesToQName(out appliesToName, out appliesToNamespace);
                if (appliesToName == AddressingStrings.EndpointReference && appliesToNamespace == request.Version.Addressing.Namespace)
                {
                    if (request.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        appliesToSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), DataContractSerializerDefaults.MaxItemsInObjectGraph);
                        appliesTo           = requestSecurityToken.GetAppliesTo <EndpointAddress10>(appliesToSerializer).ToEndpointAddress();
                    }
                    else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        appliesToSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), DataContractSerializerDefaults.MaxItemsInObjectGraph);
                        appliesTo           = requestSecurityToken.GetAppliesTo <EndpointAddressAugust2004>(appliesToSerializer).ToEndpointAddress();
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
                    }
                }
                else
                {
                    appliesTo           = null;
                    appliesToSerializer = null;
                }
                if (this.shouldMatchRstWithEndpointFilter)
                {
                    SecurityUtils.MatchRstWithEndpointFilter(request, this.EndpointFilterTable, this.ListenUri);
                }
                int           issuedKeySize;
                byte[]        issuerEntropy;
                byte[]        proofKey;
                SecurityToken proofToken;
                WSTrust.Driver.ProcessRstAndIssueKey(requestSecurityToken, null, this.KeyEntropyMode, this.SecurityAlgorithmSuite,
                                                     out issuedKeySize, out issuerEntropy, out proofKey, out proofToken);
                UniqueId contextId      = SecurityUtils.GenerateUniqueId();
                string   id             = SecurityUtils.GenerateId();
                DateTime effectiveTime  = DateTime.UtcNow;
                DateTime expirationTime = TimeoutHelper.Add(effectiveTime, this.ServiceTokenLifetime);
                // ensure that a SecurityContext is present in the message
                SecurityMessageProperty securityProperty = request.Properties.Security;
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;
                if (securityProperty != null)
                {
                    authorizationPolicies = SecuritySessionSecurityTokenAuthenticator.CreateSecureConversationPolicies(securityProperty, expirationTime);
                }
                else
                {
                    authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
                }
                SecurityContextSecurityToken serviceToken = this.IssueSecurityContextToken(contextId, id, proofKey, effectiveTime, expirationTime, authorizationPolicies,
                                                                                           this.EncryptStateInServiceToken);
                if (this.preserveBootstrapTokens)
                {
                    serviceToken.BootstrapMessageProperty = (securityProperty == null) ? null : (SecurityMessageProperty)securityProperty.CreateCopy();
                    SecurityUtils.ErasePasswordInUsernameTokenIfPresent(serviceToken.BootstrapMessageProperty);
                }
                RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(this.StandardsManager);
                rstr.Context = requestSecurityToken.Context;
                rstr.KeySize = issuedKeySize;
                rstr.RequestedUnattachedReference = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.External);
                rstr.RequestedAttachedReference   = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.Internal);
                rstr.TokenType = this.SecurityContextTokenUri;
                rstr.RequestedSecurityToken = serviceToken;
                if (issuerEntropy != null)
                {
                    rstr.SetIssuerEntropy(issuerEntropy);
                    rstr.ComputeKey = true;
                }
                if (proofToken != null)
                {
                    rstr.RequestedProofToken = proofToken;
                }
                if (appliesTo != null)
                {
                    if (request.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        rstr.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(appliesTo), appliesToSerializer);
                    }
                    else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        rstr.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(appliesTo), appliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
                    }
                }
                rstr.MakeReadOnly();
                negotiationState = new NegotiationTokenAuthenticatorState();
                negotiationState.SetServiceToken(serviceToken);

                if (this.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
                {
                    return(rstr);
                }
                else if (this.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversation13)
                {
                    List <RequestSecurityTokenResponse> rstrList = new List <RequestSecurityTokenResponse>(1);
                    rstrList.Add(rstr);
                    RequestSecurityTokenResponseCollection rstrCollection = new RequestSecurityTokenResponseCollection(rstrList, this.StandardsManager);
                    return(rstrCollection);
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }
            }
            finally
            {
                SecuritySessionSecurityTokenAuthenticator.RemoveCachedTokensIfRequired(request.Properties.Security);
            }
        }
Beispiel #25
0
            protected override BodyWriter GetFirstOutgoingMessageBody(IssuedSecurityTokenProvider.FederatedTokenProviderState negotiationState, out MessageProperties messageProperties)
            {
                messageProperties = null;
                RequestSecurityToken token = new RequestSecurityToken(base.StandardsManager);

                if (this.addTargetServiceAppliesTo)
                {
                    if (this.MessageVersion.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (this.MessageVersion.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { this.MessageVersion.Addressing })));
                        }
                        token.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(negotiationState.TargetAddress), DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), 0x10000));
                    }
                    else
                    {
                        token.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(negotiationState.TargetAddress), DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), 0x10000));
                    }
                }
                token.Context = negotiationState.Context;
                if (!this.isKeySizePresentInRstProperties)
                {
                    token.KeySize = this.keySize;
                }
                Collection <XmlElement> collection = new Collection <XmlElement>();

                if (this.requestProperties != null)
                {
                    for (int i = 0; i < this.requestProperties.Count; i++)
                    {
                        collection.Add(this.requestProperties[i]);
                    }
                }
                if (!this.isKeyTypePresentInRstProperties)
                {
                    XmlElement item = base.StandardsManager.TrustDriver.CreateKeyTypeElement(this.keyType);
                    collection.Insert(0, item);
                }
                if (this.keyType == SecurityKeyType.SymmetricKey)
                {
                    byte[] requestorEntropy = negotiationState.GetRequestorEntropy();
                    token.SetRequestorEntropy(requestorEntropy);
                }
                else if (this.keyType == SecurityKeyType.AsymmetricKey)
                {
                    RsaKeyIdentifierClause clause        = new RsaKeyIdentifierClause(negotiationState.Rsa);
                    SecurityKeyIdentifier  keyIdentifier = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { clause });
                    collection.Add(base.StandardsManager.TrustDriver.CreateUseKeyElement(keyIdentifier, base.StandardsManager));
                    RsaSecurityTokenParameters tokenParameters = new RsaSecurityTokenParameters {
                        InclusionMode      = SecurityTokenInclusionMode.Never,
                        RequireDerivedKeys = false
                    };
                    SupportingTokenSpecification specification = new SupportingTokenSpecification(negotiationState.RsaSecurityToken, System.ServiceModel.Security.EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, SecurityTokenAttachmentMode.Endorsing, tokenParameters);
                    messageProperties = new MessageProperties();
                    SecurityMessageProperty property = new SecurityMessageProperty {
                        OutgoingSupportingTokens = { specification }
                    };
                    messageProperties.Security = property;
                }
                if ((this.keyType == SecurityKeyType.SymmetricKey) && (this.KeyEntropyMode == SecurityKeyEntropyMode.CombinedEntropy))
                {
                    collection.Add(base.StandardsManager.TrustDriver.CreateComputedKeyAlgorithmElement(base.StandardsManager.TrustDriver.ComputedKeyAlgorithm));
                }
                token.RequestProperties = collection;
                token.MakeReadOnly();
                return(token);
            }
        private BodyWriter ProcessNegotiation(SspiNegotiationTokenAuthenticatorState negotiationState, Message incomingMessage, BinaryNegotiation incomingNego)
        {
            BinaryNegotiation outgoingBinaryNegotiation;
            ISspiNegotiation  sspiNegotiation = negotiationState.SspiNegotiation;

            byte[] outgoingBlob = sspiNegotiation.GetOutgoingBlob(incomingNego.GetNegotiationData(), System.ServiceModel.Security.SecurityUtils.GetChannelBindingFromMessage(incomingMessage), this.extendedProtectionPolicy);
            if (!sspiNegotiation.IsValidContext)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("InvalidSspiNegotiation")), incomingMessage);
            }
            if ((outgoingBlob == null) && !sspiNegotiation.IsCompleted)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("NoBinaryNegoToSend")), incomingMessage);
            }
            if (outgoingBlob != null)
            {
                outgoingBinaryNegotiation = this.GetOutgoingBinaryNegotiation(sspiNegotiation, outgoingBlob);
            }
            else
            {
                outgoingBinaryNegotiation = null;
            }
            if (sspiNegotiation.IsCompleted)
            {
                SecurityContextSecurityToken token;
                WrappedKeySecurityToken      token2;
                int num;
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = this.ValidateSspiNegotiation(sspiNegotiation);
                this.IssueServiceToken(negotiationState, authorizationPolicies, out token, out token2, out num);
                negotiationState.SetServiceToken(token);
                SecurityKeyIdentifierClause  clause   = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token, SecurityTokenReferenceStyle.External);
                SecurityKeyIdentifierClause  clause2  = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token, SecurityTokenReferenceStyle.Internal);
                RequestSecurityTokenResponse response = new RequestSecurityTokenResponse(base.StandardsManager)
                {
                    Context   = negotiationState.Context,
                    KeySize   = num,
                    TokenType = base.SecurityContextTokenUri
                };
                if (outgoingBinaryNegotiation != null)
                {
                    response.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                response.RequestedUnattachedReference = clause;
                response.RequestedAttachedReference   = clause2;
                response.SetLifetime(token.ValidFrom, token.ValidTo);
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (incomingMessage.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { incomingMessage.Version.Addressing })));
                        }
                        response.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(negotiationState.AppliesTo), negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        response.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(negotiationState.AppliesTo), negotiationState.AppliesToSerializer);
                    }
                }
                response.MakeReadOnly();
                AddToDigest(negotiationState, response, false);
                RequestSecurityTokenResponse response2 = new RequestSecurityTokenResponse(base.StandardsManager)
                {
                    RequestedSecurityToken = token,
                    RequestedProofToken    = token2,
                    Context   = negotiationState.Context,
                    KeySize   = num,
                    TokenType = base.SecurityContextTokenUri
                };
                if (outgoingBinaryNegotiation != null)
                {
                    response2.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                response2.RequestedAttachedReference   = clause2;
                response2.RequestedUnattachedReference = clause;
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (incomingMessage.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { incomingMessage.Version.Addressing })));
                        }
                        response2.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(negotiationState.AppliesTo), negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        response2.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(negotiationState.AppliesTo), negotiationState.AppliesToSerializer);
                    }
                }
                response2.MakeReadOnly();
                byte[] authenticator = ComputeAuthenticator(negotiationState, token.GetKeyBytes());
                RequestSecurityTokenResponse response3 = new RequestSecurityTokenResponse(base.StandardsManager)
                {
                    Context = negotiationState.Context
                };
                response3.SetAuthenticator(authenticator);
                response3.MakeReadOnly();
                return(new RequestSecurityTokenResponseCollection(new List <RequestSecurityTokenResponse>(2)
                {
                    response2, response3
                }, base.StandardsManager));
            }
            RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(base.StandardsManager)
            {
                Context = negotiationState.Context
            };

            rstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
            rstr.MakeReadOnly();
            AddToDigest(negotiationState, rstr, false);
            return(rstr);
        }
        protected override BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out NegotiationTokenAuthenticatorState negotiationState)
        {
            BodyWriter writer;

            if (request == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            if (requestSecurityToken == null)
            {
                throw TraceUtility.ThrowHelperArgumentNull("requestSecurityToken", request);
            }
            try
            {
                EndpointAddress        address;
                DataContractSerializer serializer;
                string        str;
                string        str2;
                int           num;
                byte[]        buffer;
                byte[]        buffer2;
                SecurityToken token;
                ReadOnlyCollection <IAuthorizationPolicy> instance;
                if ((requestSecurityToken.RequestType != null) && (requestSecurityToken.RequestType != base.StandardsManager.TrustDriver.RequestTypeIssue))
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(System.ServiceModel.SR.GetString("InvalidRstRequestType", new object[] { requestSecurityToken.RequestType })), request);
                }
                if ((requestSecurityToken.TokenType != null) && (requestSecurityToken.TokenType != base.SecurityContextTokenUri))
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(System.ServiceModel.SR.GetString("CannotIssueRstTokenType", new object[] { requestSecurityToken.TokenType })), request);
                }
                requestSecurityToken.GetAppliesToQName(out str, out str2);
                if ((str == "EndpointReference") && (str2 == request.Version.Addressing.Namespace))
                {
                    if (request.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (request.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { request.Version.Addressing })));
                        }
                        serializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), 0x10000);
                        address    = requestSecurityToken.GetAppliesTo <EndpointAddressAugust2004>(serializer).ToEndpointAddress();
                    }
                    else
                    {
                        serializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), 0x10000);
                        address    = requestSecurityToken.GetAppliesTo <EndpointAddress10>(serializer).ToEndpointAddress();
                    }
                }
                else
                {
                    address    = null;
                    serializer = null;
                }
                if (this.shouldMatchRstWithEndpointFilter)
                {
                    System.ServiceModel.Security.SecurityUtils.MatchRstWithEndpointFilter(request, base.EndpointFilterTable, base.ListenUri);
                }
                WSTrust.Driver.ProcessRstAndIssueKey(requestSecurityToken, null, this.KeyEntropyMode, base.SecurityAlgorithmSuite, out num, out buffer, out buffer2, out token);
                UniqueId contextId               = System.ServiceModel.Security.SecurityUtils.GenerateUniqueId();
                string   id                      = System.ServiceModel.Security.SecurityUtils.GenerateId();
                DateTime utcNow                  = DateTime.UtcNow;
                DateTime expirationTime          = TimeoutHelper.Add(utcNow, base.ServiceTokenLifetime);
                SecurityMessageProperty security = request.Properties.Security;
                if (security != null)
                {
                    instance = SecuritySessionSecurityTokenAuthenticator.CreateSecureConversationPolicies(security, expirationTime);
                }
                else
                {
                    instance = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
                }
                SecurityContextSecurityToken token2 = base.IssueSecurityContextToken(contextId, id, buffer2, utcNow, expirationTime, instance, base.EncryptStateInServiceToken);
                if (this.preserveBootstrapTokens)
                {
                    token2.BootstrapMessageProperty = (security == null) ? null : ((SecurityMessageProperty)security.CreateCopy());
                    System.ServiceModel.Security.SecurityUtils.ErasePasswordInUsernameTokenIfPresent(token2.BootstrapMessageProperty);
                }
                RequestSecurityTokenResponse response = new RequestSecurityTokenResponse(base.StandardsManager)
                {
                    Context = requestSecurityToken.Context,
                    KeySize = num,
                    RequestedUnattachedReference = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token2, SecurityTokenReferenceStyle.External),
                    RequestedAttachedReference   = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token2, SecurityTokenReferenceStyle.Internal),
                    TokenType = base.SecurityContextTokenUri,
                    RequestedSecurityToken = token2
                };
                if (buffer != null)
                {
                    response.SetIssuerEntropy(buffer);
                    response.ComputeKey = true;
                }
                if (token != null)
                {
                    response.RequestedProofToken = token;
                }
                if (address != null)
                {
                    if (request.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (request.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { request.Version.Addressing })));
                        }
                        response.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(address), serializer);
                    }
                    else
                    {
                        response.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(address), serializer);
                    }
                }
                response.MakeReadOnly();
                negotiationState = new NegotiationTokenAuthenticatorState();
                negotiationState.SetServiceToken(token2);
                if (base.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
                {
                    return(response);
                }
                if (base.StandardsManager.MessageSecurityVersion.SecureConversationVersion != SecureConversationVersion.WSSecureConversation13)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }
                RequestSecurityTokenResponseCollection responses = new RequestSecurityTokenResponseCollection(new List <RequestSecurityTokenResponse>(1)
                {
                    response
                }, base.StandardsManager);
                writer = responses;
            }
            finally
            {
                SecuritySessionSecurityTokenAuthenticator.RemoveCachedTokensIfRequired(request.Properties.Security);
            }
            return(writer);
        }
Beispiel #28
0
        public Message SecureMessage()
        {
            secprop = Message.Properties.Security ?? new SecurityMessageProperty();

            SecurityToken encToken =
                secprop.InitiatorToken != null ? secprop.InitiatorToken.SecurityToken : security.EncryptionToken;
            // FIXME: it might be still incorrect.
            SecurityToken signToken =
                Parameters == CounterParameters ? null :
                security.SigningToken;
            MessageProtectionOrder protectionOrder =
                security.MessageProtectionOrder;
            SecurityTokenSerializer serializer =
                security.TokenSerializer;
            SecurityBindingElement element =
                security.Element;
            SecurityAlgorithmSuite suite = element.DefaultAlgorithmSuite;

// FIXME: remove this hack
            if (!ShouldOutputEncryptedKey)
            {
                encToken = new BinarySecretSecurityToken(secprop.EncryptionKey);
            }

            string      messageId         = "uuid-" + Guid.NewGuid();
            int         identForMessageId = 1;
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;

            UniqueId relatesTo = RelatesTo;

            if (relatesTo != null)
            {
                msg.Headers.RelatesTo = relatesTo;
            }
            else             // FIXME: probably it is always added when it is stateful ?
            {
                msg.Headers.MessageId = new UniqueId("urn:" + messageId);
            }

            // FIXME: get correct ReplyTo value
            if (Direction == MessageDirection.Input)
            {
                msg.Headers.Add(MessageHeader.CreateHeader("ReplyTo", msg.Version.Addressing.Namespace, EndpointAddress10.FromEndpointAddress(new EndpointAddress(Constants.WsaAnonymousUri))));
            }

            if (MessageTo != null)
            {
                msg.Headers.Add(MessageHeader.CreateHeader("To", msg.Version.Addressing.Namespace, MessageTo.Uri.AbsoluteUri, true));
            }

            // wss:Security
            WSSecurityMessageHeader header =
                new WSSecurityMessageHeader(serializer);

            msg.Headers.Add(header);
            // 1. [Timestamp]
            if (element.IncludeTimestamp)
            {
                WsuTimestamp timestamp = new WsuTimestamp();
                timestamp.Id      = messageId + "-" + identForMessageId++;
                timestamp.Created = DateTime.Now;
                // FIXME: on service side, use element.LocalServiceSettings.TimestampValidityDuration
                timestamp.Expires = timestamp.Created.Add(element.LocalClientSettings.TimestampValidityDuration);
                header.AddContent(timestamp);
            }

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("s", msg.Version.Envelope.Namespace);
            nsmgr.AddNamespace("o", Constants.WssNamespace);
            nsmgr.AddNamespace("u", Constants.WsuNamespace);
            nsmgr.AddNamespace("o11", Constants.Wss11Namespace);

            /*WrappedKey*/ SecurityToken primaryToken = null;
            DerivedKeySecurityToken      dkeyToken    = null;
            SecurityToken actualToken = null;
            SecurityKeyIdentifierClause actualClause = null;
            Signature sig = null;

            List <DerivedKeySecurityToken> derivedKeys =
                new List <DerivedKeySecurityToken> ();

            SymmetricAlgorithm masterKey = new RijndaelManaged();

            masterKey.KeySize = suite.DefaultSymmetricKeyLength;
            masterKey.Mode    = CipherMode.CBC;
            masterKey.Padding = PaddingMode.ISO10126;
            SymmetricAlgorithm actualKey = masterKey;

            // 2. [Encryption Token]

            // SecurityTokenInclusionMode
            // - Initiator or Recipient
            // - done or notyet. FIXME: not implemented yet
            // It also affects on key reference output

            bool includeEncToken =             // /* FIXME: remove this hack */Parameters is SslSecurityTokenParameters ? false :
                                   ShouldIncludeToken(
                Security.RecipientParameters.InclusionMode, false);
            bool includeSigToken =             // /* FIXME: remove this hack */ Parameters is SslSecurityTokenParameters ? false :
                                   ShouldIncludeToken(
                Security.InitiatorParameters.InclusionMode, false);

            SecurityKeyIdentifierClause encClause = ShouldOutputEncryptedKey ?
                                                    CounterParameters.CallCreateKeyIdentifierClause(encToken, !ShouldOutputEncryptedKey ? SecurityTokenReferenceStyle.Internal : includeEncToken ? Parameters.ReferenceStyle : SecurityTokenReferenceStyle.External) : null;

            MessagePartSpecification sigSpec = SignaturePart;
            MessagePartSpecification encSpec = EncryptionPart;

            // encryption key (possibly also used for signing)
            // FIXME: get correct SymmetricAlgorithm according to the algorithm suite
            if (secprop.EncryptionKey != null)
            {
                actualKey.Key = secprop.EncryptionKey;
            }

// FIXME: remove thid hack
            if (!ShouldOutputEncryptedKey)
            {
                primaryToken = RequestContext.RequestMessage.Properties.Security.ProtectionToken.SecurityToken as WrappedKeySecurityToken;
            }
            else
            {
                primaryToken =
                    // FIXME: remove this hack?
                    encToken is SecurityContextSecurityToken ? encToken :
                    new WrappedKeySecurityToken(messageId + "-" + identForMessageId++,
                                                actualKey.Key,
                                                // security.DefaultKeyWrapAlgorithm,
                                                Parameters.InternalHasAsymmetricKey ?
                                                suite.DefaultAsymmetricKeyWrapAlgorithm :
                                                suite.DefaultSymmetricKeyWrapAlgorithm,
                                                encToken,
                                                encClause != null ? new SecurityKeyIdentifier(encClause) : null);
            }

            // If it reuses request's encryption key, do not output.
            if (ShouldOutputEncryptedKey)
            {
                header.AddContent(primaryToken);
            }

            actualToken = primaryToken;

            // FIXME: I doubt it is correct...
            WrappedKeySecurityToken requestEncKey = ShouldOutputEncryptedKey ? null : primaryToken as WrappedKeySecurityToken;

            actualClause = requestEncKey == null ? (SecurityKeyIdentifierClause)
                           new LocalIdKeyIdentifierClause(actualToken.Id, typeof(WrappedKeySecurityToken)) :
                           new InternalEncryptedKeyIdentifierClause(SHA1.Create().ComputeHash(requestEncKey.GetWrappedKey()));

            // generate derived key if needed
            if (CounterParameters.RequireDerivedKeys)
            {
                RijndaelManaged deriv = new RijndaelManaged();
                deriv.KeySize = suite.DefaultEncryptionKeyDerivationLength;
                deriv.Mode    = CipherMode.CBC;
                deriv.Padding = PaddingMode.ISO10126;
                deriv.GenerateKey();
                dkeyToken = new DerivedKeySecurityToken(
                    GenerateId(doc),
                    null,                     // algorithm
                    actualClause,
                    new InMemorySymmetricSecurityKey(actualKey.Key),
                    null,                     // name
                    null,                     // generation
                    null,                     // offset
                    deriv.Key.Length,
                    null,                     // label
                    deriv.Key);
                derivedKeys.Add(dkeyToken);
                actualToken   = dkeyToken;
                actualKey.Key = ((SymmetricSecurityKey)dkeyToken.SecurityKeys [0]).GetSymmetricKey();
                actualClause  = new LocalIdKeyIdentifierClause(dkeyToken.Id);
                header.AddContent(dkeyToken);
            }

            ReferenceList refList = new ReferenceList();

            // When encrypted with DerivedKeyToken, put references
            // immediately after the derived token (not inside the
            // primary token).
            // Similarly, when we do not output EncryptedKey,
            // output ReferenceList in the same way.
            if (CounterParameters.RequireDerivedKeys ||
                !ShouldOutputEncryptedKey)
            {
                header.AddContent(refList);
            }
            else
            {
                ((WrappedKeySecurityToken)primaryToken).ReferenceList = refList;
            }

            // [Signature Confirmation]
            if (security.RequireSignatureConfirmation && secprop.ConfirmedSignatures.Count > 0)
            {
                foreach (string value in secprop.ConfirmedSignatures)
                {
                    header.AddContent(new Wss11SignatureConfirmation(GenerateId(doc), value));
                }
            }

            SupportingTokenInfoCollection tokenInfos =
                Direction == MessageDirection.Input ?
                security.CollectSupportingTokens(GetAction()) :
                new SupportingTokenInfoCollection();                  // empty

            foreach (SupportingTokenInfo tinfo in tokenInfos)
            {
                header.AddContent(tinfo.Token);
            }

            // populate DOM to sign.
            XPathNavigator nav = doc.CreateNavigator();

            using (XmlWriter w = nav.AppendChild()) {
                msg.WriteMessage(w);
            }

            XmlElement body    = doc.SelectSingleNode("/s:Envelope/s:Body/*", nsmgr) as XmlElement;
            string     bodyId  = null;
            XmlElement secElem = null;
            Collection <WSSignedXml> endorsedSignatures =
                new Collection <WSSignedXml> ();
            bool signatureProtection = (protectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature);

            // Below are o:Security contents that are not signed...
            if (includeSigToken && signToken != null)
            {
                header.AddContent(signToken);
            }

            switch (protectionOrder)
            {
            case MessageProtectionOrder.EncryptBeforeSign:
                // FIXME: implement
                throw new NotImplementedException();

            case MessageProtectionOrder.SignBeforeEncrypt:
            case MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature:

                // sign
                // see clause 8 of WS-SecurityPolicy C.2.2
                WSSignedXml sxml = new WSSignedXml(doc);
                SecurityTokenReferenceKeyInfo sigKeyInfo;

                sig = sxml.Signature;
                sig.SignedInfo.CanonicalizationMethod =
                    suite.DefaultCanonicalizationAlgorithm;
                foreach (XmlElement elem in doc.SelectNodes("/s:Envelope/s:Header/o:Security/u:Timestamp", nsmgr))
                {
                    CreateReference(sig, elem, elem.GetAttribute("Id", Constants.WsuNamespace));
                }
                foreach (XmlElement elem in doc.SelectNodes("/s:Envelope/s:Header/o:Security/o11:SignatureConfirmation", nsmgr))
                {
                    CreateReference(sig, elem, elem.GetAttribute("Id", Constants.WsuNamespace));
                }
                foreach (SupportingTokenInfo tinfo in tokenInfos)
                {
                    if (tinfo.Mode != SecurityTokenAttachmentMode.Endorsing)
                    {
                        XmlElement el = sxml.GetIdElement(doc, tinfo.Token.Id);
                        CreateReference(sig, el, el.GetAttribute("Id", Constants.WsuNamespace));
                    }
                }
                XmlNodeList nodes = doc.SelectNodes("/s:Envelope/s:Header/*", nsmgr);
                for (int i = 0; i < msg.Headers.Count; i++)
                {
                    MessageHeaderInfo h = msg.Headers [i];
                    if (h.Name == "Security" && h.Namespace == Constants.WssNamespace)
                    {
                        secElem = nodes [i] as XmlElement;
                    }
                    else if (sigSpec.HeaderTypes.Count == 0 ||
                             sigSpec.HeaderTypes.Contains(new XmlQualifiedName(h.Name, h.Namespace)))
                    {
                        string id = GenerateId(doc);
                        h.Id = id;
                        CreateReference(sig, nodes [i] as XmlElement, id);
                    }
                }
                if (sigSpec.IsBodyIncluded)
                {
                    bodyId = GenerateId(doc);
                    CreateReference(sig, body.ParentNode as XmlElement, bodyId);
                }

                if (security.DefaultSignatureAlgorithm == SignedXml.XmlDsigHMACSHA1Url)
                {
                    // FIXME: use appropriate hash algorithm
                    sxml.ComputeSignature(new HMACSHA1(actualKey.Key));
                    sigKeyInfo = new SecurityTokenReferenceKeyInfo(actualClause, serializer, doc);
                }
                else
                {
                    SecurityKeyIdentifierClause signClause =
                        CounterParameters.CallCreateKeyIdentifierClause(signToken, includeSigToken ? CounterParameters.ReferenceStyle : SecurityTokenReferenceStyle.External);
                    AsymmetricSecurityKey signKey = (AsymmetricSecurityKey)signToken.ResolveKeyIdentifierClause(signClause);
                    sxml.SigningKey = signKey.GetAsymmetricAlgorithm(security.DefaultSignatureAlgorithm, true);
                    sxml.ComputeSignature();
                    sigKeyInfo = new SecurityTokenReferenceKeyInfo(signClause, serializer, doc);
                }

                sxml.KeyInfo = new KeyInfo();
                sxml.KeyInfo.AddClause(sigKeyInfo);

                if (!signatureProtection)
                {
                    header.AddContent(sig);
                }

                // endorse the signature with (signed)endorsing
                // supporting tokens.

                foreach (SupportingTokenInfo tinfo in tokenInfos)
                {
                    switch (tinfo.Mode)
                    {
                    case SecurityTokenAttachmentMode.Endorsing:
                    case SecurityTokenAttachmentMode.SignedEndorsing:
                        if (sxml.Signature.Id == null)
                        {
                            sig.Id = GenerateId(doc);
                            secElem.AppendChild(sxml.GetXml());
                        }
                        WSSignedXml ssxml = new WSSignedXml(doc);
                        ssxml.Signature.SignedInfo.CanonicalizationMethod = suite.DefaultCanonicalizationAlgorithm;
                        CreateReference(ssxml.Signature, doc, sig.Id);
                        SecurityToken sst = tinfo.Token;
                        SecurityKey   ssk = sst.SecurityKeys [0];                                     // FIXME: could be different?
                        SecurityKeyIdentifierClause tclause = new LocalIdKeyIdentifierClause(sst.Id); // FIXME: could be different?
                        if (ssk is SymmetricSecurityKey)
                        {
                            SymmetricSecurityKey signKey = (SymmetricSecurityKey)ssk;
                            ssxml.ComputeSignature(signKey.GetKeyedHashAlgorithm(suite.DefaultSymmetricSignatureAlgorithm));
                        }
                        else
                        {
                            AsymmetricSecurityKey signKey = (AsymmetricSecurityKey)ssk;
                            ssxml.SigningKey = signKey.GetAsymmetricAlgorithm(suite.DefaultAsymmetricSignatureAlgorithm, true);
                            ssxml.ComputeSignature();
                        }
                        ssxml.KeyInfo.AddClause(new SecurityTokenReferenceKeyInfo(tclause, serializer, doc));
                        if (!signatureProtection)
                        {
                            header.AddContent(ssxml.Signature);
                        }
                        endorsedSignatures.Add(ssxml);

                        break;
                    }
                }

                // encrypt

                WSEncryptedXml exml = new WSEncryptedXml(doc);

                EncryptedData edata = Encrypt(body, actualKey, actualToken.Id, refList, actualClause, exml, doc);
                EncryptedXml.ReplaceElement(body, edata, false);

                // encrypt signature
                if (signatureProtection)
                {
                    XmlElement sigxml = sig.GetXml();
                    edata = Encrypt(sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc);
                    header.AddContent(edata);

                    foreach (WSSignedXml ssxml in endorsedSignatures)
                    {
                        sigxml = ssxml.GetXml();
                        edata  = Encrypt(sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc);
                        header.AddContent(edata);
                    }

                    if (security.RequireSignatureConfirmation)
                    {
                        Collection <Wss11SignatureConfirmation> confs = header.FindAll <Wss11SignatureConfirmation> ();
                        int count = 0;
                        foreach (XmlElement elem in doc.SelectNodes("/s:Envelope/s:Header/o:Security/o11:SignatureConfirmation", nsmgr))
                        {
                            edata = Encrypt(elem, actualKey, confs [count].Id, refList, actualClause, exml, doc);
                            EncryptedXml.ReplaceElement(elem, edata, false);
                            header.Contents.Insert(header.Contents.IndexOf(confs [count]), edata);
                            header.Contents.Remove(confs [count++]);
                        }
                    }
                }

                // encrypt Encrypted supporting tokens
                foreach (SupportingTokenInfo tinfo in tokenInfos)
                {
                    if (tinfo.Mode == SecurityTokenAttachmentMode.SignedEncrypted)
                    {
                        XmlElement el = exml.GetIdElement(doc, tinfo.Token.Id);
                        tinfo.Encrypted = Encrypt(el, actualKey, actualToken.Id, refList, actualClause, exml, doc);
                        EncryptedXml.ReplaceElement(el, tinfo.Encrypted, false);
                        header.Contents.Insert(header.Contents.IndexOf(tinfo.Token), tinfo.Encrypted);
                        header.Contents.Remove(tinfo.Token);
                    }
                }
                break;
            }

            Message ret = Message.CreateMessage(msg.Version, msg.Headers.Action, new XmlNodeReader(doc.SelectSingleNode("/s:Envelope/s:Body/*", nsmgr) as XmlElement));

            ret.Properties.Security = (SecurityMessageProperty)secprop.CreateCopy();
            ret.Properties.Security.EncryptionKey = masterKey.Key;
            ret.BodyId = bodyId;

            // FIXME: can we support TransportToken here?
            if (element is AsymmetricSecurityBindingElement)
            {
                ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification(encToken, null);                  // FIXME: second argument
                ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification(signToken, null);                 // FIXME: second argument
            }
            else
            {
                ret.Properties.Security.ProtectionToken = new SecurityTokenSpecification(primaryToken, null);
            }

            ret.Headers.Clear();
            ret.Headers.CopyHeadersFrom(msg);

            // Header contents are:
            //	- Timestamp
            //	- SignatureConfirmation if required
            //	- EncryptionToken if included
            //	- derived key token for EncryptionToken
            //	- ReferenceList for encrypted items
            //	- signed supporting tokens
            //	- signed endorsing supporting tokens
            //	(i.e. Signed/SignedEncrypted/SignedEndorsing)
            //	- Signature Token if different from enc token.
            //	- derived key token for sig token if different
            //	- Signature for:
            //		- Timestamp
            //		- supporting tokens (regardless of
            //		  its inclusion)
            //		- message parts in SignedParts
            //		- SignatureToken if TokenProtection
            //		  (regardless of its inclusion)
            //	- Signatures for the main signature (above),
            //	  for every endorsing token and signed
            //	  endorsing token.
            //

//MessageBuffer zzz = ret.CreateBufferedCopy (100000);
//ret = zzz.CreateMessage ();
//Console.WriteLine (zzz.CreateMessage ());
            return(ret);
        }
        private async ValueTask <BodyWriter> ProcessNegotiationAsync(SspiNegotiationTokenAuthenticatorState negotiationState, Message incomingMessage, BinaryNegotiation incomingNego)
        {
            ISspiNegotiation sspiNegotiation = negotiationState.SspiNegotiation;

            byte[] outgoingBlob = sspiNegotiation.GetOutgoingBlob(incomingNego.GetNegotiationData(),
                                                                  SecurityUtils.GetChannelBindingFromMessage(incomingMessage),
                                                                  ExtendedProtectionPolicy);

            if (sspiNegotiation.IsValidContext == false)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.InvalidSspiNegotiation)), incomingMessage);
            }
            // if there is no blob to send back the nego must be complete from the server side
            if (outgoingBlob == null && sspiNegotiation.IsCompleted == false)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.NoBinaryNegoToSend)), incomingMessage);
            }
            BinaryNegotiation outgoingBinaryNegotiation;

            if (outgoingBlob != null)
            {
                outgoingBinaryNegotiation = GetOutgoingBinaryNegotiation(sspiNegotiation, outgoingBlob);
            }
            else
            {
                outgoingBinaryNegotiation = null;
            }
            BodyWriter replyBody;

            if (sspiNegotiation.IsCompleted)
            {
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = await ValidateSspiNegotiationAsync(sspiNegotiation);

                SecurityContextSecurityToken serviceToken;
                WrappedKeySecurityToken      proofToken;
                int issuedKeySize;
                IssueServiceToken(negotiationState, authorizationPolicies, out serviceToken, out proofToken, out issuedKeySize);
                negotiationState.SetServiceToken(serviceToken);

                SecurityKeyIdentifierClause externalTokenReference = IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.External);
                SecurityKeyIdentifierClause internalTokenReference = IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.Internal);

                RequestSecurityTokenResponse dummyRstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    Context   = negotiationState.Context,
                    KeySize   = issuedKeySize,
                    TokenType = SecurityContextTokenUri
                };
                if (outgoingBinaryNegotiation != null)
                {
                    dummyRstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                dummyRstr.RequestedUnattachedReference = externalTokenReference;
                dummyRstr.RequestedAttachedReference   = internalTokenReference;
                dummyRstr.SetLifetime(serviceToken.ValidFrom, serviceToken.ValidTo);
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        dummyRstr.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(
                                                                       negotiationState.AppliesTo),
                                                                   negotiationState.AppliesToSerializer);
                    }
                    else if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        dummyRstr.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(
                                                                               negotiationState.AppliesTo),
                                                                           negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, incomingMessage.Version.Addressing)));
                    }
                }
                dummyRstr.MakeReadOnly();
                AddToDigest(negotiationState, dummyRstr, false);
                RequestSecurityTokenResponse negotiationRstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    RequestedSecurityToken = serviceToken,

                    RequestedProofToken = proofToken,
                    Context             = negotiationState.Context,
                    KeySize             = issuedKeySize,
                    TokenType           = SecurityContextTokenUri
                };
                if (outgoingBinaryNegotiation != null)
                {
                    negotiationRstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                negotiationRstr.RequestedAttachedReference   = internalTokenReference;
                negotiationRstr.RequestedUnattachedReference = externalTokenReference;
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        negotiationRstr.SetAppliesTo <EndpointAddress10>(
                            EndpointAddress10.FromEndpointAddress(negotiationState.AppliesTo),
                            negotiationState.AppliesToSerializer);
                    }
                    else if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        negotiationRstr.SetAppliesTo <EndpointAddressAugust2004>(
                            EndpointAddressAugust2004.FromEndpointAddress(negotiationState.AppliesTo),
                            negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, incomingMessage.Version.Addressing)));
                    }
                }
                negotiationRstr.MakeReadOnly();

                byte[] authenticator = ComputeAuthenticator(negotiationState, serviceToken.GetKeyBytes());
                RequestSecurityTokenResponse authenticatorRstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    Context = negotiationState.Context
                };
                authenticatorRstr.SetAuthenticator(authenticator);
                authenticatorRstr.MakeReadOnly();

                List <RequestSecurityTokenResponse> rstrList = new List <RequestSecurityTokenResponse>(2)
                {
                    negotiationRstr,
                    authenticatorRstr
                };
                replyBody = new RequestSecurityTokenResponseCollection(rstrList, StandardsManager);
            }
            else
            {
                RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    Context = negotiationState.Context
                };
                rstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                rstr.MakeReadOnly();
                AddToDigest(negotiationState, rstr, false);
                replyBody = rstr;
            }

            return(replyBody);
        }