On MySQL Injection attacks (again)

I know after a very long hiatus, the last thing I probably should be wrting about is this, but this is a very serious point for me because I have recently come across sites, totally destroyed by this sort of attack. I’ve seen tables recursively dropped because of sloppy input validation on the part of the developer.

I introduce base64 to those who actually do not use it already. Now basically the idea is this: you take input from a text box and encode it as base64 before storing in the database. This changes and dangerous strings to relatively safer ones. And decode the string when you need to retrieve the information for display.

Rather a simple task in PHP with a function similar to this

function safe_insert($string){
$encoded_string = base64_encode($string);
$sql = "INSERT INTO `target_table` (`target_column`) VALUES('$encoded_string')";
if(mysql_query($sql){
return true;
}else{
return fals;
}
}

and of course to retrieve a function such as

function safe_retrieve($column, $item_id){
$sql = "SELECT `$column` FROM `target_table` WHERE `id` = $item_id";
if($result = mysql_query($sql)){
if(mysql_num_rows($result) > 0){
if($row = mysql_fetch_assoc($result)){
return base64_decode($row[$column]);
}
}
}
}

Now naturally you might want to do more with it but the main thrust of this argument is using encoding and decoding you can add an additional layer of protection to your mysql/sql database interaction.

Oh and by the way I settled for Aptana in the end. It’s solid, quicker than Netbeans (for me anyway) and tailored to exactly what I want it to do.

5 thoughts on “On MySQL Injection attacks (again)

  1. Now basically the idea is this: you take input from a text box and encode it as base64 before storing in the database

    And in doing so, you lose any way to actually search the data in a meaningful fashion.

    Much better, surely, to make sure that you escape the data properly. If you’re having to resort to base64 to protect yourself then something is fundamentally wrong with the way you’re handling the database in the first place.

  2. You’re doing it wrong! Now what happens when you want to select stuff out of that DB based on something that isn’t the primary key? Just use prepared statements.

  3. I suppose it was my mistake not to mention that these are fields you would not necessarily be searching. There’s nothing wrong with properly escaping data, I did not say this was a replacement. I said it was an added layer, it’s at your discretion really to use it or not.

  4. Pingback: An interesting take on sanitising data. | Stop, You're doing it wrong

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>