School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,109 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,028 people online right now. Registration is fast and FREE... Join Now!




Tackling SQL Injections

 

Tackling SQL Injections

saturnx

10 Jun, 2009 - 04:43 AM
Post #1

New D.I.C Head
*

Joined: 7 May, 2009
Posts: 23



Thanked: 2 times
My Contributions
I have read tutorials on mysql_real_escape_string, php filters, addslashes(), stripslashes(), etc. and still considering which combination to use and if its the right way of doing it.

Currently i am testing/using the db connection class from a tutorial found here in D.I.C (link) which I have yet to figure out how to modify properly to incorporate mysql_real_escape_string() into it since i would need a connection to db before i can use mysql_real_escape_string(). But is mysql_real_escape_string() sufficient?

As for php filters, while i like the idea of it but it seems tedious especially if i have a lot of data to filter. I know most of the work and validation can be done with javascript to help prevent this but i always make sure i have a fall back should javasript be turned off.

So yeah... I was wondering how you guys handle SQL injections in your php applications?



cheers...

User is offlineProfile CardPM
+Quote Post


ShaneK

RE: Tackling SQL Injections

10 Jun, 2009 - 04:51 AM
Post #2

require_once("brain.php"); //Fatal error :/
Group Icon

Joined: 10 May, 2009
Posts: 701



Thanked: 47 times
Dream Kudos: 75
Expert In: PHP, MySQL

My Contributions
Well, I used to use mysql_real_escape_string, but as it's been pointed out to me there's a lot of room for human error (forgetting to escape your strings before putting them in), but it's probably the best way for you to escape strings if you're using PHP's mysql_~ functions and you have that function. add slashes and strip slashes are functions mostly for people without that function...

However, I use ADOdb, my statements look like:
CODE
$execution = $sql->Execute("SELECT * FROM `users` WHERE `id` = ?", array($id));

Which is supposed to be better because it's supposed to remove room for human error. It escapes $id and plugs it into the ? in the query.

Yours,
Shane~

This post has been edited by ShaneK: 10 Jun, 2009 - 04:55 AM
User is offlineProfile CardPM
+Quote Post

AdaHacker

RE: Tackling SQL Injections

10 Jun, 2009 - 07:19 AM
Post #3

D.I.C Regular
***

Joined: 17 Jun, 2008
Posts: 395



Thanked: 86 times
My Contributions
I've said it before and I'll say it again: PREPARED STATEMENTS. Geez, I should really write a tutorial or something so that I don't have to keep repeating myself.

Unless you have a really crappy web host who doesn't support PHP5 (in which case you should just get a better host), you should be using the PDO or MySQLi extensions for database access. Both of those support something called "prepared statements", which are essentially parameterized SQL queries. Rather than inserting your data directly into the SQL string, you insert place holders and then "prepare" the query. You then execute the query in a separate step, at which point the actual data is passed in. The preparation actually pre-compiles the SQL query, so that the data can't modify the structure of the statement - it's just treated as plain data, not part of the query text.

As ShaneK mentioned, there are also libraries like ADOdb that support parameterized queries that emulate prepared statements and give you the same benefit of taking the manual work out of escaping data. Personally, I prefer to use PDO because it's a standard extension, but these types of libraries are fine too. The main point is that these days you absolutely should not be using a data access layer that requires you to escape your query data by hand.

Also:
QUOTE
I know most of the work and validation can be done with javascript to help prevent this but i always make sure i have a fall back should javasript be turned off.

For the record, nothing that involves security or data integrity should ever be done in JavaScript. Or, more precisely, you can do it in JavaScript, but you still have to do it on the server-side too. Server-side validation is never optional. It's not just about users having JavaScript disabled - any malicious user with a copy of cURL can just POST any old data they please directly to your page, completely bypassing all client-side code. Never rely on anything that comes from the client being safe.
User is offlineProfile CardPM
+Quote Post

saturnx

RE: Tackling SQL Injections

10 Jun, 2009 - 05:01 PM
Post #4

New D.I.C Head
*

Joined: 7 May, 2009
Posts: 23



Thanked: 2 times
My Contributions
QUOTE
I've said it before and I'll say it again: PREPARED STATEMENTS. Geez, I should really write a tutorial or something so that I don't have to keep repeating myself.

AdaHacker, maybe you should do the tutorial if you have the time. I definitely would have a read and bookmark it under useful resources.

QUOTE
The main point is that these days you absolutely should not be using a data access layer that requires you to escape your query data by hand.

Couldn't have agreed more with you. Kinda the reason for starting the topic to find out what and how you guys tackle the issue and how i should approach this since i've yet to put together a solid foundation to overcome the problem. Thus the reason i'm still researching on stuff while picking up PHP again, had to drop it for almost 2 years due to work requirements.

Never the less thanks ShaneK & AdaHacker for sharing your thoughts on the topic. Will do my research on PDO and ADOdb later this evening after work.

ps. thanks for moving the topic to the right forum.

This post has been edited by saturnx: 10 Jun, 2009 - 05:09 PM
User is offlineProfile CardPM
+Quote Post

nightscream

RE: Tackling SQL Injections

21 Jun, 2009 - 03:57 PM
Post #5

D.I.C Head
**

Joined: 4 Dec, 2008
Posts: 113



Thanked: 2 times
My Contributions
This was helpfull for me too!
thank you!
User is offlineProfile CardPM
+Quote Post

KuroTsuto

RE: Tackling SQL Injections

11 Jul, 2009 - 08:36 AM
Post #6

D.I.C Head
Group Icon

Joined: 13 Feb, 2009
Posts: 104



Thanked: 12 times
Dream Kudos: 25
My Contributions
Not quite the same thing but I'm a big fan of Doctrine

This is also an interesting snippit on sanitize database input, though all things considered its really just an introduction - his code could use many improvements, and it doesn't really account for all that much.

QUOTE
For the record, nothing that involves security or data integrity should ever be done in JavaScript.


AddHacker's totally right - you can pretty much circumvent any client-side code on most websites with a jQuery bookmarklet and Firebug... or even just your address bar and javascript(), really.
User is offlineProfile CardPM
+Quote Post

dreadfear

RE: Tackling SQL Injections

13 Jul, 2009 - 08:22 AM
Post #7

D.I.C Head
**

Joined: 8 Dec, 2008
Posts: 166



Thanked: 1 times
My Contributions
ohmy.gif This is so helpful, i didnt know these methods existed im new to php.

I was using a function that emulates .contains in vb.net to find potential sql hacks and remove them from the string before using it to query the database.
User is offlineProfile CardPM
+Quote Post

Lang14

RE: Tackling SQL Injections

15 Aug, 2009 - 01:41 PM
Post #8

New D.I.C Head
*

Joined: 15 Aug, 2009
Posts: 22



Thanked: 5 times
My Contributions
Hey there,

I recently came up with a neat trick. Or at least I thought it was neat.

I have a database class than handles all MySQL queries. So on top of using the many functions to ensure data is safe I also have this code:

CODE

if ((substr_count($query, 'UPDATE') > 0 || substr_count($query, 'DELETE') > 0) && substr_count($query, 'WHERE') == 0){
        //query has no WHERE clause - don't run the query.
    //log the query, if query is okay it can be allowed to run at a later time
}


Obviously, its easy to get around this with a simple WHERE 1=1 but its just an added level of protection!

This post has been edited by Lang14: 15 Aug, 2009 - 01:42 PM
User is offlineProfile CardPM
+Quote Post

evinrows

RE: Tackling SQL Injections

17 Aug, 2009 - 09:09 PM
Post #9

D.I.C Head
**

Joined: 3 Aug, 2009
Posts: 87



Thanked: 2 times
My Contributions
QUOTE(AdaHacker @ 10 Jun, 2009 - 07:19 AM) *

For the record, nothing that involves security or data integrity should ever be done in JavaScript. Or, more precisely, you can do it in JavaScript, but you still have to do it on the server-side too. Server-side validation is never optional. It's not just about users having JavaScript disabled - any malicious user with a copy of cURL can just POST any old data they please directly to your page, completely bypassing all client-side code. Never rely on anything that comes from the client being safe.

True, but if the developer has the time, it could be done in both as to allow for instant verification, since PHP is unable to do that.
User is offlineProfile CardPM
+Quote Post

PsychoCoder

RE: Tackling SQL Injections

17 Aug, 2009 - 09:49 PM
Post #10

I Code, Therefore I am
Group Icon

Joined: 26 Jul, 2007
Posts: 14,931



Thanked: 517 times
Dream Kudos: 11550
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net, jQuery

My Contributions
Excellent topic for discussion here, featured so others will get involved smile.gif
User is offlineProfile CardPM
+Quote Post

kiwi2

RE: Tackling SQL Injections

17 Aug, 2009 - 10:47 PM
Post #11

D.I.C Head
Group Icon

Joined: 16 Sep, 2008
Posts: 164



Thanked: 4 times
Dream Kudos: 300
My Contributions
Here is a very good tut on php filters and how to use them
http://www.webreference.com/programming/php/DataFiltering/
User is offlineProfile CardPM
+Quote Post

evinrows

RE: Tackling SQL Injections

19 Aug, 2009 - 09:59 PM
Post #12

D.I.C Head
**

Joined: 3 Aug, 2009
Posts: 87



Thanked: 2 times
My Contributions
QUOTE(KuroTsuto @ 11 Jul, 2009 - 08:36 AM) *

Not quite the same thing but I'm a big fan of Doctrine

This is also an interesting snippit on sanitize database input, though all things considered its really just an introduction - his code could use many improvements, and it doesn't really account for all that much.

QUOTE
For the record, nothing that involves security or data integrity should ever be done in JavaScript.


AddHacker's totally right - you can pretty much circumvent any client-side code on most websites with a jQuery bookmarklet and Firebug... or even just your address bar and javascript(), really.

His little insight about cutting out CSS, HTML, and Javascript is kind of silly imo. If he wanted to get rid of all those things, leaving just plain text, he might as well just do a simple preg_match with a regexr statement that allows only letters, numbers, and punctuation.
User is offlineProfile CardPM
+Quote Post

RudiVisser

RE: Tackling SQL Injections

20 Aug, 2009 - 02:58 AM
Post #13

.. does not guess solutions
Group Icon

Joined: 5 Jun, 2009
Posts: 1,891



Thanked: 139 times
Dream Kudos: 125
Expert In: PHP, MySQL, HTML, CSS, C#

My Contributions
Basic principles are covered at: http://beta.developercenter.org/article/ph...tion-practices/

An article on prepared statements is already planned.
User is offlineProfile CardPM
+Quote Post

Lang14

RE: Tackling SQL Injections

24 Aug, 2009 - 08:38 PM
Post #14

New D.I.C Head
*

Joined: 15 Aug, 2009
Posts: 22



Thanked: 5 times
My Contributions
That is something many people don't understand.

Just because your website is developed on the fly does not mean it cannot be saved and modified.

His method although silly, is effective and very dangerous. The only Javascript verification I use, is determining if passwords match, emails match and username availability. I also check data length for required fields.

If a user is willing to type in some crazy data, then they deserve to endure a post back telling them they need to try again!
User is offlineProfile CardPM
+Quote Post

Master Jake

RE: Tackling SQL Injections

21 Oct, 2009 - 04:51 PM
Post #15

D.I.C Head
Group Icon

Joined: 27 Feb, 2009
Posts: 106



Thanked: 6 times
Dream Kudos: 150
My Contributions
I use mysql_real_escape_string() to strip harmful characters, then when the time comes that I need to output data to the screen, I use stripslashes() on the strings to return them to their normal state.
User is offlineProfile CardPM
+Quote Post

RudiVisser

RE: Tackling SQL Injections

21 Oct, 2009 - 04:57 PM
Post #16

.. does not guess solutions
Group Icon

Joined: 5 Jun, 2009
Posts: 1,891



Thanked: 139 times
Dream Kudos: 125
Expert In: PHP, MySQL, HTML, CSS, C#

My Contributions
You shouldn't need to use stripslashes() when you retrieve the data unless your server is configured incorrectly (to use magic_quotes or the like..).
User is offlineProfile CardPM
+Quote Post

Master Jake

RE: Tackling SQL Injections

21 Oct, 2009 - 05:13 PM
Post #17

D.I.C Head
Group Icon

Joined: 27 Feb, 2009
Posts: 106



Thanked: 6 times
Dream Kudos: 150
My Contributions
I'm pretty sure magic quotes are on in the server, but what's that have to do with anything?

When I escape and store a string into the database Hello \"World\", then when I retrieve it into an associative array to print it, it will still be Hello \"World\" won't it? I've always had to strip the slashes before printing it.
User is offlineProfile CardPM
+Quote Post

AdaHacker

RE: Tackling SQL Injections

21 Oct, 2009 - 06:57 PM
Post #18

D.I.C Regular
***

Joined: 17 Jun, 2008
Posts: 395



Thanked: 86 times
My Contributions
QUOTE(Master Jake @ 21 Oct, 2009 - 07:13 PM) *
When I escape and store a string into the database Hello \"World\", then when I retrieve it into an associative array to print it, it will still be Hello \"World\" won't it?

No, it won't. That only happens when magic_quotes_runtime is turned on. It automatically escapes any strings that come out of the database. Incidentally, magic_quotes have been deprecated in PHP 5.3 and will be removed from PHP 6, so you probably shouldn't be depending on them.
User is offlineProfile CardPM
+Quote Post

Master Jake

RE: Tackling SQL Injections

22 Oct, 2009 - 10:11 AM
Post #19

D.I.C Head
Group Icon

Joined: 27 Feb, 2009
Posts: 106



Thanked: 6 times
Dream Kudos: 150
My Contributions
QUOTE(AdaHacker @ 21 Oct, 2009 - 06:57 PM) *

QUOTE(Master Jake @ 21 Oct, 2009 - 07:13 PM) *
When I escape and store a string into the database Hello \"World\", then when I retrieve it into an associative array to print it, it will still be Hello \"World\" won't it?

No, it won't. That only happens when magic_quotes_runtime is turned on. It automatically escapes any strings that come out of the database. Incidentally, magic_quotes have been deprecated in PHP 5.3 and will be removed from PHP 6, so you probably shouldn't be depending on them.


Believe me, I'm not dependent on them. Their actually a pain in the ass because I go to escape things before input into a database and it ends up escaping them twice (one for magic quotes and another for my mysql_real_escape_string()).



User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 12:52PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month