public override void SecureMessage(SoapEnvelope envelope, WSE.Security security)
            {
                // get server password from database 
                string password = parentAssertion.Password;

                if (password == null)
                    return;

                // hash password
                password = SHA1(password);

                // create username token
                UsernameToken userToken = new UsernameToken(parentAssertion.ServerId.ToString(), password,
                            PasswordOption.SendNone);

                if (parentAssertion.signRequest || parentAssertion.encryptRequest)
                {
                    // Add the token to the SOAP header.
                    security.Tokens.Add(userToken);
                }

                if (parentAssertion.signRequest)
                {
                    // Sign the SOAP message by using the UsernameToken.
                    MessageSignature sig = new MessageSignature(userToken);
                    security.Elements.Add(sig);
                }

                if (parentAssertion.encryptRequest)
                {
                    // we don't return any custom SOAP headers
                    // so, just encrypt a message Body
                    EncryptedData data = new EncryptedData(userToken);

                    // encrypt custom headers
                    for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)
                    {
                        XmlElement child = envelope.Header.ChildNodes[index] as XmlElement;

                        // find all SecureSoapHeader headers marked with a special attribute
                        if (child != null && child.NamespaceURI == "http://smbsaas/websitepanel/server/")
                        {
                            // create ID attribute for referencing purposes
                            string id = Guid.NewGuid().ToString();
                            child.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", id);

                            // Create an encryption reference for the custom SOAP header.
                            data.AddReference(new EncryptionReference("#" + id));
                        }
                    }

                    security.Elements.Add(data);
                }
            }
예제 #2
1
파일: Form1.cs 프로젝트: junkuvo/.net
 public static String FormatXml(String xml)
 {
     String ret = xml;
     try
     {
         SoapEnvelope env = new SoapEnvelope();
         env.LoadXml(xml);
         return FormatXml(env);
     }
     catch (Exception)
     {
     }
     return ret;
 }
예제 #3
0
        private string serializeSoap <T>(T messageInstance) where T : SoapMessage
        {
            if (messageInstance == null)
            {
                throw new NotSupportedException("Message instance can not be empty.");
            }
            SoapMessageAttribute[] array = (SoapMessageAttribute[])messageInstance.GetType().GetCustomAttributes(typeof(SoapMessageAttribute), inherit: false);
            if (array.Length == 0)
            {
                throw new NotSupportedException("SOAP Message must be decorated with SoapMessageAttribute");
            }
            if (string.IsNullOrEmpty(array[0].ElementName) || string.IsNullOrEmpty(array[0].NamespacePrefix) || string.IsNullOrEmpty(array[0].NamespaceUri))
            {
                throw new NotSupportedException("SOAP Message SoapMessageAttribute declaration must specify ElementName, NamespacePrefix and NamespaceUri.");
            }
            SoapEnvelope <T>        soapEnvelope            = new SoapEnvelope <T>(messageInstance);
            XmlAttributeOverrides   overrides               = messageOverrides(soapEnvelope.Body.GetType(), messageInstance.GetType(), array[0].ElementName, array[0].NamespaceUri);
            XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();

            xmlSerializerNamespaces.Add("soap", "http://schemas.xmlsoap.org/soap/envelope/");
            xmlSerializerNamespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema");
            xmlSerializerNamespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xmlSerializerNamespaces.Add(array[0].NamespacePrefix, array[0].NamespaceUri);
            Utf8StringWriter utf8StringWriter = new Utf8StringWriter();
            XmlSerializer    xmlSerializer    = new XmlSerializer(soapEnvelope.GetType(), overrides);

            xmlSerializer.Serialize(utf8StringWriter, soapEnvelope, xmlSerializerNamespaces);
            string result = utf8StringWriter.GetStringBuilder().ToString();

            utf8StringWriter.Close();
            return(result);
        }
        public async Task <DTO.UserInfo> GetUserInfo(string samlAssertionId, CancellationToken token)
        {
            var x509Certificate = await _x509Provider.Provide(token);

            var userInfoRequest = new UserInfoRequest
            {
                Tgsid = samlAssertionId
            };

            using (var soapClient = SoapClient.Prepare())
            {
                soapClient
                .WithBinarySecurityTokenHeader(x509Certificate);

                var envelope = SoapEnvelope.Prepare();
                envelope.Body(userInfoRequest.ToXElement());

                var identityInfoServiceUri = _environment.GetServiceUri("pz-services/tpUserInfo");

                var response = await soapClient.SendAsync(
                    identityInfoServiceUri.AbsoluteUri,
                    "GetTpUserInfo",
                    envelope,
                    token);

                var userInfoResponse = response.Body <UserInfoResponse>();

                return(userInfoResponse.GetTpUserInfoReturn);
            }
        }
예제 #5
0
        private string CreateXmlStringFromObject(AirShoppingRQ airShopping)
        {
            var soap = new SoapEnvelope()
            {
                body = new ResponseBody <AirShoppingRQ>
                {
                    AirShoppingRQ = airShopping
                }
            };

            XmlSerializer serializer = new XmlSerializer(typeof(SoapEnvelope));
            var           settings   = new XmlWriterSettings();

            settings.Indent             = true;
            settings.OmitXmlDeclaration = true;

            using (var stream = new StringWriter())
                using (var writer = XmlWriter.Create(stream, settings))
                {
                    serializer.Serialize(writer, soap);
                    return(stream.ToString());
                }
            //var writer = new StringWriter();
            //serializer.Serialize(writer, soap);
            //return writer.ToString();
        }
예제 #6
0
        /// <summary>
        ///     Appends the received <see cref="XElement" /> collection to the existing
        ///     ones in the received <see cref="SoapEnvelope" />.
        /// </summary>
        /// <param name="envelope">The <see cref="SoapEnvelope" /> to append the headers</param>
        /// <param name="headers">The <see cref="SoapHeader" /> collection to append</param>
        /// <returns>The <see cref="SoapEnvelope" /> after changes</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static SoapEnvelope WithHeaders(this SoapEnvelope envelope, params XElement[] headers)
        {
            if (envelope == null)
            {
                throw new ArgumentNullException(nameof(envelope));
            }
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            if (headers.Length == 0)
            {
                return(envelope);
            }

            if (envelope.Headers == null)
            {
                envelope.Headers = new XElement[0];
            }
            else
            {
                var envelopeHeaders = new List <XElement>(envelope.Headers);
                envelopeHeaders.AddRange(headers);
                envelope.Headers = envelopeHeaders.ToArray();
            }

            return(envelope);
        }
        public async Task <string> AddDocumentToSign(AddDocumentToSigningRequest request, CancellationToken token)
        {
            var certificate = await _x509Provider.Provide(token);

            using (var client = SoapClient
                                .Prepare())
            {
                client
                .AddCommonHeaders()
                .WithBinarySecurityTokenHeader(certificate);

                var envelope = SoapEnvelope
                               .Prepare()
                               .Body(request.ToXElement());

                var soapResponse = await client.SendAsync(
                    _signingServiceUri.AbsoluteUri,
                    "addDocumentToSigning",
                    envelope,
                    token);

                var response = soapResponse.Body <AddDocumentToSigningResponse>();

                return(response.AddDocumentToSigningReturn);
            }
        }
예제 #8
0
        /// <summary>
        /// Processes the SOAP Messages and decompresses them if necessary
        /// </summary>
        /// <param name="envelope">The <see cref="SoapEnvelope"/> to process.</param>
        public override void ProcessMessage(SoapEnvelope envelope)
        {
            if (envelope.Header == null)
            {
                return;
            }
            //check if the ZipFilter has been applied.
            XmlNodeList elemList = envelope.Header.GetElementsByTagName(Constants.WSCFCompressionElement);

            if (elemList.Count == 0)
            {
                return;
            }
            //The header contains the element, let's check if the body is compressed
            if (elemList[0].Attributes[Constants.WSCFAttribute].Value.Equals("0"))
            {
                return;
            }
            //make sure we decompress using the same method we used for compression.
            WSCFCompression.CompressionProvider = (CompressionType)Convert.ToInt32((string)elemList[0].Attributes[Constants.WSCFTypeAttribute].Value);
            //remove the element from the envelope, it's no longer necessary.
            envelope.Header.RemoveChild(elemList[0]);
            //decompress the envelope attachments
            MemoryStream outStream = WSCFCompression.DeCompressToStream(envelope.Context.Attachments[0].Stream);
            //replace the body element.
            XmlElement body = envelope.CreateBody();

            body.InnerXml = System.Text.Encoding.UTF8.GetString(outStream.ToArray());
            GC.Collect();
        }
예제 #9
0
        /// <summary>
        /// Processes the SOAP Messages and compresses them if necessary
        /// </summary>
        /// <param name="envelope">The <see cref="SoapEnvelope"/> to process.</param>
        public override void ProcessMessage(SoapEnvelope envelope)
        {
            if (!enabled)
            {
                return;
            }
            //add an attribute to specify that the filter has been applied on this envelope.
            XmlElement soapHeader = envelope.CreateHeader();

            if (envelope.Body.InnerText.Length < minFilterSize)
            {
                return;
            }
            else
            {
                soapHeader.AppendChild(CreateCustomHeader(soapHeader, "1" ));
            }
            //compress the body element.
            MemoryStream result = new MemoryStream(WSCFCompression.Compress(Encoding.UTF8.GetBytes(envelope.Body.InnerXml)));

            //Attach zipped result to the envelope.
            Microsoft.Web.Services2.Attachments.Attachment attch = new Microsoft.Web.Services2.Attachments.Attachment("APPLICATION/OCTET-STREAM", result);
            envelope.Context.Attachments.Add(attch);

            //remove old body.
            XmlElement newBody = envelope.CreateBody();
            newBody.RemoveAll();
            envelope.SetBodyObject(newBody);
            GC.Collect();
        }
예제 #10
0
        public async Task <string> GetUserId(string samlAssertionId, CancellationToken token)
        {
            var x509Certificate = await _x509Provider.Provide(token);

            var userIdReq = new ResolveUserIdRequest
            {
                AssertionId = samlAssertionId
            };

            using (var soapClient = SoapClient.Prepare())
            {
                soapClient
                .AddCommonHeaders()
                .WithBinarySecurityTokenHeader(x509Certificate);

                var envelope = SoapEnvelope.Prepare();
                envelope.Body(userIdReq.ToXElement());

                var identityInfoServiceUri = _environment.GetServiceUri("dt-services/idpIdentityInfoService");

                var response2 = await soapClient.SendAsync(
                    identityInfoServiceUri.AbsoluteUri,
                    "ResolveUserId",
                    envelope,
                    token);

                var userIdResp = response2.Body <ResolveUserIdResponse>();

                return(userIdResp.UserId);
            }
        }
        public async Task <byte[]> GetSignedDocument(string documentId, CancellationToken token)
        {
            var certificate = await _x509Provider.Provide(token);

            using (var client = SoapClient
                                .Prepare())
            {
                client
                .AddCommonHeaders()
                .WithBinarySecurityTokenHeader(certificate);

                var request = new GetSignedDocumentRequest
                {
                    Id = documentId
                };

                var envelope = SoapEnvelope
                               .Prepare()
                               .Body(request.ToXElement());

                var soapResponse = await client.SendAsync(
                    _signingServiceUri.AbsoluteUri,
                    "getSignedDocument",
                    envelope,
                    token);

                var response = soapResponse.Body <GetSignedDocumentResponse>();

                return(response.SignedDocumentReturn);
            }
        }
        protected void CreateToken(SoapEnvelope soap, X509Certificate2 certificateSignature, XmlElement nodeKeyInfo)
        {
            SecurityTokenReference tokenRef          = new SecurityTokenReference();
            XmlElement             tokenXmlReference = tokenRef.GetXml(soap);

            var nodeX509Data = CreateNode(tokenXmlReference, Constants.DATA);

            var nodeX509IssuerSerial = CreateNode(nodeX509Data, Constants.ISSUER_SERIAL);

            nodeX509Data.AppendChild(nodeX509IssuerSerial);

            var nodeX509IssuerName = CreateNode(nodeX509IssuerSerial, Constants.ISSUER_NAME);

            nodeX509IssuerName.InnerText = certificateSignature.Issuer;

            var nodeX509SerialNumber = CreateNode(nodeX509IssuerSerial, Constants.SERIAL_NUMBER);

            nodeX509SerialNumber.InnerText = Convert.ToString(Convert.ToInt64(certificateSignature.SerialNumber, 16));

            nodeX509IssuerSerial.AppendChild(nodeX509IssuerName);
            nodeX509IssuerSerial.AppendChild(nodeX509SerialNumber);

            tokenXmlReference.AppendChild(nodeX509Data);

            nodeKeyInfo.AppendChild(tokenXmlReference);
        }
예제 #13
0
파일: Transport.cs 프로젝트: Noisyfox/fSoap
        /**
         * Serializes the request.
         */

        protected byte[] createRequestData(SoapEnvelope envelope, String encoding)
        {
            Encoding     e   = Encoding.GetEncoding(encoding);
            MemoryStream bos = new MemoryStream(bufferLength);

            byte[] tagBytes = Encoding.UTF8.GetBytes(xmlVersionTag);
            bos.Write(tagBytes, 0, tagBytes.Length);
            XmlSerializer xw = new FXmlSerializer();

            xw.setOutput(bos, e);
            foreach (KeyValuePair <object, object> keyValuePair in prefixes)
            {
                String key = (String)keyValuePair.Key;
                xw.setPrefix(key, (String)keyValuePair.Value);
            }
            envelope.write(xw);
            xw.flush();
            bos.WriteByte((byte)'\r');
            bos.WriteByte((byte)'\n');
            bos.Flush();
            byte[] result = bos.ToArray();
            xw  = null;
            bos = null;
            return(result);
        }
예제 #14
0
        public void BuildEnvelopeHeaderTest()
        {
            bool assert   = true;
            var  envelope = SoapEnvelope.Prepare().WithHeaders(new BeginSessionHeader());

            using (var _soapClient = SoapClient.Prepare())
            {
                try
                {
                    var xml = _soapClient.Settings.SerializationProvider.ToXmlString(envelope);
                    Debug.WriteLine(xml);
                }
                catch (SoapEnvelopeSerializationException e)
                {
                    assert = false;
                    Debug.WriteLine(e.Message);
                }
                catch (SoapEnvelopeDeserializationException e)
                {
                    assert = false;
                    Debug.WriteLine(e.Message);
                }
                catch (Exception e)
                {
                    assert = false;
                    Debug.WriteLine(e.Message);
                }
            }
            Assert.IsTrue(assert);
        }
 protected void InitializeEnvelope(SoapEnvelope soap)
 {
     soap.Header.RemoveAll();
     soap.DocumentElement.Attributes.RemoveAll();
     soap.DocumentElement.SetAttribute(Constants.NS_SOAP, Constants.ENVELOPE);
     soap.DocumentElement.SetAttribute(Constants.NS_SER, Constants.ENVELOPE_TRANSBANK);
 }
예제 #16
0
        string TryRequest(SoapEnvelope env)
        {
            var    bytes    = env.ToXmlBytes();
            string response = string.Empty;

#if DEBUG
            System.Diagnostics.Debug.WriteLine(env.ToXmlString());
#endif

            try {
                response = DoPostRequest(Url, bytes);
            } catch (WebException ex) {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(ex);
#endif
                var hwr = ex.Response as HttpWebResponse;
                if (hwr != null && hwr.StatusCode == HttpStatusCode.InternalServerError)
                {
                    using (var sr = new StreamReader(hwr.GetResponseStream())) {
                        response = sr.ReadToEnd();
                    }
                }
            }

#if DEBUG
            System.Diagnostics.Debug.WriteLine(response);
#endif

            return(response);
        }
예제 #17
0
        public async Task <List <ServiceIdentifier> > GetServicesAsync(Uri securityServerUri, SubSystemIdentifier client,
                                                                       SubSystemIdentifier source)
        {
            var soapEnvelope = SoapEnvelope.Prepare()
                               .Body(new ListMethodsRequest())
                               .WithHeaders(
                new List <SoapHeader>
            {
                IdHeader.Random,
                UserIdHeader,
                ProtocolVersionHeader.Version40,
                (XRoadClient)client,
                new XRoadService
                {
                    Instance      = source.Instance,
                    MemberClass   = source.MemberClass,
                    MemberCode    = source.MemberCode,
                    SubSystemCode = source.SubSystemCode,
                    ServiceCode   = "listMethods"
                }
            });


            var soapClient = SoapClient.Prepare();
            var envelope   = await soapClient.SendAsync(securityServerUri.ToString(), string.Empty, soapEnvelope);

            soapClient.Dispose();

            envelope.ThrowIfFaulted();
            return(envelope.Body <ListMethodsResponse>().Services.Select(o => (ServiceIdentifier)o).ToList());
        }
예제 #18
0
        public bool Cancel(string issuer, string uuid)
        {
            var    env      = CreateEnvelope(issuer, uuid);
            string response = TryRequest(env);

            if (response.Length == 0)
            {
                throw new FiscoClicClientException("Bad response format.");
            }

            var doc = SoapEnvelope.FromXml(response);

            if (doc.Body.Length == 0)
            {
                throw new FiscoClicClientException("Bad response format.");
            }

            if (doc.Body[0] is CancelaCFDIResponse)
            {
                var res = doc.Body[0] as CancelaCFDIResponse;
                return(Convert.ToBoolean(res.Return));
            }

            if (doc.Body[0] is SoapFault)
            {
                var fault = doc.Body[0] as SoapFault;
                throw new FiscoClicClientException(fault.FaultString, fault.Detail.Exception);
            }

            return(false);
        }
예제 #19
0
        public void DiscoverCubes()
        {
            bool assert     = true;
            var  connection = TestHelper.CreateConnectionToSsas();

            connection.Open();

            var command = new XmlaCommand("MDSCHEMA_CUBES", connection);

            try
            {
                SoapEnvelope result = command.Execute() as SoapEnvelope;
                var          rows   = result.GetXRows();
                foreach (var r in rows)
                {
                    assert = assert && r.Elements().Where(e => e.Name.LocalName == "CUBE_NAME").Count() > 0;
                }
                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                assert = false;
            }
            Assert.IsTrue(assert);
        }
예제 #20
0
        protected async Task <TResponse> ExecuteAsync <TRequestBody, TResponse>(TRequestBody body, string action)
            where TResponse : new()
            where TRequestBody : new()
        {
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }
            if (_onvifSettingsProvider.BaseUri == null)
            {
                throw new OnvifServiceException("Onvif service Uri is not set.");
            }

            var soapHandler = new DelegatingSoapHandler
            {
                Order = int.MaxValue,
                OnSoapEnvelopeRequestAction = (c, args) =>
                {
                    if (_onvifSettingsProvider.Credentials != null)
                    {
                        args.Envelope
                        .WithHeader(KnownHeader.Oasis.Security.UsernameTokenWithPasswordDigest(_onvifSettingsProvider.Credentials.Username, _onvifSettingsProvider.Credentials.Password, DateTime.Now));
                    }
                }
            };

            using (var client = SoapClient.SoapClient.Prepare().WithHandler(soapHandler))
            {
                var requestEnvelope = SoapEnvelope
                                      .Prepare()
                                      .Body(body);

                try
                {
                    var responseEnvelope = await client.SendAsync($"http://{_onvifSettingsProvider.BaseUri}/{ServicePath}", action, requestEnvelope);

                    return(responseEnvelope.Body <TResponse>());
                }
                catch (SoapEnvelopeSerializationException e)
                {
                    throw new OnvifServiceException("Unable to serialize request SOAP envelope. See inner exception for details.", e);
                }
                catch (SoapEnvelopeDeserializationException e)
                {
                    throw new OnvifServiceException("Unable to deserialize response to SOAP envelope. See inner exception for details.", e);
                }
                catch (FaultException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    throw new OnvifServiceException("Onvif connection failed. See inner exception for details.", e);
                }
            }
        }
        /// <summary>
        /// Send the probe message.
        /// </summary>
        /// <param name="type">The probe message type.</param>
        /// <param name="scope">The scope of the probe message.</param>
        public void SendProbeMessage(string type, string scope)
        {
            SoapEnvelope req = this.client.CreateProbe(type, new string[] { scope });

            this.client.SendMessage(req);
            this.startReceiving = true;
        }
예제 #22
0
 /// <summary>
 /// Processes the SOAP Messages and decompresses them if necessary
 /// </summary>
 /// <param name="envelope">The <see cref="SoapEnvelope"/> to process.</param>
 public override void ProcessMessage(SoapEnvelope envelope)
 {
     if(envelope.Header == null)
     {
         return;
     }
     //check if the ZipFilter has been applied.
     XmlNodeList elemList = envelope.Header.GetElementsByTagName(Constants.WSCFCompressionElement);
     if (elemList.Count == 0)
     {
         return;
     }
     //The header contains the element, let's check if the body is compressed
     if (elemList[0].Attributes[Constants.WSCFAttribute].Value.Equals("0"))
     {
         return;
     }
     //make sure we decompress using the same method we used for compression.
     WSCFCompression.CompressionProvider = (CompressionType)Convert.ToInt32((string)elemList[0].Attributes[Constants.WSCFTypeAttribute].Value);
     //remove the element from the envelope, it's no longer necessary.
     envelope.Header.RemoveChild(elemList[0]);
     //decompress the envelope attachments
     MemoryStream outStream = WSCFCompression.DeCompressToStream(envelope.Context.Attachments[0].Stream);
     //replace the body element.
     XmlElement body = envelope.CreateBody();
     body.InnerXml = System.Text.Encoding.UTF8.GetString(outStream.ToArray());
     GC.Collect();
 }
예제 #23
0
        public Note[] getNotes(String fromDate, String toDate, int nNotes)
        {
            string soapString = "<soapenv:Envelope " +
                                "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
                                "xmlns:vis=\"http://vistaweb.webservices.fhie.gov\">" +
                                "<soapenv:Header/>" +
                                "<soapenv:Body>" +
                                "<vis:getNotes>" +
                                "<arg_0_0>" +
                                "<active>true</active>" +
                                "<endDate>2010-06-30T04:00:00.000Z</endDate>" +
                                "<externalUserId>9876</externalUserId>" +
                                "<externalUserName>testuser</externalUserName>" +
                                "<itemId>ITEM1</itemId>" +
                                "<patientId>DNS:FHIE.GOV/VA0/1006184063V088473</patientId>" +
                                "<startDate>2000-06-30T04:00:00.000Z</startDate>" +
                                "<status>STATUS1</status>" +
                                "<userFacilityCode>506</userFacilityCode>" +
                                "<userFacilityName>Ann Arbor, MI</userFacilityName>" +
                                "<itemIds></itemIds>" +
                                "</arg_0_0>" +
                                "</vis:getNotes>" +
                                "</soapenv:Body>" +
                                "</soapenv:Envelope>";

            SoapEnvelope response = (SoapEnvelope)cxn.query(soapString);

            return(null);
        }
예제 #24
0
            private void ProcessSoapRequest(SoapEnvelope envelope)
            {
                XmlNode authNode = envelope.Header.SelectSingleNode("Authentication");

                if (authNode == null)
                {
                    throw new Exception("Couldn't find authentication token specified");
                }

                XmlNode userNode     = authNode.SelectSingleNode("Username");
                XmlNode passwordNode = authNode.SelectSingleNode("Password");

                if (userNode == null || passwordNode == null)
                {
                    throw new Exception("Authentication token is invalid or broken");
                }

                UserInfo user = UserController.GetUserByUsernamePassword(
                    userNode.InnerText,
                    passwordNode.InnerText,
                    System.Web.HttpContext.Current.Request.UserHostAddress
                    );

                if (user == null)
                {
                    throw new Exception("Authentication token is invalid or broken");
                }

                SecurityContext.SetThreadPrincipal(user);
            }
        protected void RemoveSecurity(SoapEnvelope soap)
        {
            var security = GetSecurity(soap);
            var header   = GetEnvelopeHeader(soap, nsmanager);

            header.RemoveChild(security);
        }
예제 #26
0
        public override SoapFilterResult ProcessMessage(SoapEnvelope envelope)
        {
            var        certificate = Signering.validateSignature(envelope.DocumentElement, "MessageSignature", "", NamespaceAlias.wsse, true);
            HashValues hv          = Signering.GetHashValues(envelope);

            if (hv.IsSingleSignOn)
            {
                if (certificate.GetCertHashString() == hv.ClientVOCESHash)
                {
                    return(SoapFilterResult.Continue);
                }
            }
            else
            {
                if (CertificateUtil.Validate(certificate))
                {
                    if (cf(certificate))
                    {
                        return(SoapFilterResult.Continue);
                    }
                }
                throw new Exception("certifikat ikke accepteret");
            }
            return(SoapFilterResult.Terminate);
        }
예제 #27
0
        /// <summary>
        /// Processes the SOAP Messages and compresses them if necessary
        /// </summary>
        /// <param name="envelope">The <see cref="SoapEnvelope"/> to process.</param>
        public override void ProcessMessage(SoapEnvelope envelope)
        {
            if (!enabled)
            {
                return;
            }
            //add an attribute to specify that the filter has been applied on this envelope.
            XmlElement soapHeader = envelope.CreateHeader();

            if (envelope.Body.InnerText.Length < minFilterSize)
            {
                return;
            }
            else
            {
                soapHeader.AppendChild(CreateCustomHeader(soapHeader, "1"));
            }
            //compress the body element.
            MemoryStream result = new MemoryStream(WSCFCompression.Compress(Encoding.UTF8.GetBytes(envelope.Body.InnerXml)));

            //Attach zipped result to the envelope.
            Microsoft.Web.Services2.Attachments.Attachment attch = new Microsoft.Web.Services2.Attachments.Attachment("APPLICATION/OCTET-STREAM", result);
            envelope.Context.Attachments.Add(attch);

            //remove old body.
            XmlElement newBody = envelope.CreateBody();

            newBody.RemoveAll();
            envelope.SetBodyObject(newBody);
            GC.Collect();
        }
예제 #28
0
    public override SoapFilterResult ProcessMessage(SoapEnvelope envelope)
    {
        // Remove all WS-Addressing and WS-Security header info
        envelope.Header.RemoveAll();

        return(SoapFilterResult.Continue);
    }
예제 #29
0
        public OperationalData GetOperationalData(XRoadExchangeParameters xRoadExchangeParameters,
                                                  SecurityServerIdentifier securityServerIdentifier,
                                                  SearchCriteria searchCriteria)
        {
            byte[] attachmentBytes = { };

            var client = SoapClient.Prepare()
                         .WithHandler(new DelegatingSoapHandler
            {
                OnHttpResponseAsyncAction = async(soapClient, httpContext, cancellationToken) =>
                {
                    if (httpContext.Response.Content.IsMimeMultipartContent())
                    {
                        var streamProvider =
                            await httpContext.Response.Content.ReadAsMultipartAsync(cancellationToken);
                        var contentCursor = streamProvider.Contents.GetEnumerator();

                        contentCursor.MoveNext();
                        var soapResponse = contentCursor.Current;

                        contentCursor.MoveNext();
                        var attachment = contentCursor.Current;

                        contentCursor.Dispose();

                        attachmentBytes = await attachment.ReadAsByteArrayAsync();
                        httpContext.Response.Content = soapResponse;
                    }
                }
            });

            var body = SoapEnvelope.Prepare().Body(new GetSecurityServerOperationalData
            {
                SearchCriteria = searchCriteria
            }).WithHeaders(new List <SoapHeader>
            {
                IdHeader.Random,
                UserIdHeader,
                ProtocolVersionHeader.Version40,
                (XRoadClient)xRoadExchangeParameters.ClientSubSystem,
                new XRoadService
                {
                    Instance    = securityServerIdentifier.Instance,
                    MemberClass = securityServerIdentifier.MemberClass,
                    MemberCode  = securityServerIdentifier.MemberCode,
                    ServiceCode = "getSecurityServerOperationalData"
                },
                (XRoadSecurityServer)securityServerIdentifier
            });

            var result = client.Send(xRoadExchangeParameters.SecurityServerUri.ToString(), string.Empty, body);

            result.ThrowIfFaulted();

            var operationalData = result.Body <OperationalData>();

            operationalData.Attachment = attachmentBytes;
            return(operationalData);
        }
예제 #30
0
        public async Task <byte[]> GetWsdlAsync(Uri securityServerUri, SubSystemIdentifier subSystemId,
                                                ServiceIdentifier targetService)
        {
            byte[] wsdlFileBytes = { };

            var client = SoapClient.Prepare()
                         .WithHandler(new DelegatingSoapHandler
            {
                OnHttpResponseAsyncAction = async(soapClient, httpContext, cancellationToken) =>
                {
                    if (httpContext.Response.Content.IsMimeMultipartContent())
                    {
                        var streamProvider =
                            await httpContext.Response.Content.ReadAsMultipartAsync(cancellationToken);
                        var contentCursor = streamProvider.Contents.GetEnumerator();

                        contentCursor.MoveNext();
                        var soapResponse = contentCursor.Current;

                        contentCursor.MoveNext();
                        var wsdlFile = contentCursor.Current;

                        contentCursor.Dispose();

                        wsdlFileBytes = await wsdlFile.ReadAsByteArrayAsync();
                        httpContext.Response.Content = soapResponse;
                    }
                }
            });

            var body = SoapEnvelope.Prepare().Body(new GetWsdlRequest
            {
                ServiceCode    = targetService.ServiceCode,
                ServiceVersion = targetService.ServiceVersion
            }).WithHeaders(new List <SoapHeader>
            {
                IdHeader.Random,
                UserIdHeader,
                ProtocolVersionHeader.Version40,
                (XRoadClient)subSystemId,
                new XRoadService
                {
                    Instance       = targetService.Instance,
                    MemberClass    = targetService.MemberClass,
                    MemberCode     = targetService.MemberCode,
                    SubSystemCode  = targetService.SubSystemCode,
                    ServiceCode    = "getWsdl",
                    ServiceVersion = "v1"
                }
            });

            var result = await client.SendAsync(securityServerUri.ToString(), string.Empty, body);

            client.Dispose();

            result.ThrowIfFaulted();

            return(wsdlFileBytes);
        }
예제 #31
0
        /// <summary>
        /// Send multicast message
        /// </summary>
        /// <param name="message">The multicast message</param>
        public void SendMulticast(SoapEnvelope message)
        {
            if (null == message)
            {
                throw new ArgumentNullException("message", "The input parameter \"message\" is null.");
            }

            this.transport.SendBytes(Encoding.UTF8.GetBytes(SoapEnvelope.Serialize(message)), ProtocolStrings.MulticastAddressIPv4, ProtocolStrings.MulticastPort);
        }
예제 #32
0
        protected override void Receive( SoapEnvelope message )
        {
            if ( message.Fault != null )
                Console.WriteLine( "A Fault occured: {0}", message.Fault.ToString( ) );
            else
                Console.WriteLine( "Web Service called successfully" );

            Program.responseReceivedEventValue.Set( );
        }
        /// <summary>
        ///  Secures the SOAP message before its sent to the server
        /// </summary>
        /// <param name="envelope">Soap envelope</param>
        /// <param name="security">Security header element</param>
        public override void SecureMessage(SoapEnvelope envelope, Security security)
        {
            //create KeyInfo XML element
            messageSignature.KeyInfo = new KeyInfo();
            messageSignature.KeyInfo.LoadXml(CreateKeyInfoSignatureElement());

            security.Tokens.Add(issuedToken);
            security.Elements.Add(messageSignature);
        }
        /// <summary>
        ///  Secures the SOAP message before its sent to the server
        /// </summary>
        /// <param name="envelope">Soap envelope</param>
        /// <param name="security">Security header element</param>
        public override void SecureMessage(SoapEnvelope envelope, Security security)
        {
            //create KeyInfo XML element
            messageSignature.KeyInfo = new KeyInfo();
            messageSignature.KeyInfo.LoadXml(CreateKeyInfoSignatureElement());

            security.Tokens.Add(issuedToken);
            security.Elements.Add(messageSignature);
        }
        /// <summary>
        ///     Initializes a new instance of <see cref="SoapEnvelopeSerializationException" />
        /// </summary>
        /// <param name="envelope">The envelope that failed to serialize</param>
        /// <param name="message">The message to be used</param>
        /// <exception cref="ArgumentNullException" />
        public SoapEnvelopeSerializationException(SoapEnvelope envelope, string message) : base(message)
        {
            if (envelope == null)
            {
                throw new ArgumentNullException(nameof(envelope));
            }

            Envelope = envelope;
        }
예제 #36
0
            public override void SecureMessage(SoapEnvelope envelope, WSE.Security security)
            {
                // get server password from database
                string password = parentAssertion.Password;

                if (password == null)
                {
                    return;
                }

                // hash password
                password = CryptoUtils.SHA1(password);

                // create username token
                UsernameToken userToken = new UsernameToken(parentAssertion.ServerId.ToString(), password,
                                                            PasswordOption.SendNone);

                if (parentAssertion.signRequest || parentAssertion.encryptRequest)
                {
                    // Add the token to the SOAP header.
                    security.Tokens.Add(userToken);
                }

                if (parentAssertion.signRequest)
                {
                    // Sign the SOAP message by using the UsernameToken.
                    MessageSignature sig = new MessageSignature(userToken);
                    security.Elements.Add(sig);
                }

                if (parentAssertion.encryptRequest)
                {
                    // we don't return any custom SOAP headers
                    // so, just encrypt a message Body
                    EncryptedData data = new EncryptedData(userToken);

                    // encrypt custom headers
                    for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)
                    {
                        XmlElement child = envelope.Header.ChildNodes[index] as XmlElement;

                        // find all SecureSoapHeader headers marked with a special attribute
                        if (child != null && child.NamespaceURI == "http://com/SolidCP/server/")
                        {
                            // create ID attribute for referencing purposes
                            string id = Guid.NewGuid().ToString();
                            child.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", id);

                            // Create an encryption reference for the custom SOAP header.
                            data.AddReference(new EncryptionReference("#" + id));
                        }
                    }

                    security.Elements.Add(data);
                }
            }
예제 #37
0
 protected override void Receive(SoapEnvelope message)
 {
     try
     {
         doReceive(message);
     }
     catch (Exception e)
     {
         log.Error(e);
     }
 }
        public override SoapFilterResult ProcessMessage(SoapEnvelope envelope)
        {
            //Se crea una instancia de la componente “Intergrup.Core4.Soap.dll”
            WSSecuritySignature<SoapEnvelope, X509Certificate2> signed = new
            WSSecuritySignature<SoapEnvelope, X509Certificate2>();
            X509Certificate2 certificate = new CertManager(issuerCertificateName).Certificate;

            //Generar la firma digital
            signed.Signature(envelope, certificate);
            return SoapFilterResult.Continue;
        }
예제 #39
0
        protected void doReceive(SoapEnvelope message)
        {
            log.Info( "Request -- " + message.Envelope.InnerXml );

            SoapSender sender = new SoapSender( message.Context.Addressing.ReplyTo.Address.Value );
            SoapEnvelope responseMessage = new SoapEnvelope( );

            responseMessage.Context.Addressing.Action = new Action( "http://weblogs.shockbyte.com.ar/rodolfof/wse/samples/2006/05/SampleServiceRequest#Response" );

            log.Info("Response -- " + responseMessage.Envelope.InnerXml);
            sender.Send( responseMessage );
        }
예제 #40
0
		private void AddSubscriber(string ID, Uri replytoAddress, string Name)
		{
			SoapSender ssend = new SoapSender(replytoAddress);
			SoapEnvelope response = new SoapEnvelope();
			response.CreateBody();
			response.Body.InnerXml = String.Format("<x:AddSubscriber xmlns:x='urn:ArticlePublisherApp:Publisher' ><notify>Name: {0} ID: {1}</notify></x:AddSubscriber>", Name, ID);
			Action act = new Action("response");
			response.Context.Addressing.Action = act;
			ssend.Send(response);
			_subscribers.Add ( ID, new Subscriber(Name,replytoAddress, ID)  );
			OnNewSubscriberEvent(Name, ID, replytoAddress);

		}
예제 #41
0
        public void Run(string[] args)
        {
            SoapEnvelope message = new SoapEnvelope( );

            Uri viaUri = null;
            Uri toUri = null;
            Uri replyUri = null;
            if (args.Length >= 1)
            {
                switch (args[0])
                {
                    case "UDP":
                        viaUri = new Uri("soap.udp://127.0.0.1:6000");
                        toUri = new Uri("soap.udp://weblogs.shockbyte.com.ar/rodolfof/wse/samples/2006/05/SampleReceiver");
                        replyUri = new Uri("soap.udp://127.0.0.1:6001");
                        break;
                    case "SMTP":
                        viaUri = new Uri("soap.smtp://[email protected]");
                        toUri = new Uri("soap.smtp://weblogs.shockbyte.com.ar/rodolfof/wse/samples/2006/05/SampleReceiver");
                        replyUri = new Uri("soap.smtp://[email protected]");
                        break;
                    case "SQL":
                        viaUri = new Uri("soap.sql://localhost/sqlexpress");
                        toUri = new Uri("soap.sql://weblogs.shockbyte.com.ar/rodolfof/wse/samples/2006/05/SampleReceiver");
                        replyUri = new Uri("soap.sql://localhost/Client");
                        break;
                    default:
                        Help();
                        return;
                        break;
                }
            }
            else
            {
                Help();
                return;
            }

            message.Context.Addressing.Action = new Action( "http://weblogs.shockbyte.com.ar/rodolfof/wse/samples/2006/05/SampleServiceRequest" );
            message.Context.Addressing.ReplyTo = new ReplyTo( replyUri );

            SoapSender sender = new SoapSender( new EndpointReference( toUri, viaUri ) );

            SoapReceivers.Add( replyUri, typeof( ReplyReceiver ) );

            sender.Send( message );

            Console.WriteLine( "Calling {0}", sender.Destination.Address.Value );
        }
예제 #42
0
파일: Form1.cs 프로젝트: junkuvo/.net
        public void CreateEnv(String text)
        {
            try
            {
                this.EnvIn = new SoapEnvelope();
                this.EnvIn.DocumentElement.OwnerDocument.PreserveWhitespace = false;
                //this.EnvIn.LoadXml(this.RichIn.Text().Replace("<wsa:Action></wsa:Action>", ""))
                this.EnvIn.LoadXml(text);
            }
            catch (Exception ex)
            {
                StsBar.Text = ex.Message;
            }

        }
        public override void ProcessMessage(SoapEnvelope envelope)
        {
            var orgElm = envelope.CreateElement("OrganizationToken", _ns);

            orgElm.AppendChild(envelope.CreateElement("organizationName", _ns))
                .AppendChild(envelope.CreateTextNode(this.OrganizationName));

            if (!String.IsNullOrEmpty(SubOrganizationID))
            {
                var subElm = orgElm.AppendChild(envelope.CreateElement("subOrganizationId", _ns));

                subElm.AppendChild(envelope.CreateElement("id", _ns))
                    .AppendChild(envelope.CreateTextNode(this.SubOrganizationID));
            }

            AppendToWsseSecurity(envelope, orgElm);
        }
        private static void AppendToWsseSecurity(SoapEnvelope envelope, XmlElement elm)
        {
            IEnumerator it = envelope.Header.GetEnumerator();
            while (it.MoveNext())
            {
                XmlElement el = (XmlElement)it.Current;

                if (el.Name.Equals("wsse:Security"))
                {
                    el.AppendChild(elm);

                    // Remove Timestamp; CXF doesn't like it...
                    XmlNodeList timestamp = el.GetElementsByTagName("wsu:Timestamp");
                    el.RemoveChild(timestamp.Item(0));
                    break;
                }
            }
        }
        /// <summary>
        ///  SecureMessage 
        /// </summary>
        /// <param name="envelope">SoapEnvelope</param>
        /// <param name="security">Security</param>
        public override void SecureMessage(SoapEnvelope envelope, Security security)
        {
            if (issuedToken == null)
            {
                security.Tokens.Add(userToken);
                security.Tokens.Add(signatureToken);
                security.Elements.Add(sig);
            }
            else
            {
                //create KeyInfo XML element
                sig.KeyInfo = new KeyInfo();
                sig.KeyInfo.LoadXml(CreateKeyInfoSignatureElement());

                security.Tokens.Add(issuedToken);
                security.Elements.Add(sig);
            }
        }
예제 #46
0
        private static void CreateNode(ref SoapEnvelope envelope, string name, string password)
        {

            const string Ns = "http://zbw911.cnblogs.com/";
            /*
   * 
   * <UserName xmlns="http://zbw911.cnblogs.com/">2</UserName>
  <Password xmlns="http://zbw911.cnblogs.com/">bbbbb</Password>
   * */
            var nodeName = envelope.CreateNode("element", "UserName", Ns);
            nodeName.InnerText = name;
            nodeName.Prefix = envelope.Prefix;
            envelope.Header.AppendChild(nodeName);

            var nodePass = envelope.CreateNode("element", "Password", Ns);
            nodePass.InnerText = password;
            nodePass.Prefix = envelope.Prefix;
            envelope.Header.AppendChild(nodePass);
        }
예제 #47
0
            public override void SecureMessage(SoapEnvelope envelope, Security security)
            {
                UsernameToken userToken = new UsernameToken(
                    parentAssertion.username,
                    parentAssertion.password,
                    PasswordOption.SendNone); // we don't send password over network
                                              // but we just use username/password to sign/encrypt message

                // Add the token to the SOAP header.
                security.Tokens.Add(userToken);

                // Sign the SOAP message by using the UsernameToken.
                MessageSignature sig = new MessageSignature(userToken);
                security.Elements.Add(sig);

                // encrypt BODY
                EncryptedData data = new EncryptedData(userToken);

                // encrypt custom headers
                for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)
                {
                    XmlElement child = envelope.Header.ChildNodes[index] as XmlElement;

                    // find all SecureSoapHeader headers marked with a special attribute
                    if (child != null && child.NamespaceURI == "http://company.com/samples/wse/")
                    {
                        // create ID attribute for referencing purposes
                        string id = Guid.NewGuid().ToString();
                        child.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", id);

                        // Create an encryption reference for the custom SOAP header.
                        data.AddReference(new EncryptionReference("#" + id));
                    }
                }

                // add ancrypted data to the security context
                security.Elements.Add(data);
            }
예제 #48
0
            private void ProcessSoapRequest(SoapEnvelope envelope)
            {
                XmlNode authNode = envelope.Header.SelectSingleNode("Authentication");

                if (authNode == null)
                    throw new Exception("Couldn't find authentication token specified");

                XmlNode userNode = authNode.SelectSingleNode("Username");
                XmlNode passwordNode = authNode.SelectSingleNode("Password");

                if (userNode == null || passwordNode == null)
                    throw new Exception("Authentication token is invalid or broken");

                UserInfo user = UserController.GetUserByUsernamePassword(
                    userNode.InnerText,
                    passwordNode.InnerText,
                    System.Web.HttpContext.Current.Request.UserHostAddress
                );

                if (user == null)
                    throw new Exception("Authentication token is invalid or broken");

                SecurityContext.SetThreadPrincipal(user);
            }
예제 #49
0
            public override void ValidateMessageSecurity(SoapEnvelope envelope, Security security)
            {
                if (!ServerConfiguration.Security.SecurityEnabled)
                    return;

                // by default we consider that SOAP messages is not signed
                bool IsSigned = false;

                // if security element is null
                // the call is made not from WSE-enabled client
                if (security != null)
                {
                    foreach (ISecurityElement element in security.Elements)
                    {
                        if (element is MessageSignature)
                        {
                            // The given context contains a Signature element.
                            MessageSignature sign = element as MessageSignature;

                            if (CheckSignature(envelope, security, sign))
                            {
                                // The SOAP message is signed.
                                if (sign.SigningToken is UsernameToken)
                                {
                                    UsernameToken token = sign.SigningToken as UsernameToken;

                                    // The SOAP message is signed 
                                    // with a UsernameToken.
                                    IsSigned = true;
                                }
                            }
                        }
                    }
                }

                // throw an exception if the message did not pass all the tests
                if (!IsSigned)
                    throw new SecurityFault("Message did not meet security requirements.");
            }
예제 #50
0
            private bool CheckSignature(SoapEnvelope envelope, Security security, MessageSignature signature)
            {
                //
                // Now verify which parts of the message were actually signed.
                //
                SignatureOptions actualOptions = signature.SignatureOptions;
                SignatureOptions expectedOptions = SignatureOptions.IncludeSoapBody;

                if (security != null && security.Timestamp != null)
                    expectedOptions |= SignatureOptions.IncludeTimestamp;

                //
                // The <Action> and <To> are required addressing elements.
                //
                expectedOptions |= SignatureOptions.IncludeAction;
                expectedOptions |= SignatureOptions.IncludeTo;

                if (envelope.Context.Addressing.FaultTo != null && envelope.Context.Addressing.FaultTo.TargetElement != null)
                    expectedOptions |= SignatureOptions.IncludeFaultTo;

                if (envelope.Context.Addressing.From != null && envelope.Context.Addressing.From.TargetElement != null)
                    expectedOptions |= SignatureOptions.IncludeFrom;

                if (envelope.Context.Addressing.MessageID != null && envelope.Context.Addressing.MessageID.TargetElement != null)
                    expectedOptions |= SignatureOptions.IncludeMessageId;

                if (envelope.Context.Addressing.RelatesTo != null && envelope.Context.Addressing.RelatesTo.TargetElement != null)
                    expectedOptions |= SignatureOptions.IncludeRelatesTo;

                if (envelope.Context.Addressing.ReplyTo != null && envelope.Context.Addressing.ReplyTo.TargetElement != null)
                    expectedOptions |= SignatureOptions.IncludeReplyTo;
                //
                // Check if the all the expected options are the present.
                //
                return ((expectedOptions & actualOptions) == expectedOptions);
            }
 /// <summary>
 ///  SecureMessage 
 /// </summary>
 /// <param name="envelope">SoapEnvelope</param>
 /// <param name="security">Security</param>
 public override void SecureMessage(SoapEnvelope envelope, Security security)
 {
     security.Tokens.Add(userToken);
 }
예제 #52
0
		private void RemoveSubscriber(string ID, Uri replytoAddress)
		{
			if (_subscribers.Contains(ID) )
			{
				_subscribers.Remove(ID);
				SoapSender ssend = new SoapSender(replytoAddress);
				SoapEnvelope response = new SoapEnvelope();
				response.CreateBody();
				response.Body.InnerXml = String.Format("<x:RemoveSubscriber xmlns:x='urn:ArticlePublisherApp:Publisher' ><notify>ID: {0} Removed</notify></x:RemoveSubscriber>", ID);
				Action act = new Action("response");
				response.Context.Addressing.Action = act;
				ssend.Send(response);
				OnRemoveSubscriberEvent(ID);
			}
		}
예제 #53
0
		protected override void Receive( SoapEnvelope envelope )
		{
			
			//Determine Action if no SoapAction throw exception
			Action act = envelope.Context.Addressing.Action;
			if (act == null)
				throw new SoapHeaderException("Soap Action must be set", new XmlQualifiedName());
			
			string subscriberName = String.Empty ;
			string subscriberID = String.Empty;
			switch (act.ToString().ToLower())
			{
				case "subscribe":
					//add new subscriber
					 subscriberName = envelope.SelectSingleNode ( "//name").InnerText ;
					subscriberID = System.Guid.NewGuid().ToString();
					AddSubscriber(subscriberID, envelope.Context.Addressing.From.Address.Value, subscriberName);
					break;
				case "unsubscribe":
					subscriberID = envelope.SelectSingleNode("//name") .InnerText ;
					RemoveSubscriber(subscriberID, envelope.Context.Addressing.From.Address.Value);
					break;
				default:
					break;
			}
			
		}
        /// <summary>
        /// Handles the SoapEnvelopes.
        /// </summary>
        /// <param name="envelope"> The SoapEnvelope.</param>
        protected override void Receive(SoapEnvelope envelope)
        {
            XmlDocument document;
            AccountMessage message;
            AccountMessageSerializer serializer = new AccountMessageSerializer();

            switch ( envelope.Context.Addressing.Action.Value )
            {
                case "urn:ecyware:greenblue:licenseServices:createAccount":
                    document = DecryptBodyObject(envelope);

                    // create object (desearilize)
                    message = (AccountMessage)serializer.Create(document.DocumentElement.OuterXml);

                    // Replace body and send to base class.
                    envelope.SetBodyObject(message);
                    base.Receive(envelope);
                    break;
                case "urn:ecyware:greenblue:licenseServices:updateAccount":
                    document = DecryptBodyObject(envelope);

                    // create object (desearilize)
                    message = (AccountMessage)serializer.Create(document.DocumentElement.OuterXml);

                    // Replace body and send to base class.
                    envelope.SetBodyObject(message);
                    base.Receive(envelope);
                    break;
                default:
                    base.Receive(envelope);
                    break;
            }
        }
예제 #55
0
		private void fsw_Created(object sender, System.IO.FileSystemEventArgs e)
		{
			Uri uriThis =  new Uri (Literals.LocalhostTCP + "9090/Publisher" );
			// Send each subscriber a message
			foreach(object o in _subscribers)
			{
				DictionaryEntry de = (DictionaryEntry)o;
				
				Subscriber s = (Subscriber)_subscribers[de.Key];
				SoapEnvelope responseMsg = new SoapEnvelope ();

				FileStream fs = new FileStream(e.FullPath ,FileMode.Open, FileAccess.Read , FileShare.ReadWrite );
				StreamReader sr = new StreamReader(fs);
				string strContents = sr.ReadToEnd() ;
				sr.Close();
				fs.Close();

				// Set the From Addressing value
				responseMsg.Context.Addressing.From = new From ( uriThis );
				responseMsg.Context.Addressing.Action  = new Action( "notify");
				responseMsg.CreateBody();
				responseMsg.Body.InnerXml = "<x:ArticlePublished xmlns:x='urn:ArticlePublisherApp:Publisher'><notify><file>" + e.Name +"</file><contents>" + strContents + "</contents></notify></x:ArticlePublished>";

				// Send a Response Message
				SoapSender msgSender = new SoapSender (s.ReplyTo );
				msgSender.Send ( responseMsg );
			}
		}
            public override void ValidateMessageSecurity(SoapEnvelope envelope, WSE.Security security)
            {
                // by default we consider that SOAP messages is not signed
                bool IsSigned = false;

                // if security element is null
                // the call is made not from WSE-enabled client
                if (security != null)
                {
                    foreach (ISecurityElement element in security.Elements)
                    {
                        if (element is MessageSignature)
                        {
                            // The given context contains a Signature element.
                            MessageSignature sign = element as MessageSignature;

                            if (CheckSignature(envelope, security, sign))
                            {
                                // The SOAP message is signed.
                                if (sign.SigningToken is UsernameToken)
                                {
                                    UsernameToken token = sign.SigningToken as UsernameToken;

                                    // The SOAP message is signed 
                                    // with a UsernameToken.
                                    IsSigned = true;
                                }
                            }
                        }
                    }
                }

                // throw an exception if the message did not pass all the tests
                if (!IsSigned)
                    throw new SecurityFault("SOAP response should be signed.");

                // check encryption
                bool IsEncrypted = false;
                foreach (ISecurityElement element in security.Elements)
                {
                    if (element is EncryptedData)
                    {
                        EncryptedData encryptedData = element as EncryptedData;
                        System.Xml.XmlElement targetElement = encryptedData.TargetElement;

                        if (SoapHelper.IsBodyElement(targetElement))
                        {
                            // The given SOAP message has the Body element Encrypted.
                            IsEncrypted = true;
                        }
                    }
                }

                if (!IsEncrypted)
                    throw new SecurityFault("SOAP response should be encrypted.");

            }
예제 #57
0
 public override void ValidateMessageSecurity(SoapEnvelope envelope, WSE.Security security)
 {
     if (security != null)
         ProcessWSERequest(envelope, security);
     //else if (envelope.Header != null)
     //    ProcessSoapRequest(envelope);
     else// if (HttpContext.Current.Request.Headers["Authorization"] != null)
         ProcessBasicAuthRequest();
 }
예제 #58
0
        /// <summary>
        /// Send does not catch any exceptions - the caller must handle exceptions.
        /// </summary>
        internal void SendTo( SoapEnvelope envelope, EndpointReference destination )
        {
            if ( _localEP != null )
                SoapUdpTransport.Debug( "SoapUdpSocket[" + _localEP.ToString( ) + "] Send" );
            else
                SoapUdpTransport.Debug( "SoapUdpSocket[Unbound] Send" );
            //
            // IPv6: We need to process each of the addresses return from
            //       DNS when trying to connect. Use of AddressList[0] is
            //       bad form.
            //
            string host = destination.TransportAddress.Host;
            int port = ( destination.TransportAddress.Port == -1 ) ? _options.DefaultPort : destination.TransportAddress.Port;

            IPAddress remoteAddress = null;
            IPAddress[ ] remoteAddresses = null;

            try
            {
                if ( string.Compare( host, "localhost", true, CultureInfo.CurrentCulture ) == 0 && Socket.SupportsIPv4 )
                    remoteAddress = IPAddress.Loopback;
                else if ( string.Compare( host, "localhost6", true, CultureInfo.CurrentCulture ) == 0 && Socket.OSSupportsIPv6 )
                    remoteAddress = IPAddress.IPv6Loopback;
                else
                    remoteAddress = IPAddress.Parse( host );

                remoteAddresses = new IPAddress[ 1 ] { remoteAddress };
            }
            catch
            {
                //
                // Intentionally empty - hostname is not a plain IP address.
                // Use DNS to resolve the name.
                //
                remoteAddresses = Dns.GetHostEntry( host ).AddressList;
            }
            //
            // Now form the packet to send.
            //
            MemoryStream stream = new MemoryStream( );

            _formatter.Serialize( envelope, stream );

            System.Diagnostics.Debug.Assert( stream.Length <= SoapUdpDatagram.MaxDataSize );

            if ( stream.Length > SoapUdpDatagram.MaxDataSize )
                throw new ArgumentException( "Message is too large" );

            if ( _localEP != null )
                SoapUdpTransport.Debug( "SoapUdpSocket[" + _localEP.ToString( ) + "] Packet size is " + stream.Length.ToString( ) );
            else
                SoapUdpTransport.Debug( "SoapUdpSocket[Unbound] Packet size is " + stream.Length.ToString( ) );

            for ( int i = 0; i < remoteAddresses.Length; i++ )
            {
                //
                // Set the address family appropriately, create the socket and
                // try to connect.
                //
                remoteAddress = remoteAddresses[ i ];

                if ( _socket == null )
                {
                    //
                    // Unbound case: create a temporary socket to send the data on.
                    //
                    Socket socket = new Socket( remoteAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp );
                    socket.SendTo( stream.GetBuffer( ), 0, ( int )stream.Length, SocketFlags.None, new IPEndPoint( remoteAddress, port ) );
                    socket.Close( );

                    break;
                }
                else if ( remoteAddress.AddressFamily == _socket.AddressFamily )
                {
                    //
                    // Bound case: use the existing socket to send the data on.
                    //
                    _socket.SendTo( stream.GetBuffer( ), 0, ( int )stream.Length, SocketFlags.None, new IPEndPoint( remoteAddress, port ) );

                    break;
                }
            }
        }
        /// <summary>
        /// Decrypts the body object.
        /// </summary>
        /// <param name="envelope"> The SoapEnvelope.</param>
        /// <returns> The XmlDocument with the decrypted Soap Body object.</returns>
        private XmlDocument DecryptBodyObject(SoapEnvelope envelope)
        {
            // add to new document
            XmlNode node = envelope.SelectSingleNode("//EncryptedData");
            XmlDocument document = new XmlDocument();
            document.AppendChild(document.ImportNode(node,true));

            // decrypt
            EcyXmlEncryption.EncryptXml decrypt = new EcyXmlEncryption.EncryptXml(document);
            decrypt.AddKeyNameMapping("accountMessage", ReadTransportKey());
            decrypt.DecryptDocument();

            return document;
        }
예제 #60
0
 public override SoapFilterResult ProcessMessage(SoapEnvelope envelope)
 {
     CreateNode(ref envelope, AppContext.UserName, AppContext.Password);
     //CreateNode(ref envelope, "2", "bbbbb");
     return SoapFilterResult.Continue;
 }