private WsrmAcknowledgmentInfo(UniqueId sequenceID, SequenceRangeCollection ranges, bool final, int bufferRemaining, MessageHeaderInfo header) : base(header)
 {
     this.sequenceID = sequenceID;
     this.ranges = ranges;
     this.final = final;
     this.bufferRemaining = bufferRemaining;
 }
 public static bool WasHeaderNotUnderstood(MessageHeaders headers, string name, string ns)
 {
     if (headers == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("headers");
     }
     for (int i = 0; i < headers.Count; i++)
     {
         MessageHeaderInfo info = headers[i];
         if ((string.Compare(info.Name, "NotUnderstood", StringComparison.Ordinal) == 0) && (string.Compare(info.Namespace, "http://www.w3.org/2003/05/soap-envelope", StringComparison.Ordinal) == 0))
         {
             using (XmlDictionaryReader reader = headers.GetReaderAtHeader(i))
             {
                 string str;
                 string str2;
                 reader.MoveToAttribute("qname", "http://www.w3.org/2003/05/soap-envelope");
                 reader.ReadContentAsQualifiedName(out str, out str2);
                 if (((str != null) && (str2 != null)) && ((string.Compare(name, str, StringComparison.Ordinal) == 0) && (string.Compare(ns, str2, StringComparison.Ordinal) == 0)))
                 {
                     return(true);
                 }
             }
         }
     }
     return(false);
 }
Exemple #3
0
        public static bool WasHeaderNotUnderstood(MessageHeaders headers, string name, string ns)
        {
            if (headers == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(headers));
            }

            for (int i = 0; i < headers.Count; i++)
            {
                MessageHeaderInfo headerInfo = headers[i];
                if ((String.Compare(headerInfo.Name, Message12Strings.NotUnderstood, StringComparison.Ordinal) == 0) &&
                    (String.Compare(headerInfo.Namespace, Message12Strings.Namespace, StringComparison.Ordinal) == 0))
                {
                    using (XmlDictionaryReader reader = headers.GetReaderAtHeader(i))
                    {
                        reader.MoveToAttribute(Message12Strings.QName, Message12Strings.Namespace);

                        string actualName;
                        string actualNamespace;
                        reader.ReadContentAsQualifiedName(out actualName, out actualNamespace);

                        if ((actualName != null) &&
                            (actualNamespace != null) &&
                            (String.Compare(name, actualName, StringComparison.Ordinal) == 0) &&
                            (String.Compare(ns, actualNamespace, StringComparison.Ordinal) == 0))
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
        public DelegatingHeader(MessageHeaderInfo info, MessageHeaders originalHeaders)
        {
            Fx.Assert(info != null, "info is required");
            Fx.Assert(originalHeaders != null, "originalHeaders is required");

            this.info = info;
            this.originalHeaders = originalHeaders;
            this.index = -1;
        }
Exemple #5
0
        public Message DecryptMessage()
        {
            Message srcmsg = buf.CreateMessage();

            if (srcmsg.Version.Envelope == EnvelopeVersion.None)
            {
                throw new ArgumentException("The message to decrypt is not an expected SOAP envelope.");
            }

            string action = GetAction();

            if (action == null)
            {
                throw new ArgumentException("SOAP action could not be retrieved from the message to decrypt.");
            }

            XPathNavigator nav = doc.CreateNavigator();

            using (XmlWriter writer = nav.AppendChild()) {
                buf.CreateMessage().WriteMessage(writer);
            }

/*
 * doc.PreserveWhitespace = false;
 * doc.Save (Console.Out);
 * doc.PreserveWhitespace = true;
 */

            // read and store headers, wsse:Security and setup in-band resolver.
            ReadHeaders(srcmsg);

            ExtractSecurity();

            Message msg = Message.CreateMessage(new XmlNodeReader(doc), srcmsg.Headers.Count, srcmsg.Version);

            for (int i = 0; i < srcmsg.Headers.Count; i++)
            {
                MessageHeaderInfo header = srcmsg.Headers [i];
                if (header == wss_header)
                {
                    msg.Headers.Add(wss_header);
                }
                else
                {
                    msg.Headers.CopyHeaderFrom(srcmsg, i);
                }
            }

            // FIXME: when Local[Client|Service]SecuritySettings.DetectReplays
            // is true, reject such messages which don't have <wsu:Timestamp>

            msg.Properties.Add("Security", sec_prop);
            return(msg);
        }
 public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, MessageHeaderInfo headerInfo)
 {
     this.version = version;
     this.buffer = buffer;
     this.bufferIndex = bufferIndex;
     this.actor = headerInfo.Actor;
     this.relay = headerInfo.Relay;
     this.name = headerInfo.Name;
     this.ns = headerInfo.Namespace;
     this.isRefParam = headerInfo.IsReferenceParameter;
     this.mustUnderstand = headerInfo.MustUnderstand;
 }
Exemple #7
0
        void ReadHeaders(Message srcmsg)
        {
            SecurityTokenSerializer serializer =
                security.TokenSerializer;

            tokens         = new List <SecurityToken> ();
            token_resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                new ReadOnlyCollection <SecurityToken> (tokens),
                true);
            token_resolver = new UnionSecurityTokenResolver(token_resolver, security.OutOfBandTokenResolver);

            // Add relevant protection token and supporting tokens.
            tokens.Add(security.EncryptionToken);
            // FIXME: this is just a workaround for symmetric binding to not require extra client certificate.
            if (security.Element is AsymmetricSecurityBindingElement)
            {
                tokens.Add(security.SigningToken);
            }
            if (RequestSecurity != null && RequestSecurity.ProtectionToken != null)
            {
                tokens.Add(RequestSecurity.ProtectionToken.SecurityToken);
            }
            // FIXME: handle supporting tokens

            for (int i = 0; i < srcmsg.Headers.Count; i++)
            {
                MessageHeaderInfo header = srcmsg.Headers [i];
                // FIXME: check SOAP Actor.
                // MessageHeaderDescription.Actor needs to be accessible from here.
                if (header.Namespace == Constants.WssNamespace &&
                    header.Name == "Security")
                {
                    wss_header        = new WSSecurityMessageHeader(null);
                    wss_header_reader = new WSSecurityMessageHeaderReader(wss_header, serializer, token_resolver, doc, nsmgr, tokens);
                    wss_header_reader.ReadContents(srcmsg.Headers.GetReaderAtHeader(i));
                    headers.Add(wss_header);
                }
                else
                {
                    headers.Add(header);
                }
            }
            if (wss_header == null)
            {
                throw new InvalidOperationException("In this service contract, a WS-Security header is required in the Message, but was not found.");
            }
        }
 public static WsrmAckRequestedInfo ReadHeader(ReliableMessagingVersion reliableMessagingVersion, XmlDictionaryReader reader, MessageHeaderInfo header)
 {
     WsrmFeb2005Dictionary dictionary = XD.WsrmFeb2005Dictionary;
     XmlDictionaryString namespaceUri = WsrmIndex.GetNamespace(reliableMessagingVersion);
     reader.ReadStartElement();
     reader.ReadStartElement(dictionary.Identifier, namespaceUri);
     UniqueId sequenceID = reader.ReadContentAsUniqueId();
     reader.ReadEndElement();
     if ((reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) && reader.IsStartElement(dictionary.MessageNumber, namespaceUri))
     {
         reader.ReadStartElement();
         WsrmUtilities.ReadSequenceNumber(reader, true);
         reader.ReadEndElement();
     }
     while (reader.IsStartElement())
     {
         reader.Skip();
     }
     reader.ReadEndElement();
     return new WsrmAckRequestedInfo(sequenceID, header);
 }
        public void ReturnHeaderInfo(MessageHeaderInfo headerInfo)
        {
            HeaderInfo info = headerInfo as HeaderInfo;

            if (info != null)
            {
                if (this.headerInfos == null)
                {
                    this.headerInfos = new HeaderInfo[4];
                }
                int index = this.index;
                do
                {
                    if (this.headerInfos[index] == null)
                    {
                        break;
                    }
                    index = (index + 1) % 4;
                }while (index != this.index);
                this.headerInfos[index] = info;
                this.index = (index + 1) % 4;
            }
        }
 public void ReturnHeaderInfo(MessageHeaderInfo headerInfo)
 {
     HeaderInfo info = headerInfo as HeaderInfo;
     if (info != null)
     {
         if (this.headerInfos == null)
         {
             this.headerInfos = new HeaderInfo[4];
         }
         int index = this.index;
         do
         {
             if (this.headerInfos[index] == null)
             {
                 break;
             }
             index = (index + 1) % 4;
         }
         while (index != this.index);
         this.headerInfos[index] = info;
         this.index = (index + 1) % 4;
     }
 }
 internal MessageHeaderInfoTraceRecord(MessageHeaderInfo messageHeaderInfo)
 {
     this.messageHeaderInfo = messageHeaderInfo;
 }
        private static void AddUnknownHeader(MessageHeaderDescription unknownHeaderDescription, ArrayList unknownHeaders, XmlDocument xmlDoc, XmlDictionaryWriter bufferWriter, MessageHeaderInfo header, XmlDictionaryReader headerReader)
        {
            object unknownHeader = xmlDoc.ReadNode(headerReader);
            if (bufferWriter != null)
                ((XmlElement)unknownHeader).WriteTo(bufferWriter);
            if (unknownHeader != null && unknownHeaderDescription.TypedHeader)
                unknownHeader = TypedHeaderManager.Create(unknownHeaderDescription.Type, unknownHeader, header.MustUnderstand, header.Relay, header.Actor);

            unknownHeaders.Add(unknownHeader);
        }
 private WsrmUsesSequenceSSLInfo(MessageHeaderInfo header) : base(header)
 {
 }
Exemple #14
0
 public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, MessageHeaderInfo headerInfo)
 {
     this.version        = version;
     this.buffer         = buffer;
     this.bufferIndex    = bufferIndex;
     this.actor          = headerInfo.Actor;
     this.relay          = headerInfo.Relay;
     this.name           = headerInfo.Name;
     this.ns             = headerInfo.Namespace;
     this.isRefParam     = headerInfo.IsReferenceParameter;
     this.mustUnderstand = headerInfo.MustUnderstand;
 }
Exemple #15
0
 public static WsrmUsesSequenceSTRInfo ReadHeader(XmlDictionaryReader reader, MessageHeaderInfo header)
 {
     WsrmUtilities.ReadEmptyElement(reader);
     return(new WsrmUsesSequenceSTRInfo(header));
 }
 public WsrmAckRequestedInfo(UniqueId sequenceID, MessageHeaderInfo header)
     : base(header)
 {
     this.sequenceID = sequenceID;
 }
        public static WsrmSequencedMessageInfo ReadHeader(ReliableMessagingVersion reliableMessagingVersion,
            XmlDictionaryReader reader, MessageHeaderInfo header)
        {
            WsrmFeb2005Dictionary wsrmFeb2005Dictionary = XD.WsrmFeb2005Dictionary;
            XmlDictionaryString wsrmNs = WsrmIndex.GetNamespace(reliableMessagingVersion);

            reader.ReadStartElement();

            reader.ReadStartElement(wsrmFeb2005Dictionary.Identifier, wsrmNs);
            UniqueId sequenceID = reader.ReadContentAsUniqueId();
            reader.ReadEndElement();

            reader.ReadStartElement(wsrmFeb2005Dictionary.MessageNumber, wsrmNs);
            Int64 sequenceNumber = WsrmUtilities.ReadSequenceNumber(reader);
            reader.ReadEndElement();

            bool lastMessage = false;

            if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
            {
                if (reader.IsStartElement(wsrmFeb2005Dictionary.LastMessage, wsrmNs))
                {
                    WsrmUtilities.ReadEmptyElement(reader);
                    lastMessage = true;
                }
            }

            while (reader.IsStartElement())
            {
                reader.Skip();
            }

            reader.ReadEndElement();

            return new WsrmSequencedMessageInfo(sequenceID, sequenceNumber, lastMessage, header);
        }
Exemple #18
0
        public static WsrmAckRequestedInfo ReadHeader(ReliableMessagingVersion reliableMessagingVersion, XmlDictionaryReader reader, MessageHeaderInfo header)
        {
            WsrmFeb2005Dictionary dictionary   = XD.WsrmFeb2005Dictionary;
            XmlDictionaryString   namespaceUri = WsrmIndex.GetNamespace(reliableMessagingVersion);

            reader.ReadStartElement();
            reader.ReadStartElement(dictionary.Identifier, namespaceUri);
            UniqueId sequenceID = reader.ReadContentAsUniqueId();

            reader.ReadEndElement();
            if ((reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) && reader.IsStartElement(dictionary.MessageNumber, namespaceUri))
            {
                reader.ReadStartElement();
                WsrmUtilities.ReadSequenceNumber(reader, true);
                reader.ReadEndElement();
            }
            while (reader.IsStartElement())
            {
                reader.Skip();
            }
            reader.ReadEndElement();
            return(new WsrmAckRequestedInfo(sequenceID, header));
        }
Exemple #19
0
 public WsrmAckRequestedInfo(UniqueId sequenceID, MessageHeaderInfo header) : base(header)
 {
     this.sequenceID = sequenceID;
 }
Exemple #20
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);
        }
 protected bool IsSecurityElement(MessageHeaderInfo header)
 {
     return header.Name == ProtocolStrings.SecurityHeaderName &&
         header.Namespace == this.DiscoveryInfo.DiscoveryNamespace;
 }
 static bool ActorIsNextDestination(MessageHeaderInfo header, MessageVersion messageVersion)
 {
     return (header.Actor != null && string.Equals(header.Actor, messageVersion.Envelope.NextDestinationActorValue));
 }
 static string MessageHeaderKey(MessageHeaderInfo header)
 {
     return header.Name + "+" + header.Namespace;
 }
 private bool EnsureDigestValidityIfIdMatches(SignedInfo signedInfo, string id, XmlDictionaryReader reader, bool doSoapAttributeChecks, MessagePartSpecification signatureParts, MessageHeaderInfo info, bool checkForTokensAtHeaders)
 {
     if (signedInfo == null)
     {
         return false;
     }
     if (doSoapAttributeChecks)
     {
         this.VerifySoapAttributeMatchForHeader(info, signatureParts, reader);
     }
     bool flag = false;
     bool flag2 = checkForTokensAtHeaders && base.StandardsManager.SecurityTokenSerializer.CanReadToken(reader);
     try
     {
         flag = signedInfo.EnsureDigestValidityIfIdMatches(id, reader);
     }
     catch (CryptographicException exception)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("FailedSignatureVerification"), exception));
     }
     if (flag && flag2)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("SecurityTokenFoundOutsideSecurityHeader", new object[] { info.Namespace, info.Name })));
     }
     return flag;
 }
 WsrmSequencedMessageInfo(
     UniqueId sequenceID,
     Int64 sequenceNumber,
     bool lastMessage,
     MessageHeaderInfo header)
     : base(header)
 {
     this.sequenceID = sequenceID;
     this.sequenceNumber = sequenceNumber;
     this.lastMessage = lastMessage;
 }
 private void VerifySoapAttributeMatchForHeader(MessageHeaderInfo info, MessagePartSpecification signatureParts, XmlDictionaryReader reader)
 {
     if (signatureParts.IsHeaderIncluded(info.Name, info.Namespace))
     {
         EnvelopeVersion envelope = base.Version.Envelope;
         EnvelopeVersion version2 = (envelope == EnvelopeVersion.Soap11) ? EnvelopeVersion.Soap12 : EnvelopeVersion.Soap11;
         bool flag = null != reader.GetAttribute(System.ServiceModel.XD.MessageDictionary.MustUnderstand, envelope.DictionaryNamespace);
         if ((null != reader.GetAttribute(System.ServiceModel.XD.MessageDictionary.MustUnderstand, version2.DictionaryNamespace)) && !flag)
         {
             throw TraceUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("InvalidAttributeInSignedHeader", new object[] { info.Name, info.Namespace, System.ServiceModel.XD.MessageDictionary.MustUnderstand, version2.DictionaryNamespace, System.ServiceModel.XD.MessageDictionary.MustUnderstand, envelope.DictionaryNamespace })), base.SecurityVerifiedMessage);
         }
         flag = null != reader.GetAttribute(envelope.DictionaryActor, envelope.DictionaryNamespace);
         if ((null != reader.GetAttribute(version2.DictionaryActor, version2.DictionaryNamespace)) && !flag)
         {
             throw TraceUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("InvalidAttributeInSignedHeader", new object[] { info.Name, info.Namespace, version2.DictionaryActor, version2.DictionaryNamespace, envelope.DictionaryActor, envelope.DictionaryNamespace })), base.SecurityVerifiedMessage);
         }
     }
 }
        public static WsrmAcknowledgmentInfo ReadHeader(ReliableMessagingVersion reliableMessagingVersion,
            XmlDictionaryReader reader, MessageHeaderInfo header)
        {
            WsrmFeb2005Dictionary wsrmFeb2005Dictionary = XD.WsrmFeb2005Dictionary;
            XmlDictionaryString wsrmNs = WsrmIndex.GetNamespace(reliableMessagingVersion);

            UniqueId sequenceID;
            SequenceRangeCollection rangeCollection;
            bool final;
            ReadAck(reliableMessagingVersion, reader, out sequenceID, out rangeCollection, out final);

            int bufferRemaining = -1;

            // Parse the extensibility section.
            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(wsrmFeb2005Dictionary.BufferRemaining,
                    XD.WsrmFeb2005Dictionary.NETNamespace))
                {
                    if (bufferRemaining != -1)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(
                            SR.GetString(SR.UnexpectedXmlChildNode, reader.Name, reader.NodeType,
                            MessageStrings.Body)));
                    }

                    reader.ReadStartElement();
                    bufferRemaining = reader.ReadContentAsInt();
                    reader.ReadEndElement();

                    if (bufferRemaining < 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(
                            SR.GetString(SR.InvalidBufferRemaining, bufferRemaining)));
                    }

                    // Found BufferRemaining, continue parsing.
                    continue;
                }

                if (reader.IsStartElement(wsrmFeb2005Dictionary.AcknowledgementRange, wsrmNs))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(
                        SR.GetString(SR.UnexpectedXmlChildNode, reader.Name, reader.NodeType,
                        MessageStrings.Body)));
                }
                else if (reader.IsStartElement(wsrmFeb2005Dictionary.Nack, wsrmNs))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(
                        SR.GetString(SR.UnexpectedXmlChildNode, reader.Name, reader.NodeType,
                        MessageStrings.Body)));
                }
                else if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
                {
                    Wsrm11Dictionary wsrm11Dictionary = DXD.Wsrm11Dictionary;

                    if (reader.IsStartElement(wsrm11Dictionary.None, wsrmNs)
                        || reader.IsStartElement(wsrm11Dictionary.Final, wsrmNs))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(
                            SR.GetString(SR.UnexpectedXmlChildNode, reader.Name, reader.NodeType,
                            wsrmFeb2005Dictionary.SequenceAcknowledgement)));
                    }
                }

                // Advance the reader in all cases.
                reader.Skip();
            }

            reader.ReadEndElement();

            return new WsrmAcknowledgmentInfo(sequenceID, rangeCollection, final, bufferRemaining, header);
        }
 bool ShouldProtectHeader(MessageHeaderInfo header)
 {
     // Only /s:Envelope/s:Header/* and /s:Envelope/s:Body can be referenced.
     // From those, we want to protect the addressing and the discovery headers
     // together with the Body.
     return header.Namespace == this.DiscoveryInfo.AddressingNamespace ||
         header.Namespace == this.DiscoveryInfo.DiscoveryNamespace;
 }
 WsrmUsesSequenceSTRInfo(MessageHeaderInfo header)
     : base(header)
 {
 }
 public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, MessageHeaderInfo headerInfo)
 {
     _version = version;
     _buffer = buffer;
     _bufferIndex = bufferIndex;
     _actor = headerInfo.Actor;
     _relay = headerInfo.Relay;
     _name = headerInfo.Name;
     _ns = headerInfo.Namespace;
     _isRefParam = headerInfo.IsReferenceParameter;
     _mustUnderstand = headerInfo.MustUnderstand;
 }
Exemple #31
0
 private WsrmUsesSequenceSTRInfo(MessageHeaderInfo header) : base(header)
 {
 }
Exemple #32
0
 private WsrmSequencedMessageInfo(UniqueId sequenceID, long sequenceNumber, bool lastMessage, MessageHeaderInfo header) : base(header)
 {
     this.sequenceID     = sequenceID;
     this.sequenceNumber = sequenceNumber;
     this.lastMessage    = lastMessage;
 }
 public static WsrmUsesSequenceSSLInfo ReadHeader(XmlDictionaryReader reader, MessageHeaderInfo header)
 {
     WsrmUtilities.ReadEmptyElement(reader);
     return new WsrmUsesSequenceSSLInfo(header);
 }
        bool EnsureDigestValidityIfIdMatches(
            SignedInfo signedInfo,
            string id, XmlDictionaryReader reader, bool doSoapAttributeChecks,
            MessagePartSpecification signatureParts, MessageHeaderInfo info, bool checkForTokensAtHeaders)
        {
            if (signedInfo == null)
            {
                return false;
            }
            if (doSoapAttributeChecks)
            {
                VerifySoapAttributeMatchForHeader(info, signatureParts, reader);
            }

            bool signed = false;
            bool isRecognizedSecurityToken = checkForTokensAtHeaders && this.StandardsManager.SecurityTokenSerializer.CanReadToken(reader);

            try
            {
                signed = signedInfo.EnsureDigestValidityIfIdMatches(id, reader);
            }
            catch (CryptographicException exception)
            {
                //
                // Wrap the crypto exception here so that the perf couter can be updated correctly
                //
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.FailedSignatureVerification), exception));
            }

            if (signed && isRecognizedSecurityToken)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SecurityTokenFoundOutsideSecurityHeader, info.Namespace, info.Name)));
            }

            return signed;
        }
Exemple #35
0
 public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, MessageHeaderInfo headerInfo)
 {
     _version        = version;
     _buffer         = buffer;
     _bufferIndex    = bufferIndex;
     _actor          = headerInfo.Actor;
     _relay          = headerInfo.Relay;
     _name           = headerInfo.Name;
     _ns             = headerInfo.Namespace;
     _isRefParam     = headerInfo.IsReferenceParameter;
     _mustUnderstand = headerInfo.MustUnderstand;
 }
 public static WsrmAcknowledgmentInfo ReadHeader(ReliableMessagingVersion reliableMessagingVersion, XmlDictionaryReader reader, MessageHeaderInfo header)
 {
     UniqueId id;
     SequenceRangeCollection ranges;
     bool flag;
     WsrmFeb2005Dictionary dictionary = XD.WsrmFeb2005Dictionary;
     XmlDictionaryString namespaceUri = WsrmIndex.GetNamespace(reliableMessagingVersion);
     ReadAck(reliableMessagingVersion, reader, out id, out ranges, out flag);
     int bufferRemaining = -1;
     while (reader.IsStartElement())
     {
         if (reader.IsStartElement(dictionary.BufferRemaining, XD.WsrmFeb2005Dictionary.NETNamespace))
         {
             if (bufferRemaining != -1)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedXmlChildNode", new object[] { reader.Name, reader.NodeType, "Body" })));
             }
             reader.ReadStartElement();
             bufferRemaining = reader.ReadContentAsInt();
             reader.ReadEndElement();
             if (bufferRemaining < 0)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("InvalidBufferRemaining", new object[] { bufferRemaining })));
             }
         }
         else
         {
             if (reader.IsStartElement(dictionary.AcknowledgementRange, namespaceUri))
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedXmlChildNode", new object[] { reader.Name, reader.NodeType, "Body" })));
             }
             if (reader.IsStartElement(dictionary.Nack, namespaceUri))
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedXmlChildNode", new object[] { reader.Name, reader.NodeType, "Body" })));
             }
             if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
             {
                 Wsrm11Dictionary dictionary2 = DXD.Wsrm11Dictionary;
                 if (reader.IsStartElement(dictionary2.None, namespaceUri) || reader.IsStartElement(dictionary2.Final, namespaceUri))
                 {
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedXmlChildNode", new object[] { reader.Name, reader.NodeType, dictionary.SequenceAcknowledgement })));
                 }
             }
             reader.Skip();
         }
     }
     reader.ReadEndElement();
     return new WsrmAcknowledgmentInfo(id, ranges, flag, bufferRemaining, header);
 }
 protected WsrmHeaderInfo(MessageHeaderInfo messageHeader)
 {
     this.messageHeader = messageHeader;
 }
Exemple #38
0
 private WsrmAcknowledgmentInfo(UniqueId sequenceID, SequenceRangeCollection ranges, bool final, int bufferRemaining, MessageHeaderInfo header) : base(header)
 {
     this.sequenceID      = sequenceID;
     this.ranges          = ranges;
     this.final           = final;
     this.bufferRemaining = bufferRemaining;
 }
        void VerifySoapAttributeMatchForHeader(MessageHeaderInfo info, MessagePartSpecification signatureParts, XmlDictionaryReader reader)
        {
            if (!signatureParts.IsHeaderIncluded(info.Name, info.Namespace))
            {
                return;
            }

            EnvelopeVersion currentVersion = this.Version.Envelope;
            EnvelopeVersion otherVersion = currentVersion == EnvelopeVersion.Soap11 ? EnvelopeVersion.Soap12 : EnvelopeVersion.Soap11;

            bool presentInCurrentVersion;
            bool presentInOtherVersion;

            presentInCurrentVersion = null != reader.GetAttribute(XD.MessageDictionary.MustUnderstand, currentVersion.DictionaryNamespace);
            presentInOtherVersion = null != reader.GetAttribute(XD.MessageDictionary.MustUnderstand, otherVersion.DictionaryNamespace);
            if (presentInOtherVersion && !presentInCurrentVersion)
            {
                throw TraceUtility.ThrowHelperError(
                    new MessageSecurityException(SR.GetString(
                        SR.InvalidAttributeInSignedHeader, info.Name, info.Namespace,
                        XD.MessageDictionary.MustUnderstand, otherVersion.DictionaryNamespace,
                        XD.MessageDictionary.MustUnderstand, currentVersion.DictionaryNamespace)), this.SecurityVerifiedMessage);
            }

            presentInCurrentVersion = null != reader.GetAttribute(currentVersion.DictionaryActor, currentVersion.DictionaryNamespace);
            presentInOtherVersion = null != reader.GetAttribute(otherVersion.DictionaryActor, otherVersion.DictionaryNamespace);
            if (presentInOtherVersion && !presentInCurrentVersion)
            {
                throw TraceUtility.ThrowHelperError(
                    new MessageSecurityException(SR.GetString(
                        SR.InvalidAttributeInSignedHeader, info.Name, info.Namespace,
                        otherVersion.DictionaryActor, otherVersion.DictionaryNamespace,
                        currentVersion.DictionaryActor, currentVersion.DictionaryNamespace)), this.SecurityVerifiedMessage);
            }
        }
Exemple #40
0
        public static WsrmAcknowledgmentInfo ReadHeader(ReliableMessagingVersion reliableMessagingVersion, XmlDictionaryReader reader, MessageHeaderInfo header)
        {
            UniqueId id;
            SequenceRangeCollection ranges;
            bool flag;
            WsrmFeb2005Dictionary dictionary   = XD.WsrmFeb2005Dictionary;
            XmlDictionaryString   namespaceUri = WsrmIndex.GetNamespace(reliableMessagingVersion);

            ReadAck(reliableMessagingVersion, reader, out id, out ranges, out flag);
            int bufferRemaining = -1;

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(dictionary.BufferRemaining, XD.WsrmFeb2005Dictionary.NETNamespace))
                {
                    if (bufferRemaining != -1)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedXmlChildNode", new object[] { reader.Name, reader.NodeType, "Body" })));
                    }
                    reader.ReadStartElement();
                    bufferRemaining = reader.ReadContentAsInt();
                    reader.ReadEndElement();
                    if (bufferRemaining < 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("InvalidBufferRemaining", new object[] { bufferRemaining })));
                    }
                }
                else
                {
                    if (reader.IsStartElement(dictionary.AcknowledgementRange, namespaceUri))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedXmlChildNode", new object[] { reader.Name, reader.NodeType, "Body" })));
                    }
                    if (reader.IsStartElement(dictionary.Nack, namespaceUri))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedXmlChildNode", new object[] { reader.Name, reader.NodeType, "Body" })));
                    }
                    if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
                    {
                        Wsrm11Dictionary dictionary2 = DXD.Wsrm11Dictionary;
                        if (reader.IsStartElement(dictionary2.None, namespaceUri) || reader.IsStartElement(dictionary2.Final, namespaceUri))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedXmlChildNode", new object[] { reader.Name, reader.NodeType, dictionary.SequenceAcknowledgement })));
                        }
                    }
                    reader.Skip();
                }
            }
            reader.ReadEndElement();
            return(new WsrmAcknowledgmentInfo(id, ranges, flag, bufferRemaining, header));
        }
        public static WsrmMessageInfo Get(MessageVersion messageVersion, ReliableMessagingVersion reliableMessagingVersion, IChannel channel, ISession session, System.ServiceModel.Channels.Message message, bool csrOnly)
        {
            WsrmMessageInfo info = new WsrmMessageInfo {
                message = message
            };
            bool isFault = true;

            try
            {
                isFault = message.IsFault;
                MessageHeaders headers = message.Headers;
                string         action  = headers.Action;
                info.action = action;
                bool flag2 = false;
                bool flag3 = reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005;
                bool flag4 = reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11;
                bool flag5 = false;
                if (action == WsrmIndex.GetCreateSequenceResponseActionString(reliableMessagingVersion))
                {
                    info.createSequenceResponseInfo = System.ServiceModel.Channels.CreateSequenceResponseInfo.ReadMessage(messageVersion, reliableMessagingVersion, message, headers);
                    ValidateMustUnderstand(messageVersion, message);
                    return(info);
                }
                if (csrOnly)
                {
                    return(info);
                }
                if (action == WsrmIndex.GetTerminateSequenceActionString(reliableMessagingVersion))
                {
                    info.terminateSequenceInfo = System.ServiceModel.Channels.TerminateSequenceInfo.ReadMessage(messageVersion, reliableMessagingVersion, message, headers);
                    flag2 = true;
                }
                else if (action == WsrmIndex.GetCreateSequenceActionString(reliableMessagingVersion))
                {
                    info.createSequenceInfo = System.ServiceModel.Channels.CreateSequenceInfo.ReadMessage(messageVersion, reliableMessagingVersion, session as ISecureConversationSession, message, headers);
                    if (flag3)
                    {
                        ValidateMustUnderstand(messageVersion, message);
                        return(info);
                    }
                    flag5 = true;
                }
                else if (flag4)
                {
                    if (action == "http://docs.oasis-open.org/ws-rx/wsrm/200702/CloseSequence")
                    {
                        info.closeSequenceInfo = System.ServiceModel.Channels.CloseSequenceInfo.ReadMessage(messageVersion, message, headers);
                        flag2 = true;
                    }
                    else if (action == "http://docs.oasis-open.org/ws-rx/wsrm/200702/CloseSequenceResponse")
                    {
                        info.closeSequenceResponseInfo = System.ServiceModel.Channels.CloseSequenceResponseInfo.ReadMessage(messageVersion, message, headers);
                        flag2 = true;
                    }
                    else if (action == WsrmIndex.GetTerminateSequenceResponseActionString(reliableMessagingVersion))
                    {
                        info.terminateSequenceResponseInfo = System.ServiceModel.Channels.TerminateSequenceResponseInfo.ReadMessage(messageVersion, message, headers);
                        flag2 = true;
                    }
                }
                string namespaceString = WsrmIndex.GetNamespaceString(reliableMessagingVersion);
                bool   flag6           = messageVersion.Envelope == EnvelopeVersion.Soap11;
                bool   flag7           = false;
                int    num             = -1;
                int    headerIndex     = -1;
                int    num3            = -1;
                int    num4            = -1;
                int    num5            = -1;
                int    num6            = -1;
                int    index           = -1;
                int    num8            = -1;
                int    num9            = -1;
                for (int i = 0; i < headers.Count; i++)
                {
                    MessageHeaderInfo info2 = headers[i];
                    if (messageVersion.Envelope.IsUltimateDestinationActor(info2.Actor) && (info2.Namespace == namespaceString))
                    {
                        bool flag8 = true;
                        if (flag5)
                        {
                            if (flag4 && (info2.Name == "UsesSequenceSSL"))
                            {
                                if (num8 != -1)
                                {
                                    num = i;
                                    break;
                                }
                                num8 = i;
                            }
                            else if (flag4 && (info2.Name == "UsesSequenceSTR"))
                            {
                                if (num9 != -1)
                                {
                                    num = i;
                                    break;
                                }
                                num9 = i;
                            }
                            else
                            {
                                flag8 = false;
                            }
                        }
                        else if (info2.Name == "Sequence")
                        {
                            if (headerIndex != -1)
                            {
                                num = i;
                                break;
                            }
                            headerIndex = i;
                        }
                        else if (info2.Name == "SequenceAcknowledgement")
                        {
                            if (num3 != -1)
                            {
                                num = i;
                                break;
                            }
                            num3 = i;
                        }
                        else if (info2.Name == "AckRequested")
                        {
                            if (num4 != -1)
                            {
                                num = i;
                                break;
                            }
                            num4 = i;
                        }
                        else if (flag6 && (info2.Name == "SequenceFault"))
                        {
                            if (index != -1)
                            {
                                num = i;
                                break;
                            }
                            index = i;
                        }
                        else
                        {
                            flag8 = false;
                        }
                        if (flag8)
                        {
                            if (i > num5)
                            {
                                num5 = i;
                            }
                            if (num6 == -1)
                            {
                                num6 = i;
                            }
                        }
                    }
                }
                if (num != -1)
                {
                    Collection <MessageHeaderInfo> notUnderstoodHeaders = new Collection <MessageHeaderInfo> {
                        headers[num]
                    };
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MustUnderstandSoapException(notUnderstoodHeaders, messageVersion.Envelope));
                }
                if (num5 > -1)
                {
                    BufferedMessage message2 = message as BufferedMessage;
                    if ((message2 != null) && message2.Headers.ContainsOnlyBufferedMessageHeaders)
                    {
                        flag7 = true;
                        using (XmlDictionaryReader reader = headers.GetReaderAtHeader(num6))
                        {
                            for (int j = num6; j <= num5; j++)
                            {
                                MessageHeaderInfo header = headers[j];
                                if (flag5)
                                {
                                    if (flag4 && (j == num8))
                                    {
                                        info.usesSequenceSSLInfo = WsrmUsesSequenceSSLInfo.ReadHeader(reader, header);
                                        headers.UnderstoodHeaders.Add(header);
                                    }
                                    else if (flag4 && (j == num9))
                                    {
                                        info.usesSequenceSTRInfo = WsrmUsesSequenceSTRInfo.ReadHeader(reader, header);
                                        headers.UnderstoodHeaders.Add(header);
                                    }
                                    else
                                    {
                                        reader.Skip();
                                    }
                                }
                                else if (j == headerIndex)
                                {
                                    info.sequencedMessageInfo = WsrmSequencedMessageInfo.ReadHeader(reliableMessagingVersion, reader, header);
                                    headers.UnderstoodHeaders.Add(header);
                                }
                                else if (j == num3)
                                {
                                    info.acknowledgementInfo = WsrmAcknowledgmentInfo.ReadHeader(reliableMessagingVersion, reader, header);
                                    headers.UnderstoodHeaders.Add(header);
                                }
                                else if (j == num4)
                                {
                                    info.ackRequestedInfo = WsrmAckRequestedInfo.ReadHeader(reliableMessagingVersion, reader, header);
                                    headers.UnderstoodHeaders.Add(header);
                                }
                                else
                                {
                                    reader.Skip();
                                }
                            }
                        }
                    }
                }
                if ((num5 > -1) && !flag7)
                {
                    flag7 = true;
                    if (flag5)
                    {
                        if (num8 != -1)
                        {
                            using (XmlDictionaryReader reader2 = headers.GetReaderAtHeader(num8))
                            {
                                MessageHeaderInfo info4 = headers[num8];
                                info.usesSequenceSSLInfo = WsrmUsesSequenceSSLInfo.ReadHeader(reader2, info4);
                                headers.UnderstoodHeaders.Add(info4);
                            }
                        }
                        if (num9 == -1)
                        {
                            goto Label_05CB;
                        }
                        using (XmlDictionaryReader reader3 = headers.GetReaderAtHeader(num9))
                        {
                            MessageHeaderInfo info5 = headers[num9];
                            info.usesSequenceSTRInfo = WsrmUsesSequenceSTRInfo.ReadHeader(reader3, info5);
                            headers.UnderstoodHeaders.Add(info5);
                            goto Label_05CB;
                        }
                    }
                    if (headerIndex != -1)
                    {
                        using (XmlDictionaryReader reader4 = headers.GetReaderAtHeader(headerIndex))
                        {
                            MessageHeaderInfo info6 = headers[headerIndex];
                            info.sequencedMessageInfo = WsrmSequencedMessageInfo.ReadHeader(reliableMessagingVersion, reader4, info6);
                            headers.UnderstoodHeaders.Add(info6);
                        }
                    }
                    if (num3 != -1)
                    {
                        using (XmlDictionaryReader reader5 = headers.GetReaderAtHeader(num3))
                        {
                            MessageHeaderInfo info7 = headers[num3];
                            info.acknowledgementInfo = WsrmAcknowledgmentInfo.ReadHeader(reliableMessagingVersion, reader5, info7);
                            headers.UnderstoodHeaders.Add(info7);
                        }
                    }
                    if (num4 != -1)
                    {
                        using (XmlDictionaryReader reader6 = headers.GetReaderAtHeader(num4))
                        {
                            MessageHeaderInfo info8 = headers[num4];
                            info.ackRequestedInfo = WsrmAckRequestedInfo.ReadHeader(reliableMessagingVersion, reader6, info8);
                            headers.UnderstoodHeaders.Add(info8);
                        }
                    }
                }
Label_05CB:
                if (flag5)
                {
                    System.ServiceModel.Channels.CreateSequenceInfo.ValidateCreateSequenceHeaders(messageVersion, session as ISecureConversationSession, info);
                    ValidateMustUnderstand(messageVersion, message);
                    return(info);
                }
                if ((info.sequencedMessageInfo == null) && (info.action == null))
                {
                    if (flag3)
                    {
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(System.ServiceModel.SR.GetString("NoActionNoSequenceHeaderReason"), messageVersion.Addressing.Namespace, "Action", false));
                    }
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateWsrmRequiredException(messageVersion));
                }
                if ((info.sequencedMessageInfo == null) && message.IsFault)
                {
                    System.ServiceModel.Channels.WsrmHeaderFault fault;
                    info.faultInfo = System.ServiceModel.Channels.MessageFault.CreateFault(message, 0x10000);
                    if (flag6)
                    {
                        if (System.ServiceModel.Channels.WsrmHeaderFault.TryCreateFault11(reliableMessagingVersion, message, info.faultInfo, index, out fault))
                        {
                            info.faultInfo      = fault;
                            info.faultException = WsrmFault.CreateException(fault);
                        }
                    }
                    else if (System.ServiceModel.Channels.WsrmHeaderFault.TryCreateFault12(reliableMessagingVersion, message, info.faultInfo, out fault))
                    {
                        info.faultInfo      = fault;
                        info.faultException = WsrmFault.CreateException(fault);
                    }
                    if (fault == null)
                    {
                        FaultConverter property = channel.GetProperty <FaultConverter>();
                        if (property == null)
                        {
                            property = FaultConverter.GetDefaultFaultConverter(messageVersion);
                        }
                        if (!property.TryCreateException(message, info.faultInfo, out info.faultException))
                        {
                            info.faultException = new ProtocolException(System.ServiceModel.SR.GetString("UnrecognizedFaultReceived", new object[] { info.faultInfo.Code.Namespace, info.faultInfo.Code.Name, System.ServiceModel.FaultException.GetSafeReasonText(info.faultInfo) }));
                        }
                    }
                    flag2 = true;
                }
                if (!flag7 && !flag2)
                {
                    if (flag3)
                    {
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ActionNotSupportedException(System.ServiceModel.SR.GetString("NonWsrmFeb2005ActionNotSupported", new object[] { action })));
                    }
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateWsrmRequiredException(messageVersion));
                }
                if (!flag2 && !WsrmUtilities.IsWsrmAction(reliableMessagingVersion, action))
                {
                    return(info);
                }
                ValidateMustUnderstand(messageVersion, message);
            }
            catch (InternalFaultException exception)
            {
                if (System.ServiceModel.DiagnosticUtility.ShouldTraceInformation)
                {
                    System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information);
                }
                info.FaultReply     = exception.FaultReply;
                info.faultException = exception.InnerException;
            }
            catch (CommunicationException exception2)
            {
                if (System.ServiceModel.DiagnosticUtility.ShouldTraceInformation)
                {
                    System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information);
                }
                if (isFault)
                {
                    info.parsingException = exception2;
                    return(info);
                }
                FaultConverter defaultFaultConverter = channel.GetProperty <FaultConverter>();
                if (defaultFaultConverter == null)
                {
                    defaultFaultConverter = FaultConverter.GetDefaultFaultConverter(messageVersion);
                }
                if (defaultFaultConverter.TryCreateFaultMessage(exception2, out info.faultReply))
                {
                    info.faultException = new ProtocolException(System.ServiceModel.SR.GetString("MessageExceptionOccurred"), exception2);
                    return(info);
                }
                info.parsingException = new ProtocolException(System.ServiceModel.SR.GetString("MessageExceptionOccurred"), exception2);
            }
            catch (XmlException exception3)
            {
                if (System.ServiceModel.DiagnosticUtility.ShouldTraceInformation)
                {
                    System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Information);
                }
                info.parsingException = new ProtocolException(System.ServiceModel.SR.GetString("MessageExceptionOccurred"), exception3);
            }
            return(info);
        }
 protected WsrmHeaderInfo(MessageHeaderInfo messageHeader)
 {
     this.messageHeader = messageHeader;
 }