Tuesday, December 27, 2011

Yes, it still happens: FreeBSD Telnet BOF

Buffer Overflows has been one of the major cause of exploiting during the past years, many remote exploits, malware and viruses took advantage from this technique to keep the control of a target machine. I am not going to write about Buffer Overflows, I've been widely discussing this topics in several past posts ( just take a look here) but here I want to discuss how this vulnerability still infects many softwares including amazing project like the FreeBSD Operative System.

The telnet's bug is place into the file encrypt.c which defining a key_info struct with a fixed length buffer of 64 bytes to hold the key id passed by the telnet client, does copy the passed data into the key_info struct using memcpy without any restriction on the length specified by MAXKEYLEN. Following the bugged code:


This code is almost 20 years old and it is pretty interesting that nobody discovered it until the 2011 Christmas's eve. And yes... Apple is vulnerable too (take a look here). The simple but well written exploit made by PainSec is available here. Attackers used a "/bin/sh execve() shellcode " as shown following:


And filled the buffer in the most classic way:


Again another BOF example to show to everybody thinks that Safe Libraries, NX/DEP, ASLR, StackGuard and Canaries resolved the security Buffer Overflow problem. I do not believe it will be easy to solve in a permeant way this problem that afflicts security since the beginning of such a field.

To have more details of the telnet code go here.

Wednesday, December 21, 2011

IDA FindCrypt

Finally a great IDA Plugin for Cryptography. Often we'd like to know what kind of cryptographic algorithm has been used in the binary we are analyzing: FindCrypt comes to help us ! The idea behind this Plugin is pretty simple: since almost all cryptographic algorithms use magic constants placed inside the binary, FindCrypt just looks for these constants in the program body.
"This approach will fail if the S-boxes have been altered but in most cases they are untouched (can you admit that you understand all consequences of modifying an S-box, say, in AES?)"
 The plugin supports the following crypto algorithms:

  • Blowfish
  • Camellia 
  • CAST 
  • CAST256 
  • CRC32 
  • DES 
  • GOST 
  • HAVAL
  • MARS 
  • MD2
  • MD4 
  • MD5
  • PKCS_MD2 (byte sequence used in PKCS envelope) 
  • PKCS_MD5 (byte sequence used in PKCS envelope)
  • PKCS_RIPEMD160 (byte sequence used in PKCS envelope)
  • PKCS_SHA256 (byte sequence used in PKCS envelope) 
  • PKCS_SHA384 (byte sequence used in PKCS envelope) 
  • PKCS_SHA512 (byte sequence used in PKCS envelope) 
  • PKCS_Tiger (byte sequence used in PKCS envelope) 
  • RawDES 
  • RC2 
  • RC5
  • RC6 
  • Rijndael 
  • SAFER 
  • SHA-1 
  • SHA-256 
  • SHA-512 
  • SHARK 
  • SKIPJACK 
  • Square 
  • Tiger 
  • Twofish 
  • WAKE 
  • Whirlpool 
  • zlib
The Plugin is very simple to be used just select it from the Plugin menu and it will do its job ending up with the following window:


It will also rename the constant arrays and it will put them in the marked location list. I definitely suggest this great Plugin to everybody who's working in reversing engineering. Good joob Guilfanov ! Download it directly from here.

Monday, December 19, 2011

Book Review: A Bug Hunter's Diary

It has been asking my personal revision on the Tobias Klein's english version of "A Bug Hunter's Diary" book. As the title suggests "A Bug Hunter's Diary" is not a normal book, it's not a manual or a guide to exploiting it's a new way to interpret the bug hunting teaching process. It follows the "blog paradigm" where the author seems to talk to his personal diary, just for personal memories and not for relating or for writing a book. Each chapter begins with the "Dear Diary" sentence , the language is technical but simple, the text is essential: no additional adjectives or related stories to support to the main concepts.  The writer style is very clear, everybody should be able to understand what Tobias is talking about, the text form follows a standard path, after a couple of chapters the reader enjoys it because he  will known exactly where "he is" and where the text "is going to take him".


The First chapter (Bug Hunting), is the weakest section of the book. It is a small chapter introducing the bug hunting process as well as some basic security concepts such as the necessary tools, well know hunting  techniques, and best practices. Under my personal point of view this chapter should be much more elaborated then the current one by going deeper into the details giving to the reader much more background for better understand the following chapters.

The Second chapter (Back to the '90s) shows the abilities of the writer in going straight into the core arguments with no unnecessary words or sentences. Every section is well written with the less possible words letting an avid reader going directly into the main aspect of the problem without being distracted from additional contexts. This chapter walks through the first vulnerability of the book: VLC TiVo demuxed stack overflow.

The Third chapter (Escape from the WWW Zone) explains the entire process to exploit the Sun Solaris IOCTL Kernel NULL pointer dereference. In my personal opinion, this chapter is the most valuable one since it describes with meticulous details (but always without unnecessary words or sections) a quite rare exploit. Sun solaris resources are pretty rare and difficult to be documented since the referenced platform is not well known as Microsoft or Linux are.

The Fourth chapter (NULL Pointer FTW) walks through the famous FFmpeg type conversion vulnerability. While the chapter and the vulnerability, under some aspects, could be compared to the first chapter, I believe that this is one of the most didactic chapters of the book. The writer shows a mature writing in describing his steps, in particular I am referring to the steps 2 and 3 where the author with extremely mastery explains firstly how is made the  srtk chunk layout and secondly how to manipulate it.

The Fifth chapter (Browse and You're Owned) shows the WebEx meeting manager activeX stack overflow.  Probably the easiest to read chapter. I personally don't get why the author preferred the use of WinDbG rather then Immunity debugger which has a lot of scripts and plugins ready to be used which might help a lot the reader.

The Sixth chapter (On Kernel to Rule Them all) walks to the Avast! kernel memory corruption vulnerability disclosed here. This is one of my favorite chapters. The author shows his confidence in finding vulnerabilities in IOCTL handlers. Probably the most complete, technical and difficult to follow chapter.

The Seventh  chapter (A Bug Older Than 4.4BSD) shows another really interesting Kernel vulnerability  against XNU

The Eight chapter (The Ringtone Massacre) is the last book's chapter. The author ends up in the mobile world walking through a classic buffer overflow found in IOS (from 1 to 3.2.1) AudioToolbox library.  The beauty of this chapter is in the way the stack buffer overflow is applied to the mobile world and for this reason I consider it as "innovative chapter" perfect to be the conclusive chapter of this book.

The book presents three didactic appendixes titled: Hints For Hunting, Debugging, Mitigation.


Conclusions:
I did enjoy reading  this book. I did enjoy the way the book is written, it's pretty different from the books I' am used to read and I think this new way to report, pretty close to a blog, is immediate and effective. The book amazingly describes the way the author hunts the bugs and take them into vulnerabilities. I would definitely suggest this book to everyone is interested on "touch with hands" the real words exploiting processes.


Thursday, December 15, 2011

Testing ASLR on Linux Kernel 2.6.38 and Lion

This morning I'd like to share some results on two Asynchronous Space Layout Randomization implementations: in particular on Linux Kernel 2.6.38 and on Darwin 11.2.0 Lion. I am not getting into the details about ASLR, I've been writing a lot in past blog posts and journal articles  about this topic ( for example here ), but I want to share a little study of their randomization. The goal of this early morning hour is to build a simple but relevant randomization statistic about these kernels, proving their differences.

I started by writing a simple program like the following one:

#include
int main(int argc, char **argv)
{

unsigned int ebp;
asm("movl %%ebp, %0\n":"=r" (ebp));
printf("Current ebp: 0x%x \n", ebp);
return 0;

}

It takes %ebp and prints it out. I run it one Million of times putting the results into a .txt file ready to be processed through my favorite spreadsheet. Here the results . More then one Million of tests only few duplicates, and very high entropy functions as shown following.





Wednesday, December 14, 2011

From ROP to JOP

Researchers from North Carolina State University and National University of Singapore presented an interesting paper to ASIACCS11 titled: "Jump-Oriented Programming: A New Class of Code-Reuse Attack".


The previous image (click on it to make bigger), taken from the original paper, shows the differences between the well known Return Oriented Programming and the new Jump Oriented Programming. As in ROP, a jump-oriented program consists of a set of gadget ad- dresses and data values loaded into memory, with the gadget addresses being analogous to opcodes within a new jump- oriented machine. In ROP, this data is stored in the stack, so the stack pointer esp serves as the “program counter” in a return-oriented program. JOP is not limited to using esp to reference its gadget addresses, and control flow is not driven by the ret instruction. Instead, JOP uses a dispatch table to hold gadget addresses and data. The “program counter” is any register that points into the dispatch table. Control flow is driven by a special dispatcher gadget that executes the sequence of gadgets. At each invocation, the dispatcher advances the virtual program counter, and launches the as- sociated gadget.

This new way to see reusable code exploitation makes the use of  three main actors: (1) the dispatcher, which has to hijack the control flow by jumping to different entries on the dispatch table, (2) the dispatch table which has to wrap out gadgets addresses and data/padding, and finally (3) the gadget catalog, which contains the effective code to be executed. Gadgets are not terminating with RET as we were accustomed, but with JMP to the dispatcher. A dispatcher example could be:

add %ecx, 4
jmp %[ecx]

Each time it is executed it jumps to the next gadget  (+4 bytes) through the dispatch table (base address on %ecx).  Each time an addressed gadget is executed it ends with a jump to the dispatcher, in this way a jumping chain is built.  The paper follows on describing a MOC example and providing algorithms to find JOP gadgets. 

I did like this reading and I do suggest it to all the interested security guys that are reading my post,  but I have some issues on believing the real implementation of the dispatcher. As you might see the dispatcher increases the jump offset by a fixed step, this assumes that the respective gadgets don't use data or  at least use a fixed number of data (variables). This is highly impractical in a real exploitation scenario in which the attacker needs many different gadgets which use respectively different quantity of data. I have made here a simple explanation to what I mean.

Sunday, December 11, 2011

ETTERCAP is still alive

As many of you might know, Ettercap has been one of the most important tools during the past decade. It was one of the most powerful, fast and easy to use "man-in-the-middle" attacks tools. When it reached it first "NG" version during 2004 it was able to automatically decrypt WEP packets, to perform ICMP, DHCP and DNS attacks and it was able to sniff many of the most used protocols grabbing credential, certificates and symmetric encryption keys.


It has been six year since Ettercap developers released the last update.  But in these days 11-12-04 a new version of Ettercap (0.7.4 - Lazarus) became available. This version fixed a lot of Buffer Overflows bugs and made Ettercap compatible with mac OS X Lion and 64bit architectures.

I think Ettercap developer team is not anymore the same of six year ago, but I totally encourage these new guys to bring it to a new life implementing new features such as HTTPS stripping, WPA 3-handshake sniffing, etc. Keep up the good work guys.

Saturday, December 3, 2011

iCTF2011 experience

Yesterday I participated once again to the iCTF organized by UCSB. For everybody who does not know what this event is about:

The Capture The Flag contest is multi-site, multi-team hacking contest in which a number of teams compete independently against each other.
In traditional editions of the iCTF (2003-2007), the goal of each team was to maintain a set of services such that they remain available and uncompromised throughout the contest phase. Each team also has to attempt to compromise the other teams' services. Since all the teams received an identical copy of the virtual host containing the vulnerable services, each team has to find vulnerabilities in their copy of the hosts and possibly fix the vulnerabilities without disrupting the services. At the same time, the teams have to leverage their knowledge about the vulnerabilities they found to compromise the servers run by other teams. Compromising a service allows a team to bypass the service's security mechanisms and to "capture the flag" associated with the service.
For the past three years (2008, 2009, and 2010), new competition designs have been introduced. More precisely, in 2008 we created a separate virtual network for each team. The goal was to attack a terrorist network and defuse a bomb after compromising a number of hosts. In 2009, the participants had to compromise the browsers of a large group of simulated users, steal their money, and create a botnet. In 2010, the participants had to attack the rogue nation of Litya, ruled by the evil Lisvoy Bironulesk. A new design forced the team to attack the services supporting Litya's infrastructure only at specific times, when certain activities were in progress. In addition, an intrusion detection system would temporarily firewall out the teams whose attacks were detected.  (from here)

iCTF namely: "international Capture The Flag" is only one of the many capture the flags (FTC) happening over the year. Here you might find some of the most famous ones. This year iCTF was organized in a amazing way, plenty challenges (to get money), and plenty services to exploit (to get flags in order to convert money into points). Finally the winners were We_0wn_Y0u while a brand new team named "More Smoked Leet Chicken" got the second place.


I've been involved in iCTF competition for several years, and this time it has been a very good organized one, but as you might see, especially if you have participated to some of them over the past years,  current iCTFs tend to go more and more far away from the original concept of hacking school. At the beginning CTFs were organized as simple challenges, in which participants should solve different kind of problems in order to get the flag. For example teams should solve problems like: forensic, reverse engineering, trivial questions, patching bugged code, etc. All these problems were very close to what is the global concept of cracking.  Some years later the so called "offline CTFs" became what we call nowadays the "online CTFs" where hacking teams fight each other by pawning the attacked team's online services in order to get the flags. This kind of challenges are pretty close to what people call hacking. 

Yesterday, everything was much more complicated. "Offline challenges" to get money (the "cracking" side of the hacking competition). "Online attacks" to convert money into points (the hacking part of the hacking competition) and a linear function that modified the value of the money depending on several parameters. In other words, if you got 100 dollars and you want to change them, the value of the change from dollars to points was different depending on the current value of the given function. So, if you got a lot of money but if you don't submit them in "the right way", you are going to loose them. This was more like a linear problem solving. The result was that pretty good hacking teams, pretty good to solve challenges and pretty good to attack services got high amount of money, but since not prepared to solve dynamic linear programming problems got very very low scores. The result has been that pretty good hacking teams not reached hight score, this happened because some of the good teams were not prepared to solve linear programing problems during the runtime competition.

In my personal point of view (which of course it could be wrong) CTFs are getting harder and harder but not in the direction of hacking, in the direction of multi-disciplinarity. In other words, rather then making more and more difficult  "cracking" challenges or "hacking" services, CTFs are increasing  the difficulty by increasing the number of "things to do" during the competition. So CTFs are not working to increase the quality of hacking but are working to increase the quantity of taksI am not saying that this is bad. Not really.... don't write me emails about that. After all CTFs have been made to teach people security,  and more different people CTFs can involve more reached is the original scope. But again, following this way, the risk is to promote the quantity (of thins to do, of people, of tasks, etc..)  rather then the quality (of hacking). Since many of the participants will be hired from companies in order to solve security related jobs, assuring the quality is an important goal.

This has been a great Capture the flag challenge, Good job UCSB security team !!

Sunday, November 27, 2011

POP POP RET: SEH Exploiting process

This morning I want to talk a little bit about Structured Exception Handling (SEH) exploitation. Some readers, during a Skype meeting early last week, pointed me out that I never wrote about it, se lets talk a little bit about it.

First of all SEH is a piece of code written in the application with the purpose of dealing with exceptions. Each exception is a special event that interrupts the "normal" program behavior, and it mostly happens during errors and/or unexpected behaviors. Writing exception handlers are  one of the "best practice" in software engineering. Each exception handler, once compiled from the favorite language,  is mapped into the stack in 8 Bytes divided into 2 pointers.
  1. Pointer to the next "exception registration" structure. This pointer is only used in case of the current handler is not able to catch the exception.
  2. Pointer to the actual code. This pointer points to the actual code of the current handler which tries to handle the happened exception.
The following image (click on it to make it bigger) shows how the structured chain is build over the stack

Image from Corelan

Obviously from the attacker point of view, overwriting SEH pointers could mean hijacking control flow and/or executing arbitrary instructions. So the first question to be answered is: where is place the SEH chain in the stack layout ?  The following image (click on it to make it bigger) shows where SEH chain is placed.



Image From openrce

As you can note in (%EBP - 12) is placed the SEH Handler while in (%EBP - 16) is placed the Next SEH Frame. It seems pretty easy so far right ? But in the reality there are a couple of protections that must be investigated:
  • XOR. Before the exception handler is called all the register are cleaned (xored each other) 
  • DEP and Stack Cookies Stack Cookies or Canary words are setup. DEP or NX bit set to 0 (non executable area) 
  • SafeSEH Saves and checks the original value of SEH. If it has been overwritten SafeSEH brings it back to the original value. 
 Those actions make difficult the exploiting process to SEH chains. I am not going to talk about DEP, I've been widely discussed about it in these posts, so lets see what we have so far:
Firstly we cannot jump to the stack, the registers are "XORed", so we cannot use the JMP to Register technique to point to our shellcode or to our PAYLOAD. BUT, we can overwrite SE Handler address. The OS knows the exception handling routing so it will pass the control flow to the next SEH record. We need to make the pointer to "next SEH" bringing us to the injected Shellcode.

In other words, the injected PAYLOAD should follow these steps: 
  1. Cause an exception. Without exception the SEH handler won’t start. 
  2. Overwrite the pointer to the next SEH with some jumpcode (to make it jump to the shell code).
  3. Overwrite the SE handler with a pointer to an instruction that brings the control back to next SEH executing the jumpcode. (The shellcode should be directly placed after the overwritten SE Handler)

The following image (click on it to make it bigger) shows how to implement the SEH Exploiting process (from this image you can understand the post title)




Again, the attacker needs to force an exception (by injecting the PAYLOAD). The exception causes the execution of the current SEHandler. The current SEHandler has been replaced by the attacker to make a short jump ( If DEP then Gadget to POP POP RET) to the pointer to the next SEHandler which point to the injected Shellcode. In the previous image it has been assumed an active DEP protection and for that the Current SEHandler points to a POP POP RET gadget which increments %SP and returns to the next SEhandler pointer which it points to the injected Shellcode. Before ending up I want to thank you corelan team which provides to me a lot of great material such as: images, ideas and from time to time good suggestions ! Thank you Corelan, you are doing a great job !

That's all for today.





Sunday, November 20, 2011

ruCTF2011 - ESP(CardGame) Exploiting Process-

During the past ruCTF I found particularly interesting the ESP (CardGame) exercise. ESP is a java implemented client-server  card game, in which you have to find the correct ascending sequence of the displayed cards. 

As usually happens during the exploiting process the attacker needs to understand how the software correctly works. So lets try to play some games and lets find out where the game provides us the flags we need to win the challenge. The flags are provided only when you correctly order all the 54 cards in the deck. 

Once understood the game we are ready to decompile our code. Using JAD and handily parsing the decompiled JAR files we want to focalize our attention on two classes: 
  1. CardGameClient.jar -> org.ructf.cardgame.client -> CardGameClient.class
  2. CardGameServer.jar -> org.ructf.cardgame.network -> CardGameProtocol.class
The first interesting class "CardGameClient.class" is called by the CardGameClientApp for initialize the game an it's called each time the user clicks on a given card for picking up a card. The following image (click on it to make it bigger) describes the starting game procedure. I used 3 colors in order to distinguish between:


  1. Bytes sent (RED color)
  2. Bytes received (GREEN color)
  3. Bytes processed (BLUE color)
The first action performed by the startGame() function is to send to the CardGame Server the byte representation of the "reset" string.  After sending the "reset" string, the application sends the byte representation of "PLAY" and gets back a stream of bytes that calls deck1. Immediately after, the application uses an internal function called shuffle() to (try to guess :) ) shuffle the received deck, it creates a key vector of 20 randomly generated bytes (chars lower and upper case, no number nor symbols) it encodes the received deck (deck1) and it sends to the CardGameServer the encoded deck1.

CardGameClient waits for another incoming stream of bytes that calls deck2. It decodes deck2 by re-using the "single key" generated randomly in during previous deck (deck1). Now it generates a new key vector by randomly generate 20 bytes for each card (54 is the size of the deck) like in the previous key vector generation. It now encodes the second deck (deck2) using the new key vector and sends it to the CardGameServer. Finally it decodes the deck2 and keeps it clearly into the memory for later. 

This was the initialization of the game. Now lets see the main game function: playgame(). 
The following picture shows the game procedure playgame().


The palyGame procedure sends to the CardGameServer the byte representation of the "PICK"  string followed by:  a number, representing  the picked card,  and 20 byte representing the key to be used to decode the card symbol. If the picked up card, decoded through the given  key,  matches to the one in the server, the server sends back to the CardGameClient application the string "LUCK" (number 3, in the previous picture). If the user picks up all the 54 cards in the deck in the right order the server sends back to the CardGame Client the string "WIN" followed by the Flags we need. This is easy understandable from the CardGameServer.jar -> org.ructf.cardgame.network -> CardGameProtocol.class.

Now we know how the game works. What we need is to find a way to cheat the CardGameServer in the way we always reach the state "WIN". There are plenty of ways to cheat this CardGameServer, but my favorite one is based on the key generation procedure. In few words...  both of the key vectors, but most important the second one, is randomly generated in the client procedure ( code lines number: 4 and 7 in the starGame procedure ) what if we generate a static string that encodes and decodes each card ? If you do like that you are breaking the assumption of picking up the card in the right order.  Since the key vector is associated to a specific card order, and each entry of the key vector is randomly generated, if you put to each key a fixed 20 bytes sequence it doesn't matter what card you choose because every card has been encoded with the static 20 bytes sequence. In other words whatever you choose will always be decoded in the server side, and it will result as good as if you really picked up the right card.  Following my exploit.

I decided to implement a small CardGameClient using Java technology. I decided to use Java because I was able to reuse all the libraries and the decompiled code without write it from scratch. The following image shows my startGame() procedure


I used a fixed single key "ciao" to exchange the first deck. I later on used a single 20 bytes string ( "aaaaaaaaaaaaaaaaaaaa" ) to populate the key vector . I finally implemented a loop over the 54 cards (DECK_SIZE) to get 53 "LUCK" strings reaching the "WIN" state and getting from the server side the Flags.



This little CardGame Client was always winning. How to fix it up ? Well, the right way should be to invert the paradigm of the key generation. Instead of letting the client to decide the key vector the programmer should let the server to shuffle and to generate the key vector. I am not going deeper in this, since the post is already pretty big and probably everybody is getting bored :( . I'll post my impression on ruCTF later in another post.














Monday, November 14, 2011

Thread Injection

Today I suggest this short but intensive ( :D ) reading. It's a simple tutorial for thread injection in x86 systems. I believe it is useful for everybody likes thread hijacking . It shortly describes 7 simple steps to attack a generic running process  by showing code examples to make the reading even faster.
Here the seven main steps:
  1. Detect the target process
  2. Identify the main thread
  3. Suspend the main thread
  4. Obtain the thread content
  5. Create the "code-cave" (the code to be injected)
  6. Spoof the %IP and hijacking control flow
  7. Resume the thread, continue execution and free the memory



Friday, November 4, 2011

Global Offset Table Injection Procedure

Have you ever thought about how a program can call external functions ? Lets say we have a classic printf() which is imported from "libc" how does the program know where exactly printf() is located into the memory ? Well the answer in the Global Offset Table. The following sketch sows how the calls between external function work:


In other words the Global Offset Table redirects a position independent address calculations to an absolute location and is located in the .got section of an ELF executable or shared object. It stores the final (absolute) location of a function calls symbol, used in dynamically linked code. When a program requests to use printf() for instance, after the rtld locates the symbol, the location is then relocated in the GOT and allows for the executable via the Procedure Linkage Table, to directly access the symbols location. For a complete resource about ELF and its sections I suggest to take a look here, you want find many useful references such as: blog posts, articles,  books and papers. But this post is not about describing ELF, GOT or PLT it's about describing a procedure to redirect control flow by injection code into the GOT table.

Lets assume to have the following function (click on the image to make it bigger) in a give program. The program copies one input parameter to a support buffer following a given offset. The execution string looks like: program.o 4 30 AAAA. Basically 4 is the number of bytes to be copied into the destination buffer (size [256]) 30 is the offset from the beginning of the destination buffer and AAAA  is the data to copy on it.


The external function that we want to follow is the "puts()" function. The  GOT table will be "filled" dynamically during the execution so lets see what happens by running the system. Breaking on main():



Disassembly the "main()".




The puts() function is reached by the "callq  0x100000e8a ".  Following 0x100000e8a address we see the PLT pointing to the GOT table. Lets see the dynamic pointer *0x1b2(%rip) . PLT table is on 100000ea8.



The program itself prints out to the buffer address in which the data should be copied. (0x66f37a60). A little bit of hexadecimal math: just remember we got the memory address in which we want to inject our data (AAAA) placed into 0x100000e8a and we have the buffer address in 0x66f37a60. And here we go !  A nice and easy segmentation fault ;D !!



This post shows a quick'n dirty procedure on how attackers could manipulate programs control flows by injecting address/code into the GOT table. Don't take it as a tutorial or a guide but as simple and fast way to sum up the entire procedure. 


Tuesday, November 1, 2011

Does AV really increase security ?

From a user point of view any AV increases the security of his system since it's a defense mechanism able to detect and to block most of the known viruses affecting Internet. But let think the other way around, what is an AV from a ROP expert ? Since every AV is at least one running processes within loaded libraries and imported functions it is an additional component where to look for Gadgets. During the past days I've been installing some of the most used AV (trial commercial versions only) and I investigated the distribution of the Gadgets that such AVs introduce into a running Windows XP system.


The above picture (click on it to make it bigger) shows the gadgets distribution ordered by gadget's length. The smallest gadget found is composed by one operation (RETN) while the biggest one is composed by 15 operations. The analyzed AVs (Avast, AVG, Avira, kaspersky, ThreatFire and TrendMicro), as shown in picture, share the same distribution even if in different quantity. The picture also shows how similar the analyzed AVs are from the attacker (ROP expert) point of view. The attacker assuming the AV presence might ignore what kind of AV is (except for TrendMcro which provides lot of help to the attacker, letting he to choose between a wide amount of gadgets). These are only few preliminary results of what I really found. I'll be back with more details on that in next few months (I have to analyze tons of data and to figure out similarities and differences ).

Thursday, October 27, 2011

ROP Chain for Windows 8

Today I want to share a really good blog post about Windows 8 ROP mitigation. As described here Windows 8 implements a simple protection mechanism which aims to check the %ESP. The testing stack happens by comparing %ESP register before calling new functions (switching frames). If ESP is in between StackBase (FS:[8]) and StackTop (FS:[4]), the stack address is assumed as valid and functions will continue to be executed. Otherwise, the stack is assumed as invalid and the program will be terminated. Following a fragment of the implemented code by Alex Ionescu:


As it might be simple to figure out, the attacker having the full control over the stack could firstly save %ESP (by using a gadgets for example) and secondly he could restore it directly on the stack before calling functions. Bikis describes a ROP chain able to exploit this theory in order to break Windows 8 countermeasure. They reused the Firefox vulnerability described here and its payload described here to build the Windows 8 ROP chain.  The described ROP chain is developed by following these steps:

  • Using msvcr71.dll – v7.10.3052.4 module
  • Integrated with: JRE (Java) 1.6
  • Loading with browser
  • Able to work on Windows XP/Vista/Win7/Win8/2003/2008
  • ASLR-free
  • Using kernel32.VirtualProtect function
  • Base: 0x7c340000.
  • Size 0×56000.
I've been testing their demo code too. Of course, I had to use their ROP chain instead of the old one when the change of the stack address was required for my ROP exploit code. In my test case the chain started with %EBX pointing to a valid stack area (i.e. between FS:[4] and FS:[8]), so it was pretty similar to the original one.

I think Bikis made a great job in developing this new ROP chain proving the inefficiency of Windows 8 countermeasure, it is for sure a "security byte" to remember.  Again another great example of "the eternal battle between attack and defense".

Tuesday, October 25, 2011

Amazon and Eucalyptus hacked.

Today I'd like to point out a paper entitled "All Your Clouds are Belong to us - Security Analysis of Cloud Management Interfaces"by Juraj Somorovsky et Al. 

In this paper, they provide a security analysis pertaining to the control interfaces of a large Public Cloud (Amazon) and a widely used Private Cloud software (Eucalyptus). Their research results are alarming: in regards to the Amazon EC2 and S3 services, the control interfaces could be compromised via the novel signature wrapping and advanced XSS techniques. Similarly, the Eucalyptus control interfaces were vulnerable to classical signature wrapping attacks, and had nearly no protection against XSS.

The following picture shows a classic XML Signature Wrapping Attack 

As shown in the figure, the original SOAP body element is moved to a newly added bogus wrapper element in the SOAP security header. Note that the moved body is still referenced by the signature using its identifierattribute Id="body". The signature is still cryptographically valid, as the body element in question has not been modified (but simply relocated). Subsequently, in order to make the SOAP message XML schema compliant, the attacker changes the identifier of the cogently placed SOAP body (in this example he uses Id="attack"). The filling of the empty SOAP body with bogus content can now begin, as any of the operations defined by the attacker can be effectively executed due to the successful signature verification.


The paper follows by describing the practical attacks on Amazon EC2 and on Eucalyptus specifying attack vectors and consequence of the designed attacks. Finally, the paper describes some countermeasures for the described attacks. The most important lesson learned from their analysis is that managing and maintaining the security of a cloud control system and interface is one of the most critical challenges for cloud system providers worldwide.

My personal opinion is that of course they did a pretty nice job with the vulnerability analysis even if they clearly did not use a specific "bug hunting" methodology. It would be quite interesting, at least to me, mapping what they found and the way they discovered it to the current penetration testing methodologies to see what kind of correlation is there. Such a great work without any contribution to the current methodologies might be "end to itself", like a single attacker that has experimented a vulnerability to a big system and finally found it. 

Thursday, October 20, 2011

Malware 2011

Hi Folks,
during the past days I have been in Puerto Rico presenting at Malware 2011. Well, Puerto Rico is an amazing place and the conference was a "cozy" and "worm" place to share knowledge about Malware. A small and "family conference" this is my definition of Malware 2011, and  for this particular reason it has been a very great one ! I had the pleasure to meet a lot of interesting people from Academia as well as from main Vendors. I totally suggest to attend to next Malware, 2012 because it is a great place where you might meet Academia and Professionals. Over many interesting papers today I suggest the winner of Malware 2011 -best paper award-  from Michalis Polychronakis and Angelos D. Keromitys titled: ROP Payload Detection Using Speculative Code Execution.


Overview of the scanning process. If the 4-byte value at the current position does not correspond to a mapped executable memory page, the sliding window advances one byte (a). When a valid address is found, EIP and esp are initialized appropriately and a new execution begins (b).



Their presented a way to detect ROP Payload Detection by executing the code. Their technique speculatively drives the execution of code that already exists in the address space of a targeted process, and identifies the execution of valid ROP code at runtime. They made experiments which demonstrated their theory.  Good Job guys !

Thursday, October 13, 2011

Bypassing Windows 7 ASLR

Hi Folks,
few days ago Stefan Le Berre from NES security labs wrote an interesting document about Windows 7 ASLR.  Most of my readers know that exploiting a randomized user space is quite difficult, and  I am sure they appreciated NES effort. In ASLR attackers are forced to use heap spraying and other padding techniques that make difficult the whole exploiting process. Keeping trace of the randomized address by rebooting the system many times is always a good solution for understanding how randomization works, but this time Microsoft made things in the right way making impossible a statistic attack over ASLR.

A first study to attempt to analyze the user space randomization came in September from Oleksiuk Dmytro who discovered that a static memory zone is always mapped at 0xFFDF0000 within RWX rights. This is pretty different from a statistic analysis on ASLR. Oleksiuk made a simple "show diff" of the memory contents over multiple system reboots. After a month or so, NES laboratories discovered that more areas are always statically allocated. The following picture shows (in green) the static allocated piece of memory.


Now, why this is such an important finding ? Well, if there are some static allocated memory spaces, it means you know what is in there ! And why is so important knowing what is in there ? Well you should know something about Return Oriented Programming  :D :D (if you don't please read some of my posts on ROP: here, here, here, here, here, here, here ). If you are familiar with it you know that by "ropping" you might find useful gadgets to build your own exploit! The "paper" (more then a paper it looks like a presentation slides) follows by saying they had issues on finding useful gadgets (they had some issues to use RET2LIBC attack). I wonder how they looked for ROP and how many misalignment bytes they used. Probably if they used more then one byte of misalignment they might find more useful gadgets ...  Anyway, they exploited the address space layout randomization by using the RWX rights over the memory static allocated addresses and by controlling one register.


By setting the desired instruction on a register (lets say %EAX) and %EBP to the next address they where able to control the stack. When the processor executes the instruction it will overwrite the next instruction by arbitrary values. If "POP %EAX" is the first value to set (see picture above) and last byte is "RETN" it is possible to force a new execution of the gadget over time. Making a loop.  For every loop it is possible to execute new data (for setting arguments or for setting up the stack)  and after loops it's possible to execute the shellcode.


NES laboratory made up a PoC. The above picture (taken from the original "paper") shows that what they did succeed in bypassing Windows 7 ASLR. Actually they didn't proved that the machine in which the PoC run was a Windows 7 machine ;), but we trust them ;). Again, I still did not test it, so I am not saying that it really works, I am only reporting on my personal blog an interesting piece of security history that I consider important to keep in mind. I suggest the reading as soon as they will come out with a full paper on the great work they did ! Good job Stefan !

Wednesday, October 12, 2011

Your Browser Matters

A very interesting project founded by Microsoft measures your browser security. It is called  your browser matters and analyzes IExplorer, Firefox and Chrome basing on 4 macro categories of attacks: 

  1. Dangerous Downloads
  2. Phishing Websites
  3. Attacks on Browsers
  4. Attacks on Websites
My old Firefox got reasonably quite low score (1.5 out of 4):




And if you want you can see what's the average of the browsers score.  It really surprised me:


Well, well, well a project founded by Microsoft which says that Internet Explorer is way long more safe (4 out of 4) then Google Chrome (2.5 out of 4) and Mozilla Firefox (2 out of 4)? Sound interesting, doesn't it ?  Anyway, I really would like to investigate how these tests have been chosen, for example why these tests and not others ? What about the "attack on your browser" section ? What attacks have been implemented ?How do they test them ? I actually have many more questions for them. BUT, beside my questions I do agree that it's a nice place where users can get a first security check. I bookmarked it, let's see if they will release some source code in the future ;) .

PS: Many Thanks to Wouter Rogiest for the typo in the title and in the body ;)



Another simple Backdoor Shell

Hi folks, this morning I am going to share a little and simple "backdoor shell" written in Perl.
This is nothing exceptional, really, but I think it is a perfect didactic script for everyone is approaching to the backdoor world (I am thinking now at students ... ;). So here it is:


Well, the most interesting part of the script is the way the standards output/input and error are redirected to the opened socket. This is the right way to redirecting strings (command results) directly through the connected socket. Beside that everything is pretty simple and straight. 

Sunday, October 9, 2011

Communication between multiple ARDUINO

Hi folks,
Today I want to show how it could be quite easy making two, or more, ARDUINO talking together. The used protocol is called I2C-bus protocol. I2C is a Master to Slave protocol in which the Master asks data to the Slave or it directly sends data to it. The Slave could only replay to the only Master without making any query. I2C protocol runs over analog pins, meaning that you will have much more digital pins free for your sensors.  Obviously if you need more analog pins (for example if you have analog sensors) I2C is not the right protocol for you. I often need more  digital pins then analog ones, so it perfectly works for me.

In the above example three ARDUINO (one Master and 2 slaves) are used to show how I2C-bus protocol works, but you might hang up to 128 ARDUINO. The only links you need to wire are SCL (System Clock), SDA (System Data) and GND (Common Ground). Optionally you might want to include a wire for a common VCC. In our example, made by a student of mine Samuele Solari the 3 ARDUINO are connected through pins A4 (SCL) and A5 (SDA) GND and VCC (5v).

Lets analyze a simple sketch which reads strings from Serial input (USB) and sends them to I2C-bus. The Master sketch looks like the following code:


The only needed library is Wire.h, already included into Arduino IDE. The setup procedure sets up the Wire library (Wire.begin) and starts up the Serial (9600 baudR). The loop procedure reads integers from serial input, prepares the Wire transmission to Slave1 (Slave1 is the first ARDUINO Slave given address) and sends byte (see the casting) to the first Slave. Thus it ends the wired transmission.

On the Slave side the sketch does the opposite task: it reads from I2c-bus and it sends out characters to USB serial output.



Again the only needed library is Wire.h. The setup procedure sets up the wire library giving its own address (const int Slave1 = 1; ), it sets up the serial communication (USB) and finally it sets up a event handler. Wire.h works with handlers rather then using the structured loop, this makes a so called "interrupted communication", in other words ARDUINO does not verifies the presence of bytes on the analog pin A5 by running the loop procedure, but it becomes "interrupted" as soon as a byte is available on analog pin A5. The sketch handler is called "receiveEvent", it loops over the number of available bytes and it sends to the serial (USB) the just received bytes.

Hope this will be useful, it has been really useful for me !

Friday, October 7, 2011

AmericanExpress and the hidden page.

This morning the Americanexpress company closed the door to the so lovely /us/admin/ page. If some  of you are not aware about the hidden debugging pages, to make it quick, AmericanExpress company collected cookies sessions to investigate their website news from users' prospective. A fancy but hidden debugging webpage were used to set the cookies to the tester's browser.  Here an example I took some days ago.




The funny story abut this page (that is actually described here for the first time) which makes me laugh is not really about the vulnerability that it is affected (really ? they hit an administration page without protection and they made it vulnerable too ??), but for the ingenuity of programmers that are still trusting to the net. Automatic scanners and Autonomic exploitation engines are always directed to such targets (for example: banks, credit card companies and so on..): why people are still thinking that hiding pages/codes/algorithms/etc. is a good solution against attacks  ?



Monday, October 3, 2011

ICEGov 2011 and Internet Voting.

It was a great conference: Tallinn is a very nice city and the organization has been just  perfect. Nice food, worm and cosy rooms, nice sessions and detailed conference information. So what is my post about ? My post is about Internet voting. A special session about internet voting during the last days opened my doubts on the ingenuity of people. Ingenuity often comes from disinformation. Disinformations about hacking, disinformation about security holes and disinformation about what the attacks can do in real life. I am not going to bore you writing about successful past attacks, but I am really interested on what Internet voting is for. 

Internet voting enables people to vote for their favorite candidate directly from home, or from coffee shops or wherever they prefer. The first main issue about "voting by home" is that voters can technically be able to prove what they voted for. This issues triggers the so called "covert channel attacks" where candidates can buy votes by asking proves of them. It's pretty obvious that letting the voting period be one week long does not prevent this kind of attack. Indeed the attacker might force voters to vote in the last day, he might install Malware on the voters computer to control what they voted for or he might gather people in the same room during the last voting "night" and force them to vote for a specific candidate. This scenario is pretty common, just lets try to think about organizations, political movements, religious groups etc. Kiosk election, theoretically, doesn't let you in the position of proving what you voted for. Cameras, cell phones, copy markers and whatever,  are not allowed in the kiosk room. States that enforce this laws put security checks before the poling stations, for example Iran, Iraq, some Africa states are well enforcing this law.


 

Another interesting issue that people that are using Internet voting don't care about is the trust of people platforms. When I asked: "  How do you deal with Malware  on voters computer ? ", Estonian's Internet Voting chief answered me: " We need to trust people !". This is false. Except few rare cases, people wont to install Malware on their own machines. Malware get installed for many different reasons but not because people want to install them on their computer. So it is not about trusting voters, is about trusting Internet, is about trusting the entire world, even enemies that might hire hackers to compromise your elections. A well studied malware can easily change the vote directly on the voter's machine without the voters know it; it can easily try to compromise the election server and it can easily monitor what you voted for. Even more complicated is when a voter uses an Internet caffe. In this scenario the Internet Voting system must trust a "mercenary" machine. Where with the word "mercenary" I mean a machine that has been used by many different people, potentially used by attackers too. In a well implemented kiosk systems (where voters are checked before getting close to the system) this scenario is not possible since the kiosk operative system is controlled and enforced.



Another huge problem about voting from home, even if by using smart-cards or identification tokens is about "family voting". In other words smart-cards, if used in the way many Internet voting systems are doing, can be borrowed to friends, family members and group leaders. A smart card if used "at home" does not identify the voter, it identifies the cardholder (the same problem we had with credit card bearer). The result is that the cardholder can vote for the real voter. In a kiosk system this cannot happen since pol workers identify the real voter and control that his card is with his name on it.




At this point people can think about paper mail systems. They do allows these insecurity levels too. But again, it is not an excuse to say: "they do bad I can do bad as well". What's the point here ? We are talking about democracy, and as we all know, who leads the democracy of a country can have a huge impact to the real life of citizens.

I am not saying that Internet voting is totally wrong and that we should never use it. I do believe that Internet voting is the future, it increases participation, it easy to manage, it is economic and cheaper then a paper system, it is fast and potentially with low errors rate. My point here  is that right now we don't have enough tools to ensure democracy,  if using Internet voting systems. Internet voting is good, even nowadays, but for "secondary" elections not for "primary ones". "Secondary" elections can be a great test cases for Internet voting systems but letting the presidential election to the hands of Internet voting system could be very dangerous.




Friday, September 23, 2011

IDA2LateX

Hi Folks,
today I want to share a very nice plugin made by Tamaroth, called IDA2Latex. As many researchers I do have the problem of converting "IDA codes" (in other words, what IDA disassembles ) into Latex source code to print out a nice paper. I always used screenshots and then applied the resulted PNG (JPEG or PDF) images in the documents, but I hadn't perfect results. Indeed, the  resolution (especially on the printed versions of the papers) was pretty poor and it was pretty hard to read. Today thanks to IDA2LateX everything is better. Following the result:

From IDA by using the plugin you can save a .tex file like this one:


Once compiled it becomes :



Which is great ! Acoording to Tamaroh the plugin is is still a little bit bugged (it's on its first release), but I am confident in seeing it pretty soon in a stable version. Now I am just waiting for something like that applied to Blogs :D .... specially for blogger  .... 

Thursday, September 22, 2011

Bug Hunting

Sometime people (often it happens with good students) asks to me how to find vulnerabilities. This is a great question but unfortunately the answer might take forever. The short answer is to look for bugs. Indeed, a vulnerability is a specific bug. A vulnerability is a particular bug which affects the security of the entire system. So usually I say,  find a bug, then come to me and I will show you how it's possible to transform some kind of bugs in vulnerabilities.

Well, the second question comes automatic, how do I find a bug ? Even this answer could fill up a whole book but usually I say: you might find a bug by doing fuzzing. Today I wanna introduce to you BAD: the Bruteforce Exploit Detector.

BED is a program which is designed to check daemons for potential buffer overflows, format string bugs et. al. BED simply sends the commands to the server and checks whether it is still alive afterwards.
Of course this will not detect all bugs of the specified daemon but it will (at least it should) help you to check your software for common vulnerabilities.
BED is particularly good for remote fuzzing while if you need "something more local", testing local parsing file bug I do always suggest gruba. I know ...  those are pretty old and now there are "universal" fuzzers including PE, MACHO, ELF, HTTP, FTP, UDP, SNMP and so forth and so on... but both BED and gruba are pretty easy to analyze and, eventually, to expand.

Monday, September 19, 2011

IEEE Malware 2011 two research papers accepted !

Hi folks,
I know .... during the past month I didn't update often my blog. I am traveling a lot between conferences and I find very few time for posting in my little piece of Internet. Anyway I am glad to announce that I'll present at IEEE Malware 2011 in Puerto Rico the next October.


As usually, if someone will be attending Malware 2011 or if someone of my readers want to have a beer with me (like happened in California last year) just email-me I'll be glad to have a beer with you guys talking about our favorite security topics. ;) See you in Puerto Rico.

Wednesday, September 14, 2011

Misha Glenny: Hire the hackers!

Hi Folks, today I want to share this amazing TED's talk. Finally information is coming true and people starts to talk bout cyberterrorism. In the USA there are plenty organizations founded for fighting cyberterrorism or, at least, to study it. What about Europe ? Somebody knows any European Organization against cyberterrorism?