Every now and then, a developer makes a post on their blog that, to the unsuspecting novice, seems like common sense.
Beware, though. If the post is less than comprehensive or accurate, it better not be about security matters or that newly acquired peace of mince may be quickly shattered.
Exhibit A: This post on the topic of PHP and SQL injections. It’s not like there is a lack of information already freely available on the web.
The author even references this excellent material at the end of his post. It is too bad that his own article actually contains less relevant information than the original post.
For instance, he recommends the use of mysql_real_escape_string().
- Observation #1: this implies that you are using mysql as your database of choice. Granted you may use this method before sending a SQL query to Postgresql, but then there is no guarantee that mysql functions were compiled in the current php library.
- Observation #2: mysql_real_escape_string() does nothing more than escape quotes. From the original article: “Be aware that “sanitizing the input” doesn’t mean merely “remove the quotes”, because even “regular” characters can be troublesome.“
He recommends validating for the proper input, which is good practice. So, brownie points for that. But it wouldn’t hurt to have, for instance, mentioned the use of intval() to enforce that integer values are nothing but that. Integer values. I would say that it’s advice just as important as escaping input strings.
Now, the part that I found horrifying, but it’s just me, I’m a stickler: the author encourages you to code your HTML forms so that they will not accept too many characters. I see here some confusion: this is good usability advice, granted, but as far as security it is misguided.
The golden rule is simple: Always perform input validation server-side, where the user cannot ‘fake’ the values they are sending to your application.
Never, ever accept data “as-is” if it came through a path that allowed it to be tampered with.
Two other equally important points I wish he had mentioned are:
- Configure error reporting so that your server does not display these “helpful” error messages that he mentions and attackers are delighted to find
- A good SQL query is one cautiously put together, but a great SQL query relies on prepared statements. There are cases when you are after raw speed and direct queries feel more ‘natural’ -I know, I use them a lot- but whenever possible, use prepared statements, since the user is then not given a chance to “write” your query string himself.
