Codetcha

I’ve sat on the concept for a long time and it has had many names but I’ve got a bit of free time now so I decided to create a proof of concept. It isn’t perfect yet and there may be false positives due to a few bugs but if you read my blog you know I like to release code early :)

So what is it I hear you ask? Well Codetcha is CAPTCHA but not in the traditional sense, it purposely creates code bugs and uses the developers debugging skills to determine if he/she is human or not. In the first version I’ve used Javascript as the error prone code and a PHP mirror behind the scenes to get the relevant value. However any programming language could be used, I decided on Javascript because you can use the native debugging in the browser to help you pass the test.

It’s worth noting that this sort of system couldn’t be used on a non-technical forum or blog because it assumes knowledge of a programming language but it could be used on technical blogs and forums.

Update…

Fixed more bugs, reduced the settings slightly. I’ll release the source code soon once I’ve refined it a bit more.

Update again…

I’ve fixed many bugs, reduced the code by 50% and improved the replace algorithm.

Codetcha demo

Hidden javascript properties

Javascript contains hidden properties in many objects, I first discovered this when DoctorDan from the slackers forum demonstrated a technique to get the text from a regular expression object without specifying the source property. Later I found a post by John Resig about weird IE behavior again with -1 properties.

So I decided to experiment and write a little script to investigate further. I discovered that it’s possible to access strings of global object names. For example:-

alert(Boolean[-6]);
alert(typeof Boolean[-6]);

It seems that Firefox at least stores names of objects in “-6″, the example above returns the value “Boolean” as a string. Here’s a few examples I posted slackers which use Objects to create strings.

This is the simple script I wrote to find the properties, feel free to experiment and find any other “hidden” gems.

function inspectObject(obj) {
 var prop;
 var props = [];
 for(var i=-1000;i<1000;i++) {
  if(i > 0) {
     prop = obj[String.fromCharCode(i)];
     if(prop != null) {
      props.push(String.fromCharCode(i) + '=' + prop);
     }  
  } else {
     prop = obj[i];
     if(prop != null) {
      props.push(i + '=' + prop);
    }
  }
 }
 return props;
}
 
x=function x(){};
inspectObject(x)

Polymorphic javascript

Finding a pattern in malicious javascript is difficult, it’s possible to selectively change the source code yet still execute the same payload. There are many ways to morph Javascript and I shall go through a few of the possibilities and provide examples through Hackvertor (which now supports code morphing).

In order for a pattern to be established the detection mechanism needs to understand hexadecimal, unicode, octal escapes along with general javascript syntax. It’s difficult to maintain polymorphic code without an increase in size, this could be an indicator that malicious code exists because the code only has so many characters it can selectively modify without encoding the whole payload again. Of course an encoding/compression algorithm could maintain the same size but I think this is easier to detect.

A common factor with malicious javascript is the use of eval or external connections, if a site is using eval in more than one instance and on multiple pages it could contain malicious code. Even the use of a single eval is not that common on the average web site and whitelisting the existing known code could be a good way of detecting malicious content.

I believe the best form of defense is attack and therefore I’ve created code morphing tags in Hackvertor, the tags are not comprehensive but provide a good reference on how javascript code can be selectively modified. There are two classes of morph currently in Hackvertor, random morph and full morph. Random mode will modify a small section of the code without changing the result and full mode will encode the entire payload, this is similar to the code morphing script I wrote previously but contains more features.

Random morphing

Ternary operators can be used to partially morph a string:-
Random ternary morph

Unicode morphing can be used in function calls and javascript strings, the following example shows how the alert function can be changed. Click convert a few times to see the different results:-
Unicode morph

Character codes can partially modify a string like this:-
Charcodes morph

Finally I’ll show the variable morph, there are more morphs available but I’ll leave you to experiment with them. The variable morph simply selects an individual character and creates a sepate string:-

Variable morph

Full morphing

Here I show how the urlencode functions can be used to morph the entire payload:-
Escape morph

Ternary morphs can also be applied to a full payload:-
Ternary morph

Advanced examples

The example below shows how to create a javascript link with multiple random morphs which uses hex entity encoding with a unicode and character code random morph.
Javascript link url

Here’s how to take a string and randomly encode parts of it with urlencoding and character codes:-
Random parts morph

This is my last one now, there are so many combinations I could show you. Click the execute output button to view :-
Reversing keywords

Firefox javascript sandboxing

As a technical challenge and maybe in future to allow Hackvertor to execute javascript code from the user. I decided to create a javascript sandbox.

It works by first running the code through a new Function constructor and tosource, the reason for this is that Firefox actually converts the code supplied e.g. ‘te\st’ becomes ‘test’ etc. Then a private function is created to handle the supplied code, it loops through global objects and assigns each of them as a local variable to remove dangerous functions. Underscores are removed from the code because I found it impossible to secure __parent__ as it cannot be redefined. The global Function is overwritten and the constructor to prevent access to new Function() calls.

Giorgio Maone found some excellent holes in my code which hopefully I’ve fixed now. Giorgio makes the excellent noscript simply the best Firefox extension on the net! Thanks Giorgio :)

Update…

Waldo on the slackers forum found some excellent vectors to slip through the sandbox. I’ve updated the script to take into account that there are millions of ways to return to the window object in Javascript. This time I’ve changed the sandbox to nullify the actual window object properties and restore them when the sandbox is run. Big thanks to Waldo for the awesome stuff, more of his sandbox breaking (for Facebook) can be viewed here.

So join in the fun and see if you can execute code:-
Firefox sandbox

Submit any alert executions here

Hackvertlets

I thought about adding basic bookmarklets to Hackvertor but then I had an idea..wouldn’t it be cool if you could create your own :) This simple yet powerful feature will allow you to perform a Hackvertor conversion on any text from any web page. This means you can convert a selection of text to hex entities, urlencoded string, base64 or all of them at once if you like!

How to create

1. Click the Hackvertlet button (Make sure there’s no text in the input box)
2. Choose the tags you would like to perform the conversions.
3. Click the Hackvertlet button again.
4. Give the Hackvertlet a descriptive name like “urlencode”
5. Drag the link to your bookmarks.

So what are you waiting for go make your life easier with Hackvertlets:-
Hackvertor

Please note I’ve designed this for Firefox only.

Hackvertor fixes

Simplicity is always the best policy

I’ve finally and completely (I hope) fixed nested tags. This was an absolute nightmare to solve because the engine kept matching the wrong sets of tags. For example if you placed the following tags in Hackvertor:-

<hex_ent><hex_ent>test</hex_ent></hex_ent>

Hackvertor wouldn’t know which one it should convert first, the way to actually solve the problem would be to match the first ending tag and look backwards in regular expressions to find the next starting tag but….Javascript doesn’t support lookbehind correctly. I tried numerous regular expressions to solve this problem and today I just thought to myself that there must be a easier way…I was right :) Simply appending a unique number to a tag makes each tag different and therefore solving the problem, the result :-
Multiple tags

IE fix

Internet Explorer now supports the base64 encoding functions and URL’s, I thought this was already the case but it turns out that the base64 code I added was missing a few things. I’ve fixed it now though so they should work fine in IE.

More vectors

I recently discovered that you can use zero spaced named entities in Javascript (when in a url), I thought it would be a good idea to add them into Hackvertor so here you go:-
Zero spaced entities

Total Recall No Javascript

My friend Ronald has a excellent post where he uses XML to gather entities from the various extensions to check if they are installed. Awesome stuff! The problem though is that it requires Javascript to be successful. I wanted a way to check any extension even if they had Javascript disabled or noscript installed. The following POC detects noscript even when you have a site as untrusted.

Check the POC here (detects just noscript at the moment):-
Total Recall noscript

Source

kuza55 (Alex) also did a great POC with CSS:-
CSS extension detect

CSRF chat

You may think adding tokens to your forms will completely protect you from CSRF, you’d be wrong. I’ve shown in previous blog entries how you can use CSS overlays to bypass tokens. I decided to create a real world example which uses these techniques to create something cool. The world’s first CSRF chat! I got a couple of friends to try it out on various browsers and we could successfully communicate in pretty much real time.

Try it out here:-
CSRF chat

The technique uses delicious as a central hub to store the chat data, using a bookmarked url as a username and the description as chat data. A login is performed first using a hidden iframe with one delicious account shared between chat users. Another iframe is then used to load the messages, using JSON which is provided by delicious the chat data is then displayed. Confirmation is required because delicious uses tokens, I simply overlay the request using yet another iframe which displays the save button from the delicious web site.

Big thanks to David, Ronald, Mario and everyone else who helped test the chat room.

Moz-binding XSS fun

CSS supports hex encoding within styles as well html entities, but did you know you could combine them both? I didn’t. To construct an attack similar to the one displayed below you first need to convert your CSS property to hex, so -moz-binding becomes: \2d\6d\6f\7a\2d\62\69\6e\64\69\6e\67, notice there is no “x” prefix or double zeros like you would see in HTML entities or Unicode Javascript. The link contains a Hackvertor URL to help you with the conversion.

You can do the same conversion on the value of the property, so the url of the moz-binding payload: //businessinfo.co.uk/labs/xbl/xbl.xml#xss becomes : \2f\2f\62\75\73\69\6e\65\73\73\69\6e\66\6f\2e\63\6f\2e\75\6b\2f\6c\61\62
\73\2f\78\62\6c\2f\78\62\6c\2e\78\6d\6c\23\78\73\73

I hope you’re following so far, we can now take the property string and encode it further, crazy eh? Any part of the property can now be encoded with html entities. I went for the backslash and malformed entities but you can experiment with different combinations. The property “\2d\6d\6f\7a\2d\62\69\6e\64\69\6e\67″ now becomes: &#x5c2d&#x5c6d&#x5c6f&#x5c7a&#x5c2d&#x5c62&#x5c69&
#x5c6e&#x5c64&#x5c69&#x5c6e&#x5c67
.

Here is the final vector with a link to hackvertor for testing:-
The final vector

Javascript regular expressions

Ronald and I had a good conversation about Javascript regular expressions comparing them to PHP. He was having difficultly with the syntax because he was used to preg in PHP so I promised to share my knowledge gained from developing various online scripts.

First up preg_match in PHP can be achieved using the match function in Javascript, they are both very similar but it’s just a matter of getting your head round the different syntax. Match is part of the String object and here is how to use it:-

alert('Test'.match(/[a-z]/|>))

You can match subpatterns like this (I’ve tried to keep it close to PHP syntax as possible):-

pattern = /([a-z]+)([0-9]+)([A-Z]+)/|>;
subject = 'test1234TEST';
matches = subject.match(pattern);
match1 = matches[1];
match2 = matches[2];
match3 = matches[3];
alert(match1);
alert(match2);
alert(match3);

You can also create matches using the RegExp object, this is useful for passing variables into the pattern which to my knowledge isn’t possible with “//” syntax.

a = 'a+';
alert(new RegExp(a).exec('123aaaabcdef'));

The exec method can also be called from “//” patterns.

alert((/[0-9]+/|>).exec('12345abcdef'))

Javascript supports the modifiers “g”, “i” and “m”, here’s how to use them with “//” syntax:-

matches = 'ababababababa'.match(/[a]/g|>);
alert(matches);
alert(matches.length);

Here’s how to use modifiers with the RegExp object:-

alert(RegExp('[test]+','i').exec('TeSt'))

Ok I hope you’re following so far, I’m going to move onto replace now and how to use the various combinations.

Here’s how to use replace, notice how only one “t” is replaced:-

str = 'test';
alert(str.replace('t','x'))

In order to match more than one instance of the string and use a regular expression you have to do the following:-

alert('test'.replace(/t/g,'x'))

Javascript also supports anonymous functions within replace which is really powerful, you can even nest the replaces and perform other logic:-

alert('teeest'.replace(/e+/g, function(str) {
  return str.replace(/e/g,'x');
}));

You can also use parenthesis with replace and match the subpatterns like this:-

alert('567'.replace(/([0-9])([0-9])([0-9])/|>,'$3$2$1'));

That’s all for now I may follow up this article at a later date when I have some spare time, I hope you enjoyed it.