Return to HomePage



Perform XML schema validation of Web Service payload (VB.NET)


Applies to

* .NET Framework 2.0
* VB.NET
* Web Services

Summary

The purpose of this code sample is to demonstrate a technique to securely validate the XML payload received during a web service web method call using .NET.


Objectives

* Mitigate data validation induced vulnerabilities through use of XML schema validation which employs strong validation using regular expression patterns on expected data
* Improve application efficiency by first requiring validation of XML payload prior to executing business logic


Scenarios

* Application component needs to access functionality that only exists in a different runtime component
* Application occasionally needs access to privileged functionality but wants to use a low-privileged security context for enhanced overall security

Solution Example


Custom Web method for performing some action on an XML String Blob

		    ' The following private members must be defined for this example
		    Private Shared [validationErrCnt] As Integer = 0
		    Private Shared lastError As String = ""
	

		    [<WebMethod()>] _
		    Public Function [ProcessValue(ByVal] strXML As String) As Boolean
	

		        Dim connectionString As String = "Initial Catalog=snippets;Data Source=cindy\sqlexpress;Integrated Security=SSPI;"
		        Dim cn As [SqlConnection] = New [SqlConnection(connectionString)]
		        Dim retval As Boolean = False
		        Try
		            ' Create an [XmlReaderSettings] object since  we'll need to add our schema to it
		            Dim xrs As [XmlReaderSettings] = New [XmlReaderSettings()]
		            ' Create a schema set which we'll use to validate our XML Document against
		            Dim xset As [XmlSchemaSet] = New [XmlSchemaSet()]
	

		            ' Read in our schema under the web root.
		            Dim xmlschemareader As [XmlReader] = New [XmlTextReader(HttpContext.Current.Request.PhysicalApplicationPath] + "\xsd\Userschema.xsd")
		            ' Attribute the XML schema with our schema set
		            xset.Add(Nothing, xmlschemareader)
	

		            ' Finally attach our XML schema set to the reader settings
		            xrs.Schemas.Add(xset)
	

		            ' We define a Validation Event Handler
		            [AddHandler] [xrs.ValidationEventHandler,] [AddressOf] [ValidationCallBack]
	

		            ' We want to report warnings as well as errors
		            [xrs.ValidationFlags] = [xrs.ValidationFlags] Or [XmlSchemaValidationFlags.ReportValidationWarnings]
	

		            ' Our validation type should be set to schema so we enforce the schema on the document
		            [xrs.ValidationType] = [ValidationType.Schema]
	

		            ' Create our XML reader and associate our reader settings
		            Dim sreader As [StringReader] = New [StringReader(strXML)]
		            Dim xmlread As [XmlReader] = [XmlReader.Create(sreader,] xrs)
	

		            ' Lastly load the document which forces a schema validation to be performed in the process
		            Dim xmldoc As [XmlDocument] = New [XmlDocument()]
		            xmldoc.Load(xmlread)
	

		            ' If our event returns errors (and warnings) throw a new exception with our last error as the message
		            If [validationErrCnt] > 0 Then
		                ' FAILED VALIDATION: If we encountered errors while validating the XML
	

		                Throw New Exception(lastError)
		            Else
		                ' PASSED VALIDATION: Otherwise process our request as normal
	

		                Dim sqlcmd As [SqlCommand] = New SqlCommand("XMLValidationSample", cn)
		                Dim sqlparam As [SqlParameter] = New SqlParameter("@strxml", [SqlDbType.VarChar,] strXML.Length)
		                Dim outparam As [SqlParameter] = New SqlParameter("@retval", [SqlDbType.Int)]
		                outparam.Direction = [ParameterDirection.ReturnValue]
		                sqlparam.Value = strXML
		                [sqlcmd.CommandType] = [CommandType.StoredProcedure]
		                sqlcmd.Parameters.Add(sqlparam)
		                sqlcmd.Parameters.Add(outparam)
	

		                cn.Open()
		                [sqlcmd.ExecuteNonQuery()]
	

		                If [Convert.ToInt16(outparam.Value)] > 0 Then
		                    retval = True
		                End If
		                cn.Close()
		            End If
		        Catch ex As Exception
		            ' Replace following throw with User supplied exception handling code: 
		            '   Log exception and perform graceful error handling
		            Throw New Exception("Error validating XML: " + ex.Message)
		        End Try
		    End Function
	

		 Custom Defined XML Validation Event Handler
	


		    Private Sub [ValidationCallBack(ByVal] sender As Object, [ByVal] args As [ValidationEventArgs)]
	

		        [validationErrCnt] = [validationErrCnt] + 1
		        If [args.Severity.Equals(XmlSeverityType.Warning)] Then
		            lastError = "Warning: " + args.Message
		        [ElseIf] [args.Severity.Equals(XmlSeverityType.Error)] Then
		            lastError = "Error: " + args.Message
		        End If
		    End Sub
	

Sample XML Schema with pattern match validators
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="UserSchema" targetNamespace="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/XMLSchema.xsd" xmlns:mstns="http://tempuri.org/XMLSchema.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
		  	<xs:element name="Users">
		    	<xs:complexType>
		      	<xs:sequence>
		        <xs:element minOccurs="1" maxOccurs="100" name="User">
		          <xs:complexType>
		            <xs:sequence>
		              <xs:element name="username" type="usernamestring" />
		              <xs:element name="password" type="passwordstring" />
		              <xs:element name="name" type="namestring" />
		              <xs:element maxOccurs="2" name="streetaddress" type="addressstring" />
		              <xs:element name="city" type="namestring" />
		              <xs:element name="state" type="statevalue" />
		              <xs:element name="postalcode" type="postalstring" />
		              <xs:element name="phone" type="phonestring" />
		              <xs:element name="ssn" type="ssnstring" />
		              <xs:element name="emailaddress" type="emailstring" />
		              <xs:element minOccurs="0" name="url" type="xs:anyURI" />
		            </xs:sequence>
		          </xs:complexType>
		        </xs:element>
		      </xs:sequence>
		    </xs:complexType>
		  </xs:element>
		  <xs:simpleType name="usernamestring">
		    <xs:restriction base="xs:string">
		      <!-- Allows word characters [A-Za-z0-9_], single quote, dash and period
		           must be at least two characters long and less than 16 -->
		      <xs:minLength value="2" />
		      <xs:maxLength value="16" />
		      <xs:pattern value="^[\w-'\.]{2,16}$" />
		    </xs:restriction>
		  </xs:simpleType>
		  <xs:simpleType name="passwordstring">
		    <xs:restriction base="xs:string">
		      <!-- Allows word characters [A-Za-z0-9_], single quote, dash and period
		           must be at least two characters long and less than 16 -->
		      <xs:minLength value="8" />
		      <xs:maxLength value="16" />
		      <xs:pattern value="^.*(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[`~!@\$%\^\&amp;\*\(\)-_\=\+\[\{\]\}	\\\|;:',&lt;\.&gt;/?]).*$" />
		    </xs:restriction>
		  </xs:simpleType>
		  <xs:simpleType name="namestring">
		    <xs:restriction base="xs:string">
		      <!-- Names must be at least 2 characters, no more than 128 characters, and consist of
		           alphabetic characters, and may contain hyphens, single quotes, periods and spaces -->
		      <xs:minLength value="2" />
		      <xs:maxLength value="128" />
		      <xs:pattern value="^[a-zA-Z-'\.\s]{2,128}$" />
		    </xs:restriction>
		  </xs:simpleType>
		  <xs:simpleType name="addressstring">
		    <xs:restriction base="xs:string">
		      <!-- Since so many different types of address formats we'll do a match against a series 
		           of digits (potentially containing punctuation, followed by a series of characters 
		           representing the street name and then potentially a type of street and unit number -->
		      <xs:pattern value="^\d{1,3}.?\d{0,3}\s[a-zA-Z]{2,30}(\s[a-zA-Z]{2,15})?([#\.0-9a-zA-Z]*)?$" />
		    </xs:restriction>
		  </xs:simpleType>
		  <xs:simpleType name="statevalue">
		    <xs:restriction base="xs:string">
		      <!-- States must be one of our predefined enumeration types and consist of exactly 2 characters -->
		      <xs:length value="2" />
		      <xs:enumeration value="AL" />
		      <xs:enumeration value="AK" />
		      <xs:enumeration value="AR" />
		      <xs:enumeration value="AZ" />
		      <xs:enumeration value="CA" />
		      <xs:enumeration value="CO" />
		      <xs:enumeration value="CT" />
		      <xs:enumeration value="DE" />
		      <xs:enumeration value="DC" />
		      <xs:enumeration value="FL" />
		      <xs:enumeration value="GA" />
		      <xs:enumeration value="HI" />
		      <xs:enumeration value="ID" />
		      <xs:enumeration value="IL" />
		      <xs:enumeration value="IN" />
		      <xs:enumeration value="IA" />
		      <xs:enumeration value="KS" />
		      <xs:enumeration value="KY" />
		      <xs:enumeration value="LA" />
		      <xs:enumeration value="ME" />
		      <xs:enumeration value="MD" />
		      <xs:enumeration value="MA" />
		      <xs:enumeration value="MI" />
		      <xs:enumeration value="MN" />
		      <xs:enumeration value="MS" />
		      <xs:enumeration value="MO" />
		      <xs:enumeration value="MT" />
		      <xs:enumeration value="NE" />
		      <xs:enumeration value="NV" />
		      <xs:enumeration value="NH" />
		      <xs:enumeration value="NJ" />
		      <xs:enumeration value="NM" />
		      <xs:enumeration value="NY" />
		      <xs:enumeration value="NC" />
		      <xs:enumeration value="ND" />
		      <xs:enumeration value="OH" />
		      <xs:enumeration value="OK" />
		      <xs:enumeration value="OR" />
		      <xs:enumeration value="PA" />
		      <xs:enumeration value="RI" />
		      <xs:enumeration value="SC" />
		      <xs:enumeration value="SD" />
		      <xs:enumeration value="TN" />
		      <xs:enumeration value="TX" />
		      <xs:enumeration value="UT" />
		      <xs:enumeration value="VT" />
		      <xs:enumeration value="VA" />
		      <xs:enumeration value="WA" />
		      <xs:enumeration value="WV" />
		      <xs:enumeration value="WI" />
		      <xs:enumeration value="WY" />
		    </xs:restriction>
		  </xs:simpleType>
		  <xs:simpleType name="postalstring">
		    <xs:restriction base="xs:string">
		      <!-- The following US postal code format allows ZIP (5 digit) or ZIP+4 formats
		           as a single string or separated by hyphens -->
		      <xs:pattern value="^\d{5}[-]?(\d{4})?$" />
		      <xs:minLength value="5" />
		      <xs:maxLength value="10" />
		    </xs:restriction>
		  </xs:simpleType>
		  <xs:simpleType name="ssnstring">
		    <xs:restriction base="xs:string">
		      <!-- [SSNs] consist of 9 digits but may contain an optional 2 hyphens -->
		      <xs:minLength value="9" />
		      <xs:maxLength value="11" />
		      <xs:pattern value="^\d{3}[-]?\d{2}[-]?\d{4}$$" />
		    </xs:restriction>
		  </xs:simpleType>
		  <xs:simpleType name="phonestring">
		    <xs:restriction base="xs:string">
		      <!-- The following pattern defines a US formatted telephone number -->
		      <xs:pattern value="^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$" />
		      <xs:minLength value="10" />
		      <xs:maxLength value="32" />
		    </xs:restriction>
		  </xs:simpleType>
		  <xs:simpleType name="emailstring">
		    <xs:restriction base="xs:string">
		      <!-- Allows common email address that can start with a alphanumeric char and contain word, 
		      hyphen and period characters followed by a domain name meeting the same criteria followed 
		      by a alpha suffix between 2 and 9 character long -->
		      <xs:pattern value="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]	{2,9})$" />
		      <xs:minLength value="7" />
		      <xs:maxLength value="256" />
		    </xs:restriction>
		  </xs:simpleType>
	
</xs:schema>

Problem Example

The following example demonstrates the use of unvalidated XML received by a web service method.

		    [<WebMethod>] _ 
		    Public Function [ProcessValueNoValidation(ByVal] strXML As String) As Boolean
		        Try
		            ' Create our XML reader and associate our reader settings
		            Dim sreader As [StringReader] =  New [StringReader(strXML)] 
		            Dim xmlread As [XmlReader] =  [XmlReader.Create(sreader)] 
	

		            ' Lastly load the document which forces a schema validation to be performed in the process
		            Dim xmldoc As [XmlDocument] =  New [XmlDocument()] 
		            xmldoc.Load(xmlread)
	

		            Dim sqlcmd As [SqlCommand] =  New SqlCommand("XMLValidationSample",cn) 
		            Dim sqlparam As [SqlParameter] =  New SqlParameter("@strxml",SqlDbType.VarChar,strXML.Length) 
		            Dim outparam As [SqlParameter] =  New SqlParameter("@retval",SqlDbType.Int) 
	

		            outparam.Direction = [ParameterDirection.ReturnValue]
		            sqlparam.Value = strXML
		            [sqlcmd.CommandType] = [CommandType.StoredProcedure]
		            sqlcmd.Parameters.Add(sqlparam)
		            sqlcmd.Parameters.Add(outparam)
	

		            cn.Open()
		            [sqlcmd.ExecuteNonQuery()]
		            cn.Close()
		        Catch ex As Exception
		            Throw New Exception(ex.Message)
		        End Try
		        Return True
		    End Function
	


* No XML schema validation prior to passing the strXML string to SQL stored procedure
* Depending on stored procedure implementation SQL injection may be possible (particularly in instances where dynamic SQL is constructed from XML element values and passed as arguments to sp_executesql) clear text in a file or database


Other Secure Coding Issues
* Potential information leakage of application internals through throw exceptions


Test Case

The following classes must be included in any project making use of the sample code provided above:

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml
Imports System.Xml.Schema
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient

Leveraging WebService Studio to pass in various XML strings allows us to observe server response behavior:

Input XML:
1)
<Users xmlns="http://tempuri.org/XMLSchema.xsd"><User><username>foobar</username><password>pdw123A@1234 </password><name>Foo Bar</name><streetaddress><!CDATA[<]>SCRIPT<!CDATA[>]>alert(‘XSS’);<!CDATA[<]>/SCRIPT<!CDATA[>] ></streetaddress><city>Redmond</city><state>WA</state><postalcode>01234</postalcode><phone>1- 223-123-1234</phone><ssn>123-12-1234</ssn><emailaddress><!CDATA[' or 1=1 or ''='] ></emailaddress><url>http://www.microsoft.com</url></User></Users>
2)
<Users xmlns="http://tempuri.org/XMLSchema.xsd"><User><username>foobar</username><password>pdw123A@1234 </password><name>Foo Bar</name><streetaddress>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</streetaddress><city>Redmond</city><state>WA</state><postalcode>01234</postalcode><phone>1-223-123- 1234</phone><ssn>123-12- 1234</ssn><emailaddress>example@microsoft.com</emailaddress><url>http://www.microsoft.com</url>< /User></Users>


Expected Result

1) Output from unvalidated XML Reader
Error within stored procedure, during processing. Possible SQL injection

************** Exception Text **************
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: The error description is 'An invalid character was found in text content.'.
Could not find prepared statement with handle 0.
spxmlremovedocument: The value supplied for parameter number 1 is invalid.
The XML parse error 0xc00ce508 occurred on line number 1, near the XML text "<Users xmlns="http://tempuri.org/XMLSchema.xsd"><User><username>foobar</username><password>pdw123A@1234 </password><name>Foo Bar</name><streetaddress><!CDATA[<]>SCRIPT<!CDATA[>]>alert(".
The statement has been terminated.
		   at [Service.ProcessValueNoValidation(String] strXML) in c:\Documents and Settings\XXX\My 	Documents\Visual Studio 2005\WebSites\WebSite2\App_Code\Service.cs:line 130
		   --- End of inner exception stack trace ---
		   at [System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage] message, 	[WebResponse] response, Stream responseStream)
		   at [System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String] methodName, Object[] parameters)
		   at [Service.ProcessValueNoValidation(String] strXML)
		   --- End of inner exception stack trace ---
		   at [System.Reflection.RuntimeMethodInfo.InternalInvoke(Object] obj, [BindingFlags] invokeAttr, Binder 	binder, Object[] parameters, [CultureInfo] culture, Boolean [isBinderDefault,] Assembly caller, 	Boolean verifyAccess)
		   at [System.Reflection.RuntimeMethodInfo.InternalInvoke(Object] obj, [BindingFlags] invokeAttr, Binder 	binder, Object[] parameters, [CultureInfo] culture, Boolean verifyAccess)
		   at [System.Reflection.RuntimeMethodInfo.Invoke(Object] obj, [BindingFlags] invokeAttr, Binder binder, 	Object[] parameters, [CultureInfo] culture)
		   at [WebServiceStudio.MainForm.InvokeWebMethod()]
		   at WebServiceStudio.MainForm.buttonInvoke_Click(Object sender, [EventArgs] e)
		   at [System.Windows.Forms.Control.OnClick(EventArgs] e)
		   at [System.Windows.Forms.Button.OnClick(EventArgs] e)
		   at [System.Windows.Forms.Button.OnMouseUp(MouseEventArgs] mevent)
		   at [System.Windows.Forms.Control.WmMouseUp(Message&] m, [MouseButtons] button, Int32 clicks)
		   at [System.Windows.Forms.Control.WndProc(Message&] m)
		   at [System.Windows.Forms.ButtonBase.WndProc(Message&] m)
		   at [System.Windows.Forms.Button.WndProc(Message&] m)
		   at [System.Windows.Forms.ControlNativeWindow.OnMessage(Message&] m)
		   at [System.Windows.Forms.ControlNativeWindow.WndProc(Message&] m)
		   at [System.Windows.Forms.NativeWindow.Callback(IntPtr] hWnd, Int32 msg, [IntPtr] wparam, [IntPtr] lparam)
	


1) Output from validated XML Reader
Pattern match validation caught error

************** Exception Text **************
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: Error validating XML: Error: The 'http://tempuri.org/XMLSchema.xsd:emailaddress' element is invalid - The value _ or 1=1 or _='' is invalid according to its datatype 'http://tempuri.org/XMLSchema.xsd:emailstring' - The Pattern constraint failed.
		   at [Service.ProcessValue(String] strXML) in c:\Documents and Settings\XXX\My Documents\Visual Studio 	2005\WebSites\WebSite2\App_Code\Service.cs:line 97
		   --- End of inner exception stack trace ---
		   at [System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage] message, 	[WebResponse] response, Stream responseStream)
		   at [System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String] methodName, Object[] parameters)
		   at [Service.ProcessValue(String] strXML)
		   --- End of inner exception stack trace ---
		   at [System.Reflection.RuntimeMethodInfo.InternalInvoke(Object] obj, [BindingFlags] invokeAttr, Binder 	binder, Object[] parameters, [CultureInfo] culture, Boolean [isBinderDefault,] Assembly caller, 	Boolean verifyAccess)
		   at [System.Reflection.RuntimeMethodInfo.InternalInvoke(Object] obj, [BindingFlags] invokeAttr, Binder 	binder, Object[] parameters, [CultureInfo] culture, Boolean verifyAccess)
		   at [System.Reflection.RuntimeMethodInfo.Invoke(Object] obj, [BindingFlags] invokeAttr, Binder binder, 	Object[] parameters, [CultureInfo] culture)
		   at [WebServiceStudio.MainForm.InvokeWebMethod()]
		   at WebServiceStudio.MainForm.buttonInvoke_Click(Object sender, [EventArgs] e)
		   at [System.Windows.Forms.Control.OnClick(EventArgs] e)
		   at [System.Windows.Forms.Button.OnClick(EventArgs] e)
		   at [System.Windows.Forms.Button.OnMouseUp(MouseEventArgs] mevent)
		   at [System.Windows.Forms.Control.WmMouseUp(Message&] m, [MouseButtons] button, Int32 clicks)
		   at [System.Windows.Forms.Control.WndProc(Message&] m)
		   at [System.Windows.Forms.ButtonBase.WndProc(Message&] m)
		   at [System.Windows.Forms.Button.WndProc(Message&] m)
		   at [System.Windows.Forms.ControlNativeWindow.OnMessage(Message&] m)
		   at [System.Windows.Forms.ControlNativeWindow.WndProc(Message&] m)
		   at [System.Windows.Forms.NativeWindow.Callback(IntPtr] hWnd, Int32 msg, [IntPtr] wparam, [IntPtr] lparam)
	


2) Output from validated XML Reader
Pattern match validation caught error

************** Exception Text **************
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: Error validating XML: Error: The 'http://tempuri.org/XMLSchema.xsd:streetaddress' element is invalid - The value 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' is invalid according to its datatype 'http://tempuri.org/XMLSchema.xsd:addressstring' - The Pattern constraint failed.
		   at [Service.ProcessValue(String] strXML) in c:\Documents and Settings\XXX\My Documents\Visual Studio 	2005\WebSites\WebSite2\App_Code\Service.cs:line 97
		   --- End of inner exception stack trace ---
		   at [System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage] message, 	[WebResponse] response, Stream responseStream)
		   at [System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String] methodName, Object[] parameters)
		   at [Service.ProcessValue(String] strXML)
		   --- End of inner exception stack trace ---
		   at [System.Reflection.RuntimeMethodInfo.InternalInvoke(Object] obj, [BindingFlags] invokeAttr, Binder 	binder, Object[] parameters, [CultureInfo] culture, Boolean [isBinderDefault,] Assembly caller, 	Boolean verifyAccess)
		   at [System.Reflection.RuntimeMethodInfo.InternalInvoke(Object] obj, [BindingFlags] invokeAttr, Binder 	binder, Object[] parameters, [CultureInfo] culture, Boolean verifyAccess)
		   at [System.Reflection.RuntimeMethodInfo.Invoke(Object] obj, [BindingFlags] invokeAttr, Binder binder, 	Object[] parameters, [CultureInfo] culture)
		   at [WebServiceStudio.MainForm.InvokeWebMethod()]
		   at WebServiceStudio.MainForm.buttonInvoke_Click(Object sender, [EventArgs] e)
		   at [System.Windows.Forms.Control.OnClick(EventArgs] e)
		   at [System.Windows.Forms.Button.OnClick(EventArgs] e)
		   at [System.Windows.Forms.Button.OnMouseUp(MouseEventArgs] mevent)
		   at [System.Windows.Forms.Control.WmMouseUp(Message&] m, [MouseButtons] button, Int32 clicks)
		   at [System.Windows.Forms.Control.WndProc(Message&] m)
		   at [System.Windows.Forms.ButtonBase.WndProc(Message&] m)
		   at [System.Windows.Forms.Button.WndProc(Message&] m)
		   at [System.Windows.Forms.ControlNativeWindow.OnMessage(Message&] m)
		   at [System.Windows.Forms.ControlNativeWindow.WndProc(Message&] m)
		   at [System.Windows.Forms.NativeWindow.Callback(IntPtr] hWnd, Int32 msg, [IntPtr] wparam, [IntPtr] lparam)
	

''2) Output from unvalidated XML Reader'''
Request is simply processed without validating results

<?xml version="1.0" encoding="utf-16"?>
<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>
		    [<ProcessValueNoValidationResponse] xmlns="http://codesamples.microsoft.com/XMLValidationExample/">
		      [<ProcessValueNoValidationResult>true</ProcessValueNoValidationResult>]
		    [</ProcessValueNoValidationResponse>]
		  </soap:Body>
	
</soap:Envelope>



More Information

Web services which leverarage XML schema validation to perform pattern validation (known good characters), minimum and maximum length and bounds checking, and minimum / maximum occurances of an element is signficantly less likely to result in manipulation of application logic or result in data validation induced vulnerabilities such as SQL injection, Cross-site Scripting and failure to handle error conditions. This code sample demonstrates such a task using the an XSD with strongly defined
regular expressions for typical data elements.


Additional Resources

* Validation of XML with Schemas: http://msdn.microsoft.com/library/en-us/cpguide/html/cpconValidationOfXMLWithSchemas.asp
* XML Reader usage: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconReadingXMLWithXmlReader.asp
* Regular Expressions (.NET Framework): http://msdn2.microsoft.com/en-us/library/hs600312(VS.80).aspx


Attributes

* Applies To: .NET Framework 2.0, VB
* Category: Web Services, Data Validation
* Author: George Gal



Return to HomePage
Microsoft Communities