SQL Injection Protection: Verifying Data

Whenever we take input on a web page, we should verify the data to help prevent SQL injection attacks. Remember that query strings in URLs  input data, as do fields on a web form. Either of these input methods can be exploited in an attack.

There are a number of things that we can check depending on how the data will be used. Following is a list of some of the things that we may wish to check.

  • For inputting numbers, convert the input string to a number before using it, even if it has to be converted back to a string to use it. More on this at SQL Injection Prevention: ID’s in the Query String
  • The same thing applies to other data types, such as Dates, Times, etc.
  • For inputs with a maximum number on characters, truncate the input string to that number of characters. For example, if the maximum length of a valid data string is 50 characters, truncate the string at 50 characters.
  • For inputs that will later be used as html output, strip unwanted tags. Things I’ve heard recently say you should have a whitelist of safe (allowable) tags, and you should strip all other tags.
  • May want to check for imbedded SQL type commands such as INSERT, DELETE, UPDATE, and CAST
  • If you use a string to build a SQL statement, you should encode that string. An easy way to do this is to use parameters in the SQL statement, as the parameters encode it for you.
  • When making database calls, don’t continue if you get results you don’t expect. For example, a query to check a username/password combination should return no more than one record. If it returns more, something is not right.

Another thing to remember is that you should not rely on client side data verification, you should also do server side verification. One reason for this is that the user may not have scripting turned on, in which case, the client side verification will never run. This YouTube video demonstrates another reason why only using client side verification is a bad idea.

Advertisements
%d bloggers like this: