While it may sound defeatist to lean on the old adage of “where there’s a will, there’s a way,” it is ultimately true when it comes to getting hacked. The only sure-fire way to keep your website from being compromised is to turn the computer off and lock it in a closet.
Since that’s not an option, we try our best to defend against the unending attempts by hackers to defile our work and take what is not theirs.
While these aren’t the only methods, they are all good ones to follow.
What is an Injection Attack?
An injection attack is caused by the replacement of expected variable values in the URL address with a formed statement that is injected into a query on the page aimed at breaking, installing, stealing or uncovering something else. It is commonly found when there are variables passed in a URL address like page.php?ID=5 and the “5” is replaced with some text that when inserted into the query, it undesirably alters the result.
Tip #1: Turn Off Globals
This is a setting on the server. Turning this feature off limits what variables passed in the header will automatically be part of the page’s space.
You can access the specific variables you’re looking for via the $_GET or $_POST arrays. If you’re not sure if it’s $_GET or $_POST then use $_REQUEST.
Tip #2: Check the Source
In the case of form data, you have an option to specify POST/GET data transmission. I usually opt for POST and when I do, I make sure to check only the $_POST value of what I’m looking for and not a forced $_GET.
Tip #3: Clean Your Data
When inserting records into a table or running a query using supplied variables clean each one using the mysql_real_escape_string. It’s a great function that escapes special characters in a string for use in a query.
Tip #4: Valid the Expected Data
This one’s a bit more involved. When data is passed through the headers you should validate the passed value against what it is expected to be. If it’s a string no longer than 15 characters, make sure it’s not longer than 15 characters. If it’s supposed to be a number and it comes out as a string, then you’ve got a problem.
Tip #5: Close the Queries for Insertion
You want your queries to be more easily hacked, don’t wrap your values in single or double quotes. Take the following query for example:
$number = 5
SELECT * FROM Table WHERE ID=$number
Replace ?5? with “ID UNION SELECT Username FROM Site_Users” and your query looks like this:
SELECT * FROM Table WHERE ID=ID Union Select Username FROM Site_Users
And suddenly you have a valid query that you didn’t intend. Wrap you ID value in single quotes like this:
SELECT * FROM Table WHERE ID=”$number”
And you’ll make it more difficult to crack.
Hope you find these tips useful!