Forum Moderators: phranque

Message Too Old, No Replies

How to avoid MySQL Injection Attacks?

What are "best practices" to keep from being exploited?

         

MatthewHSE

1:56 am on Sep 3, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Okay, so maybe this post belongs in the Perl or PHP forums instead of Webmaster General. But with MySQL injection attacks being the type of thing that can exploit many programming languages, I thought the "General" category was most fitting. Mods, please feel free to move this post if I guessed wrong.

I'm about to go live with my first "major" PHP script that is database-driven. It has a PHP/MySQL backend and does gather some sensitive data, such as names and addresses. Obviously, this is the type of thing you'd like to keep private! ;)

I've tried hacking the script myself by entering bogus and potentially-malicious data into the form fields, and so far it seems pretty safe. I've been unable to execute any PHP code through the form, and though the query strings do play an important role in the operation of the script, I've managed to keep things secure enough that I can't get to anything I shouldn't have access to by changing the query strings around and otherwise messing with them.

My biggest fear comes from MySQL injection attacks. I've heard that these are some of the most difficult attacks to guard against, and I don't mind telling you that I'm a bit afraid that I don't know enough to protect against them. So I'm wondering what some "best practices" would be to help prevent this devious type of attack.

In addition to ways to prevent MySQL injection attacks, I'll welcome advice on how to try to hack my own application - if I can't hack it myself, even knowing how it works, then surely it should be safe from outsiders. (Although most hackers are way smarter than I am . . . )

So what should I do to make sure I'm secure? I'm open to any and all suggestions!

Thanks in advance,

Matthew

physics

2:36 am on Sep 3, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm not a security expert but have a couple of suggestions that can't hurt anyway.

One good practice is to only accept data that you're looking for. So if you're only looking for search phrase from 4 to 20 characters long which only consists of word characters and spaces, then use a filter on the inputted string (use regular expressions ...).

You should also use mysql_real_escape_string( ) or mysql_escape_string( ) to escape special characters in any string to insert prior to inserting.