Monday 26 November 2012

Validating User Input to Avoid Attacks

To protect against vulnerabilities such as script injection and cross-site scripting, user input can be verified and rejected, or an application can remove harmful characters and continue processing. This topic provides example code that uses regular expressions to verify user input.

Example code

The following examples shows you how to validate a string using a regular expression. The regular expression, ^[\w\.:\?&=/]*$, searches for a complete string (from beginning to end) that contains only the following characters:

  • alphanumeric or underscore (_)
  • periods (.)
  • colons (:)
  • question marks (?)
  • ampersands (&)
  • equal signs (=)
  • forward slashes (/)

The following example shows you how to use the Visual Basic programming language to include a function that returns a Boolean value indicating if the string that it sent to the function is a valid URL, which might contain a query string.

Public Function ValidateInput(ByVal sInput As String) As Boolean 
    Dim reValid As RegExp 
    Set reValid = New RegExp 

    reValid.Pattern = "^[\w\.:\?&=/]*$" 
    reValid.MultiLine = False 
    reValid.Global = True 

    ValidateInput = reValid.Test(sInput) 
End Function 

Public Function RedirectTo() As Boolean 
    If ValidateInput(myURL) Then 
        Dim objContext As ObjectContext 
        Dim objResponse As Response 
        Set objContext = GetObjectContext() 
        Set objResponse = objContext("Response") 
        objResponse.Redirect (myURL) 
        RedirectTo = True 
    Else 
        RedirectTo = False 
    End If 
End Function 
source: http://msdn.microsoft.com/en-us/library/ms525361%28v=vs.90%29.aspx

No comments:

Post a Comment