Pages

Wednesday, April 19, 2017

Bug Bounty - Remote Code Execution in Magento 1.x

Magento is a popular ecommerce solution written in PHP. It is widely used for web shops both large and small. The most current product is Magento 2 however, Magento 1.x is still supported and widely used since the upgrade path for a heavily customised sites is largely unclear.

Both version 2 and version 1 of magento make use of the Zend framework for some functionality including the sending of email. Recently issues were found in multiple PHP frameworks which wrap PHPs native mail function.

The attacks on mail() rely on an attacker being able to set the from address on an email which then gets passed to sendmail as the envelope sender of -f argument. In magento, one area where a user can set the address from which an email originates is the Send a Product to a Friend functionality.


This is meant to allow logged in customers to send an email to a friend about a product they think they may be interested in. To prevent abuse it is normally only for logged in customers and the admin can set limits on the number of emails sent per hour etc. This functionality is on by default but often custom designs will remove the link from the product page itself in favour of social media buttons.

By default magento uses the supplied email address to set the From: header on the sent email only. However, within the magento admin backend is a setting labelled  'Set Return-Path' this does indeed set the return path header in email but it also sets the sender via a -f flag passed directly to sendmail.

Code from app/code/core/Mage/Core/Model/Email/Template.php

        if ($returnPathEmail !== null) {
            $mailTransport = new Zend_Mail_Transport_Sendmail("-f".$returnPathEmail);
            Zend_Mail::setDefaultTransport($mailTransport);
        }

Dawid Golunski disclosed vulnerabilities in several wrapper scripts for PHP's mail function which used the from address to set the sender address on sendmail. The problem comes that several valid forms of email address can be used to escape the sendmail command and set additional flags on the sendmail operation. One such flag is the -X log flag which writes out to a log file at a path specified as an argument. It is worth noting that the flag used in the attack will only work if the target server is running sendmail and not postfix's sendmail compatibility interface, which is more common. This will accept the -X log flag to maintain compatbility but just ignores it.

 Both the from email addresses and that of the recipient are validated as being of a valid format.
However the local part of an email address in particular can contain more than is normally expected and still be valid according to the spec. This is because of the general rule that only the final email server should parse the local part of an email address. There are several valid email address formats that are surprising such as

"dave"@example.com

This allows PHP code from the user input to be included in the email and hence the log file. If the log file is named with a PHP extension and placed somewhere in the web root then the attacker can navigate to the log file and the PHP code will be executed.

e.g. "dave\" -oQ/tmp/ -Xmedia/log.php  some"@test.com

One thing that makes this attack, marginally, more difficult but much more fun is that the users message is escaped before being included in the email and hence log file. This turns any "<" characters, which are necessary for PHP code tags, into their html equivalents &lt;  This means it is not possible to include executable PHP code as part of the message. But the sendmail log file format helpfully quotes the email address in "<" and also removes the double quotes, so starting an email address ?php will create a valid PHP tag when shown in the log file!

For example an email address of "?php echo 'hello'; "@example.com  will get converted into <?php echo 'hello'; @example.com>


A PHP closing tag cannot be created by the same method however. The email address validation will not accept a domain ending in a "?" character and so the logfile quoting will not form a ?> tag for us.
The last piece of the puzzle is the __halt_compiler() PHP function. This means that PHP code parsing will end and the rest of the log file does not need to be valid PHP code. This is important since complete parsing of syntax happens before any code is executed.

Here is a short python script to execute the entire attack.


The fix applied by Magento as patch  SUPEE-9652 was to add email validation to the parameters before calling PHP's mail() function this prevents email address of the form "dave"@example.com being used since the -f flag is already prefixed and -f"dave"@example.com fails validation.

Magento very generously paid $3000 for this bug. While possibly not the most creative attack the high value reward reflects the seriousness of RCE and the value Magento place on customers security.

Timeline:

DateActivity
2017-01-09 Issue Reported via Bugcrowd
2017-01-13 Issue triaged at Bugcrowd and sent to Magento
2017-01-13 Magento Issues security advice to disable Set Return-Path
2017-02-7 Magento Issues security patch supee-9652 https://magento.com/security/patches/supee-9652
2017-02-13 Magento marks issue as resolved pays bug bounty $3000

Monday, September 7, 2015

MD5 collisions in ssh keys


You can insert MD5 collision blocks in many data formats and if you do it right the result will be 2 objects that differ but which when passed through MD5 have the same hash value.

MD5 hashes were used as a unique fingerprints in openssh right up until version 6.8  released 2015-03-18. The idea behind public key fingerprints is that as a client you should be able to uniquely identify the public key of a server you are connecting to. Your client will show you the fingerprint of the public key and hopefully you will recognise it. To aid this you can set your ssh client to draw you a pretty piece of random art based on the hash giving you a visual clue if something has changed.


Host key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48
+--[ RSA 2048]----+
|        .        |
|       + .       |
|      . B .      |
|     o * +       |
|    X * S        |
|   + O o . .     |
|    .   E . o    |
|       . . o     |
|        . .      |
+-----------------+

That is an example of connecting to github. You can check that fingerprint here.

MD5 is no longer considered collision resistant and in fact it is relatively simple to insert collisions in any binary format. This means you can create two ssh public keys that will have the same fingerprint in MD5 and same random art image. All we need to do is take a pre generated ssh public key cut out 128 bytes out of the modulus and replace it with a pair of collision blocks

Here are a couple of 2048 bit public key files to which this technique has been applied:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD74ICRUoaAXkRwqGW51botLrFygSC1SN3C7NR6cfFmpSdRuXZt6d20+GvAzOQKJpPTItK3YRjds1izapAqSM6o/BYWOikTKLHgzJ2s5Lwm6MZnPsnRJ9o9KbnXCytCrj3wFCcay0Re+TJrlPvXggFZlane2yMit2rWx/Fbly44wNzsJLIGTIhsz6UnfmR7Wi7GfiMZ2p48xn3rSHJ3lNPTOzWfg3PFgc2YftzUow1TQ5xaamyPRD/UOXBOj2pfCp75v3TWDwwq3qliBV6pxUhe/ou8ut1zaRET5VTN4kFNziQZoxY4WVmCnCJxjBPt71hM9VzoujZggRNXct8uPdri hostname

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD74ICRUoaAXkRwqGW51botLrFygSC1SN3C7NR6cfFmpSdRuXZt6d20+GvAzOQKJpPTItK3YRjds1izapCqSM6o/BYWOikTKLHgzJ2s5Lwm6MZnPsnRJ1o+KbnXCytCrj3wFCcaS0Re+TJrlPvXggFZlane2yMit2rWx/FbFy44wNzsJLIGTIhsz6UnfmR7Wi7GfiMZ2p68xX3rSHJ3lNPTOzWfg/PFgc2YftzUow1TQ5xaamyPRD/UOXBOj2pfCp75v3TWDwwq3qliBV6pxUhe/ou8ut1zaRET5VTN4kFNziQZoxY4WVmCnCJxjBPt71hM9VzoujZggRNXct8uPdri hostname
Despite looking pretty much identical they do in fact have different moduli. To check the fingerprint you can use ssh-keygen.
$ ssh-keygen -l -E MD5 -v -f 1.pub
2048 MD5:9e:a0:13:86:e0:40:06:59:70:84:b3:7e:57:1a:5d:1d hostname (RSA)
+---[RSA 2048]----+
|+O+       .E.    |
|*.       . .     |
|oo    . .        |
|+. . . o         |
|... o = S        |
| . o = o .       |
|  . +   o        |
|     .           |
|                 |
+------[MD5]------+

$ ssh-keygen -l -E MD5 -v -f 2.pub
2048 MD5:9e:a0:13:86:e0:40:06:59:70:84:b3:7e:57:1a:5d:1d hostname (RSA)
+---[RSA 2048]----+
|+O+       .E.    |
|*.       . .     |
|oo    . .        |
|+. . . o         |
|... o = S        |
| . o = o .       |
|  . +   o        |
|     .           |
|                 |
+------[MD5]------+

To prove they are not the same try replacing MD5 in the above command with anther hash algorithm like SHA1 or SHA256.

The problem is after messing with the moduli they almost certainly don't have two prime factors of length ~ root n and even if they did I have no idea what it might be without trying to factor them which is hard. So effectively they now have no private key which makes them useless. They do in fact have trival factors which makes them doubly useless.


Is there a way to insert a collision into a key and still maintain basic RSA functionality?



Well it turns out this at least partially quite simple too. You see following our collision blocks we can put what ever additional value of the modulus we like as long as it's the same in both keys. So if we imagine the modulus being made up of three parts concatenated together A|B|C,  A and B are essentially fixed but we can adjust C until we find an n which meets the RSA requirement that 

n = A|B|C = p .q 

Where p and q are prime and of length ~ half that of n. The best way I found to do this is to generate a random C, generate a random prime p of the correct length, divide our n made up of A|B|C by p to get the nearest integer q. Then test q to see is prime. If is we can move on  however it is very unlikely that A|B|C will divide exactly by p and q without remainder. But if we multiply our p and q together they will quite likely give us a new n which can be written in the form A|B|D where D is a new number. This n still has the collision blocks B in it and we have the two prime factors p and q. The whole process takes a few seconds to run on a normal laptop. It helps to have a larger public key and so a longer C to mess around with so I have used 4096 bit public keys.

With p and q we can reconstruct the ssh private key to match public key we just created.



What about the other private key?Here we face a pretty much insurmountable problem. The value at the end of the modulus following the collision blocks needs to be the same in both public keys. However, in order to be able to build a private key for the modulus we would need to know two prime factors the likelihood of finding two is extremely small. 


So this attack is impractical?

Yes as far as I can tell collisions in ssh keys of this sort don't throw up any security concerns. Hopefully you are all running newer versions of openssh and now comparing keys with sha256 anyway.

Tuesday, July 7, 2015

Talk Talk

In June I gave talks at both BSides London and the Dutch PHP Conference on the subject of hash functions. I really enjoyed both experences and they both helped me improve my public talking.

At Bsides London I was part of the rookie track which meant I got an excellent mentor in the shape of Yiannis Chrysanthou. It also meant I only had 15 minutes to cram something interesting into which was good as it made me concentrate on the important parts
The Dutch PHP Conference or DPC is a conference I have attended twice before. This year there was no way I could go not as a speaker as they covered travel and accommodation as well as entry to the conference. It was again an excellent conference with great organisation and venue.