Search code examples
vb.netsecurityquery-string

How to filter out some vulnerability causing characters in query string?


I need to filter out characters like /?-^%{}[];$=*`#|&@'"<>()+,\. I need replace this with empty string if it is there in the query string. I am using this in ASP pages.


Solution

  • Best idea would be to use a function something along the lines of:

    Public Function MakeSQLSafe(ByVal sql As String) As String
        'first i'd avoid putting quote chars in as they might be valid? just double them up.
        Dim strIllegalChars As String = "/?-^%{}[];$=*`#|&@\<>()+,\"
        'replace single quotes with double so they don't cause escape character
        If sql.Contains("'") Then
            sql = sql.Replace("'", "''")
        End If
        'need to double up double quotes from what I remember to get them through
        If sql.Contains("""") Then
            sql = sql.Replace("""", """""")
        End If
        'remove illegal chars
        For Each c As Char In strIllegalChars
            If sql.Contains(c.ToString) Then
                sql = sql.Replace(c.ToString, "")
            End If
        Next
    
        Return sql
    End Function
    

    This hasn't been tested and it could probably be made more efficient, but it should get you going. Wherever you execute your sql in your app, just wrap the sql in this function to clean the string before execution:

    ExecuteSQL(MakeSQLSafe(strSQL))

    Hope that helps