Building a secure XML Web Service series (ii)

Source: Internet
Author: User
Tags format config configuration settings flush soap tostring web services xmlns
web|xml| Security

Previous article Address: Building Secure XML Web service Series A probe into the use of SOAP headers

To analyze the security of XML Web service, the first problem to solve is that we can understand and clear the format and content of the SOAP message, if we can not get soapmessage, analyze how to build a secure XML Web service, even if analyzed, They may be vague and inconclusive. The following is an analysis of how to obtain SoapMessage.

First, introduce a class-SOAPEXTENSION,MSDN note to this class: ASP.net allows the SOAP-related infrastructure to be generated through extensibility mechanisms. The asp.net SOAP extension structure is centered on an extension that can examine or modify messages during a specific phase while processing messages on the client or server. The asp.net SOAP extension derives from the SoapExtension class. The GetInitializer and Initialize methods provide additional mechanisms for initializing SOAP extensions to enhance performance. ProcessMessage is the core of most SOAP extensions because the method is invoked at every stage defined in SoapMessageStage, allowing the SOAP extension to perform the desired behavior of that particular SOAP extension. For SOAP extensions that need to modify SOAP requests or SOAP responses, ChainStream provides an opportunity to receive suggested data to be sent over the network. Read this text carefully, if you have previously developed a Windows program, the first thing you should think of is: the original Web service processing mechanism and Windows window Program message mechanism unexpectedly has a piece of work. Here's how to use this class to intercept XML Web service requests and corresponding SOAP messages to see the truth of XML Web service.

First, let's take a look at this class, which is done by extending the XML Web service to the text file in the form of a log of each request and response SOAP message. There are also two ways of logging:

1. Generate a log file for each WebMethod.

2. Generate a log file for each webservice

Since a webservice may contain one or more WebMethod, if both methods are supported, then the second log two sides should include the contents of the first log, and in some cases it is not necessary to log each WebMethod. In this case, the first recording method is used to enhance the flexibility of the system.

Here's the expanded soapextension.

<webServices>
<soapExtensionTypes>
<add type= "Jillzhang.traceextension,jillzhang" priority= "1" group= "High"/>
</soapExtensionTypes>
</webServices>

Can record the SoapMessage soapextension

Namespace Jillzhang
{
public class Traceextension:soapextension
{
Static readonly string logroot = system.configuration.configurationmanager.appsettings["Logroot"];
Stream Oldstream;
Stream Newstream;
string filename;
<summary>
The request stream and response stream are saved to the memory stream and have been invoked
</summary>
<param name= "stream" > Memory buffers that contain SOAP requests or responses </param>
<returns> it represents a new memory buffer that this SOAP extension can modify. </returns>
public override stream ChainStream (Stream stream)
{
Oldstream = stream;
Newstream = new MemoryStream ();
return newstream;
}
<summary>
The first time the XML Web service runs, a one-time pass through the TraceExtensionAttribute
File name for saving log information initialization
</summary>
<param name= "MethodInfo" > Specific function Prototypes for XML WEB services methods that apply SOAP extensions </param>
<param name= "attribute" > Application to XML Web services method soapextensionattribute</param>
The &LT;RETURNS&GT;SOAP extension will initialize it for caching </returns>
public override Object GetInitializer (LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
Return ((TraceExtensionAttribute) attribute). Filename;
}
<summary>
Instead of saving SoapMessage file names configured for each method, the entire Network service
SoapMessage are saved to a log file, this file path needs to be in the Web Service
The configuration file in Web.config indicates that, as
<appSettings>
<add key= "Logroot" value= "C:\\servicelog"/>
</appSettings>
</summary>
<param name= "Webservicetype" > Network Service Type </param>
<returns> file path for saving log records </returns>
public override Object GetInitializer (Type webservicetype)
{
return logroot.trimend (' \ \ ') + "\" + webservicetype.fullname + ". Log";
return logroot.trimend (' \ \ ') + "\" + webservicetype.fullname + ". Log";
}
Get the filename and save it
public override void Initialize (object initializer)
{
filename = (string) initializer;
}
<summary>
Writes data to the log when the data is also in SOAP format
</summary>
<param name= "Message" ></param>
public override void ProcessMessage (SoapMessage message)
{
Switch (message. Stage)
{
Case Soapmessagestage.beforeserialize:
Break
Case SoapMessageStage.AfterSerialize:
WriteOutput (message);
Break
Case SoapMessageStage.BeforeDeserialize:
Writeinput (message);
Break
Case Soapmessagestage.afterdeserialize:
Break
Default
throw new Exception ("Invalid Stage");
}
}
<summary>
Write SoapMessage to the log file
</summary>
<param name= "Message" ></param>
public void WriteOutput (SoapMessage message)
{
newstream.position = 0;
Create or append a record file
FileStream fs = new FileStream (filename, filemode.append,
FileAccess.Write);
StreamWriter w = new StreamWriter (FS);
String soapstring = (message is soapservermessage)? "Soap response": "Soap Request";
W.writeline ("-----" + soapstring + "in" + DateTime.Now.ToString ("yyyy mm month DD Day hh when the minute of SS Seconds"));
W.flush ();
Copy (newstream, FS);
W.close ();
newstream.position = 0;
Copy (Newstream, oldstream);
}

public void Writeinput (SoapMessage message)
{
Copy (Oldstream, newstream);
FileStream fs = new FileStream (filename, filemode.append,
FileAccess.Write);
StreamWriter w = new StreamWriter (FS);

String soapstring = (message is soapservermessage)?
"Soap request": "Soap response";
W.writeline ("-----" + soapstring +
"In" + DateTime.Now.ToString ("yyyy mm month DD Day hh when the minute SS Seconds"));
W.flush ();
newstream.position = 0;
Copy (newstream, FS);
W.close ();
newstream.position = 0;
}
<summary>
Copy Stream to stream
</summary>
<param name= "from" ></param>
<param name= "to" ></param>
void Copy (stream from, stream to)
{
TextReader reader = new StreamReader (from);
TextWriter writer = new StreamWriter (to);
Writer. WriteLine (reader. ReadToEnd ());
Writer. Flush ();
}
}
Create a SoapExtension property for use on WebMethod
[AttributeUsage (AttributeTargets.Method)]
public class Traceextensionattribute:soapextensionattribute
{
private string filename = "C:\\log.txt";
private int priority;
<summary>
Extension type
</summary>
public override Type ExtensionType
{
get {return typeof (TraceExtension);}
}
<summary>
Priority level
</summary>
public override int Priority
{
get {return priority;}
set {priority = value;}
}
<summary>
The absolute path of the file used to record the WebMethod SoapMessage
Default is C:\\log.txt;
</summary>
public string Filename
{
Get
{
return filename;
}
Set
{
filename = value;
}
}
}
}

To get down, describe how to use the class:

Additional work to be done to enable traceextension to support the first type of recording is:

You only need to add the following attribute to the WebMethod that you want to record SoapMessage

[TraceExtension (Filename= "D:\\data.xml", priority=0)]

Of course, you can set your own

The WebMethod in the previous section became

Added WebMethod for WebMethod logging
Public Mysoapheader Header = new Mysoapheader ();
[WebMethod]
[SoapHeader ("header")]
[TraceExtension (Filename= "D:\\data.xml", priority=0)]
public string HelloWorld ()
{
if (header = null)
{
Return "You do not set SoapHeader, not normal access to this service!";
}
if (header. UserName!= "Jillzhang" | | Header. PWD!= "123456")
{
Return "The authentication information you provide is incorrect, you cannot access this service properly!";
}
Return to "Hello World";
}

When the WebService is invoked, a Data.xml file is generated in the D disk, which reads:

-----SOAP request on May 25, 2007 09:06 29 seconds
<?xml version= "1.0" encoding= "Utf-8" ><soap:envelope xmlns:soap= "http://schemas.xmlsoap.org/soap/" envelope/"xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xmlns:xsd=" Http://www.w3.org/2001/XMLSchema "><soap:header><mysoapheader xmlns=" Jillzhang 123456 http://tempuri.org/' ><USERNAME>JILLZHANG</USERNAME><PWD&G T;123456</pwd></mysoapheader></soap:header><soap:body>  
 
 
-----SOAP response in May 25, 2007 09:06 29 second
<?xml version= "1.0" encoding= "Utf-8" ><soap:envelope xmlns:soap= "http://" schemas.xmlsoap.org/soap/envelope/"xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:xsd=" Http://www.w3.org/2001/XMLSchema "><soap:body>

<webServices>
<soapExtensionTypes>
<add type= "Jillzhang.traceextension,jillzhang" priority= "1" group= "High"/>
</soapExtensionTypes>
</webServices>

The path that is retained by the configuration settings log file is then:

<appSettings>
<add key= "Logroot" value= "D:"/>
</appSettings>

Find the log file, inside also impressively has soapmessage true colors. Through the above methods, we can clearly analyze the specific format and content of SoapMessage, know this later, to deal with Web Service, you can should also launch, arbitrary, if you want, you can even "rape" a webservice, haha!



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.