Sunday, June 8, 2014

KGM2 CrackMe Analysis

Hello folks,

In our last post, we saw the interesting Hardcrypt crackme, we did some analyses and ended up writing a keygen for it. Today we are going to do the same for another easy CrackMe, but this time, a bit trickier.

Today's CrackMe named KGM2, written by Kirjava (yes, the guy we mentioned in our last article), you can find the CrackMe in the reference section in the end of this post.

Now let's start by opening KGM2, and getting a simple idea on its functionalities, and the way the CrackMe behaves with our input.

As we can see, I entered (hello) as a username and (world) as a serial, clicked the Check button, nothing happened, that might be a length problem, maybe the application accepts a specific length input? After trying other combinations with different lengths, nothing special happened again, now let's get our hands dirty a bit and start our reversing process.

First, as always let's load it into PEiD, it seems a normal executable with only one section (.text section). Now load it into our lovely immunity dbg and start the journey.
After running it within a debugger, we start by checking for strings in the process's memory, but as we can see in the screenshot below, nothing special in here:

Now, let's be a bit more tougher, by looking into the functions the CrackMe calls:

Looks like a very usual Win32 API functions, and we can notice some famous Windows API functions like CreateWindowExA ,GetDlgItemTextA, MessageBoxA,VirtualProtect (Self-Modifying code?), etc...
If you know a bit about Windows Messaging system structure, function GetDlgItemTextA() should ring a bell, this function is the one that gets your input from a created Win32 windows process, and saving it into a buffer in memory. Perfect, we are seeing two calls to the previous mentioned function, which is really expected since we have only 2 input fields in the CrackMe. Let's start tracing one of them:

As we can see, the first call is for getting the username input field, saving it into the buffer 0x004016A4, while the second GetDlgItemTextA() call is for getting the serial input field, saving it into the buffer 0x004018A4. Let's check our work by placing a breakpoint after the serial input function, on line 0x00401392, run our application, writing our input, and here we go, the debugger paused at our breakpoint, if we dumped the 0x004016A4 and 0x004018A4, we must be able to see our input. From now on, we are going to stepover in order to understand what encryption/hashing code our inputs are passing by during their way to the final check.

Let's also assume, that the serial is saved into a buffer pointed to by the variable (serial), and the username by the variable (name), so that we can point, access and alter their values whenever we need without mentioning stack and/or other CPU registers.

We can see in the code between the two GetDlgItemTextA() calls, that it simply saves the length of our username into memory address 0x004016E0, and checks if it's lower than 0xC (12), so that if we entered a username with 12 or more characters, the program won't even get our serial, and will finish the program silently (how did we know that? this is a very easy tracing you can do on your own). So far so good, after getting the serial input field, it checks if the serial is 0xC bytes, which means that our serial must be exactly 12 bytes, otherwise it (again) finishes silently. It then makes another check on the length of the username field, if it's below 8, it will finish silently. So we now know that the username length must be bigger than or equal to 8 and less than 12 digits, and the serial must be exactly 12 digits.

It now jumps to the address highlighted in the above screenshot (0x004013A6), this chunk does nothing more than getting the last character in our username, multiplying it by the length and saving it back into the first character, in a C-notation it can be written that way:


In the end of that block, we can see a jump to the address 0x004013EE, but wait, this jump is already situated at the address 0x004013ED, and the opcode of the jump is EB FF, so that if we executed that jump ,we would pad on the opcode 0xFF , this is the opcode for a CALL instruction, let's dump the address 0x004013EE:

As we expected, the jump wasn't the real instruction to be executed, this is a debugging obfuscation technique in order to confuse the debugger, the real jump is done to a routine that starts on address pointed to by register EAX, which is 0x00401251.

Now, I won't be going through each of this routine's instruction, this should be too easy for anyone knowing assembly, I will only highlight what the whole routine does, it simply changes the value of each byte of the username buffer using this simple loop:

Just the last part of this routine might be interesting, starting from address 0x004012DA to 0x004012FB, this routine changes something at address 0x0040104C, if you dumped that address after this loop, you are going to find a very fancy thing, I won't be saying it.

In the end of the 0x00401251 routine, we can find on address 0x0040130A a jump to the address 0x0040130B, the same obfuscation trick, if we dump'd the jump address:

A call to pointer at EBX, which will be a call to 0x00401166, Here we are going to find a new routine:

Again, I won't be explaining each instruction apart, this long routine is simply doing so:


So far so good, at the end of that routine, we can find another jump that uses the same trick as the two jumps before, it calls the routine at the address 0x004010BF:

This is the main checking routine, it's checking the first 8 bytes of the name (altered version of the username input), adding the value 0x41 to them, and comparing them with the first 8 bytes of the serial, after that it compares the 4 bytes (those bytes generated by the routine 0x00401166), with the last 4 bytes of our serial, and if all checks succeeded, it creates a new thread that starts its execution at address 0x004010A6, with parameter 0x0040104C (remember? this is the interesting loop we talked about earlier), we can notice that this thread only calls MessageBox that congratulates us for our good work.

Now, that we analyzed every bit of our program, we can write a very simple keygen for it:

We can now try our generator on username (redseees), with the output serial :

In the end, there are some functions used and questions we didn't discuss, I'm leaving that to the reader so he can notice and practice more on assembler language, some logical questions might be why the author of the CrackMe used VirtualProtect() and VirtualAlloc(), why he's creating threads rather than normal sequential execution flow?

If you have any question or want to know the answers of the last questions, you can drop me a message on secmania{at}hotmail{dot}com.

-KGM2 by Kirjava CrackMe :

Tuesday, June 3, 2014

HardCrypt CrackMe analysis

Hello people,

I was solving today random crackmes' as everyday ,and I passed by this easy but interesting crackme.
What really drew my attention is the key generation part, it wasn't a usual bruteforcing or some calculus equations you paste in your key generator application using your best programming/scripting language, interpret/compile and execute it to get the right key, instead it used a smart method to avoid anyone writting a simple key generator, we are going in this article to walkthrough this crackme and the way I solved it, we are going as well to discuss some other solutions people submitted.

So take a seat, bring your coffee and enjoy the ride.

First of all, you can get a copy of that crackme on the famous repository, it's named (HardCrypt), written by The Mentor.

Now, let's load our binary into PEiD to check if it was packed, luckily we found some cool info that points out no packer has been used on this binary.
Of course, that might be a false positive, experienced reverse engineers should know about "custom packers", a kind of packer that is able to fool an executable scanner tool.

We are ready to go now, let's load it into our lovely immunity disassembler (you can use your best debugger/disassembler), let's make the very usual steps anyone would begin reversing a crackme with, finding references to known strings.

As we can see here, we were lucky (until now), we found some reference strings that are well familiar to us. Let's double click the "wrong pass" one, that will take us into the text section that contains a pointer to this buffer.

Here, we can see that this application uses some glibc functions, like gets(), puts(), system() and such, that's too good until now, specially after seeing the strcmp() line. As we all know, strcmp() is a function that takes 2 parameters and returns zero if they are the same, otherwise if not. Let's take a further look in that strcmp() call, we are going to make a breakpoint on strcmp() line, and restart our application within the debugger, and as soon as you input a string, your debugger will pause on the breakpoint, a look on the stack memory, we will notice both parameters push'd as parameters to execute the strcmp() function.

Very interesting, isn't it? an unknown string passed to strcmp() with our string. Of course, you can really patch the crackme simply in this level and you are done, but I bet you enjoyed nothing by going the easy way (sometimes, in real application cases, you might not be able to even patch it).

Now let's take a deeper dive into this other unknown string, it's situated at the double word EBP-137 on the stack segment ,which is the address 0x0022FE11, also we can notice that this string is generated even before we provide our input into the crackme, if we scrolled up until we reach the beginning of our current procedure, place a break point into that address (on my machine, it is : 0x00401340), and restart the application within the debugger, we can notice that the breakpoint is hit before facing the gets() function (before inputting our  string), all that means simply that the key is generated in the prologue of the application, it doesn't have any mathematical relation with our input, which means the key is generated using one (or many) of our system's resources (date, ram usage, CPU ticks, etc...).

Let's examine that by stepping over the instructions starting from 0x00401340, the place we put a breakpoint at last time, until hitting the address 0x0040135A. Here we can notice a call to time() call, it's a windows API function that returns system time, here it's used with NULL as parameter, and the returned value is stored at address 0x0022FF34. After that we can also notice another win32 API call localtime(), which takes a time value and corrects it to the local zone timing. localtime() function takes one input, a pointer to the location where we stored the system time (the returned value of time(), in assembly any return value is saved into the accumulator register EAX).
On MSDN, localtime() returns a struct that contains an exact values about current time, this struct is named tm structure, Microsoft defined it on MSDN as follows :

struct tm {
  int tm_sec;
  int tm_min;
  int tm_hour;
  int tm_mday;
  int tm_mon;
  int tm_year;
  int tm_wday;
  int tm_yday;
  int tm_isdst;

In our crackme, after finishing localtime() function call, a pointer to tm structure is saved into EAX, then the struct members are copied into memory location 0x0022FF10 .

So far so good, after that a busy wait loop is executed at address 0x004013B2, looping while doing nothing for 190 million times.
After that loop, we can find a very interesting iteration starting at address 0x004013CF, this loop iterates 3 times, each iteration calls the win32 API function GetCursorPos(), this function (as MSDN defines) takes one parameter, a pointer to a POINT structure. Again, looking at POINT structure on MSDN, it's a structure that contains 2 members holding our cursor coordinates. In our crackme, this struct is located at address 0x0022FD08. After finishing the function GetCursorPos() call, it multiplies the y cursor coordinates by the x coordinates, adding the result into a variable initialized with the hexadecimal value 0x0022FFF0, and saved at memory address 0x0022FF38.

After the three iterations, the double word located at address 0x0022FF38 is multiplied by the sixth member of our time structure, which is the (tm_mon, month), then subtracted by the third member of the time structure, which is (tm_hour, obviously the hour). It then makes a function call to windows API function _itoa() that takes an integer variable, a pointer to a string, and a numbering system, converting that integer variable, in the number system provided, to a string, and saving it into the location we gave in the parameter list.

Finally, it appends the string "H!J" with our resulting string, and we now have the key that's going to be compared with our input string.

Now, as I mentioned earlier, we can just patch our strcmp function in an earlier stage of our analysis, and that's the easy (boring) way, but that won't always be the case, sometimes, some binaries may contain some CRC or checksums, which protect the binary image of being altered. After our analysis we now know how to write a very simple algorithm that generates a valid key, to be used in that crackme, and when checked, it outputs the happy string "Right Password".

Of course, even that solution isn't that easy, the generation function gets input from time() and our mouse cursor position, which most probably won't work by just coding a keygen, because simply the time and the cursor position will be different while executing each of them, our keygen and the crackme. One way made by Kirjava ( ) ,he injected a process that holds the execution of the crackme right at the beginning of its execution ,it then injects a dll, which reads the memory location containing the valid generated serial, printing it and restores the execution flow of the crackme, this is a smart solution in my opinion. Another solution is code caving, it's a kind of patching but still makes the job done.

Here is a sample C-like pseudocode for the key generation procedure :

Finally, I enjoyed the way the author of this crackme used in order to generate the key, so all greetz goes to him.

A thanks must go to Kirjava for his solutions, and crackmes.

-time() msdn :
-localtime() msdn :
-GetCursorPos() msdn :
-tm structure msdn :
-POINT structure msdn :

Monday, April 7, 2014

From Boot to Root, Reverse Engineering your Satellite TV Receiver

Hello guys,

Sorry for not posting anything the last couple of months, but usually, long time, means a fancy post.

Today, we are going to talk about something interesting/unusual, today's trip will be into hardware hacking.
We are going to talk about hacking a TV receiver, from watching your TV, to getting a shell inside.

Before starting, I must mention some names that helped me a lot in my journey toward getting my first hardware shell from within my tiny laptop:
- Ahmed Mamdouh Ahmed, A teacher assistant in computer and communication department, Alexandria University, Egypt.
- Ahmed Hamdy, A teacher assistant in computer and communication department, Alexandria University, Egypt.
- Google, DuckDuckgo, and the result pages inside.

Thanks for wasting time answering my boring questions, really.
Okay, so here starts our journey, have a seat, and a nice cup of coffee.

Important Notes:
- First, it's important to make sure that you have some electronics and serial communication basis, since this will be the base of all our work.
- We are going to use two basic tools in order to reverse engineer our RS-232 serial port:
Multimeter-USB to UART adapter.
- Personally, I'm going to work on a Linux machine (Arch 64-bit), and minicom serial communicator script (you are always free to get your favorite set of software tools, as long as they get the job done).
- I'm making sure to generalize the explanation as wide as possible, so that it can be applied on any kind of serial port attached with (almost) any piece of hardware.
- If you doubt making any (I really mean ANY) of this post steps, please do NOT continue following, since some of the steps can fry your hardware if you are not aware of, which is not the intended aim here.
- A brain is a big plus, so make sure you have/can use one.

Now we are ready to dig in, our target hardware is Prifix 9500 Digital Satellite TV Receiver, here is a photo of it before taking the cover apart:

After getting out the cover and the power circuit, we end up with the main board of the receiver, mine looks like this:

Pretty fancy, isn't it?

Now, from the photo above, we can notice some of the on-board chips:
-Right most chip: Hyundai HY57V28162XX DRAM family series, it's a synchronous CMOS Dynamic RAM, with a capacity of 4 blocks, each 2M, with 16-bit bandwidth.
-Middle big chip: Conexant CX24303 ARM CPU, a 32-bit RISC processing unit, also includes a tv tuner, MPEG decoder, and many other features.
-Left most chip: Spanion S29AL016D70TF, a 16-Megabit CMOS ROM for bootstrapping process, and firmware storage.

Also, we can notice some JTAG's, in the middle of the upper part of the photo (which of course we can make use of).

So far so good, we have now an overview of the chips, the board in general, what we need now is to find 4 pins, GND, Tx, Rx, and Vcc, in order to start our communication with Conexant CPU.

After some fuzzing, I've seen in the back of the board, 4 individual pins, I guess with more than 50% that this is the right serial header we are looking for, and the cause of giving it a probability of more than 50%, is that I've found only 2 4-pins headers, one was related to some capacitors in the circuit, and the other was connected to nothing.

Now, our next mission is divided into making sure that these 4-pins are the right serial header, and playing a bit with the pins in order to discover what each pin does.

In order to make sure that this is the right serial header, and as mentioned previously, it must have at least 4 pins: GND, Tx, Rx, Vcc.
Let's start with the simpler one, the ground pin, in order to know which of the 4 pins is the ground, open your multimeter on the continuity test, put one probe on the pin you are testing, and the other probe on any conducting metalic surface you have on the board, personally, I love the co-axial LNB female port, so I'll stick with it.
My multimeter buzzed at pin number 4, and this is the GND pin.
Now, let's move to the other simpler one, Vcc pin, Connect your board to the power board, switch it on, switch your multimeter, set it to Voltage reading, and put one probe on the GND pin (or of course a conducting metal in the board), and move the other probe on each of the remaining 3 (or more) pins, if your probe is on the Vcc pin, you should see some voltage on your multimeter LCD (most probably 3.3 ~ 5 volts).
Make sure to keep measuring the pin under test for a while (about 5 seconds), since that Transmitter pin gives some voltages too, for a very small amount of time, we are going to use this trick to identify Tx pin the next step.
My Vcc was at pin directly next to the ground pin.
Now we have two remaining pins, the Tx and Rx ones, it's nearly impossible to know which is the Rx one using your multimeter only, since that the Rx pin is only receiving data, so if you put your probes on, it won't give you any readings, but we can of course identify the Tx, after that, concluding that the last remaining one (of the 4 pins header) will be the Rx.
To measure Tx pin, keep your multimeter settings on voltage reading, and put your probe on one of the remaining pins, if it's the Tx, it will give you a non-stable signal, oscillating from zero to 3.3 (or 5), and here is the Tx pin.

Now, that we found our serial header, and identified each of the 4 pins, we are ready to connect our receiver to our computer via USB-Serial adapter.

So why we are using an adpater here?
Actually, Receiver serial header uses RS-232 protocol, which uses the standard of logical zero bit between +3 ~ +25 volts (+5 to +15 on load), and logical one bit between -3 ~ -25 volts (-5 to -15 on load), while our USB uses differential protocol type, and it uses 5V Vcc power, so we here need to make sure that RS-232 logical power level is decreased to the USB logical level, as well as reversing the bits (so that 0 becomes 1 and 1 becomes 0, because they are reversed in the RS-232 protocol as you noticed earlier).

Just before connecting our computer to the receiver, we have to identify the communication parameters of the RS-232 protocol.
Most devices use 8N1, and 9600/115200 baud rates for asynchronous serial communications, which means we are using 8-bit data, 1 stop bit, 1 start bit, and no parity bits, and the communication is set to the speed 9600 or 115200 symbols/seconds, but as long as we have time, we can for sure play with every parameter to make sure this is the right one.

After some trials (and a lot of errors), I identified that my communication runs on 8N1, and uses 115200 baud rate, so I connected my USB-Serial adapter, set minicom settings to open a listener on my /dev/ttyUSB0 port with the serial parameters mentioned before, turned on my receiver, and finally got some *readable* data on my minicom (yes readable, since that I was trying to get any useful data for 3 months of trial and errors, and always getting garbage on screen).

Also, make sure that you are connecting your Rx (second pin of the DB-9 port) of your USB-Serial adapter with Tx pin in your receiver, and Tx (third pin of the DB-9 port) with Rx pin in your receiver, since that RS-232 protocol is a half-duplex single ended protocol, so it can only connect 2 devices at maximum, and each device is either reading or writing data at a time.
Now, here is the output I got from my Prifix receiver when turned on, on my laptop:

As you can see here, all of these data are the bootloader's info of the receiver, trying to load the firmware in memory, and after some seconds, we are getting a shell from which we can execute some commands (stack and heap dump's, CPU status, upgrading firmware, etc...).

Voila, We started from knowing nothing about the device, until getting a code execution inside the Conexant ARM chip.
From here on, we can do any (even evil) thing with our friendly receiver, we can try reversing the firmware (or maybe dump it from the ROM), and play a bit with it in order to exploit some of its services, and maybe getting some more interesting stuff.
Finally, this was a walkthrough on a part of my journey with reverse engineering hardware, If you came across the same journey (or a similar hardware hack(s)), or if you do have any questions about this one, you can always reach me on:

Sunday, January 19, 2014

Another Obfuscated C code

hey guys ,

Just found another simple C obfuscated code ,and this one was simpler than the others ,but was kinda different ,here it is :

Obfuscated Code

I'll try to just mention the obfuscated points at it ,I won't walk through it step by step ,as it's very simple and easy to trace and understand .

Code After removing spaces

-Line 12 : c=c^10 part is used to switch variable (c) between values 42 and 32
-32 is the decimal ascii for whitespace character .
-42 is the decimal ascii for asterisk character .
-Line 4 : (s) array is used as follows :
  -even indexed numbers are used for displaying asterisks .
  -odd indexed numbers are used for displaying spaces .
  -negative numbers are used to print a new line feed .
  -58 is used to display 10 spaces ,it's just an additional way to obfuscate the   code ,we can replace every 58 element by inserting 10 instead ( doing this ,will force us to remove the s[i]&(9+6) part on line 19 in the inner for loop condition ,so now it should be s[i] only ) .
-Line 20 : function p() is given any value as a parameter ,since it's doing nothing with this parameter ( we can even remove the parameter in function definition ) .
-Line 28 : function f() is useless ,since it's not called anywhere in the code .
-Lines 32,30,15 : some garbage are added just to obfuscate the code .

And here is the last deobfuscated version of the code :

Deobfuscated Code

Enjoy .