Validation of forms against SQL injection or XSS attacks

Posted under » PHP » LAMP Security on 07 Feb 2017

SQL injection and XSS attacks can prevented if you sanitise the data that is being received by the server.

You can validate the data as the user key-in the form input using javascript to make sure the data is legit but this would mean going each and every fields that exist in the form and this can be time consuming but in some cases, a requirement from the client.

The best or safest way is to validate the input first before you do anything or begin processing it... especially if you are using the $_get method.

So rather than going to look at the codes to find out what the field names are, you should use the firebug plug-in available in chrome or firefox to find out what they are. Press the submit button and look under "Params" tab.

In PHP, what I did is to concatenate all of them and then validate using regex. If found to contain illegal data, then exit and halt all process.

// sql injection tests
$sample = $_GET['accession'].$_GET['expression'].$_GET['fl_select'].$_GET['full_length'].$_GET['keywords'];
if ((preg_match("/<[^<]+>/",$sample)) OR (preg_match("/[\'\"]/",$sample)) OR (preg_match('/(and|or|null|not|union|select|from|having|%27|%22|%3b|%3c|%3d|%3e|%29|%28|%20|\()/i',$sample))    ) { 
//   header('Location: 400.html');
   exit("<p>Sorry. Only numbers and letters are accepted. Encoded data will be rejected.");
   } 

It is necessary to put exit because the code will just run.

  1. The first regex prevents html and javascript that always starts with < and ends with >.
  2. The second prevents codes encapsulated in " or ' which is necessary in SQL commands.
  3. The third and final one looks out for SQL commands and single words.
  4. %27 = '
  5. %22 = "
  6. %3b = ;
  7. %3c = <
  8. %3d = =
  9. %3e = >
  10. %29 = )
  11. %28 = (
  12. %20 = space

If you are angry, you can kick them to another location but if want to show them more respect, you can tell them the error in their ways.
 

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data