Hash Length Extension in HTMLPurifier

HTMLPurifier is a PHP library that helps to protect against XSS by filtering bad HTML and only allowing harmless markup. Recently a new version of HTMLPurifier has been released that fixes a hash length extension issue that I reported some time ago.
Hash length extension is a crypto attack against algorithms based on Merkle-Damgard construction (md5, sha1, etc) that allows to inject arbitrary characters into the signed data without knowing the secret key. A typical vulnerable piece of code looks like this:

if hash(secret + value) == signature:

With hash length extension we can append our data to the “value” and generate such a new signature that will satisfy the expression above. More information on this kind of attack can be found in this great article.

One of HTMLPurifier’s filters, namely URIFilter.Munge, can rewrite links to some custom address. It has also an ability to generate signatures that will protect these links from altering. However this is done in a way prone to hash length extension:

if ($this->secretKey) $this->replace['%t'] = sha1($this->secretKey . ':' . $string);

Web applications that rely on this signature to check the links, for example in URL redirectors or before placing them in the DB, may be vulnerable (for example Invision Power Board), because arbitrary data can be appended despite unknown secret.

Now HTMLPurifier uses secure HMAC-SHA256 to generate and verify signatures. Upgrade to 3.6.0 and be safe.

Radamsa Fuzzer Extension for Burp Suite

Radamsa is a cool tool that combines a set of fuzzers which generate data based on input string. You can feed it a PDF file for example and Radamsa will produce a bunch of PDF-alike documents that are fuzzed in all imaginable forms. Just see this:

$ echo "test123" | radamsa -n 10

Perfect for looking for all kinds of buffer overflows. And this tool can be especially useful combined with Burp Suite, that is why here is quick and dirty extension that enables you to use Radamsa to generate Burp Suite’s Intruder payloads:
Снимок экрана от 2013-06-24 21:25:01
Grab the code here: https://github.com/Raz0r/burp-radamsa

DEFCON CTF 2013 Quals “grandprix” Writeup

This time at DEFCON CTF quals there was a special task category, namely OMGACM or competitive programming. Here is a solution to OMGACM 3 task. We have a remote host that offers to play a race game:

Connected to grandprix.shallweplayaga.me.
Escape character is '^]'.
Use 'l' and 'r' to move. Don't crash.
Press return to start

OK, we send ‘\n’ to start and see a 5×8 track with different obstacles: More »

CONFidence 2013: PHP Object Injection Revisited

PHDays 2013 CTF “Blade” Writeup

We have a simple form with login and password. There is an SQL injection, but a WAF blocks any attempt to bypass it. First step to solve this task was to reveal the contents of the script by requesting index.phps:

include 'flag.php';

if(!isset($_POST['username']) || !isset($_POST['password'])) {
	print <<<FORM
<form method=POST>
<input type=text name=username></input>
<input type=password name=password></input>
<input type=submit></input>

$this_is_baaad = array("union", "select", "from", "where", "join", "sleep", "benchmark", ",", "(", ")");
foreach($this_is_baaad as $srsly) {
	if(stripos($_POST['username'], $srsly) !== false) {
		print "Do not try to trick me!";

$q = mysql_query("SELECT * FROM users WHERE username = '{$_POST['username']}'"); 
if(mysql_num_rows($q) == 1) { 
    $user = mysql_fetch_array($q);
    if($user['password'] == $_POST['password']) {
    	print $flag;
    } else {
    	print "Login failed!";
} else {
	print "Login failed!";

The first thing we see is that the password does not get into the SQL query, so we need to use at least UNION, but it is blocked. Guys from PPP tried time delaying heavy queries that do not rely on sleep() or becnhmark(), however the right way to solve this task is as follows. Firstly, one notices that passwords are compared using == operator, and secondly the GROUP operator is not filtered. In MySQL this operator can be used with some interesting modifier: WITH ROLLUP

The GROUP BY clause permits a WITH ROLLUP modifier that causes extra rows to be added to the summary output.

If you use column password on GROUP BY WITH ROLLUP, you will get an extra empty row. And as NULL and empty string if compared with operator == are equal it is possible to bypass the authorization using the following query:

admin' GROUP BY password WITH ROLLUP LIMIT 1 OFFSET 1-- -

Simple Machines Forum <= 2.0.3 Admin Password Reset

Simple Machines Forum is a popular web community software written in PHP. Its password reset mechanism had some issues back in 2008. The vulnerability was caused by insecure random numbers generation and was patched right after the exploit was published. This time I found a more interesting vulnerability however at Positive Technologies we didn’t manage to raise awareness of SMF developers. After continuous silence of SMF devs I am disclosing the vulnerability details but I am not going to publish the exploit.

More »

ZeroNights HackQuest ErsSma Task Writeup

ErsSma task was one the most interesting puzzles at ZeroNights HackQuest, here is detailed solution.
We have a form with a single input:

POST /missions/ErsSma/index.php HTTP/1.0
Content-Type: multipart/form-data; boundary=--------336730954
Content-Length: 99

Content-Disposition: form-data; name="login"

Password is incorrect!

What do we do here? Fuzz all the things! More »

Прокачиваем Burp Suite

Burp Suite является если не основным то, пожалуй, одним из главных инструментов пентестера. С момента выхода первого релиза Burp приобрел множество новых функций, появилась платная и бесплатная версии. Однако зачастую при проведении пентеста встроенного функционала не хватает, и в этом случае на помощь приходит Burp Extender – набор интерфейсов для расширения возможностей Burp. Сама программа написана на Java, и писать расширения предлагается также на этом языке. Тем не менее усилиями сторонних разработчиков в настоящее время появилось несколько проектов, цель которых – дать возможность создавать расширения и на других языках. Среди них:

  • Buby – позволяет писать расширения на Ruby с использованием jRuby;
  • Resty Burp – предоставляет REST/JSON-интерфейс для функционала Burp, что позволяет писать расширения на любом языке (к сожалению, работает только с платной версией Burp).
  • Jython Burp API – открывает доступ к интерфейсам Burp Extender на Jython (реализация Python на Java);

More »

Конкурс “Большой ку$h” на PHDays — райтап

Буквально пару дней назад завершился PHDays, познакомился со многими интересными людьми, в целом форум оставил самые позитивные впечатления, за что огромный респект организаторам, компании Positive Technologies. Уже появилось довольно много отчетов (shr, d0znpp, toxa, asintsov), напишу лишь о том, что больше всего запомнилось лично для меня – о конкурсе Snatch, он же “Большой ку$h”.

More »

Выполнение произвольного кода на серверах с PHP CGI

Накануне был обнаружен, пожалуй, самый эпичный баг в истории PHP. Уязвимость позволяет атакующему выполнить произвольный код, используя лишь адресную строку браузера, на любом сервере, где PHP работает как CGI. Нашла уязвимость голландская команда Eindbazen, известная по своим выступлениям на различных CTF. Хронология событий:

More »

« Previous PageNext Page »