• (2 Pages)
  • +
  • 1
  • 2

SQL Injection :: What It Is, And How To Prevent It Rate Topic: ****- 1 Votes

#1 sandman85048  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 20-October 07

Post icon  Posted 11 November 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:
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/u...p?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.
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.

Is This A Good Question/Topic? 0
  • +

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

#2 didgy58  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 246
  • Joined: 23-October 07

Posted 25 November 2007 - 02:52 PM

so would it go something like this


$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
Was This Post Helpful? -1
  • +
  • -

#3 snoj  Icon User is offline

  • Married Life
  • member icon

Reputation: 84
  • View blog
  • Posts: 3,564
  • Joined: 31-March 03

Posted 25 November 2007 - 03:27 PM

If you're meaning on the records returned...not necessarily. However for the WHERE part of your SELECT query you would want to sanitize.
Was This Post Helpful? 0
  • +
  • -

#4 rockstar_  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 32
  • View blog
  • Posts: 189
  • Joined: 16-October 06

Posted 27 November 2007 - 12:58 AM

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.
Was This Post Helpful? 0
  • +
  • -

#5 darklighter  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 05-January 08

Posted 05 January 2008 - 09:03 AM

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.
Was This Post Helpful? 1
  • +
  • -

#6 Ladydice  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 25-June 08

Posted 20 August 2008 - 09:35 PM

View Postsandman85048, on 11 Nov, 2007 - 10:03 AM, said:

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:
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/u...p?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.
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...?
Was This Post Helpful? 0
  • +
  • -

#7 gakusei  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 02-December 08

Posted 02 December 2008 - 09: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.
Was This Post Helpful? 0
  • +
  • -

#8 joeyadms  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 41
  • View blog
  • Posts: 178
  • Joined: 04-May 08

Posted 20 December 2008 - 02:00 PM

View Postgakusei, on 2 Dec, 2008 - 08:28 PM, said:

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.dreaminco...wtopic52374.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.
Was This Post Helpful? 0
  • +
  • -

#9 hadi_php  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 10
  • View blog
  • Posts: 382
  • Joined: 23-August 08

Posted 31 March 2009 - 09:46 AM

Ok bro thats coolest thing i ever know abt php....

that is sql injection.....

index.php

<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>


then

insert.php

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("injection", $con);
$sql="INSERT INTO inject (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";
mysql_close($con)
?>



here i use POST method......

though GET and POST method remains same......i means works same...


then i paste browser

http://localhost/sql/insert.php?value=bwahaha


then i record added....in sql value 0

look like this

Posted Image


ohh......i use first name as primary key.......for test
then i use this code

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


i paste it in browser.......but...itz doesnt delete or add more........

why????????

i cannt understand.......i m using XAMPP ...... can any one plz telll
Was This Post Helpful? 0
  • +
  • -

#10 hadi_php  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 10
  • View blog
  • Posts: 382
  • Joined: 23-August 08

Posted 31 March 2009 - 09:52 AM

in this link

http://www.dreaminco...snippet1428.htm

i found

/*
Function: sql_sanitize( $sCode )
Description: "Sanitize" a string of SQL code to prevent SQL injection.
Parameters: $sCode: The SQL code which you wish to sanitize.
Example: mysql_query('UPDATE table SET value="' . sql_sanitize("' SET id='4'") . '" WHERE id="1"');
Requirements: PHP version 4 or greater
*/
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
}



where i use it ... i mean in which page.......

or only

mysql_query('UPDATE table SET value="' . sql_sanitize("' SET id='4'") . '" WHERE id="1"');


this code works....?
Was This Post Helpful? 0
  • +
  • -

#11 dangmnx  Icon User is offline

  • D.I.C Regular

Reputation: -1
  • View blog
  • Posts: 428
  • Joined: 10-April 09

Posted 17 May 2009 - 09:47 AM

alright, so here is my code, i would like to know what the problem is? i thought it was good, but one of the mods here said its still opening for sql injection.

Here is what i have, and on all the pages on my website, i simply add an include ('functions.php'); anyway to improve this? thanks!

<?php
include ('connect.php');
?>

<?php
function sanitize($value)
{
	if(is_array($value))
	{
		$value = array_map('sanitize', $value);
	}
	else
	{
		if(function_exists("mysql_real_escape_string"))
		{
			$value = mysql_real_escape_string($value);
		}
		else
		{
			$value = addslashes($value);
		}
	}
	return $value;
}
$_POST = array_map('sanitize', $_POST);
$_GET = array_map('sanitize', $_GET);
$_SESSION = array_map('sanitize', $_SESSION);
$_REQUEST = array_map('sanitize', $_REQUEST);
$_COOKIE = array_map('sanitize', $_COOKIE);
$$_FILES = array_map('sanitize', $_FILES);
?>


Was This Post Helpful? 0
  • +
  • -

#12 Wimpy  Icon User is offline

  • R.I.P. ( Really Intelligent Person, right? )
  • member icon

Reputation: 159
  • View blog
  • Posts: 1,038
  • Joined: 02-May 09

Posted 24 May 2009 - 06:53 AM

You would want to sanitize everything you put into any query sent to the database server that is not hard coded in the script! It doesn't matter if the query is to retrieve information or to insert information, everything has to be sanitized and nothing can be trusted! It's that simple! :)

View Postdidgy58, on 25 Nov, 2007 - 11:52 PM, said:

so would it go something like this
$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

Was This Post Helpful? 0
  • +
  • -

#13 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3515
  • View blog
  • Posts: 10,140
  • Joined: 08-June 10

Posted 06 July 2010 - 09:16 PM

nothing beats Prepared Statements, when it comes to preventing SQL Injections.
Was This Post Helpful? 0
  • +
  • -

#14 Blueorb  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 17
  • Joined: 03-July 10

Posted 15 July 2010 - 10:05 AM

View PostDormilich, on 06 July 2010 - 08:16 PM, said:

nothing beats Prepared Statements, when it comes to preventing SQL Injections.


Okay, I can understand why it would be far more effective than using a PHP function. Now, could you, or anyone else that understands this, possibly create a simple example of how to use a prepared statement with PHP?

Thanks in advance :)
Was This Post Helpful? 0
  • +
  • -

#15 Valek  Icon User is offline

  • The Real Skynet
  • member icon

Reputation: 542
  • View blog
  • Posts: 1,713
  • Joined: 08-November 08

Posted 15 July 2010 - 02:16 PM

That's actually already been done. We do need one on PDO though. I can handle it unless Dormilich would like to do it.

This post has been edited by Valek: 15 July 2010 - 02:16 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2