Example #1
0
        internal static MessageHeader GetCurrentMessageHeader(MessageHeaderInfo header)
        {
            MessageHeader messageHeader = new MessageHeader();

            messageHeader.OperationUser = new OperationUser
            {
                CompanyCode        = header.OperationUser.CompanyCode,
                FullName           = header.OperationUser.FullName,
                LogUserName        = header.OperationUser.LogUserName,
                SourceDirectoryKey = header.OperationUser.SourceDirectoryKey,
                SourceUserName     = header.OperationUser.SourceUserName,
                UniqueUserName     = header.OperationUser.UniqueUserName
            };

            messageHeader.CompanyCode      = header.CompanyCode;
            messageHeader.StoreCompanyCode = header.StoreCompanyCode;
            messageHeader.From             = header.From;
            messageHeader.FromSystem       = header.FromSystem;
            messageHeader.Tag         = header.Tag;
            messageHeader.CountryCode = header.CountryCode;
            messageHeader.Version     = header.Version;
            messageHeader.To          = header.To;
            messageHeader.ToSystem    = header.ToSystem;

            return(messageHeader);
        }
        private ChunkingMessage GetNewChunkingMessage(Message receivedMessage, TimeoutHelper timeoutHelper)
		{
			if (receivedMessage == null)
			{
				return null;
			}
			Guid messageId = this.GetMessageId(receivedMessage);
			if (this.currentInputMessage != null && messageId == this.currentInputMessage.MessageId)
			{
				throw new InvalidOperationException("A new ChunkingMessage was requested but the received message's id matches the current message id. The received message is a chunk of the current message");
			}
			ChunkingReader reader = new ChunkingReader(receivedMessage, this.maxBufferedChunks, timeoutHelper);
			string header = receivedMessage.Headers.GetHeader<string>("OriginalAction", "http://bam.nexon.com/chunking");
			ChunkingMessage chunkingMessage = new ChunkingMessage(receivedMessage.Version, header, reader, messageId);
			string addressingNamespace = ChunkingUtils.GetAddressingNamespace(receivedMessage.Version);
			for (int i = 0; i < receivedMessage.Headers.Count; i++)
			{
				MessageHeaderInfo messageHeaderInfo = receivedMessage.Headers[i];
				if (messageHeaderInfo.Namespace != "http://bam.nexon.com/chunking" && (!(messageHeaderInfo.Name == "Action") || !(messageHeaderInfo.Namespace == addressingNamespace)))
				{
					chunkingMessage.Headers.CopyHeaderFrom(receivedMessage.Headers, i);
				}
			}
			return chunkingMessage;
		}
        private void DisplayHeader()
        {
            var headers = OperationContext.Current.IncomingMessageHeaders;

            if (headers == null)
            {
                return;
            }
            for (int i = 0; i < headers.Count; i++)
            {
                MessageHeaderInfo h = OperationContext.Current.IncomingMessageHeaders[i];
                if (!h.Actor.Equals(String.Empty))
                {
                    Console.WriteLine("\t" + h.Actor);
                }
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("\t" + h.Name);
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("\t" + h.Namespace);
                Console.WriteLine("\t" + h.Relay);
                if (h.IsReferenceParameter == true)
                {
                    Console.WriteLine("IsReferenceParameter header detected: " + h.ToString());
                }
            }
        }
Example #4
0
        /// <summary>
        /// To authenticate request whether it has valid credential to proceed
        /// </summary>
        /// <param name="xCblServiceUser">Service User</param>
        /// <param name="operationContext">Current OperationContext</param>
        /// <returns></returns>
        internal static bool IsAuthenticatedRequest(OperationContext operationContext, ref XCBL_User xCblServiceUser)
        {
            try
            {
                // If a separate namespace is needed for the Credentials tag use the global const CREDENTIAL_NAMESPACE that is commented below
                int index = operationContext.IncomingMessageHeaders.FindHeader("Credentials", "");

                // Retrieve the first soap headers, this should be the Credentials tag
                MessageHeaderInfo messageHeaderInfo = operationContext.IncomingMessageHeaders[index];

                xCblServiceUser = Meridian_AuthenticateUser(operationContext.IncomingMessageHeaders, messageHeaderInfo, index);
                if (xCblServiceUser == null || string.IsNullOrEmpty(xCblServiceUser.WebUsername))
                {
                    ApplicationError.WriteMessage("UnAuthenticated Request Incorrect Credentials");

                    return(false);
                }
                return(true);
            }
            catch (Exception ex)
            {
                ApplicationError.logErrors(ex, "IsAuthenticatedRequest");
                //  MeridianSystemLibrary.LogTransaction("No WebUser", "No FTPUser", "IsAuthenticatedRequest", "03.01", "Error - New SOAP Request not authenticated", "UnAuthenticated Request", "No FileName", "No Schedule ID", "No Order Number", null, "Error 03.01 - Incorrect Credentials");
                return(false);
            }
        }
        public static CoordinationContext GetCoordinationContext(Message message, ProtocolVersion protocolVersion)
        {
            int num;
            CoordinationContext context;
            CoordinationStrings strings = CoordinationStrings.Version(protocolVersion);
            string coordinationContext  = strings.CoordinationContext;
            string ns = strings.Namespace;

            try
            {
                num = message.Headers.FindHeader(coordinationContext, ns);
            }
            catch (MessageHeaderException exception)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                return(null);
            }
            if (num < 0)
            {
                return(null);
            }
            XmlDictionaryReader readerAtHeader = message.Headers.GetReaderAtHeader(num);

            using (readerAtHeader)
            {
                context = GetCoordinationContext(readerAtHeader, protocolVersion);
            }
            MessageHeaderInfo headerInfo = message.Headers[num];

            if (!message.Headers.UnderstoodHeaders.Contains(headerInfo))
            {
                message.Headers.UnderstoodHeaders.Add(headerInfo);
            }
            return(context);
        }
Example #6
0
        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);
            }
        }
        private Message Verify(Message message)
        {
            if (message != null)
            {
                var wss = WSS.Create(MessageSecurityVersion);
                int i   = message.Headers.FindHeader("Security", wss.SecExtNs);
                if (i >= 0)
                {
                    MessageHeaderInfo   sec          = message.Headers[i];
                    XmlDictionaryReader headerReader = message.Headers.GetReaderAtHeader(i);

                    var doc    = new XmlDocument();
                    var header = (XmlElement)doc.ReadNode(headerReader);

                    wss.VerifyResponse(header);

                    message.Headers.UnderstoodHeaders.Add(sec);
                }
                else
                {
                    //TODO::OK to have unsecure responses?
                }
            }
            return(message);
        }
Example #8
0
        public void ApplySecurityAndWriteHeaders(MessageHeaders headers, XmlDictionaryWriter writer, SecurityIdGenerator securityIdGenerator)
        {
            // There is no way to look through the headers attributes without changing the way
            // Headers.WriterStartHeader / headers.writeHeadercontents writes the header
            // So i'm using a copy that I can change without worries.
            MessageHeaders copyHeaders = new MessageHeaders(headers);

            for (int i = 0; i < headers.Count; i++)
            {
                MessageHeaderInfo header = headers[i];

                // We are not supporting another d:Security header, throw if there is already one in the message
                if (this.IsSecurityElement(header))
                {
                    throw new ArgumentException("The message already contains a d:security header.");
                }

                if (this.ShouldProtectHeader(header))
                {
                    string headerId;
                    bool   idInserted;
                    this.GetHeaderId(copyHeaders.GetReaderAtHeader(i), securityIdGenerator, true, out headerId, out idInserted);

                    // Add a reference for this header
                    this.signer.AddReference(headers, i, writer, headerId, idInserted);
                }
                else
                {
                    headers.WriteHeader(i, writer);
                }
            }
        }
            void CloneHeaders(MessageHeaders targetHeaders, MessageHeaders sourceHeaders, Uri to, HashSet <string> understoodHeadersSet)
            {
                for (int i = 0; i < sourceHeaders.Count; ++i)
                {
                    MessageHeaderInfo header = sourceHeaders[i];
                    if (!understoodHeadersSet.Contains(MessageHeaderKey(header)))
                    {
                        //If Actor is SOAP Intermediary ("*actor/next" which is us) check the Relay flag
                        if (!ActorIsNextDestination(header, sourceHeaders.MessageVersion) || header.Relay)
                        {
                            //Always wrap the header because BufferedHeader isn't smart enough to allow custom
                            //headers to switch message versions
                            MessageHeader messageHeader = new DelegatingHeader(header, sourceHeaders);
                            targetHeaders.Add(messageHeader);
                        }
                    }
                }

                // To and Action (already specified) are 'special' and may be set even with AddressingVersion.None
                targetHeaders.To = to;
                if (targetHeaders.MessageVersion.Addressing != AddressingVersion.None)
                {
                    //These are used as correlation IDs. Copy these regardless of manual addressing.
                    targetHeaders.MessageId = sourceHeaders.MessageId;
                    targetHeaders.RelatesTo = sourceHeaders.RelatesTo;

                    if (this.manualAddressing)
                    {
                        //These are addresses, only copy when ManualAddressing is enabled
                        targetHeaders.FaultTo = sourceHeaders.FaultTo;
                        targetHeaders.ReplyTo = sourceHeaders.ReplyTo;
                        targetHeaders.From    = sourceHeaders.From;
                    }
                }
            }
        public static bool ReadFrom(Message message, out Guid enlistmentId, out ControlProtocol protocol)
        {
            int num;

            enlistmentId = Guid.Empty;
            protocol     = ControlProtocol.None;
            try
            {
                num = message.Headers.FindHeader("Enlistment", "http://schemas.microsoft.com/ws/2006/02/transactions", new string[] { string.Empty });
            }
            catch (MessageHeaderException exception)
            {
                Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                return(false);
            }
            if (num < 0)
            {
                return(false);
            }
            XmlDictionaryReader readerAtHeader = message.Headers.GetReaderAtHeader(num);

            using (readerAtHeader)
            {
                ReadFrom(readerAtHeader, out enlistmentId, out protocol);
            }
            MessageHeaderInfo headerInfo = message.Headers[num];

            if (!message.Headers.UnderstoodHeaders.Contains(headerInfo))
            {
                message.Headers.UnderstoodHeaders.Add(headerInfo);
            }
            return(true);
        }
Example #11
0
        /// <summary>
        /// Gets the WCF execution context from the designated operation context.
        /// </summary>
        /// <param name="ctx">
        /// Operation context.
        /// </param>
        /// <returns>
        /// Instance of <see cref="WcfExecutionContext" /> when present, otherwise
        /// faults out accordingly.
        /// </returns>
        internal static WcfExecutionContext Get(OperationContext ctx)
        {
            #region Validations

            if (ctx == null)
            {
                throw new ArgumentNullException(nameof(ctx));
            }

            #endregion

            for (int i = 0; i < ctx.IncomingMessageHeaders.Count; i++)
            {
                MessageHeaderInfo mhi = ctx.IncomingMessageHeaders[i];

                if (mhi.Name == WcfExecutionContext.HeaderName &&
                    mhi.Namespace == Zn.Namespace)
                {
                    XmlReader xr = ctx.IncomingMessageHeaders.GetReaderAtHeader(i);

                    XmlSerializer ser = new XmlSerializer(typeof(WcfExecutionContext));
                    return((WcfExecutionContext)ser.Deserialize(xr));
                }
            }

            throw new ZincException(ER.ServiceModel_ExecutionContext_NotFound);
        }
        private void MarkHeaderAsUnderstood()
        {
            // header decryption does not reorder or delete headers
            MessageHeaderInfo header = Message.Headers[HeaderIndex];

            Fx.Assert(header.Name == Name && header.Namespace == Namespace && header.Actor == Actor, "security header index mismatch");
            Message.Headers.UnderstoodHeaders.Add(header);
        }
Example #13
0
 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);
 }
Example #14
0
        public void CreateFromXmlReader()
        {
            string xml = @"<s:Envelope xmlns:a=""http://www.w3.org/2005/08/addressing"" xmlns:s=""http://www.w3.org/2003/05/soap-envelope""><s:Header><a:Action s:mustUnderstand=""1"">Ack</a:Action><TestHeaderItem>test</TestHeaderItem></s:Header><s:Body></s:Body></s:Envelope>";

            XmlReader r   = XmlReader.Create(new StringReader(xml));
            Message   msg = Message.CreateMessage(r, 10000, MessageVersion.Default);

            Assert.AreEqual(MessageVersion.Default, msg.Version, "#2");
            Assert.AreEqual(2, msg.Headers.Count, "#4");
            Assert.AreEqual("Ack", msg.Headers.Action, "#3");
            Assert.IsNull(msg.Headers.FaultTo, "#5");
            Assert.IsNull(msg.Headers.From, "#6");
            Assert.IsNull(msg.Headers.MessageId, "#7");
            Assert.IsTrue(msg.IsEmpty, "#8");

            MessageHeaderInfo hi = msg.Headers [0];

            Assert.AreEqual("Action", hi.Name, "#h1-1");
            Assert.AreEqual("http://www.w3.org/2005/08/addressing", hi.Namespace, "#h1-2");
            Assert.AreEqual(String.Empty, hi.Actor, "#h1-3");
            Assert.IsTrue(hi.MustUnderstand, "#h1-4");
            Assert.IsFalse(hi.Relay, "#h1-5");
            Assert.IsFalse(hi.IsReferenceParameter, "#h1-6");

            int count = 0;

            /* FIXME: test UnderstoodHeaders later
             * foreach (MessageHeaderInfo i in msg.Headers.UnderstoodHeaders) {
             *      count++;
             *      Assert.AreEqual ("", i.Actor, "#9");
             *      Assert.IsFalse (i.IsReferenceParameter, "#10");
             *      Assert.IsTrue (i.MustUnderstand, "#11");
             *      Assert.AreEqual ("Action", i.Name, "#12");
             *      Assert.AreEqual ("http://www.w3.org/2005/08/addressing", i.Namespace, "#13");
             *      Assert.AreEqual (false, i.Relay, "#14");
             * }
             * Assert.AreEqual (1, count, "#15"); // allow only once
             */

            // MS implementation closes XmlReader regardless of
            // its initial state, which isn't good.
            //Assert.AreEqual (ReadState.Closed, r.ReadState, "#1");

            r = XmlReader.Create(new StringReader(xml));
            r.MoveToContent();
            msg = Message.CreateMessage(r, 10000, MessageVersion.Default);
            // ditto
            // Assert.AreEqual (ReadState.Closed, r.ReadState, "#1-2");

            string xml2 = @"<Wrap><s:Envelope xmlns:a=""http://www.w3.org/2005/08/addressing"" xmlns:s=""http://www.w3.org/2003/05/soap-envelope""><s:Header><a:Action s:mustUnderstand=""1"">Ack</a:Action></s:Header><s:Body /></s:Envelope></Wrap>";

            r = XmlReader.Create(new StringReader(xml2));
            r.MoveToContent();
            r.Read(); // s:Envelope
            msg = Message.CreateMessage(r, 10000, MessageVersion.Default);
            // ditto
            // Assert.AreEqual (ReadState.Closed, r.ReadState, "#1-3");
        }
Example #15
0
        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;
        }
Example #16
0
        public void MessageCreateAddsAction()
        {
            Message           m    = Message.CreateMessage(MessageVersion.Default, "test", 1);
            MessageHeaderInfo info = m.Headers [0];

            Assert.AreEqual("Action", info.Name, "#1");
            Assert.AreEqual("http://www.w3.org/2005/08/addressing", info.Namespace, "#2");
            Assert.AreEqual(true, info.MustUnderstand, "#3");
            Assert.AreEqual(String.Empty, info.Actor, "#4");
        }
Example #17
0
        public static RequestTotalItemsCountEstimate ReadFrom(MessageHeaders messageHeaders)
        {
            int index = messageHeaders.FindHeader(ElementName, ManagementNamespaces.Namespace);

            if (index < 0)
            {
                return(null);
            }
            MessageHeaderInfo headerInfo = messageHeaders[index];

            return(new RequestTotalItemsCountEstimate());
        }
Example #18
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.RemoveAt(i);
                    msg.Headers.Add(wss_header);
                }
            }

            // 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);
        }
Example #19
0
    public void WriteMessageHeader()
    {
        OperationContext oc = OperationContext.Current;

        //output the SOAP Message Header.
        for (int i = 0; i < oc.IncomingMessageHeaders.Count; i++)
        {
            MessageHeaderInfo info = oc.IncomingMessageHeaders[i];
            Console.WriteLine("Name: " + info.Name);
            Console.WriteLine("Namespace: " + info.Namespace);
            Console.WriteLine("Content: " + oc.IncomingMessageHeaders.GetHeader <string>(i));
        }
    }
Example #20
0
 private void CopyMessageHeader(MessageHeaders messageHeaders, int index)
 {
     try
     {
         MessageHeaderInfo headerInfo  = messageHeaders[index];
         XmlQualifiedName  qName       = new XmlQualifiedName(headerInfo.Name, headerInfo.Namespace);
         string            headerValue = messageHeaders.GetHeader <string>(index);
         MessageHeader     header      = MessageHeader.CreateHeader(headerInfo.Name, headerInfo.Namespace, headerValue);
         MessageHeaders.Add(qName, header);
     }
     catch (Exception)
     {
         //eats away headers not of the right type
     }
 }
Example #21
0
        public Dictionary <string, string> GetIncomingMessageHeaders()
        {
            Dictionary <string, string> infos = new Dictionary <string, string>();
            MessageHeaders headers            = OperationContext.Current.IncomingMessageHeaders;

            // look at headers on incoming message
            for (int i = 0; i < headers.Count; ++i)
            {
                MessageHeaderInfo    h  = headers[i];
                System.Xml.XmlReader xr = headers.GetReaderAtHeader(i);
                string value            = xr.ReadElementContentAsString();
                infos.Add(string.Format("{0}//{1}", h.Namespace, h.Name), value);
            }

            return(infos);
        }
        internal ReceiveSecurityHeader TryCreateReceiveSecurityHeader(Message message, string actor, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, MessageDirection direction)
        {
            int headerIndex = message.Headers.FindHeader(this.HeaderName.Value, this.HeaderNamespace.Value, new string[] { actor });

            if ((headerIndex < 0) && string.IsNullOrEmpty(actor))
            {
                headerIndex = message.Headers.FindHeader(this.HeaderName.Value, this.HeaderNamespace.Value, message.Version.Envelope.UltimateDestinationActorValues);
            }
            if (headerIndex < 0)
            {
                return(null);
            }
            MessageHeaderInfo info = message.Headers[headerIndex];

            return(this.CreateReceiveSecurityHeader(message, info.Actor, info.MustUnderstand, info.Relay, standardsManager, algorithmSuite, direction, headerIndex));
        }
        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 object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            OperationContext ctx = OperationContext.Current;


            int            headerIndex = -1;
            MessageHeaders headers     = OperationContext.Current.IncomingMessageHeaders;

            for (int i = 0; i < headers.Count; i++)
            {
                MessageHeaderInfo header = headers[i];
                if (header.Name == UsernameTokenHeader.NAME && header.Namespace == UsernameTokenHeader.NAMESPACE)
                {
                    headerIndex = i;
                    break;
                }
            }

            if (headerIndex != -1)
            {
                XmlReader reader = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(headerIndex);

                XmlSerializer       serializer = new XmlSerializer(typeof(UsernameTokenHeader));
                UsernameTokenHeader header     = (UsernameTokenHeader)serializer.Deserialize(reader);
                // header is deserialized OK

                if (header.UsernameToken == null)
                {
                    SafeLog("Authentication failed: no username information in header");
                    CommonUtils.ReturnFault("Sender", "NotAuthorized", "No username token in request");
                }
                else
                {
                    if (!UsernameTokenValidator.Validate(header.UsernameToken))
                    {
                        SafeLog("Authentication failed: no such combination of username and password");
                        CommonUtils.ReturnFault("Sender", "NotAuthorized");
                    }
                }
            }
            else
            {
                SafeLog("Authentication failed: no header in request");
                CommonUtils.ReturnFault("Sender", "NotAuthorized");
            }
            return(null);
        }
Example #25
0
        public static SelectorSetHeader ReadFrom(MessageHeaders messageHeaders)
        {
            SelectorSetHeader result;
            int index = messageHeaders.FindHeader(ElementName, ManagementNamespaces.Namespace);

            if (index < 0)
            {
                return(null);
            }
            using (XmlDictionaryReader readerAtHeader = messageHeaders.GetReaderAtHeader(index))
            {
                result = ReadFrom(readerAtHeader);
            }
            MessageHeaderInfo headerInfo = messageHeaders[index];

            return(result);
        }
Example #26
0
        public static IdentifierHeader ReadFrom(MessageHeaders messageHeaders)
        {
            IdentifierHeader result;
            int index = messageHeaders.FindHeader(ElementName, EventingActions.Namespace);

            if (index < 0)
            {
                return(null);
            }
            using (XmlDictionaryReader readerAtHeader = messageHeaders.GetReaderAtHeader(index))
            {
                result = ReadFrom(readerAtHeader);
            }
            MessageHeaderInfo headerInfo = messageHeaders[index];

            return(result);
        }
Example #27
0
        public static WsatRegistrationHeader ReadFrom(Message message)
        {
            int num;
            WsatRegistrationHeader header;

            try
            {
                num = message.Headers.FindHeader("RegisterInfo", "http://schemas.microsoft.com/ws/2006/02/transactions");
            }
            catch (MessageHeaderException exception)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                return(null);
            }
            if (num < 0)
            {
                return(null);
            }
            XmlDictionaryReader readerAtHeader = message.Headers.GetReaderAtHeader(num);
            XmlDictionaryReader reader2        = readerAtHeader;

            try
            {
                header = ReadFrom(readerAtHeader);
            }
            catch (XmlException exception2)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Error);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnlistmentHeaderException(exception2.Message, exception2));
            }
            finally
            {
                if (reader2 != null)
                {
                    reader2.Dispose();
                }
            }
            MessageHeaderInfo headerInfo = message.Headers[num];

            if (!message.Headers.UnderstoodHeaders.Contains(headerInfo))
            {
                message.Headers.UnderstoodHeaders.Add(headerInfo);
            }
            return(header);
        }
        public static OleTxTransactionHeader ReadFrom(Message message)
        {
            int num;
            OleTxTransactionHeader header;

            try
            {
                num = message.Headers.FindHeader("OleTxTransaction", "http://schemas.microsoft.com/ws/2006/02/tx/oletx");
            }
            catch (MessageHeaderException exception)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Error);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TransactionException(System.ServiceModel.SR.GetString("OleTxHeaderCorrupt"), exception));
            }
            if (num < 0)
            {
                return(null);
            }
            XmlDictionaryReader readerAtHeader = message.Headers.GetReaderAtHeader(num);
            XmlDictionaryReader reader2        = readerAtHeader;

            try
            {
                header = ReadFrom(readerAtHeader);
            }
            catch (XmlException exception2)
            {
                DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Error);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TransactionException(System.ServiceModel.SR.GetString("OleTxHeaderCorrupt"), exception2));
            }
            finally
            {
                if (reader2 != null)
                {
                    reader2.Dispose();
                }
            }
            MessageHeaderInfo headerInfo = message.Headers[num];

            if (!message.Headers.UnderstoodHeaders.Contains(headerInfo))
            {
                message.Headers.UnderstoodHeaders.Add(headerInfo);
            }
            return(header);
        }
 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 OleTxTransactionHeader ReadFrom(Message message)
        {
            int index;

            try
            {
                index = message.Headers.FindHeader(OleTxHeaderElement, OleTxNamespace);
            }
            catch (MessageHeaderException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TransactionException(SR.GetString(SR.OleTxHeaderCorrupt), e));
            }

            if (index < 0)
            {
                return(null);
            }

            OleTxTransactionHeader oleTxHeader;
            XmlDictionaryReader    reader = message.Headers.GetReaderAtHeader(index);

            using (reader)
            {
                try
                {
                    oleTxHeader = ReadFrom(reader);
                }
                catch (XmlException xe)
                {
                    DiagnosticUtility.TraceHandledException(xe, TraceEventType.Error);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TransactionException(SR.GetString(SR.OleTxHeaderCorrupt), xe));
                }
            }

            MessageHeaderInfo header = message.Headers[index];

            if (!message.Headers.UnderstoodHeaders.Contains(header))
            {
                message.Headers.UnderstoodHeaders.Add(header);
            }

            return(oleTxHeader);
        }