[thelist] Keeping PHP forms secure

Sales @ Lycosa sales at lycosa.co.uk
Tue Aug 7 04:28:31 CDT 2007


> Is this enough to keep the database safe from attack? It seems like there
should more to this but I have googled and didn't find anything.

This is important, but there is much more that you can do. Some useful ideas
are:
1. Use regular expressions to sanitize the variables by removing dodgy
characters such as ` 

2. Your script should know what variable names are being supplied, what type
of value they should contain and the maximum length. Check all these
variable names for content, and force an error if it contains the wrong
value type, or is too long.

[ Eg. if someone types in 'delete from customers' (sql injection) into the
telephone field, you should check the field length - 22 chars is rather long
for a phone number - and that it contains only 0-9, space and +- ]

3. Use only POST variables for forms, so they cannot be spoofed by GET
variables.

4. Record the IP address and datetime of each request in a separate table in
your database. Run a check to assess the speed of requests, and push a 404
error or similar if you are getting brute force attacks. You could also have
a '3 and out' or similar within a set time frame.

5. Have global variables turned off, and use import_request_variables("pgc",
"prefix").

6. If set, check HTTP_REFERER. If it is set, and is not the referring form
page, then some spoofing is occurring. You can't always trust this, though,
and it's not foolproof.

7. Use drop down lists. Wherever possible, use a drop down list of
predefined variables. This stops the user typing anything in, and allows
your script to take action on certain selected values. If the user creates a
post with values outside of that list, force an error.

8. Use replacement. Instead of using input variables directly in you SQL
statement, create a separate variable according to the value of the input
which suits your database needs. This is not possible for all fields, but is
useful for ENUM and SET datatypes (which should be used wherever possible).
Forcing the user to select from a list and then only have those possible
values in your database allows you to sanitize the input closely.

[Eg. user creates a POST from a web server and creates the variable
$salutation='DELETE FROM customers'

Your form has salutation as mr./mrs./miss/ms/dr. dropdown. Max length 4.
Trim the variable, instantly making the sql injection safe. Then use logic
(if/switch) to check the value and build the query you are going to use:

If (strtolower(trim($salutation)) == "mr.") $query .= "salutation='mr.',\n";

Or similar. That way you are not directly entering the user input into the
query string. It's not always possible to do this, but it is prudent and
good practice to do this wherever possible.

I recommend reading all you can on security and hacking. It will help you to
code defensively. 

Hth.

Phil






More information about the thelist mailing list