вторник, 29 апреля 2014 г.

SQL injection scanners benchmark

Positives (vulnerable)False positives (not vulnerable)Positives with unstable responseFalse positives with unstable response
Total16224114562016840
sqlmap 0.8-11128229576229
skipfish 1.81b10937378237
wapiti 2.2.1111515813443
acunetix7395010030
w3af 1.0-rc5133161981572126

Potential HTTP Headers for SQL injections

HTTP Header fields
HTTP header fields are components of the message header of requests and responses in the Hypertext Transfer Protocol (HTTP). They define the operating parameters of an HTTP transaction.
Example: Request HTTP
GET / HTTP/1.1
Connection: Keep-Alive
Keep-Alive: 300
Accept:*/*
Host: host
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16 ( .NET CLR 3.5.30729; .NET4.0E)
Cookie: guest_id=v1%3A1328019064; pid=v1%3A1328839311134
We can consider the HTTP Cookies, when are stored in databases for sessions identification, as the first potential HTTP variables which should be tested. We will see next in an example of Cookie based SQL injection. There are also other HTTP headers related to the application.

X-Forwarded-For

X-Forwarded-For is an HTTP header field considered as a de facto standard for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or load balancer.

We will see an example of this flaw basing of a form submission.
$req = mysql_query("SELECT user,password FROM admins WHERE user='".sanitize($_POST['user'])."' AND password='".md5($_POST['password'])."' AND ip_adr='".ip_adr()."'"); 
The variable login is correctly controlled due to the sanitize() method.
function sanitize($param){ if (is_numeric($param)) { return $param; } else { return mysql_real_escape_string($param); } }
Let us inspect the ip variable. It is allocating the output of the ip_addr() method.
function ip_adr() { if
(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip_adr = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip_adr = $_SERVER["REMOTE_ADDR"]; } if (preg_match("#^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}#",$ip_addr)) { return $ip_adr; } else { return $_SERVER["REMOTE_ADDR"]; } }
Obviously, the IP address is retrieved from the HTTP header X_FORWARDED_FOR. This later is controlled by the preg_match which verifies if this parameter does hold at least one IP address. As a matter of fact, the environment variable HTTP_X_FORWARDED_FOR is not properly sanitized before its value being used in the SQL query. This can lead to run any SQL query by injecting arbitrary SQL code into this field.
The simple modification of this header field to something like:
GET /index.php HTTP/1.1
Host: [host]
X_FORWARDED_FOR :127.0.0.1' or 1=1#
will lead to bypass the authentication control.


User-agent

User agent is an HTTP header field gives the software program used by the original client. This is for statistical purposes and the tracing of protocol violations. It should be included. The first white space delimited word must be the software product name, with an optional slash and version designator.
Not all applications are written to capture the user-agent data, but sometimes applications are designed to store such information (ex: shopping cart providers) to make use of it. In this case, it’s worth investigating the user-agent header for possible issues.
HTTP query example:
GET /index.php HTTP/1.1
Host: [host]
User-Agent: aaa' or 1/* 
 
Referer

Referer is another HTTP header which can be vulnerable to SQL injection once the application is storing it in database without sanitizing it. It’s an optional header field that allows the client to specify, for the server’s benefit, the address ( URI ) of the document (or element within the document) from which the URI in the request was obtained. This allows a server to generate lists of back-links to documents, for interest, logging, etc. It allows bad links to be traced for maintenance.
Example:
GET /index.php HTTP/1.1 Host: [host] User-Agent: aaa' or 1/* Referer: http://www.yaboukir.com

Attacker’s perspective?

As we all know, injection flaws are ranked the first in The OWASP Top 10 Web Application Security Risks. Attackers are increasingly seeking for injection points to get full access of your databases. No matter the injection input vector’s type, whether it’s a GET, POST, Cookie or other HTTP headers; the important for intruders is always to have at least one injection point which let them start the exploitation phase.

Manually testing Cookie based SQL injections

Sqlmap as example

Sqlmap is a popular open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers.
Sqlmap supports the HTTP cookie features so it can be useful in two ways:
  • Authentication based upon cookies when the web application requires that.
  • Detection and exploitation of SQL injection on such header values.
By default sqlmap tests all GET parameters and POST parameters. When the value of –level is set to 2 or above it tests also HTTP Cookie header values. When this value is set to 3 or above, it tests also HTTP User-Agent and HTTP Referer header value for SQL injections. It is however possible to manually specify a comma-separated list of parameter(s) that you want sqlmap to test. This will bypass the dependence on the value of –level too.

Tested HTTP parameter Level in sqlmap
GET 1 (Default)
POST 1 (Default)
HTTP Cookie 2 ≥
HTTP User-Agent 3 ≥
HTTP Referer 3 ≥

For instance, to test for GET parameter id and for HTTP User-Agent only, provide -p id,user-agent.
This is an example of how we can test the parameter named security of an HTTP Cookie of the DVWA (Damn Vulnerable Web Application).
./sqlmap.py -u 'http://127.0.0.1/vulnerabilities/sqli/?id=1&Submit=Submit#'
--cookie='PHPSESSID=0e4jfbrgd8190ig3uba7rvsip1; security=low'
--string='First name' --dbs --level 3 -p PHPSESSID
 
 
 

Туннелирование порта через SSH

Например, работаем на виртуальном хостинге, там Apache, MySQL. Хотим подключить визуальный клиент администрирования MySQL. Много есть случаев, когда было бы удобно коннектится на удаленном компьютере к его локальным портам.
Организация туннеля

Давайте попробуем подключить клиент администрирования MySQL на удаленном компьютере.

Естественно считаем, что вход по SSH по ключу уже настроен.

Тогда поднять туннель не просто, а очень просто. На своем локальном компьютере выполняем команду:
ssh -f username@remote_host -L 127.0.0.1:4306:127.0.0.1:3306 -N

Где:

-f    Говорит ssh уйти в бэкграунд
username    Имя пользователя на удаленном компьютере
remote_host    Имя или IP адрес удаленного хоста
-L 127.0.0.1:4306:127.0.0.1:3306    Пробросить тоннель с локального порта 4306 на удаленный порт 3306
-N    Не выполнять команду на удаленном хосте.
Подключение клиента

Теперь можно подключать клиента. Запускаем mysql-admin и конфигурируем его следующим образом:
Server Hostname:    127.0.0.1
Port:    4306

Пользователь и пароль - ну ясно, так как у нас сконфигурировано.

Примечание: Мы перенаправили с нашего хоста порт 4306, для того, чтобы в случае, если у нас на локальном хосте тоже работает MySQL, не мешать ему.

http://blog.swlogic.eu/2011/07/16/tunnelirovanie-porta-cherez-ssh/