Breaking Weak CAPTCHA in 26 Lines of Code

February 23rd, 2010

During one of our latest engagements we found a weak CAPTCHA implementation being used in the target Web application. The assessment was being performed on-site, and after identifying this vulnerability we started to talk with the CSO about how easy it would be to break it.

jxt9e4ya9ko0

The general consensus of course was “very easy”. The problem was that we were unable to find any good CAPTCHA breaking software that average joe could download and run on his computer; so I spent some minutes creating a simple Python script that returns the CAPTCHA solution for this particular implementation.

Before we dig into the script, lets analyze why this CAPTCHA is weak (might not be obvious for some readers):

  1. The letters are not rotated
  2. All letters have the same height
  3. All letters have the exact same color
  4. The letters are not deformed in any way
  5. The background noise color is the same for the whole image

Now, lets see the code that breaks this CAPTCHA:

from PIL import Image

img = Image.open('input.gif')
img = img.convert("RGBA")

pixdata = img.load()

# Clean the background noise, if color != black, then set to white.
for y in xrange(img.size[1]):
    for x in xrange(img.size[0]):
        if pixdata[x, y] != (0, 0, 0, 255):
            pixdata[x, y] = (255, 255, 255, 255)

img.save("input-black.gif", "GIF")

#   Make the image bigger (needed for OCR)
im_orig = Image.open('input-black.gif')
big = im_orig.resize((116, 56), Image.NEAREST)

ext = ".tif"
big.save("input-NEAREST" + ext)

#   Perform OCR using pytesser library
from pytesser import *
image = Image.open('input-NEAREST.tif')
print image_to_string(image)

This simple script works with ~ 90% of the CAPTCHA images created using this specific implementation. Enjoy!

andres.riancho bonsai, security , , , ,


Second w3af training @ New York

October 13th, 2009

Bonsai and NopSec have partnered to deliver the second w3af ninja training course in New York City.

The w3af ninja training course is focused on manual and automated discovery and exploitation of web application vulnerabilities using w3af. During this course you’ll also learn how to write your own exploits and customized plugins in order to achieve your goals during a web application penetration test.

This course is an intense hands-on class in which you won’t stop learning for a minute. In each practice we’ll focus on a particular type of web application vulnerability which will be analyzed and understood manually and then it’s detection and exploitation is automated using w3af.

All around the training interesting plugin code snippets will be subject to analysis and modification, which will give you great understanding of the framework and will also give you the means to automate your future web application penetration tests.

Important information

This is a great opportunity to master the w3af framework, don’t miss it!

admin bonsai, security, w3af , , , ,


Cross Site Scripting Payloads

October 13th, 2009

Most of us are tired from the usual Cross Site Scripting vulnerabilities that get reported every day in full-disclosure, so when one of our researchers found a XSS in an Open Source project, we hesitated to publish it. After some thinking, we started to realize that maybe it would be interesting to the general public to see a customized XSS payload that would exploit the Web application, which suddenly made our newly discovered XSS vulnerability much more fun.

The vulnerability that we’re going to be exploiting is a persistent cross site scripting in Achievo . For those that do not know, Achievo is a flexible web-based resource management tool for business environments. Achievo’s resource management capabilities will enable organizations to support their business processes in a simple, but effective manner. This vulnerability was found a while ago by our research team, and has been fixed in version 1.4.0.

The vulnerability is a really basic persistent XSS, where we can write virtually anything in the title of a scheduled meeting. As the meetings from a user can be seen by other users, and most interestingly administrators, the XSS can be exploited to elevate privileges in the application.

With the objective of writing the XSS payload, I developed a JavaScript export feature, that allows w3af users to export any HTTP request to JavaScript, that will reproduce the same request when a user loads the script in a browser.

w3af's JavaScript Export

Using the newly created feature, we were able to easily create a JavaScript payload, that when accessed by an Achievo administrator will perform the following tasks:

  • Create a new application profile
  • Apply administrator privileges to the profile
  • Assign the newly created profile to a common user

You can find the customized XSS payload by clicking here. In order to exploit this vulnerability, a user would need to change the first four variables in the script, upload the script to a publicly accessible web server, and then point the Cross Site Scripting to that resource. After some time, and if an Achievo administrator browses through the schedule, the configured user will elevate their privileges to administrator.

In this case it was impossible (because of the application not having that particular feature) to actually upload new files to the web server, but in many other Web applications, it would have been completely possible to create a XSS payload that would use the administrator privileges to upload a specially crafted file to the web server, which would then provide operating system access to the intruder.

With the creation of tools like w3af’s JavaScript export feature, and the huge amount of XSS vulnerabilities found every day, we think that the time for customized XSS payloads written in minutes instead of hours, has arrived!

andres.riancho security, w3af , , , ,


Web Application Security training @ FRHACK

July 29th, 2009

I’m going to be delivering a Web Application Security training at FRHACK next September 2009! FRHACK is a highly technical, non-business conference that is going to be held at Besançon, France. The training is a two day, hands-on class where the w3af project leader will train you in the techniques and methodologies needed to discover and exploit web application vulnerabilities.

Here is some extra information regarding the training,

Training name: Discovery and exploitation of web application vulnerabilities

Overview

This training course focus is on manual and automated, discovery and exploitation of web application vulnerabilities. During this course you are going to go through a series of lectures followed by hands on practice. In each practice you will find vulnerabilities to exploit, each with a different level of complexity, which will defy your understanding of the subject. After the hands on practice, a small lecture on how the vulnerability is fixed is presented, together with common errors introduced by developers in that process.

The training will also teach you how to use the most advanced tools used by professionals in the field, like w3af (developed by the trainer), the burp suite, sqlmap and many others.

Course Structure

This is a two-day course that combines lectures with increasingly difficult hands-on exercises designed to teach the attendee different ways to discover and exploit web application vulnerabilities. All course materials, and a certificate of completion will be offered. You must provide your own laptop.

Deliverables

- Training booklet with printed slides and trainer comments
- Live CD with Web Application Security Tools
- VMware image with the training environment
- w3af T-Shirt ;)

Audience

Security consultants, system and network administrators, experienced web application developers, information security officers, government agencies.

Topics Covered

  • Day One
    1. HTTP protocol review
      • Web architecture
      • HTTP headers and methods
      • HTTP authentication
      • HTTPS
      • Session management: cookies
    2. Common web server misconfigurations
      • Banners
      • Directory Indexing
      • HTTP authentication
      • HTTP method restrictions
    3. Common development and configuration errors
      • HTML comments and versioning
      • File inclusions
      • Backup and local database files
      • Hidden HTML Fields
      • Path Disclosure and directory enumeration
      • Exceptions and error messages
    4. Types of analysis
      • Static code analysis, black box testing and gray box testing:
      • Definitions
      • Vulnerabilities that can be detected
      • Vulnerabilities that CAN’T be detected
    5. Web Application Vulnerabilities
      • Reverse engineering of Java applets y Flash movies
      • Local file read
      • Local file inclusions
      • Path Traversal and Null Bytes
      • Remote file inclusions
      • Cross Site Scripting (XSS)
      • Cross Site Tracing
      • Cross Site Request Forgeries / Session Riding
      • HTTP Response Splitting
  • Day Two
    1. Web Application Vulnerabilities
      • Uncommon attack vectors
      • LDAP Injection
      • OS Commanding
      • SQL Injection:
        • Enumeration of tables and columns
        • Execution of queries and stored procedures
        • Creation of files
        • Execution of OS commands
      • Blind SQL Injection
    2. Web application privilege escalation
      • Session handling
      • Logical vulnerabilities
    3. Countermeasures
      • mod_security
      • Hardening for Java
        • HDIV
        • Spring Security
      • PHP hardening:
        • Secure configuration parameters
        • GRASP
        • PHP-IDS

andres.riancho bonsai, conferences , , , ,


Not the average SQL Injection

July 19th, 2009

SQL Injections are one of the most common and most critical Web application vulnerabilities that can be identified during a Web Application Penetration Test. SQL injections can occur in any part of a SQL query, but they usually occur in the “where_definition” section, to clarify what I’m talking about, here’s the syntax definition for the SELECT statement for MySQL:

SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr, ...
[INTO OUTFILE 'file_name' export_options
| INTO DUMPFILE 'file_name']
[FROM table_references
[WHERE where_definition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_definition]
[ORDER BY {col_name | expr | position}
[ASC | DESC] , ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[FOR UPDATE | LOCK IN SHARE MODE]]

While performing some vulnerability research in e-commerce Web applications, Ryan Dewhurst (ryan@bonsai-sec.com) found a rather uncommon SQL Injection vector in the “col_name” section of the SELECT query, which at first looks like the average SQL Injection, but when actually trying to exploit it we discovered that it was more difficult than expected. This is the code snippet for the vulnerability, were we only control the $sort_order value:

$userlog = db_get_array("SELECT change_id, action, timestamp,
                         amount, reason FROM points_table
                         WHERE user_id = ?i ORDER BY $sort_by
                         $sort_order $limit", $user_id);

First of all, no SQL Injection tool works with this type of SQL injection. The reason is that they all assume that they are going to be injecting in the where_definition part of the query, and in this case that assumption is false. So we went back to the SELECT syntax, and we found that we had not much space to play:

[ORDER BY {col_name | expr | position}
[ASC | DESC] , ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[FOR UPDATE | LOCK IN SHARE MODE]]

The first idea was to use a UNION clause in order to join two different queries, the one controlled by the web application, and the other controlled by us; which seemed to be a good idea, but a flawed one also:

  • select 1,2,3 union select 4,5,6 Works perfectly.
  • select 1,2,3 order by 1 ASC union select 4,5,6 Throws an "Incorrect usage of UNION and ORDER BY error."
  • (select 1,2,3 order by 1 ASC) union (select 4,5,6) Works perfectly, but we can't add the "(" at the beginning of the query.

UNION was out of the picture.

Without even noticing that I was testing something syntactically incorrect, I tried to write a file to disk using “INTO OUTFILE”, and surprisingly enough, it worked. But the problem is that we can’t control the contents of the file, because in this particular Web application we had no control of the contents of the points_table, so once again we’re were we started because we can’t write a PHP shell to disk.

So the next step was to find a way to execute a SELECT statement after an ORDER BY, the best thing that we could find was to inject a sub-SELECT statement in the col_name section of the order by. Finally the SQL injection ended up like this:

,(SELECT BENCHMARK(1000000,MD5(1)) FROM points_table where
CURRENT_USER() like 'root@localhost' limit 1)

Which makes,

SELECT change_id, action, timestamp, amount, reason FROM
       points_table WHERE user_id = i ORDER BY timestamp,
       (SELECT BENCHMARK(1000000,MD5(1)) FROM points_table
        where CURRENT_USER() like 'root@localhost' limit 1)

The only problem is that this injection only works if the first SELECT statement actually has more than one row to order (this is because of MySQL performance enhancements). So to be able to exploit this particular SQL injection, we had to buy two items from the e-commerce store in order to add a couple of rows to the points_table, which would then trigger the sub-select in the order by section of the query.

The above injection can be modified to perform almost any query to the database, which leads to total e-commerce web application compromise.

The conclusion is simple: while automated tools can help is in many cases, an experienced security professional can never be replaced.

andres.riancho security ,