How to unpack a packed javascript!
April 28th, 2009
Sometimes malicious scripts float around and you are asked to run them in your browser by script kiddies. You try and have a look at the code, and find it all to be obfuscated something like function(p,a,c,k,e,d){…}. It is actually a packed version so that ‘normal’ users cannot modify it for their own purpose. But this script can be easily unpacked without using any third party tool. I will explain how can it be done in Firefox.
This is an informational post only, and has no intent of encouraging malicious attacks via javascript.
For this example I will use this javascipt :
function demoMatchClick() {
var re = new RegExp(document.demoMatch.regex.value);
if (document.demoMatch.subject.value.match(re)) {
alert("Successful match");
} else {
alert("No match");
}
}
function demoShowMatchClick() {
var re = new RegExp(document.demoMatch.regex.value);
var m = re.exec(document.demoMatch.subject.value);
if (m == null) {
alert("No match");
} else {
var s = "Match at position " + m.index + ":n";
for (i = 0; i < m.length; i++) {
s = s + m[i] + "n";
}
alert(s);
}
}
function demoReplaceClick() {
var re = new RegExp(document.demoMatch.regex.value, "g");
document.demoMatch.result.value =
document.demoMatch.subject.value.replace(re,
document.demoMatch.replacement.value);
}
After packing it from here, I get this
eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\b'+e(c)+'\b','g'),k[c]);return p}('7 h(){4 a=8 9(1.2.b.3);d(1.2.c.3.5(a)){6("j 5")}e{6("f 5")}}7 k(){4 a=8 9(1.2.b.3);4 m=a.l(1.2.c.3);d(m==o){6("f 5")}e{4 s="p q r "+m.t+":\n";u(i=0;i<m.v;i++){s=s+m[i]+"\n"}6(s)}}7 w(){4 a=8 9(1.2.b.3,"g");1.2.x.3=1.2.c.3.ya,1.2.z.3)}',36,36,'|document|demoMatch|value|var|match|alert|function|new|RegExp||regex|subject|if|else|No||demoMatchClick||Successful|demoShowMatchClick|exec|||null|Match|at|position||index|for|length|demoReplaceClick|result|replace|replacement'.split('|'),0,{}))
To unpack it in Firefox,
- Goto Tools->Error Console (or Ctrl+Shift+J).
- Paste the packed script in input box
- Add “eval = alert;” (without quotes) before the packed script.
- Hit Evaluate, a pop up shows the unpacked script as
You got the original javascript back! This is pretty useful while analyzing malicious code to find a solution to counter-attack(or stop) that code.


















