SQL Injections

Joined
Sep 9, 2005
Messages
316
Reaction score
8
Location
RO-mania
Introduction
When a machine has only port 80 opened, your most trusted vulnerability scanner cannot return anything useful, and you know that the admin always patch his server, we have to turn to web hacking. SQL injection is one of type of web hacking that require nothing but port 80 and it might just work even if the admin is patch-happy. It attacks on the web application (like ASP, JSP, PHP, CGI, etc) itself rather than on the web server or services running in the OS.

This article does not introduce anything new, SQL injection has been widely written and used in the wild. I wrote the article because i would like to document some of users to test the server SQL injection security and i hope that it may be of some use to others. You may find a trick or two but please check out the RageZone Rulez!

SQL injection.
One of the most common problems with security in web applications is SQL injection. To begin with I will present this comic for you:
HurryPoker - SQL Injections - RaGEZONE Forums


The comic clearly illustrates the problems with SQL injection. If you do not get it, do not worry, you will in just a moment.

SQL injections work by injecting SQL into the queries you have already written in your script. Often you will pass some sort of variable data to your queries; this data might be influenced by user input. In the above comment we might imagine that the school had a query that looks something like this:
view plaincopy to clipboard

Code:
   1. $sql = "INSERT INTO Students (name) VALUES ('{$_POST['student_name']}')";  

$sql = "INSERT INTO Students (name) VALUES ('{$_POST['student_name']}')";
The above snippet works. As long as users input data that conforms to an expected format. Now, the mother in the comic did not provide expected data, rather she injected an entire additional query into the existing query. Let's take a look at how the query looks when we enter the string given by the mother:
view plaincopy to clipboard

Code:
  1. INSERT INTO students (name) VALUES ('Robert'); DROP TABLE Students;--')  

INSERT INTO students (name) VALUES ('Robert'); DROP TABLE Students;--')

(Note: PHP does not support stacking queries with all DBMSs. MySQL in particular)

As you probably know, a semi-colon ends a query and most times it is actually required, but PHP just adds it automatically if you omit it. Therefore, by closing the string and finishing the query by entering the closing parenthesis and a semi-colon we will be able to add an additional query that drops the student table. The two hyphens at the end make whatever comes after it a comment, so whatever remaining characters that might have been in the original query will simply be ignored.

It should not take too much brain power to figure out why this is a bad thing. Malicious users will basically be able to execute any kind of queries they would like to. This can be done for various purposes. It could be retrieving confidential information or destroying your data just to name a few.
3.1. Protecting your script from SQL injections

Fortunately, protecting yourself from SQL injections is rather easy. It is just a matter of calling a single function which make data safe for use in a query. How you should do this depends on which PHP extension you are using. Many people use the regular mysql extension, so let us start with that one. That particular extension has a function called mysql_real_escape_string(). Let us take a look at how that one works with a simple example that illustrates its usage:
view plaincopy to clipboard

Code:
   1. <?php  
   2. $db = mysql_connect('localhost', 'username', 'password');  
   3. mysql_select_db('school', $db);  
   4.   
   5. $studentName = mysql_real_escape_string($_POST['student_name'], $db);  
   6.   
   7. $queryResult = mysql_query("INSERT INTO Students (name) VALUE ('{$studentName}')");  
   8.   
   9. if ($queryResult) {  
  10.     echo 'Success.';  
  11. }  
  12. else {  
  13.     echo 'Insertion failed. Please try again.';  
  14. }  
  15. ?>  

<?php $db = mysql_connect('localhost', 'username', 'password'); mysql_select_db('school', $db); $studentName = mysql_real_escape_string($_POST['student_name'], $db); $queryResult = mysql_query("INSERT INTO Students (name) VALUE ('{$studentName}')"); if ($queryResult) { echo 'Success.'; } else { echo 'Insertion failed. Please try again.'; } ?>
As you see, doing it is incredibly easy yet many people fail to do this and only find out when it is too late. Other extensions support something called prepared statements. An example of a such extension is PDO (PHP Data Objects). Let us take a look at how that works:
view plaincopy to clipboard

Code:
   1. <?php  
   2. $db = new PDO('mysql:host=localhost;dbname=school', 'username', 'password');  
   3.   
   4. $stmt = $db->prepare('INSERT INTO Students (name) VALUES (?)');  
   5.   
   6. try {  
   7.     $stmt->execute(array($_POST['student_name']));  
   8.     echo 'Success.';  
   9. }  
  10. catch(PDOException $e) {  
  11.     echo 'Insertion failed. Please try again.';  
  12. }  
  13. ?>  

<?php $db = new PDO('mysql:host=localhost;dbname=school', 'username', 'password'); $stmt = $db->prepare('INSERT INTO Students (name) VALUES (?)'); try { $stmt->execute(array($_POST['student_name'])); echo 'Success.'; } catch(PDOException $e) { echo 'Insertion failed. Please try again.'; } ?>

If you have many fields you need to use in your query then it might be a little difficult remembering the order of all these different question marks which act as place holders for the data. An alternate syntax is using named parameters. In our case it would look like this:
view plaincopy to clipboard

Code:
   1. <?php  
   2. $db = new PDO('mysql:host=localhost;dbname=school', 'username', 'password');  
   3.   
   4. $stmt = $db->prepare('INSERT INTO Students (name) VALUES (:name)');  
   5.   
   6. try {  
   7.     $stmt->execute(array('name' => $_POST['student_name']));  
   8.     echo 'Success.';  
   9. }  
  10. catch(PDOException $e) {  
  11.     echo 'Insertion failed. Please try again.';  
  12. }  
  13. ?>  

<?php $db = new PDO('mysql:host=localhost;dbname=school', 'username', 'password'); $stmt = $db->prepare('INSERT INTO Students (name) VALUES (:name)'); try { $stmt->execute(array('name' => $_POST['student_name'])); echo 'Success.'; } catch(PDOException $e) { echo 'Insertion failed. Please try again.'; } ?>

Obviously, in our case this would not have any benefits, but as I said, if you have many parameters then you might find that more useful. There can be other reasons why using prepared statements would be useful, but I will leave that to research for yourself.

The mysqli (MySQL improved) extension has support for prepared statements as well, so if you are using that then check out its documentation to see the syntax.

The golden rule regarding this is that nothing is to be trusted and all data should be escaped.

Additionally, I mentioned earlier that users should not get information from error messages. Not only is it irrelevant, but it may also be information that may aid people with malicious purposes. You may sometimes be told that you should add or die(mysql_error()) to the end of your query calls to functions like mysql_query(). However, you should not do that. By doing that you are no longer using PHP's error and exception handling functionality and you remove the opportunity to control whether errors should be displayed or not. In my opinion the best solution would be to use PHP's exceptions. If you do not want to do that then at least do something like or trigger_error('Query failed: '. mysql_error()). By doing that you are utilizing PHP's built-in functionality and you will be able to use the methods discussed under Error Reporting. Moreover, ending script execution with die() is simply bad practice. You will not be able to give the user a proper error page and you will not be able to do any cleaning up for the rest of the script.

Source: phpfreaks.com

How do you test if it is vulnerable?

Oky i made a littel test for your sql!
How is work?
Simple!
Go to web page => Register new Account => Add account info!
BUT! BUT in e-mail add this code:
Code:
'';shutdown;--
Then click: Create New Account!
If your web is not secured in 5---10 seconds your SQL will sleep!SQL SHOTDOWN!
Or you can do same sh*t to: web page =>Lost Password=> Add account info! in e-mail add this code:
Code:
'';shutdown;--
For example view images:

BEFORE:
HurryPoker - SQL Injections - RaGEZONE Forums


AFTER:
HurryPoker - SQL Injections - RaGEZONE Forums


Credits: hackalin , HurryPoker

How to avoid SQL Injection?
Filter out character like single quote, double quote, slash, back slash, semi colon, extended character like NULL, carry return, new line, etc, in all strings from:
- Input from users
- Parameters from URL
- Values from cookie

For numeric value, convert it to an integer before parsing it into SQL statement. Or using ISNUMERIC to make sure it is an integer.

Change "Startup and run SQL Server" using low privilege user in SQL Server Security tab.

Delete stored procedures that you are not using like:

master..Xp_cmdshell, xp_startmail, xp_sendmail, sp_makewebtask

The information has been provided: HurryPoker
 
Last edited:
Re: [Info]SQL injections

doing for nothing if thei protect the sql....
Man, i did test my SQL Security without doing what you told...and it didn't shutdown nothing...is still runing like a rochet...so means that my sql is secure already ? :) cas it din't stop from 10 minutes when i tested...
 
Re: [Info]SQL injections

Good you are showing how injection works, but could you please tell how to avoid injection?

If not i'll have t delete this topic cus its nothing but a guide how to shut down sql on other ppl servers.
 
Re: [Info]SQL injections

Good you are showing how injection works, but could you please tell how to avoid injection?

If not i'll have t delete this topic cus its nothing but a guide how to shut down sql on other ppl servers.

No No No!
Is Show how to Test the Server Security in Website!
If you Use a noob website your server will be easy to hack!

I recomend MuWeb0.3 or MuWeb0.9with xampp
There are many GUIDEs , How to protect your SQL!

http://forum.ragezone.com/showthread.php?t=402037

http://forum.ragezone.com/showthread.php?t=56696

http://forum.ragezone.com/showthread.php?t=458163

Topic EDIT NOW!LooK Up!
 
Re: [Guide]SQL injections

i tryed that command on my website i'm creating and nothing :), the sql dosen't stop...and i putet on email field :P...so my website is protected anti sql injection :).nice, and i use apache by the way :P not xampp :).
 
Re: [Guide] SQL injections

i find this code in SecuredMuWeb0.8 !
its a fake?? or ...

PHP:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$time = date("l dS of F Y h:i:s A");
$script = $_SERVER[PATH_TRANSLATED];
$fp = fopen ("D:/MuServer/[WEB]SQL_Injection.txt", "a+");

$sql_inject_1 = array(";","'","%",'"'); #Whoth need replace
$sql_inject_2 = array("", "","","""); #To wont replace
$GET_KEY = array_keys($_GET); #array keys from $_GET
$POST_KEY = array_keys($_POST); #array keys from $_POST
$COOKIE_KEY = array_keys($_COOKIE); #array keys from $_COOKIE
/*begin clear $_GET */
for($i=0;$i<count($GET_KEY);$i++)
{
$real_get[$i] = $_GET[$GET_KEY[$i]];
$_GET[$GET_KEY[$i]] = str_replace($sql_inject_1, $sql_inject_2, HtmlSpecialChars($_GET[$GET_KEY[$i]]));
  if($real_get[$i] != $_GET[$GET_KEY[$i]])
  {
  fwrite ($fp, "IP: $ip\r\n");
  fwrite ($fp, "Method: GET\r\n");
  fwrite ($fp, "Value: $real_get[$i]\r\n");
  fwrite ($fp, "Script: $script\r\n");
  fwrite ($fp, "Time: $time\r\n");
  fwrite ($fp, "==================================\r\n");
  }
}
/*end clear $_GET */
/*begin clear $_POST */
for($i=0;$i<count($POST_KEY);$i++)
{
$real_post[$i] = $_POST[$POST_KEY[$i]];
$_POST[$POST_KEY[$i]] = str_replace($sql_inject_1, $sql_inject_2, HtmlSpecialChars($_POST[$POST_KEY[$i]]));
  if($real_post[$i] != $_POST[$POST_KEY[$i]])
  {
  fwrite ($fp, "IP: $ip\r\n");
  fwrite ($fp, "Method: POST\r\n");
  fwrite ($fp, "Value: $real_post[$i]\r\n");
  fwrite ($fp, "Script: $script\r\n");
  fwrite ($fp, "Time: $time\r\n");
  fwrite ($fp, "==================================\r\n");
  }
}
/*end clear $_POST */
/*begin clear $_COOKIE */
for($i=0;$i<count($COOKIE_KEY);$i++)
{
$real_cookie[$i] = $_COOKIE[$COOKIE_KEY[$i]];
$_COOKIE[$COOKIE_KEY[$i]] = str_replace($sql_inject_1, $sql_inject_2, HtmlSpecialChars($_COOKIE[$COOKIE_KEY[$i]]));
  if($real_cookie[$i] != $_COOKIE[$COOKIE_KEY[$i]])
  {
  fwrite ($fp, "IP: $ip\r\n");
  fwrite ($fp, "Method: COOKIE\r\n");
  fwrite ($fp, "Value: $real_cookie[$i]\r\n");
  fwrite ($fp, "Script: $script\r\n");
  fwrite ($fp, "Time: $time\r\n");
  fwrite ($fp, "==================================\r\n");
  }
}

/*end clear $_COOKIE */
fclose ($fp);
?>
<?
error_reporting(E_ALL ^E_NOTICE ^E_WARNING);

$muweb['connection'] = 'mssql';

$muweb['localhost'] = 'xxx.xxx.xxx.xxx';

$muweb['dbhost'] = 'xxx.xxx.xxx.xxx';

$muweb['database'] = 'MuOnline';

$muweb['dbuser'] = 'sa';

$muweb['dbpassword'] = 'sql_pass';


require("includes/muweb.php");

?>


@ for hackalin :)) its "n" methods for inject !

new example from TosaMu
08-10-2008 10:13:26 88.232.213.113 [ ][ mu.dorin1.ro/index.php?op=reg ][ (ALEMCİ27)(ALEMCİ(564564456)(6564656454)(PİSKOPATOKAN_27_HOTMAİL,COM)(27500)(NE)(NE)(Submit)( ] 08-10-2008 10:13:56 88.232.213.113 [ ][ mu.dorin1.ro/index.php?op=reg ][ (ALEMCİ27)(ALEMCİ(1990)(1990)(PİSKOPATOKAN_27_HOTMAİL,COM)(27500)(NE)(NE)(Submit)( ] 08-10-2008 10:15:43 88.232.213.113 [ ][ mu.dorin1.ro/index.php?op=reg ][ (ALEMCİ27)(ALEMCİ(7894561230)(7894561230)(PİSKOPATOKAN_27_HOTMAİL,COM)(27500)(NE)(NE)(Submit)( ]
 
Re: [Guide] SQL injections

And here is a list of SQL Injection functions...you better protect yourself against those otherwise I will be the guy destroying your noob a55 server :thumbup:
Code:
ABORT -- abort the current transaction
ALTER DATABASE -- change a database
ALTER GROUP -- add users to a group or remove users from a group
ALTER TABLE -- change the definition of a table
ALTER TRIGGER -- change the definition of a trigger
ALTER USER -- change a database user account
ANALYZE -- collect statistics about a database
BEGIN -- start a transaction block
CHECKPOINT -- force a transaction log checkpoint
CLOSE -- close a cursor
CLUSTER -- cluster a table according to an index
COMMENT -- define or change the comment of an object
COMMIT -- commit the current transaction
COPY -- copy data between files and tables
CREATE AGGREGATE -- define a new aggregate function
CREATE CAST -- define a user-defined cast
CREATE CONSTRAINT TRIGGER -- define a new constraint trigger
CREATE CONVERSION -- define a user-defined conversion
CREATE DATABASE -- create a new database
CREATE DOMAIN -- define a new domain
CREATE FUNCTION -- define a new function
CREATE GROUP -- define a new user group
CREATE INDEX -- define a new index
CREATE LANGUAGE -- define a new procedural language
CREATE OPERATOR -- define a new operator
CREATE OPERATOR CLASS -- define a new operator class for indexes
CREATE RULE -- define a new rewrite rule
CREATE SCHEMA -- define a new schema
CREATE SEQUENCE -- define a new sequence generator
CREATE TABLE -- define a new table
CREATE TABLE AS -- create a new table from the results of a query
CREATE TRIGGER -- define a new trigger
CREATE TYPE -- define a new data type
CREATE USER -- define a new database user account
CREATE VIEW -- define a new view
DEALLOCATE -- remove a prepared query
DECLARE -- define a cursor
DELETE -- delete rows of a table
DROP AGGREGATE -- remove a user-defined aggregate function
DROP CAST -- remove a user-defined cast
DROP CONVERSION -- remove a user-defined conversion
DROP DATABASE -- remove a database
DROP DOMAIN -- remove a user-defined domain
DROP FUNCTION -- remove a user-defined function
DROP GROUP -- remove a user group
DROP INDEX -- remove an index
DROP LANGUAGE -- remove a user-defined procedural language
DROP OPERATOR -- remove a user-defined operator
DROP OPERATOR CLASS -- remove a user-defined operator class
DROP RULE -- remove a rewrite rule
DROP SCHEMA -- remove a schema
DROP SEQUENCE -- remove a sequence
DROP TABLE -- remove a table
DROP TRIGGER -- remove a trigger
DROP TYPE -- remove a user-defined data type
DROP USER -- remove a database user account
DROP VIEW -- remove a view
END -- commit the current transaction
EXECUTE -- execute a prepared query
EXPLAIN -- show the execution plan of a statement
FETCH -- retrieve rows from a table using a cursor
GRANT -- define access privileges
INSERT -- create new rows in a table
LISTEN -- listen for a notification
LOAD -- load or reload a shared library file
LOCK -- explicitly lock a table
MOVE -- position a cursor on a specified row of a table
NOTIFY -- generate a notification
PREPARE -- create a prepared query
REINDEX -- rebuild corrupted indexes
RESET -- restore the value of a run-time parameter to a default value
REVOKE -- remove access privileges
ROLLBACK -- abort the current transaction
SELECT -- retrieve rows from a table or view
SELECT INTO -- create a new table from the results of a query
SET -- change a run-time parameter
SET CONSTRAINTS -- set the constraint mode of the current transaction
SET SESSION AUTHORIZATION -- set the session user identifier and the current user identifier of the current session
SET TRANSACTION -- set the characteristics of the current transaction
SHOW -- show the value of a run-time parameter
START TRANSACTION -- start a transaction block
TRUNCATE -- empty a table
UNLISTEN -- stop listening for a notification
UPDATE -- update rows of a table
VACUUM -- garbage-collect and optionally analyze a database
Enjoy!
 
Re: [Guide] SQL injections

hehe i dont whanna give all this info i just create a littel guide to test the webserver protection! damn man you give here all hack info!
 
Re: [Guide] SQL injections

hehe i dont whanna give all this info i just create a littel guide to test the webserver protection! damn man you give here all hack info!
Every good hacker knows this info.And there are many good hackers.
Learns what a hacker learns,think like a hacker thinks,and then you will understand how to protect yourself :thumbup1: I am scarred shitless of hackers.You should see the precautions I take....I impress myself on what I do not to get hacked in any ways :ott1:
 
Back