Friday, April 30, 2010
Cloning jQuery UI datepicker
In case you were having problems with cloning fields with jQuery UI datepicker attached to them - solutions mentioned in the interwebs are similar to this one:
$('.cloned-input').removeClass('hasDatepicker').datepicker();
However, that did not work for me. If you happen to have a set of similar symptoms: - new datepicker is not instantiated at all
- JS errors occur while instantiating new datepicker
- even if datepicker is cloned, it refers to the old field
Solution
Either imitate datepicker('destroy') manually:$input = $('.cloned-input');
// remove still present related DOM objects
$input.siblings('.ui-datepicker-trigger,.ui-datepicker-apply').remove();
// remove datepicker object and detach events
$input
.removeClass('hasDatepicker')
.removeData('datepicker')
.unbind()
.datepicker();
or implement a different procedure:- before cloning destroy the datepicker on the base input
- clone(true)
- recreate the datepicker on base input
- use unbind() and recreate datepicker on cloned input
Friday, April 16, 2010
When overloading eval() fails
Today I encountered a small issue when decoding yet another 'crackme' challenge from Paweł Goleń. This time it turned out to be just a little bit more difficult, as Paweł:
And all I did was to replace eval('code') with code. To be more specific, that is the actual code:
Such operation usually has no side effects - after all, eval is meant to immediately evaluate the passed code. But my eval was overloaded (check my previous post to see how I achieved this) and this caused problems. What's even worse - it turned out overloaded eval will not always work as expected and you cannot avoid it!
Here we define a global variable y and we try to read the value of y from
1st case works as expected (this is window, and global y is accessed), so is the 2nd (this is img, y is local), eval() does not change the scope nor variable visibility. But eval2()suddenly sees our global variable, even though it's in the context of <img>! WTF??
So there is a slight difference between original and overloaded eval() - although the context stays the same (thanks to Function.apply I used in original overloading), variable visibility is different - so one could potentially detect that eval() is overloaded.
Luckily, malware authors are is the same position - they usually obfuscate eval call by using some intermediate function (in other words, there is eval2 = eval equivalent somewhere in their code). But still, I'd rather have a perfect emulation... Is there any?
- used some onerror handlers to run the code
- tried (unsuccessfully) to beat my function overloading
- used multi-level obfuscation
And all I did was to replace eval('code') with code. To be more specific, that is the actual code:
<img onerror="eval('code;') // ok" src="http://i.dont.exist" />
<img onerror="code; //gives errors" src="http://i.dont.exist" />
Such operation usually has no side effects - after all, eval is meant to immediately evaluate the passed code. But my eval was overloaded (check my previous post to see how I achieved this) and this caused problems. What's even worse - it turned out overloaded eval will not always work as expected and you cannot avoid it!
Eval() is special
The 'original' eval turned out to be a very special function (just like arguments being a very special array) - it has its own execution context and you cannot emulate it with any other function. See the below example:<html>
<head>
<script type="text/javascript">
var y = 'Klaatu barada nikto';
var eval2 = eval;
console.log('in global: ',y,this);
</script>
<body>
<img src="about:blank" onerror="console.log('in event handler:',y,this)">
<img src="about:blank" onerror="eval("console.log('in eval:',y,this)")">
<img src="about:blank" onerror="eval2("console.log('in eval2:',y,this)")">
</body>
</html>
Here we define a global variable y and we try to read the value of y from
- global context (<script> element)
- an event handler
- eval() function inside an event handler
- eval2() which is just a reference to 'original' eval (let's call it dummy overload ;))
1st case works as expected (this is window, and global y is accessed), so is the 2nd (this is img, y is local), eval() does not change the scope nor variable visibility. But eval2()suddenly sees our global variable, even though it's in the context of <img>! WTF??
So there is a slight difference between original and overloaded eval() - although the context stays the same (thanks to Function.apply I used in original overloading), variable visibility is different - so one could potentially detect that eval() is overloaded.
We're doomed?
I tried to overcome this using various known techniques (wrapping in anonymous function, playing with scopes etc.) but to no avail. I cannot emulate eval without getting this strange behaviour.Luckily, malware authors are is the same position - they usually obfuscate eval call by using some intermediate function (in other words, there is eval2 = eval equivalent somewhere in their code). But still, I'd rather have a perfect emulation... Is there any?
Wednesday, April 14, 2010
Beating JavaScript obfuscators with Firebug
Today I encountered a very pleasant 'crackme' challenge from Paweł Goleń. The purpose is to find out what is the purpose of demo page set up by Paweł.
Visiting this page with e.g. Firebug enabled (or with any HTTP proxy) quickly shows that a POST request is sent upon visiting. You didn't submit any form manually so it must be JavaScript sending it. So, you just need to view the source of the page to find the JS code. And this is where the fun starts. The code looks like this:
The encoded software usually tries to hack into the machine, so it can:
In JavaScript obfuscation is usually based on heavy usage of unescape, String.fromCharCode and eval functions.
Luckily, JavaScript itself, with the help of Firebug, has tools that enable you to decode such obfuscated script, so it is only a matter of time to reverse engineer it.
Here we overload widely used alert function - instead of a message box it will insert a given message to a <div id="alert"> element. Two things to note:
With this code you may start decoding the script, consistently replacing obfuscated code in HTML with decoded one coming from Firebug console. You can also insert the debugger; line anywhere in a JS to add a breakpoint.
One thing to note - when debugging malware, be sure to make it in a safe environment (e.g. a separate virtual machine, some sort of sandbox), because otherwise there is a risk you'll become its victim.
Visiting this page with e.g. Firebug enabled (or with any HTTP proxy) quickly shows that a POST request is sent upon visiting. You didn't submit any form manually so it must be JavaScript sending it. So, you just need to view the source of the page to find the JS code. And this is where the fun starts. The code looks like this:
Obfuscation
Not really readable... This code is obfuscated - modifed to make its analysis difficult. This is the technique widely used with malware software.The encoded software usually tries to hack into the machine, so it can:
- download even more code from a remote URL
- send some data to a remote (attacker) server
- exploit a browser vulnerability to execute a code on the machine
- scan the internal network
- hack into your router and convert it to a spam server
In JavaScript obfuscation is usually based on heavy usage of unescape, String.fromCharCode and eval functions.
Luckily, JavaScript itself, with the help of Firebug, has tools that enable you to decode such obfuscated script, so it is only a matter of time to reverse engineer it.
Function overloading
JavaScript is a functional language, so - in plain words - the function itself can be written to variable, passed as an argument etc. And - as a variable - it can be reassigned. So it is possible to change the behaviour of any JavaScript function. Example:<html><head>
</head>
<body><div id="alert"></div>
<script type="text/javascript">
window.alert = function() {
document.getElementById('alert').innerHTML = arguments[0]
};
alert('hello world');
</script>
</body></html>
Here we overload widely used alert function - instead of a message box it will insert a given message to a <div id="alert"> element. Two things to note:
- alert is in fact window.alert because JS in browsers has a global object named window
- arguments is an array-like object containing parameters passed to the function, so in this case it's ['hello world']
Let's decode
Analysing any obfuscated script will be much easier if you overloaded the key functions: unescape, String.fromCharCode and eval. But, for the script to actually work, our overloaded functions must call the original ones:var oldunescape = window.unescape;
window.unescape = function() {
var u = oldunescape.apply(this,arguments); // this calls the old function
console.log('unescape ', arguments, u);
return u;
}
var oldCharCode = String.fromCharCode;
String.fromCharCode = function() {
var u = oldCharCode.apply(this,arguments);
console.log('charcode ', arguments, u);
return u;
}
var oldeval = window.eval;
window.eval = function() {
var args = arguments;
console.log('eval ', arguments, u);
var u = oldeval.apply(this,arguments);
debugger; // here the debugger (e.g. Firebug) will kick in
return u;
}
With this code you may start decoding the script, consistently replacing obfuscated code in HTML with decoded one coming from Firebug console. You can also insert the debugger; line anywhere in a JS to add a breakpoint.
One thing to note - when debugging malware, be sure to make it in a safe environment (e.g. a separate virtual machine, some sort of sandbox), because otherwise there is a risk you'll become its victim.
We're finished...?
Unfortunately, that's only the first part of analyzing the software. After getting the plaintext version we need to understand what it actually does (and that's usually intentionally hidden in many functions, variables, exceptions, browser differences and strange program flow). It is hard and requires both patience and a bit of JavaScript knowledge, but it is, I think, one of the fastest and most exciting ways to learn. So, go grab your Firebugs and try for yourself - what does this page do?Friday, March 19, 2010
Hardening PHP: SQL injection - Complete walkthrough
Below are the slides from the presentation I recently gave on SQL injection on OWASP Poland Chapter meeting. The materials teach how to use prepared statements, how to escape and write secure stored procedures. Many PHP projects are covered - PDO, Propel, Doctrine, Zend Framework and MDB2. Multiple gotchas and caveats are included. I discuss why escaping is usually the wrong choice, which practices to avoid or follow and how stored procedures sometimes offer no protection at all.
I tried to make this as complete as possible, so a PHP developer could learn how to protect his applications no matter what framework / database he uses.
You could also watch video recorded from the presentation. There are already some comments on the slides on niebezpiecznik.pl (Polish), but of course feel free to add comment here.
I tried to make this as complete as possible, so a PHP developer could learn how to protect his applications no matter what framework / database he uses.
English version
SQL Injection: complete walkthrough (not only) for PHP developers [埋込みオブジェクト:http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=owasp-sql-injection-en-100317143725-phpapp02&stripped_title=sql-injection-complete-walktrough-not-only-for-php-developers]
View more presentations from Krzysztof Kotowicz.
Polish version
Kompletny przewodnik po SQL injection dla developerów PHP (i nie tylko) [埋込みオブジェクト:http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=owasp-sql-injection-100225191337-phpapp01&stripped_title=owasp-sql-injection]
You could also watch video recorded from the presentation. There are already some comments on the slides on niebezpiecznik.pl (Polish), but of course feel free to add comment here.
Wednesday, March 3, 2010
You're from Cracow and want to beat SQL injection?
Anyone interested in secure development probably knows what OWASP is. If not - it's a worldwide non-profit organization focused on web application security.
There is an upcoming OWASP Poland chapter meeting in Cracow, Poland next week. This time it is focused on secure PHP application development.
I will be giving a presentation there - it's entitled
"SQL injection: Complete walktrough (not only) for PHP developers".
We will talk a bit about the theory and demonstrate an attack. Then I'll show how to write code immune to SQL injection in various PHP frameworks, using various databases. We'll also talk about writing secure stored procedures in Oracle, MS SQL Server and MySQL. Different gothchas, bugs and tricks will be covered, so even if you think you know the subject - it will surprise you.
The meeting is totally free and no registration is required*, so if anyone wants to develop securely in PHP or deals with databases (who doesn't?), please bring your fellow developers and come. It's important - please come and let's beat the SQL injection once and for all!
I'll share the floor with Łukasz Pilorz who will talk about creating Secure PHP framework - and, given some internal details, I can assure you there's much to expect from this talk - don't miss it!
Date: 10.03.2010 (Wednesday), 17:00
Place: Compendium Centrum Edukacyjne, ul. Tatarska 5, Kraków, I piętro
Update: Read the full announcement from OWASP mailing list.
* If you're planning to go, please drop a mail to Przemysław from the link above to prepare the room for the audience.
There is an upcoming OWASP Poland chapter meeting in Cracow, Poland next week. This time it is focused on secure PHP application development.
I will be giving a presentation there - it's entitled
"SQL injection: Complete walktrough (not only) for PHP developers".
We will talk a bit about the theory and demonstrate an attack. Then I'll show how to write code immune to SQL injection in various PHP frameworks, using various databases. We'll also talk about writing secure stored procedures in Oracle, MS SQL Server and MySQL. Different gothchas, bugs and tricks will be covered, so even if you think you know the subject - it will surprise you.
The meeting is totally free and no registration is required*, so if anyone wants to develop securely in PHP or deals with databases (who doesn't?), please bring your fellow developers and come. It's important - please come and let's beat the SQL injection once and for all!
I'll share the floor with Łukasz Pilorz who will talk about creating Secure PHP framework - and, given some internal details, I can assure you there's much to expect from this talk - don't miss it!
Date: 10.03.2010 (Wednesday), 17:00
Place: Compendium Centrum Edukacyjne, ul. Tatarska 5, Kraków, I piętro
Update: Read the full announcement from OWASP mailing list.
* If you're planning to go, please drop a mail to Przemysław from the link above to prepare the room for the audience.
Wednesday, December 23, 2009
5 ways to prevent clickjacking on your website (and why they suck)
Clickjacking attack is a very nasty attack. The most common form of it is when an attacker creates a webpage and tricks the visitor to click somewhere (on a link, button, image). Attacker in the code of his website includes a victim website (like Facebook, your webmail, amazon) that is cleverly hidden from the user and placed so that a user actually clicks on a victim website. Citing the example from OWASP page on clickjacking:
Browsers nowadays use same origin policy to protect your data if you're framing or being framed from another domain (this prevents JavaScripts from talking to each other and accesing documents across the domain boundary). But JavaScript is not required for a clickjacking attack - CSS is enough. In the simplest form (e.g. used in recent Facebook users attack), you're just using a small <iframe>, and position it absolutely. The rest is just social engineering.
Our users have a few options to protect themselves. So maybe 1% of them will be "protected". But what can we - web developers do to prevent the clickjacking on our sites? Sadly, not much, but here's the list:
For example, imagine an attacker who builds a web site that has a button on it that says "click here for a free iPod". However, on top of that web page, the attacker has loaded an iframe with your mail account, and lined up exactly the "delete all messages" button directly on top of the "free iPod" button. The victim tries to click on the "free iPod" button but instead actually clicked on the invisible "delete all messages" button. In essence, the attacker has "hijacked" the user's click, hence the name "Clickjacking".The problem with clickjacking attack is that it is extremely difficult to prevent. Unlike other popular vulnerabilities like CSRF, XSS, SQL injection, this one is based on a functionality that is widely used in the web nowadays - frames (I'm skipping the case of plugin-based-clickjacking for clarity here). Frames allow you to nest one webpage or widget in another page - this is now used for login pages, commenting, previewing content in CMSes, for JavaScript interactions and a million other things.
Browsers nowadays use same origin policy to protect your data if you're framing or being framed from another domain (this prevents JavaScripts from talking to each other and accesing documents across the domain boundary). But JavaScript is not required for a clickjacking attack - CSS is enough. In the simplest form (e.g. used in recent Facebook users attack), you're just using a small <iframe>, and position it absolutely. The rest is just social engineering.
Our users have a few options to protect themselves. So maybe 1% of them will be "protected". But what can we - web developers do to prevent the clickjacking on our sites? Sadly, not much, but here's the list:
Monday, December 21, 2009
New Facebook clickjacking attack in the wild - fb.59.to
There's a malicious website set up at http://fb.59.to that tries to trick users into a clickjacking attack that shares the link on victims' Facebook accounts.
Some Facebook users today saw a comment looking like this (new pix!):
Clicking on the comment that links to
redirects users to http://fb.59.to web page.
On this page they are given a fake Turing test that tricks them into clicking a "blue button" which is their clickjacked Facebook page positioned at adding a new comment ("Share" button). The whole web page looks like this (clickjacked area is marked green):
In page source we can see that there is a IFRAME element:
The target URL (2.php) has another IFRAME which in turn has yet another one with the target page being
Clicking on the button shares the malicious link on Facebook.
The page has a meta-redirect set up to a Youtube movie launching in 12 seconds so a users might get the impression that the movie launched because they successfully passed the Turing test.
(削除) Multiple iframes are probably set up to trick clickjacking protections within browsers. (削除ここまで)A quick look tells that currently Firefox and Chrome are vulnerable to the attack, (削除) IE and Opera being safe (削除ここまで), although that requires a bit more time to investigate.
Update: The attack does not work in IE and Opera only because of incorrect HTML used in one of the pages in this malicious site. Doing a simple fix in HTML makes both mentioned browsers also vulnerable to the attack.
Thanks go to Grzegorz Ciborowski and Pawel Czernikowski for detecting the attack.
Some Facebook users today saw a comment looking like this (new pix!):
Clicking on the comment that links to
http://www.facebook.com/l.php?u=http%253A%252F%252Ffb.59.to%252F%253F4ff11a526ae73e9f170bbe6702ebb93c&h=..somehash...&ref=nf
redirects users to http://fb.59.to web page.
On this page they are given a fake Turing test that tricks them into clicking a "blue button" which is their clickjacked Facebook page positioned at adding a new comment ("Share" button). The whole web page looks like this (clickjacked area is marked green):
In page source we can see that there is a IFRAME element:
<iframe frameborder=0 scrolling=no height=25 width=100 src="2.php?u=http://fb.59.to/?...somehash...." ></iframe><span style=background-color:yellow;><font style=font-size:13 ; color=white>
The target URL (2.php) has another IFRAME which in turn has yet another one with the target page being
<div style="left:-90px;top:-386px;position:absolute;" <iframe height=400 width=250 src="http://www.facebook.com/sharer.php?u=http://fb.59.to/?hash" frameborder=0 scrolling=no> </iframe> </div>
Clicking on the button shares the malicious link on Facebook.
The page has a meta-redirect set up to a Youtube movie launching in 12 seconds so a users might get the impression that the movie launched because they successfully passed the Turing test.
Update: The attack does not work in IE and Opera only because of incorrect HTML used in one of the pages in this malicious site. Doing a simple fix in HTML makes both mentioned browsers also vulnerable to the attack.
Thanks go to Grzegorz Ciborowski and Pawel Czernikowski for detecting the attack.
Subscribe to:
Comments (Atom)