Welcome to Dream.In.Code
Become an Expert!

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




SQL Injection :: What It Is, And How To Prevent It

 
Reply to this topicStart new topic

> SQL Injection :: What It Is, And How To Prevent It

Rating  4
sandman85048
Group Icon



post 11 Nov, 2007 - 09:03 AM
Post #1


SQL Injection is a form of hacking that has taken down innumerable amounts of websites, and it's no comforting idea that your site could be next. In this tutorial, I will give you a brief synopsis of what SQL Injection really is, and how to protect your website from it. This tutorial assumes that you have a fairly good knowledge of PHP, you understand GET and POST methods, and you have used and at least partly understand SQL.

SQL Injection is usually done through areas where user input is added into a database, or where GET/POST values are parsed and added into a database. For example, this is a piece of code that will get a POST value and add it to the database:
CODE
mysql_query("INSERT INTO table VALUES('" . $_GET["value"] . "')");
Now let's create the scenario. That code is located at http://example.com/update.php. If the page was visited with the GET values:
http://example.com/update.php?value=bwahaha
This would give us an SQL query like this:
INSERT INTO table VALUES('bwahaha')

That code is all fine and dandy, but what if someone visited the page like this:
http://example.com/update.php?value=blah'); DELETE * FROM table WHERE value != 0; INSERT INTO table VALUES('HACKED!
This would make an SQL query:
INSERT INTO table VALUES('blah'); DELETE * FROM table WHERE value != 0; INSERT INTO table VALUES('HACKED!')
That is one piece of malicious code. This would essentially delete all rows from the database, except for ones with a value of 0. Then, you would probably have one row which would let you know that you were hacked.


Now you probably want to know how to protect your site(s) from this, right? It's fairly simple, actually.

We can use a function from a code snippet I published, called sql_sanitize.
CODE
function sql_sanitize( $sCode ) {
        if ( function_exists( "mysql_real_escape_string" ) ) { // If PHP version > 4.3.0
                $sCode = mysql_real_escape_string( $sCode ); // Escape the MySQL string.
        } else { // If PHP version < 4.3.0
                $sCode = addslashes( $sCode ); // Precede sensitive characters with a slash \
        }
        return $sCode; // Return the sanitized code
}
Now let's put this into action. Remember the code we had earlier? Let's change that:
mysql_query("INSERT INTO table VALUES('" . sql_sanitize($_GET["value"]) . "')");
This will "sanitize" the code and protect your database from people doing anything malicious to it.

Well, there you go! I suggest you implement this method wherever you are putting user input into the database. Instead of using $_GET["value"], for instance, just use sql_sanitize($_GET["value"])! It really is that simple.
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

didgy58
**



post 25 Nov, 2007 - 01:52 PM
Post #2
so would it go something like this

CODE


$query = "INSERT INTO $tbl_name (Name, Email, Comment, Datetime) " .
             "VALUES ('".sql_sanitizer('$name', '$email', '$message', '$datetime')."')";



could you only use this for when you are adding to the database what if you where just pulling records out of the database to display in a table could you also use the sanitizer function then??

thanks

dan
Go to the top of the page
+Quote Post

snoj
Group Icon



post 25 Nov, 2007 - 02:27 PM
Post #3
If you're meaning on the records returned...not necessarily. However for the WHERE part of your SELECT query you would want to sanitize.
Go to the top of the page
+Quote Post

rockstar_
Group Icon



post 26 Nov, 2007 - 11:58 PM
Post #4
CODE
function sql_sanitize( $sCode ) {
        if ( function_exists( "mysql_real_escape_string" ) ) { // If PHP version > 4.3.0
                $sCode = mysql_real_escape_string( $sCode ); // Escape the MySQL string.
        } else { // If PHP version < 4.3.0
                                                        die('Your PHP version is too old!');  // Addslashes is unsafe
        }
        return $sCode; // Return the sanitized code
}

It would probably best not to try addslashes at all. There are far too many vectors to get around addslashes. PHP 4 will be EOL'd starting Jan 1, 2008 for a reason. Just FYI. If I wanted to try out SQL injection, I'd find out the PHP version first, to see if I could just fire in some escape codes and the like to get it to error out.
Go to the top of the page
+Quote Post

darklighter
*



post 5 Jan, 2008 - 08:03 AM
Post #5
Remember to us stripslashes when trying to display the data from the db, otherwise you may end up with text that looks like:

"Let/'s go!"

And worse if you resubmit that data cuz you'd end up with more slashes on it if you don't strip em again each time you display it.
Go to the top of the page
+Quote Post

Ladydice
*



post 20 Aug, 2008 - 08:35 PM
Post #6
QUOTE(sandman85048 @ 11 Nov, 2007 - 10:03 AM) *

SQL Injection is a form of hacking that has taken down innumerable amounts of websites, and it's no comforting idea that your site could be next. In this tutorial, I will give you a brief synopsis of what SQL Injection really is, and how to protect your website from it. This tutorial assumes that you have a fairly good knowledge of PHP, you understand GET and POST methods, and you have used and at least partly understand SQL.

SQL Injection is usually done through areas where user input is added into a database, or where GET/POST values are parsed and added into a database. For example, this is a piece of code that will get a POST value and add it to the database:
CODE
mysql_query("INSERT INTO table VALUES('" . $_GET["value"] . "')");
Now let's create the scenario. That code is located at http://example.com/update.php. If the page was visited with the GET values:
http://example.com/update.php?value=bwahaha
This would give us an SQL query like this:
INSERT INTO table VALUES('bwahaha')

That code is all fine and dandy, but what if someone visited the page like this:
http://example.com/update.php?value=blah'); DELETE * FROM table WHERE value != 0; INSERT INTO table VALUES('HACKED!
This would make an SQL query:
INSERT INTO table VALUES('blah'); DELETE * FROM table WHERE value != 0; INSERT INTO table VALUES('HACKED!')
That is one piece of malicious code. This would essentially delete all rows from the database, except for ones with a value of 0. Then, you would probably have one row which would let you know that you were hacked.


Now you probably want to know how to protect your site(s) from this, right? It's fairly simple, actually.

We can use a function from a code snippet I published, called sql_sanitize.
CODE
function sql_sanitize( $sCode ) {
        if ( function_exists( "mysql_real_escape_string" ) ) { // If PHP version > 4.3.0
                $sCode = mysql_real_escape_string( $sCode ); // Escape the MySQL string.
        } else { // If PHP version < 4.3.0
                $sCode = addslashes( $sCode ); // Precede sensitive characters with a slash \
        }
        return $sCode; // Return the sanitized code
}
Now let's put this into action. Remember the code we had earlier? Let's change that:
mysql_query("INSERT INTO table VALUES('" . sql_sanitize($_GET["value"]) . "')");
This will "sanitize" the code and protect your database from people doing anything malicious to it.

Well, there you go! I suggest you implement this method wherever you are putting user input into the database. Instead of using $_GET["value"], for instance, just use sql_sanitize($_GET["value"])! It really is that simple.



does this method only used for $_GET statements...what about $_REQUEST statements...?
Go to the top of the page
+Quote Post

gakusei
*



post 2 Dec, 2008 - 08:28 PM
Post #7
Hello,

After reading the article, I still don't quite get what's the problem with not sanitizing the GET parameters when using PHP-MYSQL (in terms of unauthorized insertions/deletion of data). For instance, with regard to the sql injection example in the article,

http://example.com/update.php?value=blah'); DELETE * FROM table WHERE value != 0; INSERT INTO table VALUES('HACKED!

since php mysql_query method does not support multiple queries, so stacking queries as the example above should not work (will throw sql error). Is there really anyway to put sql injection into a php-mysql script even without the sanitization of the GET parameters? Hope you can shed some more light on this subject. Many thanks.
Go to the top of the page
+Quote Post

joeyadms
Group Icon



post 20 Dec, 2008 - 01:00 PM
Post #8
QUOTE(gakusei @ 2 Dec, 2008 - 08:28 PM) *

Hello,

After reading the article, I still don't quite get what's the problem with not sanitizing the GET parameters when using PHP-MYSQL (in terms of unauthorized insertions/deletion of data). For instance, with regard to the sql injection example in the article,

http://example.com/update.php?value=blah'); DELETE * FROM table WHERE value != 0; INSERT INTO table VALUES('HACKED!

since php mysql_query method does not support multiple queries, so stacking queries as the example above should not work (will throw sql error). Is there really anyway to put sql injection into a php-mysql script even without the sanitization of the GET parameters? Hope you can shed some more light on this subject. Many thanks.


Good catch, However not everyone creates php applications for mysql, and the other flavors are particularly vulnerable to this.

MYSQL on the other hand, IS, still vulnerable of modifying statements, this article doesnt even break the tip on sql attacks. For a better primer, and one tuned to php, visit my article below:

http://www.dreamincode.net/forums/showtopic52374.htm

Also google for whitepapers.

I LOVE sql injections and XSS, as a pen-tester, it brings out creativity, and it is a lot of fun battling against the server and filters to try to take control of execution.
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 1/9/09 05:54AM

Be Social

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

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month