ASP.NET protects you pretty good when user tries to post a malicious content thru an entry form. With @page directive “ValidateRequest=true” (which is true by default) if anybody attempts to enter something like <script type=”text/javascript”>…nasty stuff here…</script> the page will throw HttpRequestValidationException exception: A potentially dangerous value was detected from the client…
But this does not work for some form elements, for example framework variables such as __EVENTVALIDATION or __VIEWSTATE over which user or developer do not have direct control. A maliciously crafted POST request can insert JavaScript into those elements which then can execute in user’s browser. Yes the page may crash because of invalid data, but JavaScript is still echoed to the client and gets executed. In this case ASP.NET needs a little help.
The simplest way is to have a list of such elements and at a very basic level test it for a presence of angle brackets which should never be there. If such element is found – we can throw HttpRequestValidationException ourselves. Here is an example of such validator function:
''' <summary> ''' Performs Request validation when "ValidateRequest = true" fails ''' </summary> ''' <param name="i_oRequest">WebRequest object</param> Sub ValidateWebRequest(i_oRequest As HttpRequest) 'Array of protected Request values Dim sProtectedNames() As String = {"__IG_CALLBACK", "__EVENTVALIDATION", "__VIEWSTATE"} For Each sName As String In sProtectedNames If i_oRequest(sName) IsNot Nothing AndAlso (i_oRequest(sName).Contains("<") OrElse i_oRequest(sName).Contains(">")) Then Throw New HttpRequestValidationException("A potentially dangerous value was detected from the client (" & sName & ")") End If Next End Sub
Code accepts am HttpRequest objects, loops thru specified elements and throws an exception if malicious content is found. Call to this code can be placed into the Init event of the page:
Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init ValidateWebRequest(Request) End Sub